BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / Wiki.php

Wiki.php

fix: hide an empty wiki from readers
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 5 weeks ago
f4ebf519 History
Wiki.php 19.9 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 wikiHasPages(): bool {
112 return (int)query('SELECT COUNT(*) FROM wiki_pages')->fetchColumn() > 0;
113}
114
115function wikiVisible(bool $admin): bool {
116 return $admin || wikiHasPages();
117}
118
119function listWikiCategories(): array {
120 $rows = query('SELECT * FROM wiki_categories ORDER BY position, title, slug')->fetchAll();
121 return ['categories' => array_map('wikiCategoryPayload', $rows)];
122}
123
124function loadWikiCategory(string $slug): array {
125 return wikiCategoryPayload(wikiCategoryRow($slug));
126}
127
128function createWikiCategory(array $input): array {
129 $title = cleanText($input['title'] ?? null, 80, 'De categorietitel');
130 $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedCategorySlugs());
131 $position = wikiOptionalPosition($input);
132 transaction(function () use ($title, $slug, $position): void {
133 if (query('SELECT 1 FROM wiki_categories WHERE slug=?', [$slug])->fetchColumn()) {
134 throw new AppException('Die slug is al in gebruik.', 409);
135 }
136 $now = time();
137 query('INSERT INTO wiki_categories (slug, title, position, created, updated) VALUES (?,?,?,?,?)', [
138 $slug, $title, $position ?? wikiNextCategoryPosition(), $now, $now,
139 ]);
140 });
141 return loadWikiCategory($slug);
142}
143
144function updateWikiCategory(string $slug, array $input): array {
145 foreach (['title', 'slug', 'position'] as $key) {
146 if (array_key_exists($key, $input)) {
147 $present = true;
148 break;
149 }
150 }
151 if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
152 $stored = $slug;
153 transaction(function () use ($slug, $input, &$stored): void {
154 $row = wikiCategoryRow($slug);
155 $title = array_key_exists('title', $input) ? cleanText($input['title'], 80, 'De categorietitel') : $row['title'];
156 $newSlug = array_key_exists('slug', $input)
157 ? wikiChooseSlug($input['slug'], $title, wikiReservedCategorySlugs())
158 : $row['slug'];
159 $position = array_key_exists('position', $input) ? wikiOptionalPosition($input) : (int)$row['position'];
160 if ($position === null) $position = (int)$row['position'];
161 $clash = query('SELECT 1 FROM wiki_categories WHERE slug=? AND id<>?', [$newSlug, $row['id']])->fetchColumn();
162 if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
163 query('UPDATE wiki_categories SET slug=?, title=?, position=?, updated=? WHERE id=?', [
164 $newSlug, $title, $position, time(), $row['id'],
165 ]);
166 $stored = $newSlug;
167 });
168 return loadWikiCategory($stored);
169}
170
171function deleteWikiCategory(string $slug): string {
172 transaction(function () use ($slug): void {
173 $row = wikiCategoryRow($slug);
174 $count = (int)query('SELECT COUNT(*) FROM wiki_pages WHERE category_id=?', [$row['id']])->fetchColumn();
175 if ($count > 0) throw new AppException('Deze categorie heeft nog pagina\'s. Verplaats of verwijder die eerst.', 409);
176 query('DELETE FROM wiki_categories WHERE id=?', [$row['id']]);
177 });
178 return $slug;
179}
180
181function wikiPageSummary(array $row): array {
182 return [
183 'slug' => $row['slug'],
184 'title' => $row['title'],
185 'position' => (int)$row['position'],
186 'updated' => (int)$row['updated'],
187 'category' => ['slug' => $row['category_slug'], 'title' => $row['category_title']],
188 ];
189}
190
191function listWikiPages(?string $categorySlug, ?string $query): array {
192 if ($categorySlug !== null && $categorySlug !== '') {
193 if (!wikiSlugOk($categorySlug)) throw new AppException('De categorie moet een slug zijn.');
194 $category = wikiCategoryRow($categorySlug);
195 $rows = query(
196 'SELECT p.*, c.slug AS category_slug, c.title AS category_title
197 FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
198 WHERE p.category_id=? ORDER BY p.position, p.title, p.slug',
199 [$category['id']]
200 )->fetchAll();
201 } else {
202 $rows = query(
203 'SELECT p.*, c.slug AS category_slug, c.title AS category_title
204 FROM wiki_pages p JOIN wiki_categories c ON c.id = p.category_id
205 ORDER BY c.position, p.position, p.title, p.slug'
206 )->fetchAll();
207 }
208 $needle = $query === null ? '' : trim($query);
209 if ($needle !== '') {
210 if (mb_strlen($needle) > 200) throw new AppException('De zoekterm is te lang (maximaal 200 tekens).');
211 $folded = mb_strtolower($needle, 'UTF-8');
212 $rows = array_values(array_filter($rows, function (array $row) use ($folded): bool {
213 return str_contains(mb_strtolower($row['title'], 'UTF-8'), $folded)
214 || str_contains(mb_strtolower($row['content'], 'UTF-8'), $folded);
215 }));
216 }
217 return array_map('wikiPageSummary', $rows);
218}
219
220/**
221 * @return list<array{anchor:string,title:?string,blocks:list<array{inlines:list<array<string,mixed>>}>}>
222 */
223function parseWikiChapters(string $content): array {
224 $content = str_replace(["\r\n", "\r"], "\n", $content);
225 $lines = $content === '' ? [] : explode("\n", $content);
226 $sections = [];
227 $title = null;
228 $buffer = [];
229 $open = false;
230 foreach ($lines as $line) {
231 if (preg_match('/^##[ \t]*$/u', $line)) throw new AppException('Een hoofdstuk heeft een titel nodig.');
232 if (preg_match('/^##[ \t]+(.*)$/u', $line, $match)) {
233 $heading = trim($match[1]);
234 if ($heading === '') throw new AppException('Een hoofdstuk heeft een titel nodig.');
235 if (mb_strlen($heading) > 200) throw new AppException('Een hoofdstuktitel is te lang (maximaal 200 tekens).');
236 if ($open || trim(implode("\n", $buffer)) !== '') {
237 $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
238 }
239 $buffer = [];
240 $open = true;
241 $title = $heading;
242 continue;
243 }
244 $buffer[] = $line;
245 }
246 if ($open || trim(implode("\n", $buffer)) !== '') {
247 $sections[] = ['title' => $open ? $title : null, 'body' => implode("\n", $buffer)];
248 }
249 return wikiAssignAnchors($sections);
250}
251
252/** @param list<array{title:?string,body:string}> $sections */
253function wikiAssignAnchors(array $sections): array {
254 $used = [];
255 $chapters = [];
256 foreach ($sections as $section) {
257 if ($section['title'] === null) {
258 $base = 'inleiding';
259 } else {
260 $base = wikiSlugify($section['title']);
261 if ($base === '') $base = 'hoofdstuk';
262 }
263 $anchor = $base;
264 $n = 2;
265 while (isset($used[$anchor])) {
266 $anchor = $base.'-'.$n;
267 $n++;
268 }
269 $used[$anchor] = true;
270 $chapters[] = [
271 'anchor' => $anchor,
272 'title' => $section['title'],
273 'blocks' => wikiParagraphs($section['body']),
274 ];
275 }
276 return $chapters;
277}
278
279/** @return list<array{inlines:list<array<string,mixed>>}> */
280function wikiParagraphs(string $body): array {
281 $parts = preg_split("/\n[ \t]*\n/u", $body) ?: [];
282 $blocks = [];
283 foreach ($parts as $part) {
284 $lines = array_values(array_filter(array_map('trim', explode("\n", $part)), fn(string $line): bool => $line !== ''));
285 if (!$lines) continue;
286 $inlines = wikiParseInlines(implode(' ', $lines));
287 if ($inlines) $blocks[] = ['inlines' => $inlines];
288 }
289 return $blocks;
290}
291
292/** @return list<array<string,mixed>> */
293function wikiParseInlines(string $text): array {
294 $inlines = [];
295 $offset = 0;
296 if (preg_match_all('/\[\[([^\[\]\n]+)\]\]/u', $text, $matches, PREG_OFFSET_CAPTURE)) {
297 foreach ($matches[0] as $index => $full) {
298 $start = $full[1];
299 if ($start > $offset) {
300 $inlines[] = ['type' => 'text', 'text' => substr($text, $offset, $start - $offset)];
301 }
302 $inlines[] = wikiRawLink($matches[1][$index][0]);
303 $offset = $start + strlen($full[0]);
304 }
305 }
306 if ($offset < strlen($text)) $inlines[] = ['type' => 'text', 'text' => substr($text, $offset)];
307 return $inlines;
308}
309
310/** @return array<string,mixed> */
311function wikiRawLink(string $inner): array {
312 $label = null;
313 $target = $inner;
314 $bar = strpos($inner, '|');
315 if ($bar !== false) {
316 $target = substr($inner, 0, $bar);
317 $label = trim(substr($inner, $bar + 1));
318 if ($label === '') $label = null;
319 }
320 $target = trim($target);
321 $page = null;
322 $anchor = null;
323 if (str_starts_with($target, '#')) {
324 $anchor = substr($target, 1);
325 } elseif (str_contains($target, '#')) {
326 [$page, $anchor] = explode('#', $target, 2);
327 if ($page === '') $page = null;
328 } else {
329 $page = $target;
330 }
331 $pageOk = $page === null || wikiSlugOk($page);
332 $anchorOk = $anchor === null || ($anchor !== '' && wikiSlugOk($anchor));
333 $valid = $pageOk && $anchorOk && ($page !== null || ($anchor !== null && $anchor !== ''));
334 return [
335 'type' => 'link',
336 'page' => $page,
337 'anchor' => $anchor === '' ? null : $anchor,
338 'label' => $label,
339 'raw' => trim($inner),
340 'valid' => $valid,
341 ];
342}
343
344/** @return array<string,array{title:string,anchors:array<string,string>,chapters:list<array<string,mixed>>}> */
345function wikiCatalog(): array {
346 $rows = query('SELECT slug, title, content FROM wiki_pages')->fetchAll();
347 $catalog = [];
348 foreach ($rows as $row) {
349 $chapters = parseWikiChapters($row['content']);
350 $anchors = [];
351 foreach ($chapters as $chapter) $anchors[$chapter['anchor']] = $chapter['title'] ?? 'Inleiding';
352 $catalog[$row['slug']] = [
353 'title' => $row['title'],
354 'anchors' => $anchors,
355 'chapters' => $chapters,
356 ];
357 }
358 return $catalog;
359}
360
361/** @param array<string,mixed> $link */
362function wikiResolveLink(array $link, string $pageSlug, array $catalog): array {
363 $targetPage = $link['page'] ?? $pageSlug;
364 $anchor = $link['anchor'];
365 $known = ($link['valid'] && is_string($targetPage) && isset($catalog[$targetPage])) ? $catalog[$targetPage] : null;
366 $broken = $known === null;
367 $chapterTitle = null;
368 if (!$broken && $anchor !== null) {
369 if (!isset($known['anchors'][$anchor])) $broken = true;
370 else $chapterTitle = $known['anchors'][$anchor];
371 }
372 $text = $link['label'];
373 if ($text === null || $text === '') {
374 if ($broken) $text = $link['raw'];
375 elseif ($anchor !== null) $text = $chapterTitle ?? $anchor;
376 else $text = $known['title'];
377 }
378 return [
379 'type' => 'link',
380 'page' => $broken ? null : $targetPage,
381 'anchor' => $broken ? null : $anchor,
382 'text' => $text,
383 'broken' => $broken,
384 ];
385}
386
387/** @param list<array<string,mixed>> $chapters */
388function wikiResolveChapters(array $chapters, string $pageSlug, array $catalog): array {
389 $resolved = [];
390 foreach ($chapters as $chapter) {
391 $blocks = [];
392 foreach ($chapter['blocks'] as $block) {
393 $inlines = [];
394 foreach ($block['inlines'] as $inline) {
395 if (($inline['type'] ?? '') === 'text') {
396 if (($inline['text'] ?? '') !== '') $inlines[] = ['type' => 'text', 'text' => $inline['text']];
397 continue;
398 }
399 $inlines[] = wikiResolveLink($inline, $pageSlug, $catalog);
400 }
401 if ($inlines) $blocks[] = ['inlines' => $inlines];
402 }
403 $resolved[] = [
404 'anchor' => $chapter['anchor'],
405 'title' => $chapter['title'],
406 'blocks' => $blocks,
407 ];
408 }
409 return $resolved;
410}
411
412function loadWikiPage(string $slug): array {
413 $page = wikiPageRow($slug);
414 $category = query('SELECT slug, title FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
415 if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
416 $catalog = wikiCatalog();
417 $chapters = wikiResolveChapters($catalog[$page['slug']]['chapters'], $page['slug'], $catalog);
418 return [
419 'slug' => $page['slug'],
420 'title' => $page['title'],
421 'position' => (int)$page['position'],
422 'category' => ['slug' => $category['slug'], 'title' => $category['title']],
423 'content' => $page['content'],
424 'created' => (int)$page['created'],
425 'updated' => (int)$page['updated'],
426 'chapters' => $chapters,
427 ];
428}
429
430function createWikiPage(array $input): array {
431 $title = cleanText($input['title'] ?? null, 200, 'De paginatitel');
432 if (!is_string($input['category'] ?? null) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
433 $content = wikiNormalizeContent($input['content'] ?? '');
434 parseWikiChapters($content);
435 $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedPageSlugs());
436 $position = wikiOptionalPosition($input);
437 transaction(function () use ($title, $input, $content, $slug, $position): void {
438 $category = wikiCategoryRow($input['category']);
439 if (query('SELECT 1 FROM wiki_pages WHERE slug=?', [$slug])->fetchColumn()) {
440 throw new AppException('Die slug is al in gebruik.', 409);
441 }
442 $now = time();
443 query('INSERT INTO wiki_pages (category_id, slug, title, content, position, created, updated) VALUES (?,?,?,?,?,?,?)', [
444 $category['id'], $slug, $title, $content, $position ?? wikiNextPagePosition((int)$category['id']), $now, $now,
445 ]);
446 });
447 return loadWikiPage($slug);
448}
449
450function updateWikiPage(string $slug, array $input): array {
451 foreach (['title', 'slug', 'position', 'content', 'category'] as $key) {
452 if (array_key_exists($key, $input)) {
453 $present = true;
454 break;
455 }
456 }
457 if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
458 $stored = $slug;
459 transaction(function () use ($slug, $input, &$stored): void {
460 $page = wikiPageRow($slug);
461 $title = array_key_exists('title', $input) ? cleanText($input['title'], 200, 'De paginatitel') : $page['title'];
462 $newSlug = array_key_exists('slug', $input)
463 ? wikiChooseSlug($input['slug'], $title, wikiReservedPageSlugs())
464 : $page['slug'];
465 $content = array_key_exists('content', $input) ? wikiNormalizeContent($input['content']) : $page['content'];
466 parseWikiChapters($content);
467 if (array_key_exists('category', $input)) {
468 if (!is_string($input['category']) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
469 $category = wikiCategoryRow($input['category']);
470 } else {
471 $category = query('SELECT * FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
472 if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
473 }
474 $moved = (int)$category['id'] !== (int)$page['category_id'];
475 if (array_key_exists('position', $input)) $position = wikiOptionalPosition($input);
476 else $position = $moved ? null : (int)$page['position'];
477 if ($position === null) $position = wikiNextPagePosition((int)$category['id']);
478 $clash = query('SELECT 1 FROM wiki_pages WHERE slug=? AND id<>?', [$newSlug, $page['id']])->fetchColumn();
479 if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
480 query('UPDATE wiki_pages SET category_id=?, slug=?, title=?, content=?, position=?, updated=? WHERE id=?', [
481 $category['id'], $newSlug, $title, $content, $position, time(), $page['id'],
482 ]);
483 $stored = $newSlug;
484 });
485 return loadWikiPage($stored);
486}
487
488function deleteWikiPage(string $slug): string {
489 transaction(function () use ($slug): void {
490 $page = wikiPageRow($slug);
491 query('DELETE FROM wiki_pages WHERE id=?', [$page['id']]);
492 });
493 return $slug;
494}