BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / Wiki.php

Wiki.php

feat: render wiki Markdown and move API keys onto Beheer
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 5 weeks ago
4388c66f History
Wiki.php 40.2 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/**
280 * Blokken binnen een hoofdstuk. Een lege regel scheidt alinea's. Een gewone
281 * regeleinde wordt een spatie, twee spaties of een backslash aan het regeleinde
282 * een zichtbare breuk. Lijsten, citaten, nadruk, code en externe links komen
283 * hierbij; ##-hoofdstukken zijn dan al apart gezet.
284 *
285 * @return list<array<string,mixed>>
286 */
287function wikiParagraphs(string $body): array {
288 $body = str_replace(["\r\n", "\r"], "\n", $body);
289 $lines = $body === '' ? [] : explode("\n", $body);
290 return wikiParseBlockLines($lines, 0, count($lines), 0)['blocks'];
291}
292
293/** @return array{blocks:list<array<string,mixed>>,next:int} */
294function wikiParseBlockLines(array $lines, int $i, int $n, int $depth): array {
295 if ($depth > 30) {
296 $text = trim(implode(' ', array_map(fn(string $line): string => trim($line), $lines)));
297 $inlines = $text === '' ? [] : wikiParseInlines($text);
298 return ['blocks' => $inlines ? [['type' => 'paragraph', 'inlines' => $inlines]] : [], 'next' => $n];
299 }
300 $blocks = [];
301 while ($i < $n) {
302 if (trim($lines[$i]) === '') { $i++; continue; }
303 $list = wikiMatchList($lines[$i]);
304 if ($list) {
305 $parsed = wikiParseList($lines, $i, $n, $list['indent'], $list['ordered'], $depth);
306 if ($parsed['block']) $blocks[] = $parsed['block'];
307 $i = $parsed['next'];
308 continue;
309 }
310 if (wikiIsQuoteLine($lines[$i])) {
311 $parsed = wikiParseQuote($lines, $i, $n, $depth);
312 if ($parsed['block']) $blocks[] = $parsed['block'];
313 $i = $parsed['next'];
314 continue;
315 }
316 $parsed = wikiParseParagraph($lines, $i, $n);
317 if ($parsed['block']) $blocks[] = $parsed['block'];
318 $i = $parsed['next'];
319 }
320 return ['blocks' => $blocks, 'next' => $i];
321}
322
323function wikiIsQuoteLine(string $line): bool {
324 return preg_match('/^[ \t]*>/u', $line) === 1;
325}
326
327/** @return array{block:?array<string,mixed>,next:int} */
328function wikiParseQuote(array $lines, int $i, int $n, int $depth): array {
329 $collected = [];
330 while ($i < $n && preg_match('/^[ \t]*> ?(.*)$/u', $lines[$i], $match)) {
331 $collected[] = $match[1];
332 $i++;
333 }
334 $inner = wikiParseBlockLines($collected, 0, count($collected), $depth + 1)['blocks'];
335 return ['block' => $inner ? ['type' => 'quote', 'blocks' => $inner] : null, 'next' => $i];
336}
337
338/** @return ?array{indent:int,ordered:bool,number:?int,text:string} */
339function wikiMatchList(string $line): ?array {
340 if (preg_match('/^([ \t]*)([-*]|\d{1,9}\.)([ \t]+)(.*)$/u', $line, $match) !== 1) return null;
341 $marker = $match[2];
342 $ordered = str_ends_with($marker, '.');
343 return [
344 'indent' => wikiIndentColumns($match[1]),
345 'ordered' => $ordered,
346 'number' => $ordered ? (int)$marker : null,
347 'text' => $match[4],
348 ];
349}
350
351function wikiIndentColumns(string $whitespace): int {
352 $columns = 0;
353 $length = strlen($whitespace);
354 for ($i = 0; $i < $length; $i++) $columns += $whitespace[$i] === "\t" ? 4 : 1;
355 return $columns;
356}
357
358function wikiLeadingColumns(string $line): int {
359 if (preg_match('/^[ \t]*/', $line, $match) !== 1) return 0;
360 return wikiIndentColumns($match[0]);
361}
362
363/** @return array{block:?array<string,mixed>,next:int} */
364function wikiParseList(array $lines, int $i, int $n, int $base, bool $ordered, int $depth): array {
365 $items = [];
366 $start = null;
367 while ($i < $n) {
368 while ($i < $n && trim($lines[$i]) === '') {
369 $k = $i + 1;
370 while ($k < $n && trim($lines[$k]) === '') $k++;
371 $sibling = $k < $n ? wikiMatchList($lines[$k]) : null;
372 if ($sibling && $sibling['indent'] === $base && $sibling['ordered'] === $ordered) {
373 $i = $k;
374 break;
375 }
376 break 2;
377 }
378 if ($i >= $n) break;
379 $item = wikiMatchList($lines[$i]);
380 if (!$item || $item['indent'] !== $base || $item['ordered'] !== $ordered) break;
381 if ($start === null) $start = $item['number'];
382 $i++;
383 $body = [$item['text']];
384 while ($i < $n) {
385 if (trim($lines[$i]) === '') {
386 $k = $i + 1;
387 while ($k < $n && trim($lines[$k]) === '') $k++;
388 if ($k >= $n) { $i = $n; break; }
389 $next = wikiMatchList($lines[$k]);
390 if ($next && $next['indent'] === $base && $next['ordered'] === $ordered) {
391 $i = $k;
392 break;
393 }
394 if ($next && $next['indent'] <= $base) break;
395 if (wikiLeadingColumns($lines[$k]) <= $base) break;
396 $body[] = '';
397 $i++;
398 continue;
399 }
400 $next = wikiMatchList($lines[$i]);
401 if ($next && $next['indent'] <= $base) break;
402 if (wikiLeadingColumns($lines[$i]) <= $base) break;
403 $body[] = $lines[$i];
404 $i++;
405 }
406 $items[] = ['blocks' => wikiParseBlockLines($body, 0, count($body), $depth + 1)['blocks']];
407 }
408 if (!$items) return ['block' => null, 'next' => $i];
409 $block = ['type' => 'list', 'ordered' => $ordered, 'items' => $items];
410 if ($ordered && $start !== null && $start !== 1) $block['start'] = $start;
411 return ['block' => $block, 'next' => $i];
412}
413
414/** @return array{block:?array<string,mixed>,next:int} */
415function wikiParseParagraph(array $lines, int $i, int $n): array {
416 $chunks = [];
417 while ($i < $n) {
418 $line = $lines[$i];
419 if (trim($line) === '' || wikiMatchList($line) || wikiIsQuoteLine($line)) break;
420 $chunks[] = $line;
421 $i++;
422 }
423 $inlines = wikiJoinParagraph($chunks);
424 return ['block' => $inlines ? ['type' => 'paragraph', 'inlines' => $inlines] : null, 'next' => $i];
425}
426
427/** @return list<array<string,mixed>> */
428function wikiJoinParagraph(array $rawLines): array {
429 $segments = [];
430 foreach ($rawLines as $line) {
431 if (trim($line) === '') continue;
432 [$text, $hard] = wikiSplitHard($line);
433 if ($text === '' && !$hard) continue;
434 $segments[] = ['text' => $text, 'hard' => $hard];
435 }
436 if (!$segments) return [];
437 $joined = '';
438 foreach ($segments as $index => $segment) {
439 if ($index > 0) $joined .= $segments[$index - 1]['hard'] ? "\n" : ' ';
440 $joined .= $segment['text'];
441 }
442 return wikiParseInlines($joined);
443}
444
445/** @return array{0:string,1:bool} */
446function wikiSplitHard(string $line): array {
447 if (preg_match('/^(.*?)([ \t]{2,})$/u', $line, $match) === 1 && trim($match[1]) !== '') {
448 return [trim($match[1]), true];
449 }
450 $trimmed = rtrim($line, " \t");
451 if ($trimmed !== '' && str_ends_with($trimmed, '\\') && wikiEndsWithOddBackslash($trimmed)) {
452 return [trim(substr($trimmed, 0, -1)), true];
453 }
454 return [trim($line), false];
455}
456
457function wikiEndsWithOddBackslash(string $line): bool {
458 $count = 0;
459 for ($i = strlen($line) - 1; $i >= 0 && $line[$i] === '\\'; $i--) $count++;
460 return $count % 2 === 1;
461}
462
463/** @return list<array<string,mixed>> */
464function wikiParseInlines(string $text): array {
465 if ($text === '') return [];
466 $scanned = wikiScanInlines($text, 0, strlen($text), false);
467 return wikiMatchEmphasis($scanned['tokens']);
468}
469
470/**
471 * @return array{tokens:list<array<string,mixed>>,next:int,stopped:bool}
472 */
473function wikiScanInlines(string $text, int $i, int $end, bool $inLabel): array {
474 $tokens = [];
475 $buffer = '';
476 $flush = function () use (&$tokens, &$buffer): void {
477 if ($buffer !== '') {
478 $tokens[] = ['kind' => 'text', 'text' => $buffer];
479 $buffer = '';
480 }
481 };
482 while ($i < $end) {
483 if ($inLabel && $text[$i] === ']') {
484 $flush();
485 return ['tokens' => $tokens, 'next' => $i, 'stopped' => true];
486 }
487 if ($text[$i] === "\n") {
488 $flush();
489 $tokens[] = ['kind' => 'break'];
490 $i++;
491 continue;
492 }
493 if ($text[$i] === '\\' && $i + 1 < $end) {
494 $next = wikiCharAt($text, $i + 1, $end);
495 if (wikiEscapable($next)) {
496 $buffer .= $next;
497 $i += 1 + strlen($next);
498 continue;
499 }
500 }
501 if ($text[$i] === '`') {
502 $code = wikiTryCode($text, $i, $end);
503 if ($code) {
504 $flush();
505 $tokens[] = $code['token'];
506 $i = $code['next'];
507 continue;
508 }
509 }
510 if ($text[$i] === '[' && $i + 1 < $end && $text[$i + 1] === '[') {
511 $link = wikiTryWikiLink($text, $i, $end);
512 if ($link) {
513 $flush();
514 $tokens[] = ['kind' => 'wiki', 'link' => $link['link']];
515 $i = $link['next'];
516 continue;
517 }
518 }
519 if (!$inLabel && $text[$i] === '[') {
520 $link = wikiTryExternalLink($text, $i, $end);
521 if ($link) {
522 $flush();
523 $tokens[] = $link['token'];
524 $i = $link['next'];
525 continue;
526 }
527 }
528 if ($text[$i] === '*' || $text[$i] === '_') {
529 $marker = $text[$i];
530 $run = 0;
531 while ($i + $run < $end && $text[$i + $run] === $marker) $run++;
532 $before = wikiCharClass(wikiPrevChar($text, $i));
533 $after = wikiCharClass(wikiCharAt($text, $i + $run, $end));
534 $flush();
535 $tokens[] = [
536 'kind' => 'delim',
537 'marker' => $marker,
538 'len' => $run,
539 'canOpen' => wikiCanOpen($before, $after, $marker),
540 'canClose' => wikiCanClose($before, $after, $marker),
541 ];
542 $i += $run;
543 continue;
544 }
545 $char = wikiCharAt($text, $i, $end);
546 if ($char === '') { $i++; continue; }
547 $buffer .= $char;
548 $i += strlen($char);
549 }
550 $flush();
551 return ['tokens' => $tokens, 'next' => $i, 'stopped' => false];
552}
553
554function wikiEscapable(string $char): bool {
555 return $char !== '' && str_contains('\\`*_{}[]()#+-.!|>', $char);
556}
557
558function wikiCharAt(string $text, int $byte, int $end): string {
559 if ($byte < 0 || $byte >= $end) return '';
560 $slice = substr($text, $byte, min(4, $end - $byte));
561 if (preg_match('/\A./us', $slice, $match) === 1) return $match[0];
562 return $text[$byte];
563}
564
565function wikiPrevChar(string $text, int $byte): string {
566 if ($byte <= 0) return '';
567 $start = max(0, $byte - 4);
568 $slice = substr($text, $start, $byte - $start);
569 if (preg_match('/.\z/us', $slice, $match) === 1) return $match[0];
570 return $text[$byte - 1];
571}
572
573function wikiCharClass(string $char): string {
574 if ($char === '') return 'edge';
575 if (preg_match('/\A\s\z/u', $char) === 1) return 'space';
576 if (preg_match('/\A[\p{L}\p{N}]\z/u', $char) === 1) return 'word';
577 return 'punct';
578}
579
580function wikiLeftFlanking(string $before, string $after): bool {
581 if ($after === 'space' || $after === 'edge') return false;
582 if ($after === 'punct' && $before !== 'space' && $before !== 'edge' && $before !== 'punct') return false;
583 return true;
584}
585
586function wikiRightFlanking(string $before, string $after): bool {
587 if ($before === 'space' || $before === 'edge') return false;
588 if ($before === 'punct' && $after !== 'space' && $after !== 'edge' && $after !== 'punct') return false;
589 return true;
590}
591
592function wikiCanOpen(string $before, string $after, string $marker): bool {
593 if (!wikiLeftFlanking($before, $after)) return false;
594 if ($marker === '_' && wikiRightFlanking($before, $after) && $before !== 'punct') return false;
595 return true;
596}
597
598function wikiCanClose(string $before, string $after, string $marker): bool {
599 if (!wikiRightFlanking($before, $after)) return false;
600 if ($marker === '_' && wikiLeftFlanking($before, $after) && $after !== 'punct') return false;
601 return true;
602}
603
604/** @return ?array{token:array<string,mixed>,next:int} */
605function wikiTryCode(string $text, int $i, int $end): ?array {
606 if ($text[$i] !== '`') return null;
607 $run = 0;
608 while ($i + $run < $end && $text[$i + $run] === '`') $run++;
609 $j = $i + $run;
610 while ($j < $end) {
611 if ($text[$j] !== '`') { $j++; continue; }
612 $close = 0;
613 while ($j + $close < $end && $text[$j + $close] === '`') $close++;
614 if ($close === $run) {
615 $content = substr($text, $i + $run, $j - ($i + $run));
616 $content = str_replace("\n", ' ', $content);
617 if (strlen($content) >= 2 && $content[0] === ' ' && str_ends_with($content, ' ') && trim($content) !== '') {
618 $content = substr($content, 1, -1);
619 }
620 return ['token' => ['kind' => 'code', 'text' => $content], 'next' => $j + $run];
621 }
622 $j += $close;
623 }
624 return null;
625}
626
627/** @return ?array{link:array<string,mixed>,next:int} */
628function wikiTryWikiLink(string $text, int $i, int $end): ?array {
629 if ($i + 3 >= $end || $text[$i] !== '[' || $text[$i + 1] !== '[') return null;
630 if (preg_match('/\A\[\[([^\[\]\n]+)\]\]/u', substr($text, $i, $end - $i), $match) !== 1) return null;
631 return ['link' => wikiRawLink($match[1]), 'next' => $i + strlen($match[0])];
632}
633
634/** @return ?array{token:array<string,mixed>,next:int} */
635function wikiTryExternalLink(string $text, int $i, int $end): ?array {
636 if ($text[$i] !== '[') return null;
637 $label = wikiScanInlines($text, $i + 1, $end, true);
638 if (!$label['stopped']) return null;
639 $j = $label['next'];
640 if ($j + 1 >= $end || $text[$j + 1] !== '(') return null;
641 $urlStart = $j + 2;
642 if ($urlStart >= $end) return null;
643 $url = '';
644 $next = $urlStart;
645 if ($text[$urlStart] === '<') {
646 $close = strpos($text, '>', $urlStart + 1);
647 if ($close === false || $close >= $end || $close + 1 >= $end || $text[$close + 1] !== ')') return null;
648 $url = substr($text, $urlStart + 1, $close - $urlStart - 1);
649 $next = $close + 2;
650 } else {
651 $depth = 0;
652 $k = $urlStart;
653 while ($k < $end) {
654 $char = wikiCharAt($text, $k, $end);
655 if ($char === '\\' && $k + strlen($char) < $end) {
656 $escaped = wikiCharAt($text, $k + 1, $end);
657 if (wikiEscapable($escaped)) {
658 $url .= $escaped;
659 $k += 1 + strlen($escaped);
660 continue;
661 }
662 }
663 if ($char === '(') { $depth++; $url .= '('; $k++; continue; }
664 if ($char === ')') {
665 if ($depth === 0) break;
666 $depth--;
667 $url .= ')';
668 $k++;
669 continue;
670 }
671 if (wikiCharClass($char) === 'space') return null;
672 $url .= $char;
673 $k += strlen($char);
674 }
675 if ($k >= $end || $text[$k] !== ')') return null;
676 $next = $k + 1;
677 }
678 $safe = wikiSafeUrl($url);
679 if ($safe === null) return null;
680 $children = $label['tokens'];
681 if (!$children) $children = [['kind' => 'text', 'text' => $safe]];
682 return ['token' => ['kind' => 'url', 'href' => $safe, 'children' => $children], 'next' => $next];
683}
684
685function wikiSafeUrl(string $url): ?string {
686 $url = trim($url);
687 if ($url === '' || strlen($url) > 2000) return null;
688 if (preg_match('/[\x00-\x20\x7F<>"\'\\\\]/', $url) === 1) return null;
689 if (preg_match('#\Ahttps?://[^\s/]+#i', $url) === 1) return $url;
690 if (preg_match('#\Amailto:[^@\s]+@[^@\s]+#i', $url) === 1) return $url;
691 return null;
692}
693
694/** @param list<array<string,mixed>> $tokens */
695function wikiMatchEmphasis(array $tokens): array {
696 $budget = count($tokens) + 1;
697 foreach ($tokens as $token) {
698 if (($token['kind'] ?? '') === 'delim') $budget += (int)($token['len'] ?? 0);
699 }
700 $guard = 0;
701 while ($guard++ < $budget) {
702 $found = wikiFirstEmphasisMatch($tokens);
703 if ($found === null) break;
704 [$open, $close, $use] = $found;
705 $inner = array_slice($tokens, $open + 1, $close - $open - 1);
706 $tokens[$open]['len'] -= $use;
707 $tokens[$close]['len'] -= $use;
708 $node = ['kind' => $use === 2 ? 'strong' : 'em', 'children' => $inner];
709 $replacement = [];
710 if ($tokens[$open]['len'] > 0) $replacement[] = $tokens[$open];
711 $replacement[] = $node;
712 if ($tokens[$close]['len'] > 0) $replacement[] = $tokens[$close];
713 array_splice($tokens, $open, $close - $open + 1, $replacement);
714 }
715 return wikiTokensToInlines($tokens);
716}
717
718/** @param list<array<string,mixed>> $tokens
719 * @return ?array{0:int,1:int,2:int}
720 */
721function wikiFirstEmphasisMatch(array $tokens): ?array {
722 $count = count($tokens);
723 for ($close = 0; $close < $count; $close++) {
724 $closer = $tokens[$close];
725 if (($closer['kind'] ?? '') !== 'delim' || empty($closer['canClose']) || (int)$closer['len'] < 1) continue;
726 for ($open = $close - 1; $open >= 0; $open--) {
727 $opener = $tokens[$open];
728 if (($opener['kind'] ?? '') !== 'delim' || empty($opener['canOpen']) || (int)$opener['len'] < 1) continue;
729 if ($opener['marker'] !== $closer['marker']) continue;
730 if (!wikiDelimLengthsOk((int)$opener['len'], (int)$closer['len'])) continue;
731 $use = ((int)$opener['len'] >= 2 && (int)$closer['len'] >= 2) ? 2 : 1;
732 return [$open, $close, $use];
733 }
734 }
735 return null;
736}
737
738function wikiDelimLengthsOk(int $opener, int $closer): bool {
739 if ($opener < 1 || $closer < 1) return false;
740 if (($opener % 3 === 0 || $closer % 3 === 0) && (($opener + $closer) % 3 !== 0)) return false;
741 return true;
742}
743
744/** @param list<array<string,mixed>> $tokens
745 * @return list<array<string,mixed>>
746 */
747function wikiTokensToInlines(array $tokens): array {
748 $inlines = [];
749 $buffer = '';
750 $flush = function () use (&$inlines, &$buffer): void {
751 if ($buffer !== '') {
752 $inlines[] = ['type' => 'text', 'text' => $buffer];
753 $buffer = '';
754 }
755 };
756 foreach ($tokens as $token) {
757 $kind = $token['kind'] ?? '';
758 if ($kind === 'text') { $buffer .= $token['text']; continue; }
759 if ($kind === 'delim') {
760 $length = (int)($token['len'] ?? 0);
761 if ($length > 0) $buffer .= str_repeat((string)$token['marker'], $length);
762 continue;
763 }
764 $flush();
765 if ($kind === 'break') { $inlines[] = ['type' => 'break']; continue; }
766 if ($kind === 'code') { $inlines[] = ['type' => 'code', 'text' => (string)($token['text'] ?? '')]; continue; }
767 if ($kind === 'wiki') { $inlines[] = $token['link']; continue; }
768 if ($kind === 'url') {
769 $children = wikiMatchEmphasis($token['children'] ?? []);
770 if (!$children) $children = [['type' => 'text', 'text' => (string)$token['href']]];
771 $inlines[] = ['type' => 'url', 'href' => (string)$token['href'], 'inlines' => $children];
772 continue;
773 }
774 if ($kind === 'strong' || $kind === 'em') {
775 $inlines[] = ['type' => $kind, 'inlines' => wikiTokensToInlines($token['children'] ?? [])];
776 }
777 }
778 $flush();
779 return $inlines;
780}
781
782/** @return array<string,mixed> */
783function wikiRawLink(string $inner): array {
784 $label = null;
785 $target = $inner;
786 $bar = strpos($inner, '|');
787 if ($bar !== false) {
788 $target = substr($inner, 0, $bar);
789 $label = trim(substr($inner, $bar + 1));
790 if ($label === '') $label = null;
791 }
792 $target = trim($target);
793 $page = null;
794 $anchor = null;
795 if (str_starts_with($target, '#')) {
796 $anchor = substr($target, 1);
797 } elseif (str_contains($target, '#')) {
798 [$page, $anchor] = explode('#', $target, 2);
799 if ($page === '') $page = null;
800 } else {
801 $page = $target;
802 }
803 $pageOk = $page === null || wikiSlugOk($page);
804 $anchorOk = $anchor === null || ($anchor !== '' && wikiSlugOk($anchor));
805 $valid = $pageOk && $anchorOk && ($page !== null || ($anchor !== null && $anchor !== ''));
806 return [
807 'type' => 'link',
808 'page' => $page,
809 'anchor' => $anchor === '' ? null : $anchor,
810 'label' => $label,
811 'raw' => trim($inner),
812 'valid' => $valid,
813 ];
814}
815
816/** @return array<string,array{title:string,anchors:array<string,string>,chapters:list<array<string,mixed>>}> */
817function wikiCatalog(): array {
818 $rows = query('SELECT slug, title, content FROM wiki_pages')->fetchAll();
819 $catalog = [];
820 foreach ($rows as $row) {
821 $chapters = parseWikiChapters($row['content']);
822 $anchors = [];
823 foreach ($chapters as $chapter) $anchors[$chapter['anchor']] = $chapter['title'] ?? 'Inleiding';
824 $catalog[$row['slug']] = [
825 'title' => $row['title'],
826 'anchors' => $anchors,
827 'chapters' => $chapters,
828 ];
829 }
830 return $catalog;
831}
832
833/** @param array<string,mixed> $link */
834function wikiResolveLink(array $link, string $pageSlug, array $catalog): array {
835 $targetPage = $link['page'] ?? $pageSlug;
836 $anchor = $link['anchor'];
837 $known = ($link['valid'] && is_string($targetPage) && isset($catalog[$targetPage])) ? $catalog[$targetPage] : null;
838 $broken = $known === null;
839 $chapterTitle = null;
840 if (!$broken && $anchor !== null) {
841 if (!isset($known['anchors'][$anchor])) $broken = true;
842 else $chapterTitle = $known['anchors'][$anchor];
843 }
844 $text = $link['label'];
845 if ($text === null || $text === '') {
846 if ($broken) $text = $link['raw'];
847 elseif ($anchor !== null) $text = $chapterTitle ?? $anchor;
848 else $text = $known['title'];
849 }
850 return [
851 'type' => 'link',
852 'page' => $broken ? null : $targetPage,
853 'anchor' => $broken ? null : $anchor,
854 'text' => $text,
855 'broken' => $broken,
856 ];
857}
858
859/** @param list<array<string,mixed>> $chapters */
860function wikiResolveChapters(array $chapters, string $pageSlug, array $catalog): array {
861 $resolved = [];
862 foreach ($chapters as $chapter) {
863 $resolved[] = [
864 'anchor' => $chapter['anchor'],
865 'title' => $chapter['title'],
866 'blocks' => wikiResolveBlocks($chapter['blocks'], $pageSlug, $catalog),
867 ];
868 }
869 return $resolved;
870}
871
872/** @param list<array<string,mixed>> $blocks
873 * @return list<array<string,mixed>>
874 */
875function wikiResolveBlocks(array $blocks, string $pageSlug, array $catalog): array {
876 $resolved = [];
877 foreach ($blocks as $block) {
878 $type = $block['type'] ?? 'paragraph';
879 if ($type === 'list') {
880 $items = [];
881 foreach ($block['items'] ?? [] as $item) {
882 $items[] = ['blocks' => wikiResolveBlocks($item['blocks'] ?? [], $pageSlug, $catalog)];
883 }
884 $copy = ['type' => 'list', 'ordered' => (bool)($block['ordered'] ?? false), 'items' => $items];
885 if (isset($block['start'])) $copy['start'] = (int)$block['start'];
886 $resolved[] = $copy;
887 continue;
888 }
889 if ($type === 'quote') {
890 $inner = wikiResolveBlocks($block['blocks'] ?? [], $pageSlug, $catalog);
891 if ($inner) $resolved[] = ['type' => 'quote', 'blocks' => $inner];
892 continue;
893 }
894 $inlines = wikiResolveInlines($block['inlines'] ?? [], $pageSlug, $catalog, false);
895 if ($inlines) $resolved[] = ['type' => 'paragraph', 'inlines' => $inlines];
896 }
897 return $resolved;
898}
899
900/** @param list<array<string,mixed>> $inlines
901 * @return list<array<string,mixed>>
902 */
903function wikiResolveInlines(array $inlines, string $pageSlug, array $catalog, bool $insideUrl): array {
904 $resolved = [];
905 foreach ($inlines as $inline) {
906 $type = $inline['type'] ?? '';
907 if ($type === 'text') {
908 if (($inline['text'] ?? '') !== '') $resolved[] = ['type' => 'text', 'text' => $inline['text']];
909 continue;
910 }
911 if ($type === 'break') { $resolved[] = ['type' => 'break']; continue; }
912 if ($type === 'code') { $resolved[] = ['type' => 'code', 'text' => (string)($inline['text'] ?? '')]; continue; }
913 if ($type === 'link') {
914 $link = wikiResolveLink($inline, $pageSlug, $catalog);
915 if ($insideUrl) {
916 if ($link['text'] !== '') $resolved[] = ['type' => 'text', 'text' => $link['text']];
917 continue;
918 }
919 $resolved[] = $link;
920 continue;
921 }
922 if ($type === 'strong' || $type === 'em') {
923 $resolved[] = [
924 'type' => $type,
925 'inlines' => wikiResolveInlines($inline['inlines'] ?? [], $pageSlug, $catalog, $insideUrl),
926 ];
927 continue;
928 }
929 if ($type === 'url') {
930 $href = wikiSafeUrl((string)($inline['href'] ?? ''));
931 if ($href === null) {
932 foreach (wikiResolveInlines($inline['inlines'] ?? [], $pageSlug, $catalog, true) as $child) $resolved[] = $child;
933 continue;
934 }
935 $children = wikiResolveInlines($inline['inlines'] ?? [], $pageSlug, $catalog, true);
936 if (!$children) $children = [['type' => 'text', 'text' => $href]];
937 $resolved[] = ['type' => 'url', 'href' => $href, 'inlines' => $children];
938 }
939 }
940 return $resolved;
941}
942
943function loadWikiPage(string $slug): array {
944 $page = wikiPageRow($slug);
945 $category = query('SELECT slug, title FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
946 if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
947 $catalog = wikiCatalog();
948 $chapters = wikiResolveChapters($catalog[$page['slug']]['chapters'], $page['slug'], $catalog);
949 return [
950 'slug' => $page['slug'],
951 'title' => $page['title'],
952 'position' => (int)$page['position'],
953 'category' => ['slug' => $category['slug'], 'title' => $category['title']],
954 'content' => $page['content'],
955 'created' => (int)$page['created'],
956 'updated' => (int)$page['updated'],
957 'chapters' => $chapters,
958 ];
959}
960
961function createWikiPage(array $input): array {
962 $title = cleanText($input['title'] ?? null, 200, 'De paginatitel');
963 if (!is_string($input['category'] ?? null) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
964 $content = wikiNormalizeContent($input['content'] ?? '');
965 parseWikiChapters($content);
966 $slug = wikiChooseSlug($input['slug'] ?? null, $title, wikiReservedPageSlugs());
967 $position = wikiOptionalPosition($input);
968 transaction(function () use ($title, $input, $content, $slug, $position): void {
969 $category = wikiCategoryRow($input['category']);
970 if (query('SELECT 1 FROM wiki_pages WHERE slug=?', [$slug])->fetchColumn()) {
971 throw new AppException('Die slug is al in gebruik.', 409);
972 }
973 $now = time();
974 query('INSERT INTO wiki_pages (category_id, slug, title, content, position, created, updated) VALUES (?,?,?,?,?,?,?)', [
975 $category['id'], $slug, $title, $content, $position ?? wikiNextPagePosition((int)$category['id']), $now, $now,
976 ]);
977 });
978 return loadWikiPage($slug);
979}
980
981function updateWikiPage(string $slug, array $input): array {
982 foreach (['title', 'slug', 'position', 'content', 'category'] as $key) {
983 if (array_key_exists($key, $input)) {
984 $present = true;
985 break;
986 }
987 }
988 if (!isset($present)) throw new AppException('Geef iets om bij te werken.');
989 $stored = $slug;
990 transaction(function () use ($slug, $input, &$stored): void {
991 $page = wikiPageRow($slug);
992 $title = array_key_exists('title', $input) ? cleanText($input['title'], 200, 'De paginatitel') : $page['title'];
993 $newSlug = array_key_exists('slug', $input)
994 ? wikiChooseSlug($input['slug'], $title, wikiReservedPageSlugs())
995 : $page['slug'];
996 $content = array_key_exists('content', $input) ? wikiNormalizeContent($input['content']) : $page['content'];
997 parseWikiChapters($content);
998 if (array_key_exists('category', $input)) {
999 if (!is_string($input['category']) || !wikiSlugOk($input['category'])) throw new AppException('Kies een categorie.');
1000 $category = wikiCategoryRow($input['category']);
1001 } else {
1002 $category = query('SELECT * FROM wiki_categories WHERE id=?', [$page['category_id']])->fetch();
1003 if (!$category) throw new AppException('Deze categorie bestaat niet.', 404);
1004 }
1005 $moved = (int)$category['id'] !== (int)$page['category_id'];
1006 if (array_key_exists('position', $input)) $position = wikiOptionalPosition($input);
1007 else $position = $moved ? null : (int)$page['position'];
1008 if ($position === null) $position = wikiNextPagePosition((int)$category['id']);
1009 $clash = query('SELECT 1 FROM wiki_pages WHERE slug=? AND id<>?', [$newSlug, $page['id']])->fetchColumn();
1010 if ($clash) throw new AppException('Die slug is al in gebruik.', 409);
1011 query('UPDATE wiki_pages SET category_id=?, slug=?, title=?, content=?, position=?, updated=? WHERE id=?', [
1012 $category['id'], $newSlug, $title, $content, $position, time(), $page['id'],
1013 ]);
1014 $stored = $newSlug;
1015 });
1016 return loadWikiPage($stored);
1017}
1018
1019function deleteWikiPage(string $slug): string {
1020 transaction(function () use ($slug): void {
1021 $page = wikiPageRow($slug);
1022 query('DELETE FROM wiki_pages WHERE id=?', [$page['id']]);
1023 });
1024 return $slug;
1025}