BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / Wiki.php

Wiki.php

feat: add a wiki with categories, chapters and internal links
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 5 weeks ago
2556ae87 History
Wiki.php 19.7 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4function wikiSlugOk(string $slug): bool {
5 return strlen($slug) <= 80 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) === 1;
6}
7
8/** @return list<string> */
9function wikiReservedPageSlugs(): array {
10 return ['nieuw', 'bewerken', 'categorie'];
11}
12
13/** @return list<string> */
14function wikiReservedCategorySlugs(): array {
15 return ['nieuw'];
16}
17
18function wikiSlugify(string $text): string {
19 $text = mb_strtolower(trim($text), 'UTF-8');
20 $text = strtr($text, [
21 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae',
22 'ç' => 'c',
23 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
24 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
25 'ñ' => 'n',
26 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'ö' => 'o', 'ø' => 'o', 'œ' => 'oe',
27 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u',
28 'ý' => 'y', 'ÿ' => 'y', 'ß' => 'ss',
29 'ij' => 'ij',
30 ]);
31 $text = preg_replace('/[^a-z0-9]+/', '-', $text) ?? '';
32 $text = trim($text, '-');
33 if (strlen($text) > 80) $text = rtrim(substr($text, 0, 80), '-');
34 return $text;
35}
36
37function wikiChooseSlug(mixed $given, string $title, array $reserved): string {
38 if ($given === null || $given === '') {
39 $slug = wikiSlugify($title);
40 if ($slug === '' || in_array($slug, $reserved, true)) {
41 throw new AppException('Kies een slug: de titel levert geen bruikbare slug op.');
42 }
43 return $slug;
44 }
45 if (!is_string($given) || !wikiSlugOk($given)) {
46 throw new AppException('De slug mag alleen kleine letters, cijfers en streepjes bevatten.');
47 }
48 if (in_array($given, $reserved, true)) throw new AppException('Die slug is gereserveerd.');
49 return $given;
50}
51
52function wikiOptionalPosition(array $input): ?int {
53 if (!array_key_exists('position', $input) || $input['position'] === null) return null;
54 $value = $input['position'];
55 if (is_string($value) && preg_match('/^[1-9][0-9]{0,4}$/', $value)) $value = (int)$value;
56 if (!is_int($value) || $value < 1 || $value > 10000) {
57 throw new AppException('De positie moet een geheel getal vanaf 1 zijn.');
58 }
59 return $value;
60}
61
62function wikiNormalizeContent(mixed $value): string {
63 if (!is_string($value)) throw new AppException('De tekst moet tekst zijn.');
64 $value = str_replace(["\r\n", "\r"], "\n", $value);
65 if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value)) throw new AppException('De tekst bevat ongeldige tekens.');
66 if (mb_strlen($value) > 100000) throw new AppException('De tekst is te lang (maximaal 100000 tekens).');
67 return $value;
68}
69
70function wikiCategoryRow(string $slug): array {
71 if (!wikiSlugOk($slug)) throw new AppException('Deze categorie bestaat niet.', 404);
72 $row = query('SELECT * FROM wiki_categories WHERE slug=?', [$slug])->fetch();
73 if (!$row) throw new AppException('Deze categorie bestaat niet.', 404);
74 return $row;
75}
76
77function wikiPageRow(string $slug): array {
78 if (!wikiSlugOk($slug)) throw new AppException('Deze pagina bestaat niet.', 404);
79 $row = query('SELECT * FROM wiki_pages WHERE slug=?', [$slug])->fetch();
80 if (!$row) throw new AppException('Deze pagina bestaat niet.', 404);
81 return $row;
82}
83
84function wikiNextCategoryPosition(): int {
85 return (int)query('SELECT COALESCE(MAX(position), 0) FROM wiki_categories')->fetchColumn() + 1;
86}
87
88function wikiNextPagePosition(int $categoryId): int {
89 return (int)query('SELECT COALESCE(MAX(position), 0) FROM wiki_pages WHERE category_id=?', [$categoryId])->fetchColumn() + 1;
90}
91
92/** @return list<array{slug:string,title:string,position:int}> */
93function wikiPagesInCategory(int $categoryId): array {
94 $rows = query('SELECT slug, title, position FROM wiki_pages WHERE category_id=? ORDER BY position, title, slug', [$categoryId])->fetchAll();
95 return array_map(fn(array $row): array => [
96 'slug' => $row['slug'],
97 'title' => $row['title'],
98 'position' => (int)$row['position'],
99 ], $rows);
100}
101
102function wikiCategoryPayload(array $row): array {
103 return [
104 'slug' => $row['slug'],
105 'title' => $row['title'],
106 'position' => (int)$row['position'],
107 'pages' => wikiPagesInCategory((int)$row['id']),
108 ];
109}
110
111function listWikiCategories(): array {
112 $rows = query('SELECT * FROM wiki_categories ORDER BY position, title, slug')->fetchAll();
113 return ['categories' => array_map('wikiCategoryPayload', $rows)];
114}
115
116function loadWikiCategory(string $slug): array {
117 return wikiCategoryPayload(wikiCategoryRow($slug));
118}
119
120function createWikiCategory(array $input): array {
121 $title = cleanText($input['title'] ?? null, 80, 'De categorietitel');
122 $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedCategorySlugs());
123 $position = wikiOptionalPosition($input);
124 transaction(function () use ($title, $slug, $position): void {
125 if (query('SELECT 1 FROM wiki_categories WHERE slug=?', [$slug])->fetchColumn()) {
126 throw new AppException('Die slug is al in gebruik.', 409);
127 }
128 $now = time();
129 query('INSERT INTO wiki_categories (slug, title, position, created, updated) VALUES (?,?,?,?,?)', [
130 $slug, $title, $position ?? wikiNextCategoryPosition(), $now, $now,
131 ]);
132 });
133 return loadWikiCategory($slug);
134}
135
136function updateWikiCategory(string $slug, array $input): array {
137 foreach (['title', 'slug', 'position'] as $key) {
138 if (array_key_exists($key, $input)) {
139 $present = true;
140 break;
141 }
142 }
143 if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
144 $stored = $slug;
145 transaction(function () use ($slug, $input, &$stored): void {
146 $row = wikiCategoryRow($slug);
147 $title = array_key_exists('title', $input) ? cleanText($input['title'], 80, 'De categorietitel') : $row['title'];
148 $newSlug = array_key_exists('slug', $input)
149 ? wikiChooseSlug($input['slug'], $title, wikiReservedCategorySlugs())
150 : $row['slug'];
151 $position = array_key_exists('position', $input) ? wikiOptionalPosition($input) : (int)$row['position'];
152 if ($position === null) $position = (int)$row['position'];
153 $clash = query('SELECT 1 FROM wiki_categories WHERE slug=? AND id<>?', [$newSlug, $row['id']])->fetchColumn();
154 if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
155 query('UPDATE wiki_categories SET slug=?, title=?, position=?, updated=? WHERE id=?', [
156 $newSlug, $title, $position, time(), $row['id'],
157 ]);
158 $stored = $newSlug;
159 });
160 return loadWikiCategory($stored);
161}
162
163function deleteWikiCategory(string $slug): string {
164 transaction(function () use ($slug): void {
165 $row = wikiCategoryRow($slug);
166 $count = (int)query('SELECT COUNT(*) FROM wiki_pages WHERE category_id=?', [$row['id']])->fetchColumn();
167 if ($count > 0) throw new AppException('Deze categorie heeft nog pagina\'s. Verplaats of verwijder die eerst.', 409);
168 query('DELETE FROM wiki_categories WHERE id=?', [$row['id']]);
169 });
170 return $slug;
171}
172
173function wikiPageSummary(array $row): array {
174 return [
175 'slug' => $row['slug'],
176 'title' => $row['title'],
177 'position' => (int)$row['position'],
178 'updated' => (int)$row['updated'],
179 'category' => ['slug' => $row['category_slug'], 'title' => $row['category_title']],
180 ];
181}
182
183function listWikiPages(?string $categorySlug, ?string $query): array {
184 if ($categorySlug !== null && $categorySlug !== '') {
185 if (!wikiSlugOk($categorySlug)) throw new AppException('De categorie moet een slug zijn.');
186 $category = wikiCategoryRow($categorySlug);
187 $rows = query(
188 'SELECT p.*, c.slug AS category_slug, c.title AS category_title
189 FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
190 WHERE p.category_id=? ORDER BY p.position, p.title, p.slug',
191 [$category['id']]
192 )->fetchAll();
193 } else {
194 $rows = query(
195 'SELECT p.*, c.slug AS category_slug, c.title AS category_title
196 FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
197 ORDER BY c.position, p.position, p.title, p.slug'
198 )->fetchAll();
199 }
200 $needle = $query === null ? '' : trim($query);
201 if ($needle !== '') {
202 if (mb_strlen($needle) > 200) throw new AppException('De zoekterm is te lang (maximaal 200 tekens).');
203 $folded = mb_strtolower($needle, 'UTF-8');
204 $rows = array_values(array_filter($rows, function (array $row) use ($folded): bool {
205 return str_contains(mb_strtolower($row['title'], 'UTF-8'), $folded)
206 || str_contains(mb_strtolower($row['content'], 'UTF-8'), $folded);
207 }));
208 }
209 return array_map('wikiPageSummary', $rows);
210}
211
212/**
213 * @return list<array{anchor:string,title:?string,blocks:list<array{inlines:list<array<string,mixed>>}>}>
214 */
215function parseWikiChapters(string $content): array {
216 $content = str_replace(["\r\n", "\r"], "\n", $content);
217 $lines = $content === '' ? [] : explode("\n", $content);
218 $sections = [];
219 $title = null;
220 $buffer = [];
221 $open = false;
222 foreach ($lines as $line) {
223 if (preg_match('/^##[ \t]*$/u', $line)) throw new AppException('Een hoofdstuk heeft een titel nodig.');
224 if (preg_match('/^##[ \t]+(.*)$/u', $line, $match)) {
225 $heading = trim($match[1]);
226 if ($heading === '') throw new AppException('Een hoofdstuk heeft een titel nodig.');
227 if (mb_strlen($heading) > 200) throw new AppException('Een hoofdstuktitel is te lang (maximaal 200 tekens).');
228 if ($open || trim(implode("\n", $buffer)) !== '') {
229 $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
230 }
231 $buffer = [];
232 $open = true;
233 $title = $heading;
234 continue;
235 }
236 $buffer[] = $line;
237 }
238 if ($open || trim(implode("\n", $buffer)) !== '') {
239 $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
240 }
241 return wikiAssignAnchors($sections);
242}
243
244/** @param list<array{title:?string,body:string}> $sections */
245function wikiAssignAnchors(array $sections): array {
246 $used = [];
247 $chapters = [];
248 foreach ($sections as $section) {
249 if ($section['title'] === null) {
250 $base = 'inleiding';
251 } else {
252 $base = wikiSlugify($section['title']);
253 if ($base === '') $base = 'hoofdstuk';
254 }
255 $anchor = $base;
256 $n = 2;
257 while (isset($used[$anchor])) {
258 $anchor = $base.'-'.$n;
259 $n++;
260 }
261 $used[$anchor] = true;
262 $chapters[] = [
263 'anchor' => $anchor,
264 'title' => $section['title'],
265 'blocks' => wikiParagraphs($section['body']),
266 ];
267 }
268 return $chapters;
269}
270
271/** @return list<array{inlines:list<array<string,mixed>>}> */
272function wikiParagraphs(string $body): array {
273 $parts = preg_split("/\n[ \t]*\n/u", $body) ?: [];
274 $blocks = [];
275 foreach ($parts as $part) {
276 $lines = array_values(array_filter(array_map('trim', explode("\n", $part)), fn(string $line): bool => $line !== ''));
277 if (!$lines) continue;
278 $inlines = wikiParseInlines(implode(' ', $lines));
279 if ($inlines) $blocks[] = ['inlines' => $inlines];
280 }
281 return $blocks;
282}
283
284/** @return list<array<string,mixed>> */
285function wikiParseInlines(string $text): array {
286 $inlines = [];
287 $offset = 0;
288 if (preg_match_all('/\[\[([^\[\]\n]+)\]\]/u', $text, $matches, PREG_OFFSET_CAPTURE)) {
289 foreach ($matches[0] as $index => $full) {
290 $start = $full[1];
291 if ($start > $offset) {
292 $inlines[] = ['type' => 'text', 'text' => substr($text, $offset, $start - $offset)];
293 }
294 $inlines[] = wikiRawLink($matches[1][$index][0]);
295 $offset = $start + strlen($full[0]);
296 }
297 }
298 if ($offset < strlen($text)) $inlines[] = ['type' => 'text', 'text' => substr($text, $offset)];
299 return $inlines;
300}
301
302/** @return array<string,mixed> */
303function wikiRawLink(string $inner): array {
304 $label = null;
305 $target = $inner;
306 $bar = strpos($inner, '|');
307 if ($bar !== false) {
308 $target = substr($inner, 0, $bar);
309 $label = trim(substr($inner, $bar + 1));
310 if ($label === '') $label = null;
311 }
312 $target = trim($target);
313 $page = null;
314 $anchor = null;
315 if (str_starts_with($target, '#')) {
316 $anchor = substr($target, 1);
317 } elseif (str_contains($target, '#')) {
318 [$page, $anchor] = explode('#', $target, 2);
319 if ($page === '') $page = null;
320 } else {
321 $page = $target;
322 }
323 $pageOk = $page === null || wikiSlugOk($page);
324 $anchorOk = $anchor === null || ($anchor !== '' && wikiSlugOk($anchor));
325 $valid = $pageOk && $anchorOk && ($page !== null || ($anchor !== null && $anchor !== ''));
326 return [
327 'type' => 'link',
328 'page' => $page,
329 'anchor' => $anchor === '' ? null : $anchor,
330 'label' => $label,
331 'raw' => trim($inner),
332 'valid' => $valid,
333 ];
334}
335
336/** @return array<string,array{title:string,anchors:array<string,string>,chapters:list<array<string,mixed>>}> */
337function wikiCatalog(): array {
338 $rows = query('SELECT slug, title, content FROM wiki_pages')->fetchAll();
339 $catalog = [];
340 foreach ($rows as $row) {
341 $chapters = parseWikiChapters($row['content']);
342 $anchors = [];
343 foreach ($chapters as $chapter) $anchors[$chapter['anchor']] = $chapter['title'] ?? 'Inleiding';
344 $catalog[$row['slug']] = [
345 'title' => $row['title'],
346 'anchors' => $anchors,
347 'chapters' => $chapters,
348 ];
349 }
350 return $catalog;
351}
352
353/** @param array<string,mixed> $link */
354function wikiResolveLink(array $link, string $pageSlug, array $catalog): array {
355 $targetPage = $link['page'] ?? $pageSlug;
356 $anchor = $link['anchor'];
357 $known = ($link['valid'] && is_string($targetPage) && isset($catalog[$targetPage])) ? $catalog[$targetPage] : null;
358 $broken = $known === null;
359 $chapterTitle = null;
360 if (!$broken && $anchor !== null) {
361 if (!isset($known['anchors'][$anchor])) $broken = true;
362 else $chapterTitle = $known['anchors'][$anchor];
363 }
364 $text = $link['label'];
365 if ($text === null || $text === '') {
366 if ($broken) $text = $link['raw'];
367 elseif ($anchor !== null) $text = $chapterTitle ?? $anchor;
368 else $text = $known['title'];
369 }
370 return [
371 'type' => 'link',
372 'page' => $broken ? null : $targetPage,
373 'anchor' => $broken ? null : $anchor,
374 'text' => $text,
375 'broken' => $broken,
376 ];
377}
378
379/** @param list<array<string,mixed>> $chapters */
380function wikiResolveChapters(array $chapters, string $pageSlug, array $catalog): array {
381 $resolved = [];
382 foreach ($chapters as $chapter) {
383 $blocks = [];
384 foreach ($chapter['blocks'] as $block) {
385 $inlines = [];
386 foreach ($block['inlines'] as $inline) {
387 if (($inline['type'] ?? '') === 'text') {
388 if (($inline['text'] ?? '') !== '') $inlines[] = ['type' => 'text', 'text' => $inline['text']];
389 continue;
390 }
391 $inlines[] = wikiResolveLink($inline, $pageSlug, $catalog);
392 }
393 if ($inlines) $blocks[] = ['inlines' => $inlines];
394 }
395 $resolved[] = [
396 'anchor' => $chapter['anchor'],
397 'title' => $chapter['title'],
398 'blocks' => $blocks,
399 ];
400 }
401 return $resolved;
402}
403
404function loadWikiPage(string $slug): array {
405 $page = wikiPageRow($slug);
406 $category = query('SELECT slug, title FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
407 if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
408 $catalog = wikiCatalog();
409 $chapters = wikiResolveChapters($catalog[$page['slug']]['chapters'], $page['slug'], $catalog);
410 return [
411 'slug' => $page['slug'],
412 'title' => $page['title'],
413 'position' => (int)$page['position'],
414 'category' => ['slug' => $category['slug'], 'title' => $category['title']],
415 'content' => $page['content'],
416 'created' => (int)$page['created'],
417 'updated' => (int)$page['updated'],
418 'chapters' => $chapters,
419 ];
420}
421
422function createWikiPage(array $input): array {
423 $title = cleanText($input['title'] ?? null, 200, 'De paginatitel');
424 if (!is_string($input['category'] ?? null) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
425 $content = wikiNormalizeContent($input['content'] ?? '');
426 parseWikiChapters($content);
427 $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedPageSlugs());
428 $position = wikiOptionalPosition($input);
429 transaction(function () use ($title, $input, $content, $slug, $position): void {
430 $category = wikiCategoryRow($input['category']);
431 if (query('SELECT 1 FROM wiki_pages WHERE slug=?', [$slug])->fetchColumn()) {
432 throw new AppException('Die slug is al in gebruik.', 409);
433 }
434 $now = time();
435 query('INSERT INTO wiki_pages (category_id, slug, title, content, position, created, updated) VALUES (?,?,?,?,?,?,?)', [
436 $category['id'], $slug, $title, $content, $position ?? wikiNextPagePosition((int)$category['id']), $now, $now,
437 ]);
438 });
439 return loadWikiPage($slug);
440}
441
442function updateWikiPage(string $slug, array $input): array {
443 foreach (['title', 'slug', 'position', 'content', 'category'] as $key) {
444 if (array_key_exists($key, $input)) {
445 $present = true;
446 break;
447 }
448 }
449 if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
450 $stored = $slug;
451 transaction(function () use ($slug, $input, &$stored): void {
452 $page = wikiPageRow($slug);
453 $title = array_key_exists('title', $input) ? cleanText($input['title'], 200, 'De paginatitel') : $page['title'];
454 $newSlug = array_key_exists('slug', $input)
455 ? wikiChooseSlug($input['slug'], $title, wikiReservedPageSlugs())
456 : $page['slug'];
457 $content = array_key_exists('content', $input) ? wikiNormalizeContent($input['content']) : $page['content'];
458 parseWikiChapters($content);
459 if (array_key_exists('category', $input)) {
460 if (!is_string($input['category']) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
461 $category = wikiCategoryRow($input['category']);
462 } else {
463 $category = query('SELECT * FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
464 if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
465 }
466 $moved = (int)$category['id'] !== (int)$page['category_id'];
467 if (array_key_exists('position', $input)) $position = wikiOptionalPosition($input);
468 else $position = $moved ? null : (int)$page['position'];
469 if ($position === null) $position = wikiNextPagePosition((int)$category['id']);
470 $clash = query('SELECT 1 FROM wiki_pages WHERE slug=? AND id<>?', [$newSlug, $page['id']])->fetchColumn();
471 if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
472 query('UPDATE wiki_pages SET category_id=?, slug=?, title=?, content=?, position=?, updated=? WHERE id=?', [
473 $category['id'], $newSlug, $title, $content, $position, time(), $page['id'],
474 ]);
475 $stored = $newSlug;
476 });
477 return loadWikiPage($stored);
478}
479
480function deleteWikiPage(string $slug): string {
481 transaction(function () use ($slug): void {
482 $page = wikiPageRow($slug);
483 query('DELETE FROM wiki_pages WHERE id=?', [$page['id']]);
484 });
485 return $slug;
486}