LuminaWebsite/includes/wiki.php
Maaxxs 392994e1cd Activity check (website + bot), videos in the wiki, contributor search list
- Activity check: created on the website (activity.php, activity.manage) or with /aktivitaetscheck; the bot posts "I'm in" / "I'm out" buttons; title, text, color, image and button labels are configurable with a live preview; deadline; consequences for non-responders (DM, remove/add role, optionally also for "I'm out"); close early or cancel; overview of in / out / pending
- Wiki: a video link alone on a line (YouTube incl. Shorts/start time, Twitch, Vimeo, .mp4/.webm) becomes an embedded player, plus a "Video" button in the editor
- Wiki: "Add contributor" as a search list with avatar, group and class instead of a dropdown

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 01:11:49 +02:00

477 lines
19 KiB
PHP

<?php
declare(strict_types=1);
/**
* Wiki (Einsteiger-Guide) im Mitgliederbereich.
*
* Aufbau: Kapitel (parent_id NULL) mit Unterseiten, automatisch nummeriert wie im
* urspruenglichen Guide (3. / 3.1.). Jede Aenderung landet als Version in wiki_revisions.
*
* Rechte: wiki.view lesen, wiki.edit schreiben (fuer ganze Gruppen), wiki.manage verwalten.
* Zusaetzlich duerfen alle schreiben, die die Leitung im Wiki als Mitwirkende hinzugefuegt
* hat (wiki_contributors) - so lassen sich einzelne Mitglieder einbinden.
*
* Seiten werden in einem einfachen Textformat geschrieben (aehnlich Markdown, siehe
* wiki_render()). Aller Text wird zuerst HTML-maskiert, eingeschleustes HTML ist also nie aktiv.
*/
const WIKI_UPLOAD_DIR = __DIR__ . '/../assets/uploads/wiki/';
const WIKI_UPLOAD_URL = '/assets/uploads/wiki/';
const WIKI_MAX_CONTENT = 200000;
function wiki_can_manage(): bool
{
return user_has_permission('wiki.manage');
}
function wiki_is_contributor(int $userId): bool
{
try {
$stmt = db()->prepare('SELECT 1 FROM wiki_contributors WHERE user_id = ?');
$stmt->execute([$userId]);
return (bool) $stmt->fetchColumn();
} catch (PDOException $e) {
return false;
}
}
function wiki_can_edit(): bool
{
static $can = null;
if ($can === null) {
$user = current_user();
$can = user_has_permission('wiki.edit') || wiki_can_manage()
|| ($user && $user['status'] === 'active' && wiki_is_contributor((int) $user['id']));
}
return $can;
}
/** Aus einem Titel eine eindeutige Adresse machen ("Sealed Dungeon / Versiegelter Dungeon" -> sealed-dungeon-versiegelter-dungeon). */
function wiki_slugify(string $title, ?int $exceptId = null): string
{
$slug = mb_strtolower($title, 'UTF-8');
$slug = strtr($slug, ['ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss']);
$slug = trim((string) preg_replace('/[^a-z0-9]+/', '-', $slug), '-');
if ($slug === '') {
$slug = 'seite';
}
$slug = substr($slug, 0, 150);
$stmt = db()->prepare('SELECT 1 FROM wiki_pages WHERE slug = ? AND id <> ?');
$candidate = $slug;
for ($i = 2; ; $i++) {
$stmt->execute([$candidate, $exceptId ?? 0]);
if (!$stmt->fetchColumn()) {
return $candidate;
}
$candidate = $slug . '-' . $i;
}
}
/**
* Alle Kapitel mit ihren Unterseiten, sortiert und nummeriert.
*
* @return array<int, array<string, mixed>> Kapitel, jeweils mit 'number' und 'children'
*/
function wiki_tree(): array
{
$rows = db()->query(
'SELECT id, parent_id, title, slug, is_wip, sort_order FROM wiki_pages ORDER BY sort_order, id'
)->fetchAll();
$chapters = [];
$children = [];
foreach ($rows as $row) {
if ($row['parent_id'] === null) {
$chapters[] = $row;
} else {
$children[(int) $row['parent_id']][] = $row;
}
}
foreach ($chapters as $i => &$chapter) {
$chapter['number'] = ($i + 1) . '.';
$chapter['children'] = [];
foreach ($children[(int) $chapter['id']] ?? [] as $j => $child) {
$child['number'] = ($i + 1) . '.' . ($j + 1) . '.';
$chapter['children'][] = $child;
}
}
unset($chapter);
return $chapters;
}
/** Seite per Adresse, mit Namen der letzten Bearbeitung. */
function wiki_page_by_slug(string $slug): ?array
{
$stmt = db()->prepare(
"SELECT p.*, COALESCE(NULLIF(u.display_name, ''), u.username) AS updated_by_name
FROM wiki_pages p LEFT JOIN users u ON u.id = p.updated_by WHERE p.slug = ?"
);
$stmt->execute([$slug]);
return $stmt->fetch() ?: null;
}
function wiki_page_by_id(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM wiki_pages WHERE id = ?');
$stmt->execute([$id]);
return $stmt->fetch() ?: null;
}
/** Titel (klein) => Adresse, fuer [[Wiki-Links]]. */
function wiki_link_map(): array
{
static $map = null;
if ($map === null) {
$map = [];
foreach (db()->query('SELECT title, slug FROM wiki_pages')->fetchAll() as $row) {
$map[mb_strtolower($row['title'], 'UTF-8')] = $row['slug'];
$map[$row['slug']] = $row['slug'];
}
}
return $map;
}
/** Speichert eine Version (Titel, Inhalt, WIP) einer Seite. */
function wiki_add_revision(int $pageId, string $title, string $content, bool $wip, ?string $summary, ?int $userId): void
{
db()->prepare(
'INSERT INTO wiki_revisions (page_id, title, content, is_wip, summary, edited_by) VALUES (?, ?, ?, ?, ?, ?)'
)->execute([$pageId, $title, $content, $wip ? 1 : 0, $summary, $userId]);
}
/**
* Legt den Einsteiger-Guide aus includes/data/wiki_seed.json an (aus dem Spreadsheet
* umgewandelt). Gibt die Zahl der angelegten Seiten zurueck.
*/
function wiki_import_seed(int $userId): int
{
$data = json_decode((string) file_get_contents(__DIR__ . '/data/wiki_seed.json'), true);
if (!is_array($data) || empty($data['chapters'])) {
throw new RuntimeException('Die Startdatei des Guides fehlt oder ist beschädigt.');
}
$pdo = db();
$insert = $pdo->prepare(
'INSERT INTO wiki_pages (parent_id, title, slug, content, is_wip, sort_order, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
);
$order = (int) $pdo->query('SELECT COALESCE(MAX(sort_order), 0) FROM wiki_pages WHERE parent_id IS NULL')->fetchColumn();
$count = 0;
$pdo->beginTransaction();
foreach ($data['chapters'] as $chapter) {
$order += 10;
$insert->execute([null, $chapter['title'], wiki_slugify($chapter['title']), $chapter['content'], !empty($chapter['wip']) ? 1 : 0, $order, $userId, $userId]);
$chapterId = (int) $pdo->lastInsertId();
wiki_add_revision($chapterId, $chapter['title'], $chapter['content'], !empty($chapter['wip']), 'Aus dem Spreadsheet übernommen', $userId);
$count++;
foreach ($chapter['children'] ?? [] as $i => $child) {
$insert->execute([$chapterId, $child['title'], wiki_slugify($child['title']), $child['content'], !empty($child['wip']) ? 1 : 0, ($i + 1) * 10, $userId, $userId]);
wiki_add_revision((int) $pdo->lastInsertId(), $child['title'], $child['content'], !empty($child['wip']), 'Aus dem Spreadsheet übernommen', $userId);
$count++;
}
}
$pdo->commit();
return $count;
}
// ---------------------------------------------------------------------------------------
// Textformat -> HTML
// ---------------------------------------------------------------------------------------
/** Erlaubte Adressen fuer Links und Bilder: http(s), eigene Seiten (/...) und Sprungmarken (#...). */
function wiki_safe_url(string $url, bool $image = false): ?string
{
$decoded = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
if (preg_match('#^https?://#i', $decoded) || ($decoded !== '' && $decoded[0] === '/' && substr($decoded, 0, 2) !== '//')
|| (!$image && $decoded !== '' && $decoded[0] === '#')) {
return $url; // ist bereits HTML-maskiert
}
return null;
}
/**
* Video zum Einbetten, wenn die Zeile nur aus einem Video-Link besteht: YouTube (auch Shorts,
* youtu.be, Startzeit ?t=), Twitch (Clips und Videos), Vimeo oder eine Videodatei (.mp4/.webm).
* Eingebettet wird nur ueber feste Player-Adressen - die ID wird streng geprueft, der Rest der
* Adresse nie uebernommen.
*/
function wiki_video_embed(string $line): ?string
{
$url = trim($line);
if (!preg_match('#^https?://\S+$#i', $url)) {
return null;
}
$parts = parse_url($url);
$host = strtolower(preg_replace('/^(www\.|m\.)/', '', (string) ($parts['host'] ?? '')) ?? '');
$path = (string) ($parts['path'] ?? '');
parse_str((string) ($parts['query'] ?? ''), $query);
$title = 'Video';
$frame = static fn (string $src, string $class = '') => '<div class="wiki-video' . $class . '"><iframe src="' . e($src) . '" title="' . e($title)
. '" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen"'
. ' allowfullscreen referrerpolicy="strict-origin-when-cross-origin"></iframe></div>';
// YouTube: watch?v=ID, youtu.be/ID, shorts/ID, embed/ID, live/ID
$youtubeId = null;
$isShort = false;
if ($host === 'youtube.com' || $host === 'youtube-nocookie.com') {
if ($path === '/watch' && isset($query['v'])) {
$youtubeId = (string) $query['v'];
} elseif (preg_match('#^/(shorts|embed|live)/([\w-]{11})#', $path, $m)) {
$youtubeId = $m[2];
$isShort = $m[1] === 'shorts';
}
} elseif ($host === 'youtu.be' && preg_match('#^/([\w-]{11})#', $path, $m)) {
$youtubeId = $m[1];
}
if ($youtubeId !== null && preg_match('/^[\w-]{11}$/', $youtubeId)) {
// Startzeit: ?t=90, ?t=1m30s oder ?start=90
$start = 0;
$t = (string) ($query['t'] ?? $query['start'] ?? '');
if (preg_match('/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/', $t, $tm) && $t !== '') {
$start = (int) ($tm[1] ?? 0) * 3600 + (int) ($tm[2] ?? 0) * 60 + (int) ($tm[3] ?? 0);
}
return $frame('https://www.youtube-nocookie.com/embed/' . $youtubeId . '?rel=0' . ($start > 0 ? '&start=' . $start : ''), $isShort ? ' wiki-video-portrait' : '');
}
// Twitch braucht die eigene Domain als "parent"
$parent = preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? 'lumina-ascendes.de'));
if ($host === 'clips.twitch.tv' && preg_match('#^/([\w-]+)$#', $path, $m)) {
return $frame('https://clips.twitch.tv/embed?clip=' . $m[1] . '&parent=' . $parent . '&autoplay=false');
}
if ($host === 'twitch.tv') {
if (preg_match('#^/[\w]+/clip/([\w-]+)$#', $path, $m)) {
return $frame('https://clips.twitch.tv/embed?clip=' . $m[1] . '&parent=' . $parent . '&autoplay=false');
}
if (preg_match('#^/videos/(\d+)$#', $path, $m)) {
return $frame('https://player.twitch.tv/?video=v' . $m[1] . '&parent=' . $parent . '&autoplay=false');
}
}
// Vimeo: vimeo.com/123456789
if ($host === 'vimeo.com' && preg_match('#^/(\d+)$#', $path, $m)) {
return $frame('https://player.vimeo.com/video/' . $m[1]);
}
// Videodatei (z.B. auf Discord oder einem eigenen Server)
if (preg_match('#\.(mp4|webm|mov)$#i', $path)) {
return '<div class="wiki-video wiki-video-file"><video src="' . e($url) . '" controls preload="metadata" playsinline></video></div>';
}
return null;
}
/** Inline-Formatierung einer (bereits maskierten) Zeile. */
function wiki_inline(string $html): string
{
// Code zuerst herausnehmen, damit darin nichts formatiert wird.
$codes = [];
$html = (string) preg_replace_callback('/`([^`]+)`/', static function (array $m) use (&$codes): string {
$codes[] = '<code>' . $m[1] . '</code>';
return "\x01" . (count($codes) - 1) . "\x01";
}, $html);
// Bilder: ![Beschreibung](Adresse)
$html = (string) preg_replace_callback('/!\[([^\]]*)\]\(([^)\s]+)\)/', static function (array $m): string {
$url = wiki_safe_url($m[2], true);
return $url === null ? $m[0] : '<img src="' . $url . '" alt="' . $m[1] . '" loading="lazy">';
}, $html);
// Wiki-Links: [[Seitentitel]] oder [[Seitentitel|angezeigter Text]]
$html = (string) preg_replace_callback('/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/', static function (array $m): string {
$target = trim(html_entity_decode($m[1], ENT_QUOTES, 'UTF-8'));
$label = isset($m[2]) && $m[2] !== '' ? $m[2] : $m[1];
$map = wiki_link_map();
$slug = $map[mb_strtolower($target, 'UTF-8')] ?? null;
if ($slug === null) {
return '<span class="wiki-missing-link" title="Diese Seite gibt es noch nicht">' . $label . '</span>';
}
return '<a href="/wiki.php?page=' . rawurlencode($slug) . '">' . $label . '</a>';
}, $html);
// Links: [Text](Adresse)
$html = (string) preg_replace_callback('/\[([^\]]+)\]\(([^)\s]+)\)/', static function (array $m): string {
$url = wiki_safe_url($m[2]);
if ($url === null) {
return $m[0];
}
$external = (bool) preg_match('#^https?://#i', html_entity_decode($url, ENT_QUOTES, 'UTF-8'));
return '<a href="' . $url . '"' . ($external ? ' target="_blank" rel="noopener noreferrer"' : '') . '>' . $m[1] . '</a>';
}, $html);
$html = (string) preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $html);
$html = (string) preg_replace('/(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])/s', '<em>$1</em>', $html);
$html = (string) preg_replace('/(?<![\w_])_(?!\s)(.+?)(?<!\s)_(?![\w_])/s', '<em>$1</em>', $html);
$html = (string) preg_replace('/~~(.+?)~~/s', '<del>$1</del>', $html);
return (string) preg_replace_callback("/\x01(\d+)\x01/", static fn (array $m): string => $codes[(int) $m[1]], $html);
}
/** Zeile einer Tabelle in Zellen zerlegen (\| ist ein Strich im Text). */
function wiki_table_cells(string $line): array
{
$line = trim($line);
$line = (string) preg_replace('/^\||\|$/', '', $line);
$cells = preg_split('/(?<!\\\\)\|/', $line) ?: [];
return array_map(static fn (string $c): string => str_replace('\\|', '|', trim($c)), $cells);
}
/** Anker fuer Zwischenueberschriften (fuer Sprungmarken). */
function wiki_anchor(string $text): string
{
$slug = mb_strtolower(strip_tags($text), 'UTF-8');
$slug = strtr($slug, ['ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss']);
return trim((string) preg_replace('/[^a-z0-9]+/', '-', $slug), '-');
}
/**
* Wandelt den Seitentext in HTML um. Unterstuetzt:
* ## Ueberschrift, ### Unterueberschrift - Liste / 1. nummerierte Liste
* **fett**, *kursiv*, ~~durchgestrichen~~, `Code` > Hinweis-Kasten
* [Text](https://...), [[Seitentitel]], ![Bild](https://...)
* Video-Link allein in einer Zeile (YouTube, Twitch, Vimeo, .mp4) -> eingebetteter Player
* | Tabelle | mit | Spalten | (zweite Zeile | --- | macht die erste zur Kopfzeile)
* --- Trennlinie
*/
function wiki_render(string $text): string
{
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $text));
$out = [];
$i = 0;
$n = count($lines);
while ($i < $n) {
$line = $lines[$i];
$trim = trim($line);
if ($trim === '') {
$i++;
continue;
}
// Ueberschriften: # und ## werden zu h2 (der Seitentitel ist schon h1), ### zu h3 ...
if (preg_match('/^(#{1,4})\s+(.+)$/', $trim, $m)) {
$level = max(2, strlen($m[1]));
$inner = wiki_inline(e($m[2]));
$out[] = '<h' . $level . ' id="' . e(wiki_anchor($m[2])) . '">' . $inner . '</h' . $level . '>';
$i++;
continue;
}
if (preg_match('/^(-{3,}|\*{3,})$/', $trim)) {
$out[] = '<hr>';
$i++;
continue;
}
// Video-Link allein in einer Zeile
$video = wiki_video_embed($trim);
if ($video !== null) {
$out[] = $video;
$i++;
continue;
}
// Tabelle: aufeinanderfolgende Zeilen, die mit | beginnen
if ($trim[0] === '|') {
$rows = [];
while ($i < $n && ($t = trim($lines[$i])) !== '' && $t[0] === '|') {
$rows[] = $t;
$i++;
}
$head = null;
if (count($rows) > 1 && preg_match('/^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?$/', $rows[1])) {
$head = array_shift($rows);
array_shift($rows);
}
$html = '<div class="wiki-table-wrap"><table class="wiki-table">';
if ($head !== null) {
$html .= '<thead><tr>';
foreach (wiki_table_cells($head) as $cell) {
$html .= '<th>' . wiki_inline(e($cell)) . '</th>';
}
$html .= '</tr></thead>';
}
$html .= '<tbody>';
foreach ($rows as $row) {
$html .= '<tr>';
foreach (wiki_table_cells($row) as $cell) {
$html .= '<td>' . wiki_inline(e($cell)) . '</td>';
}
$html .= '</tr>';
}
$out[] = $html . '</tbody></table></div>';
continue;
}
// Hinweis-Kasten
if ($trim[0] === '>') {
$quote = [];
while ($i < $n && ($t = trim($lines[$i])) !== '' && $t[0] === '>') {
$quote[] = wiki_inline(e(ltrim(substr($t, 1))));
$i++;
}
$out[] = '<blockquote class="wiki-note">' . implode('<br>', $quote) . '</blockquote>';
continue;
}
// Listen
if (preg_match('/^([-*]|\d+\.)\s+/', $trim, $m)) {
$ordered = $m[1] !== '-' && $m[1] !== '*';
$items = [];
while ($i < $n && preg_match($ordered ? '/^\d+\.\s+(.*)$/' : '/^[-*]\s+(.*)$/', trim($lines[$i]), $im)) {
$items[] = '<li>' . wiki_inline(e($im[1])) . '</li>';
$i++;
}
$out[] = ($ordered ? '<ol>' : '<ul>') . implode('', $items) . ($ordered ? '</ol>' : '</ul>');
continue;
}
// Absatz: bis zur naechsten Leerzeile oder einem anderen Block
$para = [];
while ($i < $n) {
$t = trim($lines[$i]);
if ($t === '' || $t[0] === '|' || $t[0] === '>' || preg_match('/^(#{1,4}\s|[-*]\s|\d+\.\s|-{3,}$)/', $t) || wiki_video_embed($t) !== null) {
break;
}
$para[] = wiki_inline(e($t));
$i++;
}
$out[] = '<p>' . implode('<br>', $para) . '</p>';
}
return implode("\n", $out);
}
/**
* Volltextsuche in Titeln und Inhalten.
*
* @return array<int, array{slug: string, title: string, snippet: string}>
*/
function wiki_search(string $query): array
{
$query = trim($query);
if (mb_strlen($query) < 2) {
return [];
}
$like = '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $query) . '%';
$stmt = db()->prepare(
'SELECT slug, title, content, title LIKE ? AS in_title FROM wiki_pages
WHERE title LIKE ? OR content LIKE ? ORDER BY in_title DESC, title LIMIT 30'
);
$stmt->execute([$like, $like, $like]);
$results = [];
foreach ($stmt->fetchAll() as $row) {
$plain = (string) preg_replace('/[#*_`>|\[\]()!~-]+/', ' ', $row['content']);
$plain = (string) preg_replace('/\s+/', ' ', $plain);
$pos = mb_stripos($plain, $query, 0, 'UTF-8');
$start = $pos === false ? 0 : max(0, $pos - 60);
$snippet = mb_substr($plain, $start, 180, 'UTF-8');
$results[] = [
'slug' => $row['slug'],
'title' => $row['title'],
'snippet' => ($start > 0 ? '… ' : '') . trim($snippet) . (mb_strlen($plain, 'UTF-8') > $start + 180 ? ' …' : ''),
];
}
return $results;
}