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> 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. * * Videos fremder Anbieter erscheinen zuerst als Platzhalter und laden erst nach einem Klick * (embed_consent_html() in includes/legal.php) - vorher erfaehrt der Anbieter nichts vom Besuch. */ 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'; // Nach dem Klick auf "Video laden" startet der Player gleich (autoplay_src), bei "immer direkt laden" nicht $embed = static fn (string $provider, string $src, string $autoplaySrc, string $class = '') => embed_consent_html( 'video', $provider, $src, ['class' => 'wiki-video' . $class, 'title' => $title, 'autoplay_src' => $autoplaySrc] ); // 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); } $src = 'https://www.youtube-nocookie.com/embed/' . $youtubeId . '?rel=0' . ($start > 0 ? '&start=' . $start : ''); return $embed('youtube', $src, $src . '&autoplay=1', $isShort ? ' wiki-video-portrait' : ''); } // Twitch braucht die eigene Domain als "parent" $parent = preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? 'lumina-ascendes.de')); $twitch = static fn (string $src) => $embed('twitch', $src . '&autoplay=false', $src . '&autoplay=true'); if ($host === 'clips.twitch.tv' && preg_match('#^/([\w-]+)$#', $path, $m)) { return $twitch('https://clips.twitch.tv/embed?clip=' . $m[1] . '&parent=' . $parent); } if ($host === 'twitch.tv') { if (preg_match('#^/[\w]+/clip/([\w-]+)$#', $path, $m)) { return $twitch('https://clips.twitch.tv/embed?clip=' . $m[1] . '&parent=' . $parent); } if (preg_match('#^/videos/(\d+)$#', $path, $m)) { return $twitch('https://player.twitch.tv/?video=v' . $m[1] . '&parent=' . $parent); } } // Vimeo: vimeo.com/123456789 if ($host === 'vimeo.com' && preg_match('#^/(\d+)$#', $path, $m)) { $src = 'https://player.vimeo.com/video/' . $m[1]; return $embed('vimeo', $src, $src . '?autoplay=1'); } // Videodatei (z.B. auf Discord oder einem eigenen Server) - von fremden Servern erst nach Klick if (preg_match('#\.(mp4|webm|mov)$#i', $path)) { if (!legal_is_own_url($url)) { return embed_consent_html('videofile', embed_host_provider($url), $url, ['class' => 'wiki-video wiki-video-file']); } return '
'; } 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[] = '' . $m[1] . ''; return "\x01" . (count($codes) - 1) . "\x01"; }, $html); // Bilder: ![Beschreibung](Adresse) - wie Code herausgenommen, damit die Formatierung unten // (z.B. _kursiv_) nichts in der Adresse veraendert. Bilder fremder Server laden erst nach Klick. $html = (string) preg_replace_callback('/!\[([^\]]*)\]\(([^)\s]+)\)/', static function (array $m) use (&$codes): string { $url = wiki_safe_url($m[2], true); if ($url === null) { return $m[0]; } $rawUrl = html_entity_decode($url, ENT_QUOTES, 'UTF-8'); $codes[] = legal_is_own_url($rawUrl) ? '' . $m[1] . '' : embed_consent_html('image', embed_host_provider($rawUrl), $rawUrl, ['alt' => html_entity_decode($m[1], ENT_QUOTES, 'UTF-8')]); return "\x01" . (count($codes) - 1) . "\x01"; }, $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 '' . $label . ''; } return '' . $label . ''; }, $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 '' . $m[1] . ''; }, $html); $html = (string) preg_replace('/\*\*(.+?)\*\*/s', '$1', $html); $html = (string) preg_replace('/(?$1', $html); $html = (string) preg_replace('/(?$1', $html); $html = (string) preg_replace('/~~(.+?)~~/s', '$1', $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('/(? 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[] = '' . $inner . ''; $i++; continue; } if (preg_match('/^(-{3,}|\*{3,})$/', $trim)) { $out[] = '
'; $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 = '
'; if ($head !== null) { $html .= ''; foreach (wiki_table_cells($head) as $cell) { $html .= ''; } $html .= ''; } $html .= ''; foreach ($rows as $row) { $html .= ''; foreach (wiki_table_cells($row) as $cell) { $html .= ''; } $html .= ''; } $out[] = $html . '
' . wiki_inline(e($cell)) . '
' . wiki_inline(e($cell)) . '
'; 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[] = '
' . implode('
', $quote) . '
'; 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[] = '
  • ' . wiki_inline(e($im[1])) . '
  • '; $i++; } $out[] = ($ordered ? '
      ' : '
    ' : ''); 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[] = '

    ' . implode('
    ', $para) . '

    '; } return implode("\n", $out); } /** * Volltextsuche in Titeln und Inhalten. * * @return array */ 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; }