BlueGit

projects-timfalken-com verhalenboek

feat: add a wiki with categories, chapters and internal links

Readers can browse pages grouped by category. Admins and the same
Bearer keys as /days can create, edit and delete them. Page text
uses a small link syntax that resolves to pages and chapter anchors.

Co-authored-by: tim <tim@timfalken.com>

timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa

Authored 2026-10-11 · 5 weeks ago

Hash
2556ae87ad229ace0109c7911e9788d493150886
Parent
0b60d567
12 files changed +1146 −5
web/api.php +48 −0
@@ -136,6 +136,54 @@ try {
136 136 requireWriter($actor);
137 137 jsonOut(addStory($match[1], readJson()), 201);
138 138 }
139 if ($route === '/wiki/categories') {
140 if ($method === 'GET') jsonOut(listWikiCategories());
141 if ($method === 'POST') {
142 requireWriter($actor);
143 jsonOut(createWikiCategory(readJson()), 201);
144 }
145 fail('Deze methode is hier niet toegestaan.', 405);
146 }
147 if (preg_match('#^/wiki/categories/([a-z0-9]+(?:-[a-z0-9]+)*)$#', $route, $match)) {
148 $slug = $match[1];
149 if ($method === 'GET') jsonOut(loadWikiCategory($slug));
150 if ($method === 'PUT') {
151 requireWriter($actor);
152 jsonOut(updateWikiCategory($slug, readJson()));
153 }
154 if ($method === 'DELETE') {
155 requireWriter($actor);
156 jsonOut(['ok' => true, 'slug' => deleteWikiCategory($slug)]);
157 }
158 fail('Deze methode is hier niet toegestaan.', 405);
159 }
160 if ($route === '/wiki/pages') {
161 if ($method === 'GET') {
162 $category = $_GET['category'] ?? null;
163 $q = $_GET['q'] ?? null;
164 if ($category !== null && !is_string($category)) throw new AppException('De categorie moet een slug zijn.');
165 if ($q !== null && !is_string($q)) throw new AppException('De zoekterm moet tekst zijn.');
166 jsonOut(['pages' => listWikiPages(is_string($category) ? $category : null, is_string($q) ? $q : null)]);
167 }
168 if ($method === 'POST') {
169 requireWriter($actor);
170 jsonOut(createWikiPage(readJson()), 201);
171 }
172 fail('Deze methode is hier niet toegestaan.', 405);
173 }
174 if (preg_match('#^/wiki/pages/([a-z0-9]+(?:-[a-z0-9]+)*)$#', $route, $match)) {
175 $slug = $match[1];
176 if ($method === 'GET') jsonOut(loadWikiPage($slug));
177 if ($method === 'PUT') {
178 requireWriter($actor);
179 jsonOut(updateWikiPage($slug, readJson()));
180 }
181 if ($method === 'DELETE') {
182 requireWriter($actor);
183 jsonOut(['ok' => true, 'slug' => deleteWikiPage($slug)]);
184 }
185 fail('Deze methode is hier niet toegestaan.', 405);
186 }
139 187 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories/([123])$#', $route, $match)) {
140 188 requireWriter($actor);
141 189 if ($method === 'PUT') jsonOut(updateStory($match[1], (int)$match[2], readJson()));
@@ -136,6 +136,54 @@ try {
136 requireWriter($actor);
136 requireWriter($actor);
137 jsonOut(addStory($match[1], readJson()), 201);
137 jsonOut(addStory($match[1], readJson()), 201);
138 }
138 }
139 if ($route === '/wiki/categories') {
140 if ($method === 'GET') jsonOut(listWikiCategories());
141 if ($method === 'POST') {
142 requireWriter($actor);
143 jsonOut(createWikiCategory(readJson()), 201);
144 }
145 fail('Deze methode is hier niet toegestaan.', 405);
146 }
147 if (preg_match('#^/wiki/categories/([a-z0-9]+(?:-[a-z0-9]+)*)$#', $route, $match)) {
148 $slug = $match[1];
149 if ($method === 'GET') jsonOut(loadWikiCategory($slug));
150 if ($method === 'PUT') {
151 requireWriter($actor);
152 jsonOut(updateWikiCategory($slug, readJson()));
153 }
154 if ($method === 'DELETE') {
155 requireWriter($actor);
156 jsonOut(['ok' => true, 'slug' => deleteWikiCategory($slug)]);
157 }
158 fail('Deze methode is hier niet toegestaan.', 405);
159 }
160 if ($route === '/wiki/pages') {
161 if ($method === 'GET') {
162 $category = $_GET['category'] ?? null;
163 $q = $_GET['q'] ?? null;
164 if ($category !== null && !is_string($category)) throw new AppException('De categorie moet een slug zijn.');
165 if ($q !== null && !is_string($q)) throw new AppException('De zoekterm moet tekst zijn.');
166 jsonOut(['pages' => listWikiPages(is_string($category) ? $category : null, is_string($q) ? $q : null)]);
167 }
168 if ($method === 'POST') {
169 requireWriter($actor);
170 jsonOut(createWikiPage(readJson()), 201);
171 }
172 fail('Deze methode is hier niet toegestaan.', 405);
173 }
174 if (preg_match('#^/wiki/pages/([a-z0-9]+(?:-[a-z0-9]+)*)$#', $route, $match)) {
175 $slug = $match[1];
176 if ($method === 'GET') jsonOut(loadWikiPage($slug));
177 if ($method === 'PUT') {
178 requireWriter($actor);
179 jsonOut(updateWikiPage($slug, readJson()));
180 }
181 if ($method === 'DELETE') {
182 requireWriter($actor);
183 jsonOut(['ok' => true, 'slug' => deleteWikiPage($slug)]);
184 }
185 fail('Deze methode is hier niet toegestaan.', 405);
186 }
139 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories/([123])$#', $route, $match)) {
187 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories/([123])$#', $route, $match)) {
140 requireWriter($actor);
188 requireWriter($actor);
141 if ($method === 'PUT') jsonOut(updateStory($match[1], (int)$match[2], readJson()));
189 if ($method === 'PUT') jsonOut(updateStory($match[1], (int)$match[2], readJson()));
web/assets/app.css +59 −0
@@ -361,6 +361,65 @@ legend { padding: 0 0.3rem; color: var(--muted); }
361 361 cursor: pointer;
362 362 }
363 363 .key-open:hover span:first-child, .key-open:focus-visible span:first-child { text-decoration: underline; }
364 .wiki-search, .wiki-page, .wiki-category { margin: 0.2rem 0 1.4rem; }
365 .wiki-search { display: grid; gap: 0.55rem; }
366 .wiki-cat-head {
367 display: flex;
368 justify-content: space-between;
369 gap: 0.7rem;
370 align-items: center;
371 }
372 .wiki-cat-head h2 { margin: 0.2rem 0; }
373 .wiki-page-link, .wiki-result {
374 display: block;
375 padding: 0.85rem 1rem;
376 margin: 0.45rem 0;
377 background: var(--bg-raised);
378 border: 1px solid var(--line);
379 border-radius: 1rem;
380 text-decoration: none;
381 }
382 .wiki-page-link small, .wiki-result small, .hint { color: var(--muted); }
383 .wiki-actions, .wiki-cat-actions { display: flex; flex-wrap: wrap; gap: 0.45rem; }
384 .wiki-toc {
385 display: flex;
386 flex-wrap: wrap;
387 gap: 0.4rem;
388 margin: 0.2rem 0 1.2rem;
389 }
390 .wiki-toc a {
391 text-decoration: none;
392 border: 1px solid var(--line);
393 background: var(--bg-raised);
394 border-radius: 999px;
395 padding: 0.35rem 0.75rem;
396 min-height: 2.25rem;
397 display: inline-flex;
398 align-items: center;
399 }
400 .wiki-chapter {
401 padding-top: 0.7rem;
402 margin-top: 0.35rem;
403 border-top: 1px solid var(--line);
404 scroll-margin-top: 0.75rem;
405 }
406 .wiki-chapter h2 { font-size: 1.35rem; margin: 0.15rem 0 0.7rem; }
407 .wiki-chapter p { font-size: 1.15rem; line-height: 1.75; margin: 0 0 1rem; }
408 .wiki-link { color: var(--accent); }
409 .wiki-broken { color: var(--muted); border-bottom: 1px dashed var(--muted); }
410 .wiki-missing {
411 font-size: 0.72em;
412 letter-spacing: 0.06em;
413 text-transform: uppercase;
414 margin-left: 0.3rem;
415 }
416 .wiki-chapter.is-target h2 { color: var(--accent); }
417 textarea.wiki-source {
418 min-height: 16rem;
419 font-family: ui-monospace, "Cascadia Mono", "Liberation Mono", monospace;
420 font-size: 0.95rem;
421 }
422 .hint { margin: 0; font-size: 0.95rem; }
364 423 .docs { padding-bottom: 3rem; }
365 424 .docs h1 { font-size: clamp(2rem, 5vw, 3rem); }
366 425 .docs pre {
@@ -361,6 +361,65 @@ legend { padding: 0 0.3rem; color: var(--muted); }
361 cursor: pointer;
361 cursor: pointer;
362}
362}
363.key-open:hover span:first-child, .key-open:focus-visible span:first-child { text-decoration: underline; }
363.key-open:hover span:first-child, .key-open:focus-visible span:first-child { text-decoration: underline; }
364.wiki-search, .wiki-page, .wiki-category { margin: 0.2rem 0 1.4rem; }
365.wiki-search { display: grid; gap: 0.55rem; }
366.wiki-cat-head {
367 display: flex;
368 justify-content: space-between;
369 gap: 0.7rem;
370 align-items: center;
371}
372.wiki-cat-head h2 { margin: 0.2rem 0; }
373.wiki-page-link, .wiki-result {
374 display: block;
375 padding: 0.85rem 1rem;
376 margin: 0.45rem 0;
377 background: var(--bg-raised);
378 border: 1px solid var(--line);
379 border-radius: 1rem;
380 text-decoration: none;
381}
382.wiki-page-link small, .wiki-result small, .hint { color: var(--muted); }
383.wiki-actions, .wiki-cat-actions { display: flex; flex-wrap: wrap; gap: 0.45rem; }
384.wiki-toc {
385 display: flex;
386 flex-wrap: wrap;
387 gap: 0.4rem;
388 margin: 0.2rem 0 1.2rem;
389}
390.wiki-toc a {
391 text-decoration: none;
392 border: 1px solid var(--line);
393 background: var(--bg-raised);
394 border-radius: 999px;
395 padding: 0.35rem 0.75rem;
396 min-height: 2.25rem;
397 display: inline-flex;
398 align-items: center;
399}
400.wiki-chapter {
401 padding-top: 0.7rem;
402 margin-top: 0.35rem;
403 border-top: 1px solid var(--line);
404 scroll-margin-top: 0.75rem;
405}
406.wiki-chapter h2 { font-size: 1.35rem; margin: 0.15rem 0 0.7rem; }
407.wiki-chapter p { font-size: 1.15rem; line-height: 1.75; margin: 0 0 1rem; }
408.wiki-link { color: var(--accent); }
409.wiki-broken { color: var(--muted); border-bottom: 1px dashed var(--muted); }
410.wiki-missing {
411 font-size: 0.72em;
412 letter-spacing: 0.06em;
413 text-transform: uppercase;
414 margin-left: 0.3rem;
415}
416.wiki-chapter.is-target h2 { color: var(--accent); }
417textarea.wiki-source {
418 min-height: 16rem;
419 font-family: ui-monospace, "Cascadia Mono", "Liberation Mono", monospace;
420 font-size: 0.95rem;
421}
422.hint { margin: 0; font-size: 0.95rem; }
364.docs { padding-bottom: 3rem; }
423.docs { padding-bottom: 3rem; }
365.docs h1 { font-size: clamp(2rem, 5vw, 3rem); }
424.docs h1 { font-size: clamp(2rem, 5vw, 3rem); }
366.docs pre {
425.docs pre {
web/assets/app.js +274 −2
@@ -2,7 +2,7 @@
2 2
3 3 const MONTHS = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'];
4 4 const ROMAN = ['I', 'II', 'III'];
5 const state = { me: null, csrf: '', local: false, freshKey: null, revealedKey: null };
5 const state = { me: null, csrf: '', local: false, freshKey: null, revealedKey: null, wikiQuery: '' };
6 6 let renderToken = 0;
7 7 let menuAnchor = null;
8 8 let ignoreCloseUntil = 0;
@@ -25,6 +25,13 @@ function isDayRoute(path) {
25 25 return /^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path);
26 26 }
27 27
28 function wikiReading(path) {
29 if (path === '/wiki' || path === '/wiki/nieuw' || path.startsWith('/wiki/nieuw/') || path.startsWith('/wiki/bewerken/') || path.startsWith('/wiki/categorie/')) return null;
30 const match = path.match(/^\/wiki\/([a-z0-9]+(?:-[a-z0-9]+)*)(?:\/([a-z0-9]+(?:-[a-z0-9]+)*))?$/);
31 if (!match) return null;
32 return { slug: match[1], anchor: match[2] || null };
33 }
34
28 35 // Hash-navigatie blijft één document. De browser onthoudt het scrollpunt per
29 36 // geschiedenisregel; bij handmatig herstel zetten we een nieuw geopende dag
30 37 // bovenaan en geven terug/vooruit de opgeslagen plek terug.
@@ -72,7 +79,15 @@ function scrollToPosition(y) {
72 79 function settleScroll(path, traversal) {
73 80 let y = null;
74 81 if (traversal) y = savedScrollY();
75 if (y === null && isDayRoute(path)) y = 0;
82 const reading = wikiReading(path);
83 if (y === null && reading && reading.anchor) {
84 const node = document.getElementById('wiki-' + reading.anchor);
85 if (node) {
86 const top = node.getBoundingClientRect().top + (window.scrollY || document.documentElement.scrollTop || 0) - 12;
87 y = Math.max(0, Math.round(top));
88 } else y = 0;
89 }
90 if (y === null && (isDayRoute(path) || path === '/wiki' || path.startsWith('/wiki/'))) y = 0;
76 91 if (y === null) {
77 92 // Weekwissel en overige pagina's houden hun scrollpunt. Wel vastleggen,
78 93 // zodat terug/vooruit die plek terugzet.
@@ -145,6 +160,7 @@ function highlight(path) {
145 160 const nav = link.getAttribute('data-nav');
146 161 let current = path === nav;
147 162 if (nav === '/') current = path === '/' || path.startsWith('/week/');
163 if (nav === '/wiki') current = path === '/wiki' || path.startsWith('/wiki/');
148 164 if (nav === '/beheer') current = path.startsWith('/beheer');
149 165 if (current) link.setAttribute('aria-current', 'page');
150 166 else link.removeAttribute('aria-current');
@@ -678,6 +694,241 @@ function paintKeys(keys) {
678 694 app.replaceChildren(section);
679 695 }
680 696
697 function wikiSlugOk(value) {
698 return typeof value === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);
699 }
700
701 function appendWikiInline(parent, part) {
702 if (!part || typeof part !== 'object') return;
703 if (part.type === 'link' && part.broken === false && wikiSlugOk(part.page) && (part.anchor == null || wikiSlugOk(part.anchor))) {
704 const href = part.anchor ? '#/wiki/' + part.page + '/' + part.anchor : '#/wiki/' + part.page;
705 parent.append(el('a', { href, class: 'wiki-link' }, [part.text || part.page]));
706 return;
707 }
708 if (part.type === 'link') {
709 const mark = el('span', { class: 'wiki-broken' }, [part.text || '']);
710 mark.append(el('span', { class: 'wiki-missing' }, ['ontbreekt']));
711 parent.append(mark);
712 return;
713 }
714 parent.append(document.createTextNode(typeof part.text === 'string' ? part.text : ''));
715 }
716
717 function wikiChapterNode(chapter, currentAnchor) {
718 const section = el('section', {
719 class: 'wiki-chapter' + (chapter.anchor === currentAnchor ? ' is-target' : ''),
720 id: 'wiki-' + chapter.anchor,
721 });
722 if (chapter.title) section.append(el('h2', {}, [chapter.title]));
723 (chapter.blocks || []).forEach((block) => {
724 const paragraph = el('p', {});
725 (block.inlines || []).forEach((part) => appendWikiInline(paragraph, part));
726 section.append(paragraph);
727 });
728 if (!chapter.title && !(chapter.blocks || []).length) section.append(el('p', {}, ['']));
729 return section;
730 }
731
732 function paintWikiArticle(page, anchor) {
733 const section = el('article', { class: 'wiki-page' }, [
734 el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]),
735 el('p', { class: 'eyebrow' }, [page.category.title]),
736 el('h1', {}, [page.title]),
737 ]);
738 if (page.chapters && page.chapters.length) {
739 const toc = el('nav', { class: 'wiki-toc', 'aria-label': 'Hoofdstukken' });
740 page.chapters.forEach((chapter) => {
741 toc.append(el('a', { href: '#/wiki/' + page.slug + '/' + chapter.anchor }, [chapter.title || 'Inleiding']));
742 });
743 section.append(toc);
744 }
745 (page.chapters || []).forEach((chapter) => section.append(wikiChapterNode(chapter, anchor)));
746 if (state.me.admin) {
747 const remove = el('button', { class: 'danger', type: 'button' }, ['Pagina verwijderen']);
748 remove.addEventListener('click', async () => {
749 if (!window.confirm('Deze wikipagina verwijderen? Dit kan niet ongedaan worden.')) return;
750 try {
751 await api('DELETE', '/wiki/pages/' + page.slug);
752 navigateHash('#/wiki');
753 } catch (failure) { toast(failure.message); }
754 });
755 section.append(el('div', { class: 'wiki-actions' }, [
756 el('a', { class: 'button primary', href: '#/wiki/bewerken/' + page.slug }, ['Bewerken']),
757 remove,
758 ]));
759 }
760 app.replaceChildren(section);
761 document.title = page.title + ' · Wiki · Verhalenboek';
762 }
763
764 async function paintWikiIndex() {
765 const data = await api('GET', '/wiki/categories');
766 const query = el('input', { type: 'search', maxlength: '200', placeholder: 'Zoek op titel of tekst' });
767 query.value = state.wikiQuery || '';
768 const form = el('form', { class: 'wiki-search' }, [
769 el('label', {}, ['Zoeken', query]),
770 el('button', { class: 'quiet', type: 'submit' }, ['Zoeken']),
771 ]);
772 form.addEventListener('submit', (event) => {
773 event.preventDefault();
774 state.wikiQuery = query.value.trim();
775 render();
776 });
777 const section = el('section', { class: 'panel' }, [
778 el('h1', {}, ['Wiki']),
779 el('p', { class: 'lede' }, ['Achtergrond bij de verhalen, per categorie.']),
780 form,
781 ]);
782 if (state.me.admin) {
783 section.append(el('div', { class: 'wiki-actions' }, [
784 el('a', { class: 'button primary', href: '#/wiki/categorie/nieuw' }, ['Nieuwe categorie']),
785 el('a', { class: 'button quiet', href: '#/wiki/nieuw' }, ['Nieuwe pagina']),
786 ]));
787 }
788 if (state.wikiQuery) {
789 const found = await api('GET', '/wiki/pages?q=' + encodeURIComponent(state.wikiQuery));
790 const results = el('div', {});
791 found.pages.forEach((page) => {
792 results.append(el('a', { class: 'wiki-result', href: '#/wiki/' + page.slug }, [
793 el('strong', {}, [page.title]),
794 document.createElement('br'),
795 el('small', {}, [page.category.title]),
796 ]));
797 });
798 if (!found.pages.length) results.append(el('p', { class: 'empty' }, ['Geen pagina\'s gevonden.']));
799 section.append(el('h2', {}, ['Resultaten']), results);
800 }
801 if (!data.categories.length) section.append(el('p', { class: 'empty' }, ['Nog geen categorieën.']));
802 data.categories.forEach((category) => {
803 const head = el('div', { class: 'wiki-cat-head' }, [el('h2', {}, [category.title])]);
804 if (state.me.admin) {
805 head.append(el('a', { class: 'button quiet', href: '#/wiki/categorie/' + category.slug }, ['Wijzig']));
806 }
807 const block = el('section', { class: 'wiki-category' }, [head]);
808 if (!category.pages.length) block.append(el('p', { class: 'empty' }, ['Nog geen pagina\'s.']));
809 category.pages.forEach((page) => {
810 block.append(el('a', { class: 'wiki-page-link', href: '#/wiki/' + page.slug }, [page.title]));
811 });
812 if (state.me.admin) {
813 block.append(el('p', {}, [el('a', { href: '#/wiki/nieuw/' + category.slug }, ['Pagina in ' + category.title])]));
814 }
815 section.append(block);
816 });
817 app.replaceChildren(section);
818 document.title = 'Wiki · Verhalenboek';
819 }
820
821 async function paintWikiCategoryForm(slug) {
822 const creating = !slug;
823 const existing = creating ? { title: '', slug: '' } : await api('GET', '/wiki/categories/' + slug);
824 const title = el('input', { type: 'text', maxlength: '80', required: 'required' });
825 title.value = existing.title || '';
826 const slugInput = el('input', { type: 'text', maxlength: '80', spellcheck: 'false', autocapitalize: 'off' });
827 slugInput.value = existing.slug || '';
828 const error = el('p', { class: 'form-error' });
829 const form = el('form', { class: 'editor' }, [
830 el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]),
831 el('h1', {}, [creating ? 'Nieuwe categorie' : 'Categorie wijzigen']),
832 el('label', {}, ['Titel', title]),
833 el('label', {}, ['Slug', slugInput]),
834 el('p', { class: 'hint' }, ['Leeg laten maakt een slug van de titel. Alleen kleine letters, cijfers en streepjes.']),
835 error,
836 el('button', { class: 'primary', type: 'submit' }, ['Opslaan']),
837 ]);
838 form.addEventListener('submit', async (event) => {
839 event.preventDefault();
840 error.textContent = '';
841 const payload = { title: title.value };
842 if (slugInput.value.trim() !== '') payload.slug = slugInput.value.trim();
843 else if (!creating) payload.slug = '';
844 try {
845 const saved = creating
846 ? await api('POST', '/wiki/categories', payload)
847 : await api('PUT', '/wiki/categories/' + slug, payload);
848 toast('Opgeslagen.');
849 navigateHash('#/wiki');
850 } catch (failure) { error.textContent = failure.message; }
851 });
852 if (!creating) {
853 const remove = el('button', { class: 'danger', type: 'button' }, ['Categorie verwijderen']);
854 remove.addEventListener('click', async () => {
855 if (!window.confirm('Deze categorie verwijderen? Dat kan alleen als er geen pagina\'s meer in staan.')) return;
856 try {
857 await api('DELETE', '/wiki/categories/' + slug);
858 navigateHash('#/wiki');
859 } catch (failure) { error.textContent = failure.message; }
860 });
861 form.append(remove);
862 }
863 app.replaceChildren(form);
864 document.title = (creating ? 'Nieuwe categorie' : existing.title) + ' · Wiki · Verhalenboek';
865 }
866
867 async function paintWikiPageForm(slug, presetCategory) {
868 const creating = !slug;
869 const [listed, existing] = await Promise.all([
870 api('GET', '/wiki/categories'),
871 creating ? Promise.resolve(null) : api('GET', '/wiki/pages/' + slug),
872 ]);
873 if (!listed.categories.length) {
874 app.replaceChildren(el('section', { class: 'panel' }, [
875 el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]),
876 el('h1', {}, ['Nieuwe pagina']),
877 el('p', { class: 'empty' }, ['Maak eerst een categorie.']),
878 el('a', { class: 'button primary', href: '#/wiki/categorie/nieuw' }, ['Nieuwe categorie']),
879 ]));
880 return;
881 }
882 const title = el('input', { type: 'text', maxlength: '200', required: 'required' });
883 title.value = existing ? existing.title : '';
884 const slugInput = el('input', { type: 'text', maxlength: '80', spellcheck: 'false', autocapitalize: 'off' });
885 slugInput.value = existing ? existing.slug : '';
886 const chosen = existing ? existing.category.slug : presetCategory;
887 const select = el('select', { required: 'required' });
888 listed.categories.forEach((category) => {
889 select.append(el('option', {
890 value: category.slug,
891 selected: category.slug === chosen ? 'selected' : null,
892 }, [category.title]));
893 });
894 const content = el('textarea', { class: 'wiki-source', rows: '14' });
895 content.value = existing ? existing.content : '';
896 const error = el('p', { class: 'form-error' });
897 const form = el('form', { class: 'editor' }, [
898 el('p', { class: 'pager' }, [el('a', { href: creating ? '#/wiki' : '#/wiki/' + slug }, [creating ? '← Wiki' : '← Pagina'])]),
899 el('h1', {}, [creating ? 'Nieuwe pagina' : 'Pagina bewerken']),
900 el('label', {}, ['Categorie', select]),
901 el('label', {}, ['Titel', title]),
902 el('label', {}, ['Slug', slugInput]),
903 el('label', {}, ['Tekst', content]),
904 el('p', { class: 'hint' }, [
905 'Een hoofdstuk begint met ## en een titel op een eigen regel. Verwijzingen: [[pagina-slug]], [[#hoofdstuk]] en [[pagina-slug#hoofdstuk|tekst]]. Een kapotte verwijzing blijft zichtbaar en is geen link.',
906 ]),
907 error,
908 el('button', { class: 'primary', type: 'submit' }, ['Opslaan']),
909 ]);
910 form.addEventListener('submit', async (event) => {
911 event.preventDefault();
912 error.textContent = '';
913 const payload = { title: title.value, category: select.value, content: content.value };
914 if (slugInput.value.trim() !== '') payload.slug = slugInput.value.trim();
915 else if (!creating) payload.slug = '';
916 try {
917 const saved = creating
918 ? await api('POST', '/wiki/pages', payload)
919 : await api('PUT', '/wiki/pages/' + slug, payload);
920 toast('Opgeslagen.');
921 navigateHash('#/wiki/' + saved.slug);
922 } catch (failure) { error.textContent = failure.message; }
923 });
924 app.replaceChildren(form);
925 document.title = (creating ? 'Nieuwe pagina' : 'Bewerken') + ' · Wiki · Verhalenboek';
926 }
927
928 function wikiDenied() {
929 app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit wijzigen.']), el('a', { href: '#/wiki' }, ['Naar de wiki']));
930 }
931
681 932 async function render() {
682 933 const token = ++renderToken;
683 934 const path = pathNow();
@@ -687,6 +938,7 @@ async function render() {
687 938 state.freshKey = null;
688 939 state.revealedKey = null;
689 940 }
941 if (path !== '/wiki' && !path.startsWith('/wiki/')) state.wikiQuery = '';
690 942 closeMenu();
691 943 highlight(path);
692 944 document.title = 'Verhalenboek';
@@ -707,6 +959,26 @@ async function render() {
707 959 if (token !== renderToken) return;
708 960 paintFriendReads((friends && friends.days) || {});
709 961 });
962 } else if (path === '/wiki') {
963 await paintWikiIndex();
964 } else if (path === '/wiki/categorie/nieuw') {
965 if (!state.me.admin) { wikiDenied(); return; }
966 await paintWikiCategoryForm(null);
967 } else if (/^\/wiki\/categorie\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) {
968 if (!state.me.admin) { wikiDenied(); return; }
969 await paintWikiCategoryForm(path.slice('/wiki/categorie/'.length));
970 } else if (path === '/wiki/nieuw' || /^\/wiki\/nieuw\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) {
971 if (!state.me.admin) { wikiDenied(); return; }
972 const preset = path === '/wiki/nieuw' ? null : path.slice('/wiki/nieuw/'.length);
973 await paintWikiPageForm(null, preset);
974 } else if (/^\/wiki\/bewerken\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) {
975 if (!state.me.admin) { wikiDenied(); return; }
976 await paintWikiPageForm(path.slice('/wiki/bewerken/'.length), null);
977 } else if (wikiReading(path)) {
978 const reading = wikiReading(path);
979 const page = await api('GET', '/wiki/pages/' + reading.slug);
980 if (token !== renderToken) return;
981 paintWikiArticle(page, reading.anchor);
710 982 } else if (path === '/instellingen') {
711 983 paintSettings();
712 984 } else if (path === '/beheer') {
@@ -2,7 +2,7 @@
2
2
3const MONTHS = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'];
3const MONTHS = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'];
4const ROMAN = ['I', 'II', 'III'];
4const ROMAN = ['I', 'II', 'III'];
5const state = { me: null, csrf: '', local: false, freshKey: null, revealedKey: null };
5const state = { me: null, csrf: '', local: false, freshKey: null, revealedKey: null, wikiQuery: '' };
6let renderToken = 0;
6let renderToken = 0;
7let menuAnchor = null;
7let menuAnchor = null;
8let ignoreCloseUntil = 0;
8let ignoreCloseUntil = 0;
@@ -25,6 +25,13 @@ function isDayRoute(path) {
25 return /^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path);
25 return /^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path);
26}
26}
27
27
28function wikiReading(path) {
29 if (path === '/wiki' || path === '/wiki/nieuw' || path.startsWith('/wiki/nieuw/') || path.startsWith('/wiki/bewerken/') || path.startsWith('/wiki/categorie/')) return null;
30 const match = path.match(/^\/wiki\/([a-z0-9]+(?:-[a-z0-9]+)*)(?:\/([a-z0-9]+(?:-[a-z0-9]+)*))?$/);
31 if (!match) return null;
32 return { slug: match[1], anchor: match[2] || null };
33}
34
28// Hash-navigatie blijft één document. De browser onthoudt het scrollpunt per
35// Hash-navigatie blijft één document. De browser onthoudt het scrollpunt per
29// geschiedenisregel; bij handmatig herstel zetten we een nieuw geopende dag
36// geschiedenisregel; bij handmatig herstel zetten we een nieuw geopende dag
30// bovenaan en geven terug/vooruit de opgeslagen plek terug.
37// bovenaan en geven terug/vooruit de opgeslagen plek terug.
@@ -72,7 +79,15 @@ function scrollToPosition(y) {
72function settleScroll(path, traversal) {
79function settleScroll(path, traversal) {
73 let y = null;
80 let y = null;
74 if (traversal) y = savedScrollY();
81 if (traversal) y = savedScrollY();
75 if (y === null && isDayRoute(path)) y = 0;
82 const reading = wikiReading(path);
83 if (y === null && reading && reading.anchor) {
84 const node = document.getElementById('wiki-' + reading.anchor);
85 if (node) {
86 const top = node.getBoundingClientRect().top + (window.scrollY || document.documentElement.scrollTop || 0) - 12;
87 y = Math.max(0, Math.round(top));
88 } else y = 0;
89 }
90 if (y === null && (isDayRoute(path) || path === '/wiki' || path.startsWith('/wiki/'))) y = 0;
76 if (y === null) {
91 if (y === null) {
77 // Weekwissel en overige pagina's houden hun scrollpunt. Wel vastleggen,
92 // Weekwissel en overige pagina's houden hun scrollpunt. Wel vastleggen,
78 // zodat terug/vooruit die plek terugzet.
93 // zodat terug/vooruit die plek terugzet.
@@ -145,6 +160,7 @@ function highlight(path) {
145 const nav = link.getAttribute('data-nav');
160 const nav = link.getAttribute('data-nav');
146 let current = path === nav;
161 let current = path === nav;
147 if (nav === '/') current = path === '/' || path.startsWith('/week/');
162 if (nav === '/') current = path === '/' || path.startsWith('/week/');
163 if (nav === '/wiki') current = path === '/wiki' || path.startsWith('/wiki/');
148 if (nav === '/beheer') current = path.startsWith('/beheer');
164 if (nav === '/beheer') current = path.startsWith('/beheer');
149 if (current) link.setAttribute('aria-current', 'page');
165 if (current) link.setAttribute('aria-current', 'page');
150 else link.removeAttribute('aria-current');
166 else link.removeAttribute('aria-current');
@@ -678,6 +694,241 @@ function paintKeys(keys) {
678 app.replaceChildren(section);
694 app.replaceChildren(section);
679}
695}
680
696
697function wikiSlugOk(value) {
698 return typeof value === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);
699}
700
701function appendWikiInline(parent, part) {
702 if (!part || typeof part !== 'object') return;
703 if (part.type === 'link' && part.broken === false && wikiSlugOk(part.page) && (part.anchor == null || wikiSlugOk(part.anchor))) {
704 const href = part.anchor ? '#/wiki/' + part.page + '/' + part.anchor : '#/wiki/' + part.page;
705 parent.append(el('a', { href, class: 'wiki-link' }, [part.text || part.page]));
706 return;
707 }
708 if (part.type === 'link') {
709 const mark = el('span', { class: 'wiki-broken' }, [part.text || '']);
710 mark.append(el('span', { class: 'wiki-missing' }, ['ontbreekt']));
711 parent.append(mark);
712 return;
713 }
714 parent.append(document.createTextNode(typeof part.text === 'string' ? part.text : ''));
715}
716
717function wikiChapterNode(chapter, currentAnchor) {
718 const section = el('section', {
719 class: 'wiki-chapter' + (chapter.anchor === currentAnchor ? ' is-target' : ''),
720 id: 'wiki-' + chapter.anchor,
721 });
722 if (chapter.title) section.append(el('h2', {}, [chapter.title]));
723 (chapter.blocks || []).forEach((block) => {
724 const paragraph = el('p', {});
725 (block.inlines || []).forEach((part) => appendWikiInline(paragraph, part));
726 section.append(paragraph);
727 });
728 if (!chapter.title && !(chapter.blocks || []).length) section.append(el('p', {}, ['']));
729 return section;
730}
731
732function paintWikiArticle(page, anchor) {
733 const section = el('article', { class: 'wiki-page' }, [
734 el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]),
735 el('p', { class: 'eyebrow' }, [page.category.title]),
736 el('h1', {}, [page.title]),
737 ]);
738 if (page.chapters && page.chapters.length) {
739 const toc = el('nav', { class: 'wiki-toc', 'aria-label': 'Hoofdstukken' });
740 page.chapters.forEach((chapter) => {
741 toc.append(el('a', { href: '#/wiki/' + page.slug + '/' + chapter.anchor }, [chapter.title || 'Inleiding']));
742 });
743 section.append(toc);
744 }
745 (page.chapters || []).forEach((chapter) => section.append(wikiChapterNode(chapter, anchor)));
746 if (state.me.admin) {
747 const remove = el('button', { class: 'danger', type: 'button' }, ['Pagina verwijderen']);
748 remove.addEventListener('click', async () => {
749 if (!window.confirm('Deze wikipagina verwijderen? Dit kan niet ongedaan worden.')) return;
750 try {
751 await api('DELETE', '/wiki/pages/' + page.slug);
752 navigateHash('#/wiki');
753 } catch (failure) { toast(failure.message); }
754 });
755 section.append(el('div', { class: 'wiki-actions' }, [
756 el('a', { class: 'button primary', href: '#/wiki/bewerken/' + page.slug }, ['Bewerken']),
757 remove,
758 ]));
759 }
760 app.replaceChildren(section);
761 document.title = page.title + ' · Wiki · Verhalenboek';
762}
763
764async function paintWikiIndex() {
765 const data = await api('GET', '/wiki/categories');
766 const query = el('input', { type: 'search', maxlength: '200', placeholder: 'Zoek op titel of tekst' });
767 query.value = state.wikiQuery || '';
768 const form = el('form', { class: 'wiki-search' }, [
769 el('label', {}, ['Zoeken', query]),
770 el('button', { class: 'quiet', type: 'submit' }, ['Zoeken']),
771 ]);
772 form.addEventListener('submit', (event) => {
773 event.preventDefault();
774 state.wikiQuery = query.value.trim();
775 render();
776 });
777 const section = el('section', { class: 'panel' }, [
778 el('h1', {}, ['Wiki']),
779 el('p', { class: 'lede' }, ['Achtergrond bij de verhalen, per categorie.']),
780 form,
781 ]);
782 if (state.me.admin) {
783 section.append(el('div', { class: 'wiki-actions' }, [
784 el('a', { class: 'button primary', href: '#/wiki/categorie/nieuw' }, ['Nieuwe categorie']),
785 el('a', { class: 'button quiet', href: '#/wiki/nieuw' }, ['Nieuwe pagina']),
786 ]));
787 }
788 if (state.wikiQuery) {
789 const found = await api('GET', '/wiki/pages?q=' + encodeURIComponent(state.wikiQuery));
790 const results = el('div', {});
791 found.pages.forEach((page) => {
792 results.append(el('a', { class: 'wiki-result', href: '#/wiki/' + page.slug }, [
793 el('strong', {}, [page.title]),
794 document.createElement('br'),
795 el('small', {}, [page.category.title]),
796 ]));
797 });
798 if (!found.pages.length) results.append(el('p', { class: 'empty' }, ['Geen pagina\'s gevonden.']));
799 section.append(el('h2', {}, ['Resultaten']), results);
800 }
801 if (!data.categories.length) section.append(el('p', { class: 'empty' }, ['Nog geen categorieën.']));
802 data.categories.forEach((category) => {
803 const head = el('div', { class: 'wiki-cat-head' }, [el('h2', {}, [category.title])]);
804 if (state.me.admin) {
805 head.append(el('a', { class: 'button quiet', href: '#/wiki/categorie/' + category.slug }, ['Wijzig']));
806 }
807 const block = el('section', { class: 'wiki-category' }, [head]);
808 if (!category.pages.length) block.append(el('p', { class: 'empty' }, ['Nog geen pagina\'s.']));
809 category.pages.forEach((page) => {
810 block.append(el('a', { class: 'wiki-page-link', href: '#/wiki/' + page.slug }, [page.title]));
811 });
812 if (state.me.admin) {
813 block.append(el('p', {}, [el('a', { href: '#/wiki/nieuw/' + category.slug }, ['Pagina in ' + category.title])]));
814 }
815 section.append(block);
816 });
817 app.replaceChildren(section);
818 document.title = 'Wiki · Verhalenboek';
819}
820
821async function paintWikiCategoryForm(slug) {
822 const creating = !slug;
823 const existing = creating ? { title: '', slug: '' } : await api('GET', '/wiki/categories/' + slug);
824 const title = el('input', { type: 'text', maxlength: '80', required: 'required' });
825 title.value = existing.title || '';
826 const slugInput = el('input', { type: 'text', maxlength: '80', spellcheck: 'false', autocapitalize: 'off' });
827 slugInput.value = existing.slug || '';
828 const error = el('p', { class: 'form-error' });
829 const form = el('form', { class: 'editor' }, [
830 el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]),
831 el('h1', {}, [creating ? 'Nieuwe categorie' : 'Categorie wijzigen']),
832 el('label', {}, ['Titel', title]),
833 el('label', {}, ['Slug', slugInput]),
834 el('p', { class: 'hint' }, ['Leeg laten maakt een slug van de titel. Alleen kleine letters, cijfers en streepjes.']),
835 error,
836 el('button', { class: 'primary', type: 'submit' }, ['Opslaan']),
837 ]);
838 form.addEventListener('submit', async (event) => {
839 event.preventDefault();
840 error.textContent = '';
841 const payload = { title: title.value };
842 if (slugInput.value.trim() !== '') payload.slug = slugInput.value.trim();
843 else if (!creating) payload.slug = '';
844 try {
845 const saved = creating
846 ? await api('POST', '/wiki/categories', payload)
847 : await api('PUT', '/wiki/categories/' + slug, payload);
848 toast('Opgeslagen.');
849 navigateHash('#/wiki');
850 } catch (failure) { error.textContent = failure.message; }
851 });
852 if (!creating) {
853 const remove = el('button', { class: 'danger', type: 'button' }, ['Categorie verwijderen']);
854 remove.addEventListener('click', async () => {
855 if (!window.confirm('Deze categorie verwijderen? Dat kan alleen als er geen pagina\'s meer in staan.')) return;
856 try {
857 await api('DELETE', '/wiki/categories/' + slug);
858 navigateHash('#/wiki');
859 } catch (failure) { error.textContent = failure.message; }
860 });
861 form.append(remove);
862 }
863 app.replaceChildren(form);
864 document.title = (creating ? 'Nieuwe categorie' : existing.title) + ' · Wiki · Verhalenboek';
865}
866
867async function paintWikiPageForm(slug, presetCategory) {
868 const creating = !slug;
869 const [listed, existing] = await Promise.all([
870 api('GET', '/wiki/categories'),
871 creating ? Promise.resolve(null) : api('GET', '/wiki/pages/' + slug),
872 ]);
873 if (!listed.categories.length) {
874 app.replaceChildren(el('section', { class: 'panel' }, [
875 el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]),
876 el('h1', {}, ['Nieuwe pagina']),
877 el('p', { class: 'empty' }, ['Maak eerst een categorie.']),
878 el('a', { class: 'button primary', href: '#/wiki/categorie/nieuw' }, ['Nieuwe categorie']),
879 ]));
880 return;
881 }
882 const title = el('input', { type: 'text', maxlength: '200', required: 'required' });
883 title.value = existing ? existing.title : '';
884 const slugInput = el('input', { type: 'text', maxlength: '80', spellcheck: 'false', autocapitalize: 'off' });
885 slugInput.value = existing ? existing.slug : '';
886 const chosen = existing ? existing.category.slug : presetCategory;
887 const select = el('select', { required: 'required' });
888 listed.categories.forEach((category) => {
889 select.append(el('option', {
890 value: category.slug,
891 selected: category.slug === chosen ? 'selected' : null,
892 }, [category.title]));
893 });
894 const content = el('textarea', { class: 'wiki-source', rows: '14' });
895 content.value = existing ? existing.content : '';
896 const error = el('p', { class: 'form-error' });
897 const form = el('form', { class: 'editor' }, [
898 el('p', { class: 'pager' }, [el('a', { href: creating ? '#/wiki' : '#/wiki/' + slug }, [creating ? '← Wiki' : '← Pagina'])]),
899 el('h1', {}, [creating ? 'Nieuwe pagina' : 'Pagina bewerken']),
900 el('label', {}, ['Categorie', select]),
901 el('label', {}, ['Titel', title]),
902 el('label', {}, ['Slug', slugInput]),
903 el('label', {}, ['Tekst', content]),
904 el('p', { class: 'hint' }, [
905 'Een hoofdstuk begint met ## en een titel op een eigen regel. Verwijzingen: [[pagina-slug]], [[#hoofdstuk]] en [[pagina-slug#hoofdstuk|tekst]]. Een kapotte verwijzing blijft zichtbaar en is geen link.',
906 ]),
907 error,
908 el('button', { class: 'primary', type: 'submit' }, ['Opslaan']),
909 ]);
910 form.addEventListener('submit', async (event) => {
911 event.preventDefault();
912 error.textContent = '';
913 const payload = { title: title.value, category: select.value, content: content.value };
914 if (slugInput.value.trim() !== '') payload.slug = slugInput.value.trim();
915 else if (!creating) payload.slug = '';
916 try {
917 const saved = creating
918 ? await api('POST', '/wiki/pages', payload)
919 : await api('PUT', '/wiki/pages/' + slug, payload);
920 toast('Opgeslagen.');
921 navigateHash('#/wiki/' + saved.slug);
922 } catch (failure) { error.textContent = failure.message; }
923 });
924 app.replaceChildren(form);
925 document.title = (creating ? 'Nieuwe pagina' : 'Bewerken') + ' · Wiki · Verhalenboek';
926}
927
928function wikiDenied() {
929 app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit wijzigen.']), el('a', { href: '#/wiki' }, ['Naar de wiki']));
930}
931
681async function render() {
932async function render() {
682 const token = ++renderToken;
933 const token = ++renderToken;
683 const path = pathNow();
934 const path = pathNow();
@@ -687,6 +938,7 @@ async function render() {
687 state.freshKey = null;
938 state.freshKey = null;
688 state.revealedKey = null;
939 state.revealedKey = null;
689 }
940 }
941 if (path !== '/wiki' && !path.startsWith('/wiki/')) state.wikiQuery = '';
690 closeMenu();
942 closeMenu();
691 highlight(path);
943 highlight(path);
692 document.title = 'Verhalenboek';
944 document.title = 'Verhalenboek';
@@ -707,6 +959,26 @@ async function render() {
707 if (token !== renderToken) return;
959 if (token !== renderToken) return;
708 paintFriendReads((friends && friends.days) || {});
960 paintFriendReads((friends && friends.days) || {});
709 });
961 });
962 } else if (path === '/wiki') {
963 await paintWikiIndex();
964 } else if (path === '/wiki/categorie/nieuw') {
965 if (!state.me.admin) { wikiDenied(); return; }
966 await paintWikiCategoryForm(null);
967 } else if (/^\/wiki\/categorie\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) {
968 if (!state.me.admin) { wikiDenied(); return; }
969 await paintWikiCategoryForm(path.slice('/wiki/categorie/'.length));
970 } else if (path === '/wiki/nieuw' || /^\/wiki\/nieuw\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) {
971 if (!state.me.admin) { wikiDenied(); return; }
972 const preset = path === '/wiki/nieuw' ? null : path.slice('/wiki/nieuw/'.length);
973 await paintWikiPageForm(null, preset);
974 } else if (/^\/wiki\/bewerken\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) {
975 if (!state.me.admin) { wikiDenied(); return; }
976 await paintWikiPageForm(path.slice('/wiki/bewerken/'.length), null);
977 } else if (wikiReading(path)) {
978 const reading = wikiReading(path);
979 const page = await api('GET', '/wiki/pages/' + reading.slug);
980 if (token !== renderToken) return;
981 paintWikiArticle(page, reading.anchor);
710 } else if (path === '/instellingen') {
982 } else if (path === '/instellingen') {
711 paintSettings();
983 paintSettings();
712 } else if (path === '/beheer') {
984 } else if (path === '/beheer') {
web/docs.php +58 −0
@@ -77,6 +77,64 @@ curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
77 77 -d '{"title":"Middaglicht","paragraphs":["De schaduw werd korter."] }' \
78 78 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/days/2026-10-05/stories/2'</code></pre>
79 79 <p>Lezers gebruiken deze sleutel niet. Hun gelezen-status hoort bij een ingelogde sessie: POST of DELETE <code>/days/JJJJ-MM-DD/read</code>.</p>
80 <h2>Wiki</h2>
81 <p>De wiki staat in de app onder het tabblad Wiki, naast Overzicht. Pagina's horen bij een categorie, bijvoorbeeld Vriendjes, Plekken of Speeltjes. Elke pagina heeft een titel, een slug en hoofdstukken. Een hoofdstuk is een regel die begint met <code>##</code> en een spatie, gevolgd door de titel. Tekst vóór het eerste hoofdstuk is de inleiding.</p>
82 <p>Lezen mag een ingelogde lezer en een API-sleutel. Aanmaken, wijzigen en verwijderen mag een ingelogde beheerder of dezelfde Bearer-sleutel als bij <code>/days</code>. Een lezer die schrijft krijgt 403, met <code>how_to_authenticate</code>. De sleutel hoeft geen CSRF-header te sturen. Een beheerder in de browser wel, net als bij de dagen.</p>
83 <table>
84 <thead><tr><th>Methode</th><th>Pad</th><th>Wat</th></tr></thead>
85 <tbody>
86 <tr><td>GET</td><td><code>/wiki/categories</code></td><td>Alle categorieën, op positie. Elke categorie bevat <code>slug</code>, <code>title</code>, <code>position</code> en <code>pages</code> (slug, titel, positie).</td></tr>
87 <tr><td>POST</td><td><code>/wiki/categories</code></td><td>Nieuwe categorie. Verplicht: <code>title</code>. Optioneel: <code>slug</code>, <code>position</code>. 201.</td></tr>
88 <tr><td>GET</td><td><code>/wiki/categories/slug</code></td><td>Eén categorie met haar pagina's.</td></tr>
89 <tr><td>PUT</td><td><code>/wiki/categories/slug</code></td><td>Werk titel, slug en/of positie bij. Minstens één veld.</td></tr>
90 <tr><td>DELETE</td><td><code>/wiki/categories/slug</code></td><td>Verwijder de categorie. 409 zolang er nog pagina's in staan.</td></tr>
91 <tr><td>GET</td><td><code>/wiki/pages</code></td><td>Pagina's, zonder de lopende tekst. <code>?q=</code> zoekt in titel en tekst, hoofdletterongevoelig. <code>?category=slug</code> beperkt tot één categorie. Beide mogen samen.</td></tr>
92 <tr><td>POST</td><td><code>/wiki/pages</code></td><td>Nieuwe pagina. Verplicht: <code>title</code> en <code>category</code> (de slug van de categorie). Optioneel: <code>slug</code>, <code>content</code>, <code>position</code>. 201.</td></tr>
93 <tr><td>GET</td><td><code>/wiki/pages/slug</code></td><td>Pagina met <code>content</code>, <code>category</code> en <code>chapters</code>. Elk hoofdstuk heeft <code>anchor</code>, <code>title</code> en <code>blocks</code>.</td></tr>
94 <tr><td>PUT</td><td><code>/wiki/pages/slug</code></td><td>Werk titel, slug, categorie, tekst en/of positie bij. Minstens één veld. Een lege <code>slug</code> wordt opnieuw uit de titel gemaakt.</td></tr>
95 <tr><td>DELETE</td><td><code>/wiki/pages/slug</code></td><td>Verwijder de pagina.</td></tr>
96 </tbody>
97 </table>
98 <p>Een slug is klein, met letters, cijfers en streepjes, bijvoorbeeld <code>oude-plein</code>. Ontbreekt hij, dan maakt de server hem uit de titel. <code>nieuw</code>, <code>bewerken</code> en <code>categorie</code> zijn gereserveerd voor pagina's; <code>nieuw</code> ook voor categorieën. Een bezette slug geeft 409. Een onbekende slug geeft 404. Een lege titel, een te lange tekst of een hoofdstuk zonder titel geeft 422.</p>
99 <h3>Hoofdstukken en ankers</h3>
100 <p>Het anker is de slug van de hoofdstuktitel, stabiel zolang de titel en de volgorde van gelijke titels hetzelfde blijven. <code>## De boom</code> wordt <code>de-boom</code>. Een tweede hoofdstuk met dezelfde titel wordt <code>de-boom-2</code>, daarna <code>de-boom-3</code>. De inleiding, als die er is, heeft altijd het anker <code>inleiding</code>. In het antwoord is <code>title</code> daar <code>null</code>.</p>
101 <p>Alinea's scheid je met een lege regel. Een regeleinde binnen een alinea wordt een spatie. HTML wordt niet gelezen: wat je typt blijft tekst.</p>
102 <h3>Verwijzingen in de tekst</h3>
103 <p>In de tekst van een pagina schrijf je een verwijzing tussen dubbele rechte haken. Het doel is altijd een slug, geen titel. Een eigen zichtbare tekst zet je achter een staande streep. De streep en de tekst zijn optioneel.</p>
104 <table>
105 <thead><tr><th>Schrijfwijze</th><th>Gaat naar</th></tr></thead>
106 <tbody>
107 <tr><td><code>[[pagina-slug]]</code></td><td>Een andere pagina. Zonder eigen tekst wordt de paginatitel getoond.</td></tr>
108 <tr><td><code>[[pagina-slug|tekst]]</code></td><td>Die pagina, met de tekst die je achter de streep zet.</td></tr>
109 <tr><td><code>[[#hoofdstuk]]</code></td><td>Een hoofdstuk op dezelfde pagina. Zonder eigen tekst wordt de hoofdstuktitel getoond.</td></tr>
110 <tr><td><code>[[#hoofdstuk|tekst]]</code></td><td>Dat hoofdstuk, met eigen tekst.</td></tr>
111 <tr><td><code>[[pagina-slug#hoofdstuk]]</code></td><td>Een hoofdstuk op een andere pagina.</td></tr>
112 <tr><td><code>[[pagina-slug#hoofdstuk|tekst]]</code></td><td>Dat hoofdstuk, met eigen tekst.</td></tr>
113 </tbody>
114 </table>
115 <p>Een verwijzing die nergens heen wijst — onbekende pagina, onbekend anker, of een slug die niet aan het patroon voldoet — blijft in de tekst staan en is geen link. In de JSON heeft zo'n stuk <code>"broken": true</code> en geen <code>page</code>. In de app staat er „ontbreekt” achter. Een stuk als <code>&lt;script&gt;</code> of <code>javascript:</code> wordt gewone tekst en wordt niet uitgevoerd.</p>
116 <p>In het antwoord bestaat een alinea uit <code>inlines</code>. Een tekststuk is <code>{"type":"text","text":"…"}</code>. Een verwijzing is <code>{"type":"link","page":"oude-plein","anchor":"de-boom","text":"de boom","broken":false}</code>. <code>anchor</code> is <code>null</code> als de verwijzing de hele pagina bedoelt.</p>
117 <h3>Voorbeeld</h3>
118 <pre><code>curl -sS -X POST \
119 -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
120 -H 'Accept: application/json' \
121 -H 'Content-Type: application/json' \
122 -d '{"title":"Plekken"}' \
123 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/categories'
124
125 curl -sS -X POST \
126 -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
127 -H 'Accept: application/json' \
128 -H 'Content-Type: application/json' \
129 -d '{"title":"Het oude plein","slug":"oude-plein","category":"plekken","content":"Achter de huizen.\n\n## De boom\n\nHier komt [[bas#wie-hij-is|Bas]] vaak.\n\n## De bank\n\nZie ook [[#de-boom]]."}' \
130 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/pages'
131
132 curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
133 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/pages?q=boom&amp;category=plekken'
134
135 curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
136 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/pages/oude-plein'</code></pre>
137 <p><code>GET /wiki/pages/oude-plein</code> geeft de hoofdstukken <code>inleiding</code>, <code>de-boom</code> en <code>de-bank</code>. De eerste verwijzing wijst naar hoofdstuk <code>wie-hij-is</code> op pagina <code>bas</code>. Bestaat die niet, dan is de verwijzing kapot en blijft de tekst „Bas” staan. De tweede verwijzing springt naar <code>de-boom</code> op dezelfde pagina.</p>
80 138 </article>
81 139 </body>
82 140 </html>
@@ -77,6 +77,64 @@ curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
77 -d '{"title":"Middaglicht","paragraphs":["De schaduw werd korter."] }' \
77 -d '{"title":"Middaglicht","paragraphs":["De schaduw werd korter."] }' \
78 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/days/2026-10-05/stories/2'</code></pre>
78 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/days/2026-10-05/stories/2'</code></pre>
79<p>Lezers gebruiken deze sleutel niet. Hun gelezen-status hoort bij een ingelogde sessie: POST of DELETE <code>/days/JJJJ-MM-DD/read</code>.</p>
79<p>Lezers gebruiken deze sleutel niet. Hun gelezen-status hoort bij een ingelogde sessie: POST of DELETE <code>/days/JJJJ-MM-DD/read</code>.</p>
80<h2>Wiki</h2>
81<p>De wiki staat in de app onder het tabblad Wiki, naast Overzicht. Pagina's horen bij een categorie, bijvoorbeeld Vriendjes, Plekken of Speeltjes. Elke pagina heeft een titel, een slug en hoofdstukken. Een hoofdstuk is een regel die begint met <code>##</code> en een spatie, gevolgd door de titel. Tekst vóór het eerste hoofdstuk is de inleiding.</p>
82<p>Lezen mag een ingelogde lezer en een API-sleutel. Aanmaken, wijzigen en verwijderen mag een ingelogde beheerder of dezelfde Bearer-sleutel als bij <code>/days</code>. Een lezer die schrijft krijgt 403, met <code>how_to_authenticate</code>. De sleutel hoeft geen CSRF-header te sturen. Een beheerder in de browser wel, net als bij de dagen.</p>
83<table>
84<thead><tr><th>Methode</th><th>Pad</th><th>Wat</th></tr></thead>
85<tbody>
86<tr><td>GET</td><td><code>/wiki/categories</code></td><td>Alle categorieën, op positie. Elke categorie bevat <code>slug</code>, <code>title</code>, <code>position</code> en <code>pages</code> (slug, titel, positie).</td></tr>
87<tr><td>POST</td><td><code>/wiki/categories</code></td><td>Nieuwe categorie. Verplicht: <code>title</code>. Optioneel: <code>slug</code>, <code>position</code>. 201.</td></tr>
88<tr><td>GET</td><td><code>/wiki/categories/slug</code></td><td>Eén categorie met haar pagina's.</td></tr>
89<tr><td>PUT</td><td><code>/wiki/categories/slug</code></td><td>Werk titel, slug en/of positie bij. Minstens één veld.</td></tr>
90<tr><td>DELETE</td><td><code>/wiki/categories/slug</code></td><td>Verwijder de categorie. 409 zolang er nog pagina's in staan.</td></tr>
91<tr><td>GET</td><td><code>/wiki/pages</code></td><td>Pagina's, zonder de lopende tekst. <code>?q=</code> zoekt in titel en tekst, hoofdletterongevoelig. <code>?category=slug</code> beperkt tot één categorie. Beide mogen samen.</td></tr>
92<tr><td>POST</td><td><code>/wiki/pages</code></td><td>Nieuwe pagina. Verplicht: <code>title</code> en <code>category</code> (de slug van de categorie). Optioneel: <code>slug</code>, <code>content</code>, <code>position</code>. 201.</td></tr>
93<tr><td>GET</td><td><code>/wiki/pages/slug</code></td><td>Pagina met <code>content</code>, <code>category</code> en <code>chapters</code>. Elk hoofdstuk heeft <code>anchor</code>, <code>title</code> en <code>blocks</code>.</td></tr>
94<tr><td>PUT</td><td><code>/wiki/pages/slug</code></td><td>Werk titel, slug, categorie, tekst en/of positie bij. Minstens één veld. Een lege <code>slug</code> wordt opnieuw uit de titel gemaakt.</td></tr>
95<tr><td>DELETE</td><td><code>/wiki/pages/slug</code></td><td>Verwijder de pagina.</td></tr>
96</tbody>
97</table>
98<p>Een slug is klein, met letters, cijfers en streepjes, bijvoorbeeld <code>oude-plein</code>. Ontbreekt hij, dan maakt de server hem uit de titel. <code>nieuw</code>, <code>bewerken</code> en <code>categorie</code> zijn gereserveerd voor pagina's; <code>nieuw</code> ook voor categorieën. Een bezette slug geeft 409. Een onbekende slug geeft 404. Een lege titel, een te lange tekst of een hoofdstuk zonder titel geeft 422.</p>
99<h3>Hoofdstukken en ankers</h3>
100<p>Het anker is de slug van de hoofdstuktitel, stabiel zolang de titel en de volgorde van gelijke titels hetzelfde blijven. <code>## De boom</code> wordt <code>de-boom</code>. Een tweede hoofdstuk met dezelfde titel wordt <code>de-boom-2</code>, daarna <code>de-boom-3</code>. De inleiding, als die er is, heeft altijd het anker <code>inleiding</code>. In het antwoord is <code>title</code> daar <code>null</code>.</p>
101<p>Alinea's scheid je met een lege regel. Een regeleinde binnen een alinea wordt een spatie. HTML wordt niet gelezen: wat je typt blijft tekst.</p>
102<h3>Verwijzingen in de tekst</h3>
103<p>In de tekst van een pagina schrijf je een verwijzing tussen dubbele rechte haken. Het doel is altijd een slug, geen titel. Een eigen zichtbare tekst zet je achter een staande streep. De streep en de tekst zijn optioneel.</p>
104<table>
105<thead><tr><th>Schrijfwijze</th><th>Gaat naar</th></tr></thead>
106<tbody>
107<tr><td><code>[[pagina-slug]]</code></td><td>Een andere pagina. Zonder eigen tekst wordt de paginatitel getoond.</td></tr>
108<tr><td><code>[[pagina-slug|tekst]]</code></td><td>Die pagina, met de tekst die je achter de streep zet.</td></tr>
109<tr><td><code>[[#hoofdstuk]]</code></td><td>Een hoofdstuk op dezelfde pagina. Zonder eigen tekst wordt de hoofdstuktitel getoond.</td></tr>
110<tr><td><code>[[#hoofdstuk|tekst]]</code></td><td>Dat hoofdstuk, met eigen tekst.</td></tr>
111<tr><td><code>[[pagina-slug#hoofdstuk]]</code></td><td>Een hoofdstuk op een andere pagina.</td></tr>
112<tr><td><code>[[pagina-slug#hoofdstuk|tekst]]</code></td><td>Dat hoofdstuk, met eigen tekst.</td></tr>
113</tbody>
114</table>
115<p>Een verwijzing die nergens heen wijst — onbekende pagina, onbekend anker, of een slug die niet aan het patroon voldoet — blijft in de tekst staan en is geen link. In de JSON heeft zo'n stuk <code>"broken": true</code> en geen <code>page</code>. In de app staat er „ontbreekt” achter. Een stuk als <code>&lt;script&gt;</code> of <code>javascript:</code> wordt gewone tekst en wordt niet uitgevoerd.</p>
116<p>In het antwoord bestaat een alinea uit <code>inlines</code>. Een tekststuk is <code>{"type":"text","text":"…"}</code>. Een verwijzing is <code>{"type":"link","page":"oude-plein","anchor":"de-boom","text":"de boom","broken":false}</code>. <code>anchor</code> is <code>null</code> als de verwijzing de hele pagina bedoelt.</p>
117<h3>Voorbeeld</h3>
118<pre><code>curl -sS -X POST \
119 -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
120 -H 'Accept: application/json' \
121 -H 'Content-Type: application/json' \
122 -d '{"title":"Plekken"}' \
123 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/categories'
124
125curl -sS -X POST \
126 -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
127 -H 'Accept: application/json' \
128 -H 'Content-Type: application/json' \
129 -d '{"title":"Het oude plein","slug":"oude-plein","category":"plekken","content":"Achter de huizen.\n\n## De boom\n\nHier komt [[bas#wie-hij-is|Bas]] vaak.\n\n## De bank\n\nZie ook [[#de-boom]]."}' \
130 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/pages'
131
132curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
133 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/pages?q=boom&amp;category=plekken'
134
135curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
136 '<?= htmlspecialchars($base, ENT_QUOTES) ?>/api.php/wiki/pages/oude-plein'</code></pre>
137<p><code>GET /wiki/pages/oude-plein</code> geeft de hoofdstukken <code>inleiding</code>, <code>de-boom</code> en <code>de-bank</code>. De eerste verwijzing wijst naar hoofdstuk <code>wie-hij-is</code> op pagina <code>bas</code>. Bestaat die niet, dan is de verwijzing kapot en blijft de tekst „Bas” staan. De tweede verwijzing springt naar <code>de-boom</code> op dezelfde pagina.</p>
80</article>
138</article>
81</body>
139</body>
82</html>
140</html>
web/index.php +1 −0
@@ -37,6 +37,7 @@ $themeColor = $theme === 'dark' ? '#141210' : '#f4efe6';
37 37 <a class="brand" href="#/"><img src="<?= htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES) ?>" alt="">Verhalenboek</a>
38 38 <nav class="nav" aria-label="Hoofdmenu">
39 39 <a href="#/" data-nav="/">Overzicht</a>
40 <a href="#/wiki" data-nav="/wiki">Wiki</a>
40 41 <a href="#/instellingen" data-nav="/instellingen">Instellingen</a>
41 42 <?php if (($prefs['role'] ?? '') === 'admin'): ?>
42 43 <a href="#/beheer" data-nav="/beheer">Beheer</a>
@@ -37,6 +37,7 @@ $themeColor = $theme === 'dark' ? '#141210' : '#f4efe6';
37 <a class="brand" href="#/"><img src="<?= htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES) ?>" alt="">Verhalenboek</a>
37 <a class="brand" href="#/"><img src="<?= htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES) ?>" alt="">Verhalenboek</a>
38 <nav class="nav" aria-label="Hoofdmenu">
38 <nav class="nav" aria-label="Hoofdmenu">
39 <a href="#/" data-nav="/">Overzicht</a>
39 <a href="#/" data-nav="/">Overzicht</a>
40 <a href="#/wiki" data-nav="/wiki">Wiki</a>
40 <a href="#/instellingen" data-nav="/instellingen">Instellingen</a>
41 <a href="#/instellingen" data-nav="/instellingen">Instellingen</a>
41 <?php if (($prefs['role'] ?? '') === 'admin'): ?>
42 <?php if (($prefs['role'] ?? '') === 'admin'): ?>
42 <a href="#/beheer" data-nav="/beheer">Beheer</a>
43 <a href="#/beheer" data-nav="/beheer">Beheer</a>
web/lib/Wiki.php added +486 −0
@@ -0,0 +1,486 @@
1 <?php
2 declare(strict_types=1);
3
4 function 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> */
9 function wikiReservedPageSlugs(): array {
10 return ['nieuw', 'bewerken', 'categorie'];
11 }
12
13 /** @return list<string> */
14 function wikiReservedCategorySlugs(): array {
15 return ['nieuw'];
16 }
17
18 function 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
37 function 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
52 function 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
62 function 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
70 function 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
77 function 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
84 function wikiNextCategoryPosition(): int {
85 return (int)query('SELECT COALESCE(MAX(position), 0) FROM wiki_categories')->fetchColumn() + 1;
86 }
87
88 function 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}> */
93 function 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
102 function 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
111 function listWikiCategories(): array {
112 $rows = query('SELECT * FROM wiki_categories ORDER BY position, title, slug')->fetchAll();
113 return ['categories' => array_map('wikiCategoryPayload', $rows)];
114 }
115
116 function loadWikiCategory(string $slug): array {
117 return wikiCategoryPayload(wikiCategoryRow($slug));
118 }
119
120 function 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
136 function 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
163 function 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
173 function 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
183 function 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 */
215 function 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 */
245 function 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>>}> */
272 function 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>> */
285 function 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> */
303 function 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>>}> */
337 function 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 */
354 function 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 */
380 function 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
404 function 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
422 function 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
442 function 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
480 function 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 }
@@ -0,0 +1,486 @@
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}
web/lib/bootstrap.php +21 −1
@@ -1,6 +1,7 @@
1 1 <?php
2 2 declare(strict_types=1);
3 3 require_once __DIR__.'/Storybook.php';
4 require_once __DIR__.'/Wiki.php';
4 5 ini_set('display_errors', '0');
5 6 ini_set('log_errors', '1');
6 7 ini_set('error_log', dataDir().'/php-errors.log');
@@ -72,7 +73,26 @@ function db(): PDO {
72 73 token_cipher TEXT NOT NULL DEFAULT \'\',
73 74 created INTEGER NOT NULL,
74 75 revoked INTEGER
75 );');
76 );
77 CREATE TABLE IF NOT EXISTS wiki_categories (
78 id INTEGER PRIMARY KEY AUTOINCREMENT,
79 slug TEXT NOT NULL UNIQUE,
80 title TEXT NOT NULL,
81 position INTEGER NOT NULL,
82 created INTEGER NOT NULL,
83 updated INTEGER NOT NULL
84 );
85 CREATE TABLE IF NOT EXISTS wiki_pages (
86 id INTEGER PRIMARY KEY AUTOINCREMENT,
87 category_id INTEGER NOT NULL REFERENCES wiki_categories(id),
88 slug TEXT NOT NULL UNIQUE,
89 title TEXT NOT NULL,
90 content TEXT NOT NULL,
91 position INTEGER NOT NULL,
92 created INTEGER NOT NULL,
93 updated INTEGER NOT NULL
94 );
95 CREATE INDEX IF NOT EXISTS wiki_pages_category ON wiki_pages(category_id, position);');
76 96 $columns = array_column($db->query('PRAGMA table_info(api_keys)')->fetchAll(), 'name');
77 97 if (!in_array('token_cipher', $columns, true)) {
78 98 $db->exec("ALTER TABLE api_keys ADD COLUMN token_cipher TEXT NOT NULL DEFAULT ''");
@@ -1,6 +1,7 @@
1<?php
1<?php
2declare(strict_types=1);
2declare(strict_types=1);
3require_once __DIR__.'/Storybook.php';
3require_once __DIR__.'/Storybook.php';
4require_once __DIR__.'/Wiki.php';
4ini_set('display_errors', '0');
5ini_set('display_errors', '0');
5ini_set('log_errors', '1');
6ini_set('log_errors', '1');
6ini_set('error_log', dataDir().'/php-errors.log');
7ini_set('error_log', dataDir().'/php-errors.log');
@@ -72,7 +73,26 @@ function db(): PDO {
72 token_cipher TEXT NOT NULL DEFAULT \'\',
73 token_cipher TEXT NOT NULL DEFAULT \'\',
73 created INTEGER NOT NULL,
74 created INTEGER NOT NULL,
74 revoked INTEGER
75 revoked INTEGER
75 );');
76 );
77 CREATE TABLE IF NOT EXISTS wiki_categories (
78 id INTEGER PRIMARY KEY AUTOINCREMENT,
79 slug TEXT NOT NULL UNIQUE,
80 title TEXT NOT NULL,
81 position INTEGER NOT NULL,
82 created INTEGER NOT NULL,
83 updated INTEGER NOT NULL
84 );
85 CREATE TABLE IF NOT EXISTS wiki_pages (
86 id INTEGER PRIMARY KEY AUTOINCREMENT,
87 category_id INTEGER NOT NULL REFERENCES wiki_categories(id),
88 slug TEXT NOT NULL UNIQUE,
89 title TEXT NOT NULL,
90 content TEXT NOT NULL,
91 position INTEGER NOT NULL,
92 created INTEGER NOT NULL,
93 updated INTEGER NOT NULL
94 );
95 CREATE INDEX IF NOT EXISTS wiki_pages_category ON wiki_pages(category_id, position);');
76 $columns = array_column($db->query('PRAGMA table_info(api_keys)')->fetchAll(), 'name');
96 $columns = array_column($db->query('PRAGMA table_info(api_keys)')->fetchAll(), 'name');
77 if (!in_array('token_cipher', $columns, true)) {
97 if (!in_array('token_cipher', $columns, true)) {
78 $db->exec("ALTER TABLE api_keys ADD COLUMN token_cipher TEXT NOT NULL DEFAULT ''");
98 $db->exec("ALTER TABLE api_keys ADD COLUMN token_cipher TEXT NOT NULL DEFAULT ''");
web/sw.js +5 −2
@@ -1,7 +1,9 @@
1 1 'use strict';
2 2
3 // Shell-cache voor offline lezen. API, inloggen en andere schrijfacties gaan altijd naar het netwerk.
4 const CACHE = 'verhalenboek-v1';
3 // Shell-cache voor offline lezen. API, wiki-schrijfacties, inloggen en andere
4 // schrijfacties gaan altijd naar het netwerk. Wiki leest en schrijft via api.php
5 // (Bearer of sessie); die paden worden hieronder overgeslagen en nooit gecachet.
6 const CACHE = 'verhalenboek-v2';
5 7 const PRECACHE = [
6 8 'assets/favicon.svg',
7 9 'assets/favicon-32.png',
@@ -68,6 +70,7 @@ async function activateShell() {
68 70 }
69 71
70 72 function bypass(url) {
73 // api.php dekt ook /api.php/wiki/… (categorieën en pagina's). Niet cachen.
71 74 return /\/(?:api|auth|callback)\.php(?:\/|$)/i.test(url.pathname);
72 75 }
73 76
@@ -1,7 +1,9 @@
1'use strict';
1'use strict';
2
2
3// Shell-cache voor offline lezen. API, inloggen en andere schrijfacties gaan altijd naar het netwerk.
3// Shell-cache voor offline lezen. API, wiki-schrijfacties, inloggen en andere
4const CACHE = 'verhalenboek-v1';
4// schrijfacties gaan altijd naar het netwerk. Wiki leest en schrijft via api.php
5// (Bearer of sessie); die paden worden hieronder overgeslagen en nooit gecachet.
6const CACHE = 'verhalenboek-v2';
5const PRECACHE = [
7const PRECACHE = [
6 'assets/favicon.svg',
8 'assets/favicon.svg',
7 'assets/favicon-32.png',
9 'assets/favicon-32.png',
@@ -68,6 +70,7 @@ async function activateShell() {
68}
70}
69
71
70function bypass(url) {
72function bypass(url) {
73 // api.php dekt ook /api.php/wiki/… (categorieën en pagina's). Niet cachen.
71 return /\/(?:api|auth|callback)\.php(?:\/|$)/i.test(url.pathname);
74 return /\/(?:api|auth|callback)\.php(?:\/|$)/i.test(url.pathname);
72}
75}
73
76
web/tests/integration.py +60 −0
@@ -285,6 +285,65 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
285 285 check(all(item['date'] != '2026-05-01' or item['read_at'] for item in export['reads']) or export['reads'] == [], 'Een ongelezen dag staat niet als gelezen in de export')
286 286 check(export['reads'] == [], 'Na ongelezen zit de dag niet meer in de export')
287 287
288 check(reader.request('GET', '/wiki/categories') == {'categories': []}, 'Een lezer mag de wiki lezen')
289 reader_wiki = reader.request('POST', '/wiki/categories', {'title': 'Verboden'}, expected=403)
290 check('API-sleutel of als beheerder' in reader_wiki['how_to_authenticate'] and 'www-authenticate' not in reader.last_headers, 'Een lezer mag de wiki niet schrijven')
291 reader.request('DELETE', '/wiki/pages/bas', expected=403)
292 plekken = bearer.request('POST', '/wiki/categories', {'title': 'Plekken'}, expected=201)
293 check(plekken['slug'] == 'plekken' and plekken['pages'] == [], 'Een sleutel maakt een categorie')
294 bearer.request('POST', '/wiki/categories', {'title': 'Plekken'}, expected=409)
295 bearer.request('POST', '/wiki/categories', {'title': 'Nieuw'}, expected=422)
296 vriendjes = admin.request('POST', '/wiki/categories', {'title': 'Vriendjes'}, expected=201)
297 check(vriendjes['slug'] == 'vriendjes', 'Een beheerder maakt een categorie in de sessie')
298 speeltjes = bearer.request('POST', '/wiki/categories', {'title': 'Speeltjes'}, expected=201)
299 check([item['slug'] for item in bearer.request('GET', '/wiki/categories')['categories']] == ['plekken', 'vriendjes', 'speeltjes'], 'Categorieën komen op volgorde terug')
300 plein = bearer.request('POST', '/wiki/pages', {
301 'title': 'Het oude plein',
302 'slug': 'oude-plein',
303 'category': 'plekken',
304 'content': 'Achter de huizen.\n\n## De boom\n\nEen boom.\n\n## De bank\n\nZie [[#de-boom]].',
305 }, expected=201)
306 check([chapter['anchor'] for chapter in plein['chapters']] == ['inleiding', 'de-boom', 'de-bank'], 'De pagina antwoordt met hoofdstukken en ankers')
307 check(plein['chapters'][2]['blocks'][0]['inlines'][1]['anchor'] == 'de-boom' and plein['chapters'][2]['blocks'][0]['inlines'][1]['broken'] is False, 'Hoofdstuk op dezelfde pagina')
308 kist = bearer.request('POST', '/wiki/pages', {
309 'title': 'Speelgoedkist',
310 'slug': 'speelgoedkist',
311 'category': 'speeltjes',
312 'content': '## Deksel\n\nDe deksel. [[bas#wie-hij-is|Bas]] [[geen-pagina]] <script>alert(1)</script>',
313 }, expected=201)
314 kist_parts = kist['chapters'][0]['blocks'][0]['inlines']
315 kist_links = [part for part in kist_parts if part['type'] == 'link']
316 check(kist_links[0]['text'] == 'Bas' and kist_links[0]['broken'] is True and kist_links[1]['text'] == 'geen-pagina' and kist_links[1]['broken'] is True and kist_links[1]['page'] is None, 'Kapotte verwijzingen blijven in het antwoord')
317 check(any(part['type'] == 'text' and '<script>alert(1)</script>' in part['text'] for part in kist_parts), 'HTML in de wiki blijft tekst')
318 bas = bearer.request('POST', '/wiki/pages', {
319 'title': 'Bas',
320 'category': 'vriendjes',
321 'content': '## Wie hij is\n\nBas speelt op het [[oude-plein|oude plein]] en bij de [[speelgoedkist#deksel|kist]].\n\n## Samen\n\nKlaar.',
322 }, expected=201)
323 check(bas['slug'] == 'bas', 'Slug uit de titel')
324 links = [part for block in bas['chapters'][0]['blocks'] for part in block['inlines'] if part['type'] == 'link']
325 check(links[0]['page'] == 'oude-plein' and links[0]['anchor'] is None and links[0]['text'] == 'oude plein' and links[0]['broken'] is False, 'Link naar een andere pagina')
326 check(links[1]['page'] == 'speelgoedkist' and links[1]['anchor'] == 'deksel' and links[1]['broken'] is False, 'Link naar een hoofdstuk op een andere pagina')
327 check(bearer.request('GET', '/wiki/pages/bas')['title'] == 'Bas', 'Een pagina ophalen op slug')
328 found = bearer.request('GET', '/wiki/pages?q=deksel&category=speeltjes')['pages']
329 check([page['slug'] for page in found] == ['speelgoedkist'] and 'content' not in found[0], 'Zoeken in de tekst, gefilterd op categorie, zonder de lopende tekst')
330 check([page['slug'] for page in bearer.request('GET', '/wiki/pages?q=BANK')['pages']] == ['oude-plein'], 'Zoeken negeert hoofdletters')
331 bearer.request('GET', '/wiki/pages?category=onbekend', expected=404)
332 bearer.request('POST', '/wiki/pages', {'title': 'Nee', 'category': 'vriendjes', 'content': '##\n\nLeeg'}, expected=422)
333 edited = admin.request('PUT', '/wiki/pages/bas', {'title': 'Bas de vriend'})
334 check(edited['title'] == 'Bas de vriend' and edited['slug'] == 'bas', 'Een beheerder bewerkt een pagina')
335 reader.request('PUT', '/wiki/pages/bas', {'title': 'Nee'}, expected=403)
336 bearer.request('DELETE', '/wiki/categories/vriendjes', expected=409)
337 check(bearer.request('DELETE', '/wiki/pages/bas') == {'ok': True, 'slug': 'bas'}, 'Pagina verwijderen')
338 check(bearer.request('DELETE', '/wiki/categories/vriendjes') == {'ok': True, 'slug': 'vriendjes'}, 'Lege categorie verwijderen')
339 bearer.request('GET', '/wiki/pages/bas', expected=404)
340 bearer.request('PUT', '/wiki/categories', {'title': 'Nee'}, expected=405)
341 bearer.request('DELETE', '/wiki/pages/oude-plein')
342 bearer.request('DELETE', '/wiki/pages/speelgoedkist')
343 bearer.request('DELETE', '/wiki/categories/plekken')
344 bearer.request('DELETE', '/wiki/categories/speeltjes')
345 check(reader.request('GET', '/wiki/categories') == {'categories': []}, 'De wiki is weer leeg')
346
288 347 admin.request('PUT', '/days/2026-05-01', {'title': 'Herziene titel'})
289 348 check(admin.request('GET', '/days/2026-05-01')['title'] == 'Herziene titel', 'Beheerder bewerkt een dag in de sessie')
290 349 admin.request('PUT', '/days/2026-05-01', {'stories': stories()[:1]}, expected=422)
@@ -307,6 +366,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
307 366 docs = urllib.request.urlopen(base + '/docs.php')
308 367 body = docs.read().decode()
309 368 check(docs.status == 200 and 'precies drie verhalen' in body and 'days/latest' in body and 'how_to_authenticate' in body and 'WWW-Authenticate' in body, 'API-documentatie legt authenticatie uit')
369 check('[[pagina-slug#hoofdstuk|tekst]]' in body and '/wiki/pages' in body and 'inleiding' in body and 'broken' in body, 'API-documentatie legt de wiki en de verwijzingen uit')
310 370
311 371 auth_bootstrap = root / 'lib/bootstrap.php'
312 372 auth_bootstrap.write_text(auth_bootstrap.read_text().replace(
@@ -285,6 +285,65 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
285 check(all(item['date'] != '2026-05-01' or item['read_at'] for item in export['reads']) or export['reads'] == [], 'Een ongelezen dag staat niet als gelezen in de export')
285 check(all(item['date'] != '2026-05-01' or item['read_at'] for item in export['reads']) or export['reads'] == [], 'Een ongelezen dag staat niet als gelezen in de export')
286 check(export['reads'] == [], 'Na ongelezen zit de dag niet meer in de export')
286 check(export['reads'] == [], 'Na ongelezen zit de dag niet meer in de export')
287
287
288 check(reader.request('GET', '/wiki/categories') == {'categories': []}, 'Een lezer mag de wiki lezen')
289 reader_wiki = reader.request('POST', '/wiki/categories', {'title': 'Verboden'}, expected=403)
290 check('API-sleutel of als beheerder' in reader_wiki['how_to_authenticate'] and 'www-authenticate' not in reader.last_headers, 'Een lezer mag de wiki niet schrijven')
291 reader.request('DELETE', '/wiki/pages/bas', expected=403)
292 plekken = bearer.request('POST', '/wiki/categories', {'title': 'Plekken'}, expected=201)
293 check(plekken['slug'] == 'plekken' and plekken['pages'] == [], 'Een sleutel maakt een categorie')
294 bearer.request('POST', '/wiki/categories', {'title': 'Plekken'}, expected=409)
295 bearer.request('POST', '/wiki/categories', {'title': 'Nieuw'}, expected=422)
296 vriendjes = admin.request('POST', '/wiki/categories', {'title': 'Vriendjes'}, expected=201)
297 check(vriendjes['slug'] == 'vriendjes', 'Een beheerder maakt een categorie in de sessie')
298 speeltjes = bearer.request('POST', '/wiki/categories', {'title': 'Speeltjes'}, expected=201)
299 check([item['slug'] for item in bearer.request('GET', '/wiki/categories')['categories']] == ['plekken', 'vriendjes', 'speeltjes'], 'Categorieën komen op volgorde terug')
300 plein = bearer.request('POST', '/wiki/pages', {
301 'title': 'Het oude plein',
302 'slug': 'oude-plein',
303 'category': 'plekken',
304 'content': 'Achter de huizen.\n\n## De boom\n\nEen boom.\n\n## De bank\n\nZie [[#de-boom]].',
305 }, expected=201)
306 check([chapter['anchor'] for chapter in plein['chapters']] == ['inleiding', 'de-boom', 'de-bank'], 'De pagina antwoordt met hoofdstukken en ankers')
307 check(plein['chapters'][2]['blocks'][0]['inlines'][1]['anchor'] == 'de-boom' and plein['chapters'][2]['blocks'][0]['inlines'][1]['broken'] is False, 'Hoofdstuk op dezelfde pagina')
308 kist = bearer.request('POST', '/wiki/pages', {
309 'title': 'Speelgoedkist',
310 'slug': 'speelgoedkist',
311 'category': 'speeltjes',
312 'content': '## Deksel\n\nDe deksel. [[bas#wie-hij-is|Bas]] [[geen-pagina]] <script>alert(1)</script>',
313 }, expected=201)
314 kist_parts = kist['chapters'][0]['blocks'][0]['inlines']
315 kist_links = [part for part in kist_parts if part['type'] == 'link']
316 check(kist_links[0]['text'] == 'Bas' and kist_links[0]['broken'] is True and kist_links[1]['text'] == 'geen-pagina' and kist_links[1]['broken'] is True and kist_links[1]['page'] is None, 'Kapotte verwijzingen blijven in het antwoord')
317 check(any(part['type'] == 'text' and '<script>alert(1)</script>' in part['text'] for part in kist_parts), 'HTML in de wiki blijft tekst')
318 bas = bearer.request('POST', '/wiki/pages', {
319 'title': 'Bas',
320 'category': 'vriendjes',
321 'content': '## Wie hij is\n\nBas speelt op het [[oude-plein|oude plein]] en bij de [[speelgoedkist#deksel|kist]].\n\n## Samen\n\nKlaar.',
322 }, expected=201)
323 check(bas['slug'] == 'bas', 'Slug uit de titel')
324 links = [part for block in bas['chapters'][0]['blocks'] for part in block['inlines'] if part['type'] == 'link']
325 check(links[0]['page'] == 'oude-plein' and links[0]['anchor'] is None and links[0]['text'] == 'oude plein' and links[0]['broken'] is False, 'Link naar een andere pagina')
326 check(links[1]['page'] == 'speelgoedkist' and links[1]['anchor'] == 'deksel' and links[1]['broken'] is False, 'Link naar een hoofdstuk op een andere pagina')
327 check(bearer.request('GET', '/wiki/pages/bas')['title'] == 'Bas', 'Een pagina ophalen op slug')
328 found = bearer.request('GET', '/wiki/pages?q=deksel&category=speeltjes')['pages']
329 check([page['slug'] for page in found] == ['speelgoedkist'] and 'content' not in found[0], 'Zoeken in de tekst, gefilterd op categorie, zonder de lopende tekst')
330 check([page['slug'] for page in bearer.request('GET', '/wiki/pages?q=BANK')['pages']] == ['oude-plein'], 'Zoeken negeert hoofdletters')
331 bearer.request('GET', '/wiki/pages?category=onbekend', expected=404)
332 bearer.request('POST', '/wiki/pages', {'title': 'Nee', 'category': 'vriendjes', 'content': '##\n\nLeeg'}, expected=422)
333 edited = admin.request('PUT', '/wiki/pages/bas', {'title': 'Bas de vriend'})
334 check(edited['title'] == 'Bas de vriend' and edited['slug'] == 'bas', 'Een beheerder bewerkt een pagina')
335 reader.request('PUT', '/wiki/pages/bas', {'title': 'Nee'}, expected=403)
336 bearer.request('DELETE', '/wiki/categories/vriendjes', expected=409)
337 check(bearer.request('DELETE', '/wiki/pages/bas') == {'ok': True, 'slug': 'bas'}, 'Pagina verwijderen')
338 check(bearer.request('DELETE', '/wiki/categories/vriendjes') == {'ok': True, 'slug': 'vriendjes'}, 'Lege categorie verwijderen')
339 bearer.request('GET', '/wiki/pages/bas', expected=404)
340 bearer.request('PUT', '/wiki/categories', {'title': 'Nee'}, expected=405)
341 bearer.request('DELETE', '/wiki/pages/oude-plein')
342 bearer.request('DELETE', '/wiki/pages/speelgoedkist')
343 bearer.request('DELETE', '/wiki/categories/plekken')
344 bearer.request('DELETE', '/wiki/categories/speeltjes')
345 check(reader.request('GET', '/wiki/categories') == {'categories': []}, 'De wiki is weer leeg')
346
288 admin.request('PUT', '/days/2026-05-01', {'title': 'Herziene titel'})
347 admin.request('PUT', '/days/2026-05-01', {'title': 'Herziene titel'})
289 check(admin.request('GET', '/days/2026-05-01')['title'] == 'Herziene titel', 'Beheerder bewerkt een dag in de sessie')
348 check(admin.request('GET', '/days/2026-05-01')['title'] == 'Herziene titel', 'Beheerder bewerkt een dag in de sessie')
290 admin.request('PUT', '/days/2026-05-01', {'stories': stories()[:1]}, expected=422)
349 admin.request('PUT', '/days/2026-05-01', {'stories': stories()[:1]}, expected=422)
@@ -307,6 +366,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
307 docs = urllib.request.urlopen(base + '/docs.php')
366 docs = urllib.request.urlopen(base + '/docs.php')
308 body = docs.read().decode()
367 body = docs.read().decode()
309 check(docs.status == 200 and 'precies drie verhalen' in body and 'days/latest' in body and 'how_to_authenticate' in body and 'WWW-Authenticate' in body, 'API-documentatie legt authenticatie uit')
368 check(docs.status == 200 and 'precies drie verhalen' in body and 'days/latest' in body and 'how_to_authenticate' in body and 'WWW-Authenticate' in body, 'API-documentatie legt authenticatie uit')
369 check('[[pagina-slug#hoofdstuk|tekst]]' in body and '/wiki/pages' in body and 'inleiding' in body and 'broken' in body, 'API-documentatie legt de wiki en de verwijzingen uit')
310
370
311 auth_bootstrap = root / 'lib/bootstrap.php'
371 auth_bootstrap = root / 'lib/bootstrap.php'
312 auth_bootstrap.write_text(auth_bootstrap.read_text().replace(
372 auth_bootstrap.write_text(auth_bootstrap.read_text().replace(
web/tests/pwa.py +13 −0
@@ -50,6 +50,11 @@ check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg')
50 50 worker = (WEB / 'sw.js').read_text()
51 51 check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
52 52 check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
53 check('wiki' in worker and '/api.php/wiki/' in worker, 'Service worker noemt wiki-schrijfacties via api.php')
54 import re
55 wiki_bypass = re.compile(r'/(?:api|auth|callback)\.php(?:/|$)', re.I)
56 check(wiki_bypass.search('/verhaaltjesboek/api.php/wiki/pages') and wiki_bypass.search('/verhaaltjesboek/api.php/wiki/categories'), 'Wiki-API valt onder de api.php-uitsluiting')
57 check(worker.index("request.method !== 'GET'") < worker.index('function bypass'), 'Een schrijfactie komt niet in de cache terecht')
53 58 check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
54 59 registrar = (WEB / 'assets/pwa.js').read_text()
55 60 check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')
@@ -158,6 +163,7 @@ with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as
158 163 check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
159 164 check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
160 165 check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
166 check(page.index('>Overzicht<') < page.index('>Wiki<') < page.index('>Instellingen<'), 'Wiki staat in het menu naast Overzicht')
161 167 for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
162 168 status, headers, payload = fetch(base + '/assets/' + name)
163 169 check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
@@ -173,6 +179,13 @@ with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as
173 179 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
174 180 )
175 181 check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
182 status, _, wiki_denied = fetch(
183 base + '/api.php/wiki/categories',
184 method='POST',
185 data=b'{"title":"Plekken"}',
186 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
187 )
188 check(status == 403 and 'Ongeldige sessie' in json.loads(wiki_denied)['error'], 'Wiki-schrijven onder de submap blijft naar PHP gaan')
176 189 status, doc_headers, docs = fetch(base + '/docs.php')
177 190 check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
178 191 finally:
@@ -50,6 +50,11 @@ check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg')
50worker = (WEB / 'sw.js').read_text()
50worker = (WEB / 'sw.js').read_text()
51check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
51check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
52check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
52check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
53check('wiki' in worker and '/api.php/wiki/' in worker, 'Service worker noemt wiki-schrijfacties via api.php')
54import re
55wiki_bypass = re.compile(r'/(?:api|auth|callback)\.php(?:/|$)', re.I)
56check(wiki_bypass.search('/verhaaltjesboek/api.php/wiki/pages') and wiki_bypass.search('/verhaaltjesboek/api.php/wiki/categories'), 'Wiki-API valt onder de api.php-uitsluiting')
57check(worker.index("request.method !== 'GET'") < worker.index('function bypass'), 'Een schrijfactie komt niet in de cache terecht')
53check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
58check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
54registrar = (WEB / 'assets/pwa.js').read_text()
59registrar = (WEB / 'assets/pwa.js').read_text()
55check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')
60check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')
@@ -158,6 +163,7 @@ with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as
158 check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
163 check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
159 check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
164 check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
160 check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
165 check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
166 check(page.index('>Overzicht<') < page.index('>Wiki<') < page.index('>Instellingen<'), 'Wiki staat in het menu naast Overzicht')
161 for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
167 for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
162 status, headers, payload = fetch(base + '/assets/' + name)
168 status, headers, payload = fetch(base + '/assets/' + name)
163 check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
169 check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
@@ -173,6 +179,13 @@ with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as
173 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
179 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
174 )
180 )
175 check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
181 check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
182 status, _, wiki_denied = fetch(
183 base + '/api.php/wiki/categories',
184 method='POST',
185 data=b'{"title":"Plekken"}',
186 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
187 )
188 check(status == 403 and 'Ongeldige sessie' in json.loads(wiki_denied)['error'], 'Wiki-schrijven onder de submap blijft naar PHP gaan')
176 status, doc_headers, docs = fetch(base + '/docs.php')
189 status, doc_headers, docs = fetch(base + '/docs.php')
177 check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
190 check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
178 finally:
191 finally:
web/tests/startup.py +5 −0
@@ -37,8 +37,13 @@ with tempfile.TemporaryDirectory(prefix='startup-', dir=ARTIFACTS) as tmp:
37 37 con.execute("INSERT INTO stories (day_id, position, title, created, updated) VALUES (1,1,'Een',1,1)")
38 38 con.execute("INSERT INTO paragraphs (story_id, position, body) VALUES (1,1,'Blijft staan.')")
39 39 con.commit()
40 con.execute('DROP TABLE wiki_pages')
41 con.execute('DROP TABLE wiki_categories')
42 con.commit()
40 43 startup()
41 44 assert config.read_text() == marked, 'Bestaande config.php blijft byte voor byte staan'
45 tables = [name for (name,) in con.execute("SELECT name FROM sqlite_master WHERE type='table'")]
46 assert 'wiki_categories' in tables and 'wiki_pages' in tables, tables
42 47 row = con.execute('SELECT date, title FROM days').fetchone()
43 48 assert row == ('2026-01-01', 'Bewaard'), row
44 49 assert con.execute('SELECT body FROM paragraphs').fetchone()[0] == 'Blijft staan.'
@@ -37,8 +37,13 @@ with tempfile.TemporaryDirectory(prefix='startup-', dir=ARTIFACTS) as tmp:
37 con.execute("INSERT INTO stories (day_id, position, title, created, updated) VALUES (1,1,'Een',1,1)")
37 con.execute("INSERT INTO stories (day_id, position, title, created, updated) VALUES (1,1,'Een',1,1)")
38 con.execute("INSERT INTO paragraphs (story_id, position, body) VALUES (1,1,'Blijft staan.')")
38 con.execute("INSERT INTO paragraphs (story_id, position, body) VALUES (1,1,'Blijft staan.')")
39 con.commit()
39 con.commit()
40 con.execute('DROP TABLE wiki_pages')
41 con.execute('DROP TABLE wiki_categories')
42 con.commit()
40 startup()
43 startup()
41 assert config.read_text() == marked, 'Bestaande config.php blijft byte voor byte staan'
44 assert config.read_text() == marked, 'Bestaande config.php blijft byte voor byte staan'
45 tables = [name for (name,) in con.execute("SELECT name FROM sqlite_master WHERE type='table'")]
46 assert 'wiki_categories' in tables and 'wiki_pages' in tables, tables
42 row = con.execute('SELECT date, title FROM days').fetchone()
47 row = con.execute('SELECT date, title FROM days').fetchone()
43 assert row == ('2026-01-01', 'Bewaard'), row
48 assert row == ('2026-01-01', 'Bewaard'), row
44 assert con.execute('SELECT body FROM paragraphs').fetchone()[0] == 'Blijft staan.'
49 assert con.execute('SELECT body FROM paragraphs').fetchone()[0] == 'Blijft staan.'
web/tests/storybook.php +116 −0
@@ -23,6 +23,17 @@ function rejects(callable $fn, int $status, string $label): void {
23 23 }
24 24 check(false, $label);
25 25 }
26 function wikiLinks(array $page): array {
27 $links = [];
28 foreach ($page['chapters'] as $chapter) {
29 foreach ($chapter['blocks'] as $block) {
30 foreach ($block['inlines'] as $inline) {
31 if (($inline['type'] ?? '') === 'link') $links[] = $inline;
32 }
33 }
34 }
35 return $links;
36 }
26 37 function three(string $prefix = 'Verhaal'): array {
27 38 return [
28 39 ['title' => $prefix.' een', 'paragraphs' => ['Eerste alinea.', 'Tweede alinea.']],
@@ -290,6 +301,111 @@ check(!in_array('uur', array_column($dots['2026-10-05'], 'name'), true) && !in_a
290 301 check($dots['2026-10-07'] === [['id' => 'auth:2', 'name' => 'sam', 'avatar_url' => null]], 'Een andere dag toont alleen wie díe dag las');
291 302 check(friendReadsByDay([['id' => 'auth:1;drop', 'name' => 'x', 'avatar_url' => null]]) === [], 'Een vreemd account-id telt niet');
292 303
304 check(listWikiCategories() === ['categories' => []], 'Lege wiki');
305 check(listWikiPages(null, null) === [], 'Nog geen wikipagina\'s');
306 $vriendjes = createWikiCategory(['title' => 'Vriendjes']);
307 check($vriendjes['slug'] === 'vriendjes' && $vriendjes['position'] === 1 && $vriendjes['pages'] === [], 'Categorie krijgt een slug uit de titel');
308 $plekken = createWikiCategory(['title' => 'Plekken']);
309 $speeltjes = createWikiCategory(['title' => 'Speeltjes']);
310 check(array_column(listWikiCategories()['categories'], 'slug') === ['vriendjes', 'plekken', 'speeltjes'], 'Categorieën staan op positie');
311 rejects(fn() => createWikiCategory(['title' => ' ']), 422, 'Lege categorietitel');
312 rejects(fn() => createWikiCategory(['title' => 'Nieuw']), 422, 'Gereserveerde categorieslug uit de titel');
313 rejects(fn() => createWikiCategory(['title' => 'Nog eens', 'slug' => 'vriendjes']), 409, 'Bezette categorieslug');
314 rejects(fn() => createWikiCategory(['title' => 'X', 'slug' => 'Niet geldig']), 422, 'Ongeldige categorieslug');
315
316 $plein = createWikiPage([
317 'title' => 'Het oude plein',
318 'slug' => 'oude-plein',
319 'category' => 'plekken',
320 'content' => "Achter de huizen.\n\n## De boom\n\nEen boom. [[#inleiding|terug]]\n\n## De bank\n\nEen bank.",
321 ]);
322 check(array_column($plein['chapters'], 'anchor') === ['inleiding', 'de-boom', 'de-bank'], 'Inleiding en hoofdstukken krijgen stabiele ankers');
323 check($plein['chapters'][0]['title'] === null && $plein['chapters'][1]['title'] === 'De boom', 'De inleiding heeft geen eigen titel');
324 check($plein['chapters'][0]['blocks'][0]['inlines'][0]['text'] === 'Achter de huizen.', 'Tekst vóór het eerste hoofdstuk blijft een alinea');
325 $terug = wikiLinks($plein)[0];
326 check($terug['broken'] === false && $terug['page'] === 'oude-plein' && $terug['anchor'] === 'inleiding' && $terug['text'] === 'terug', 'Verwijzing naar een hoofdstuk op dezelfde pagina');
327
328 $kist = createWikiPage([
329 'title' => 'Speelgoedkist',
330 'slug' => 'speelgoedkist',
331 'category' => 'speeltjes',
332 'content' => "## Deksel\n\nDe deksel klemt. Zie [[#bodem]] en [[bas]].\n\n## Bodem\n\nOnderin ligt een touw.\n\n## Deksel\n\nNog een deksel.",
333 ]);
334 check(array_column($kist['chapters'], 'anchor') === ['deksel', 'bodem', 'deksel-2'], 'Een herhaalde hoofdstuktitel krijgt een volgnummer');
335 $kistLinks = [];
336 foreach (wikiLinks($kist) as $link) $kistLinks[$link['text']] = $link;
337 check($kistLinks['Bodem']['page'] === 'speelgoedkist' && $kistLinks['Bodem']['anchor'] === 'bodem' && $kistLinks['Bodem']['broken'] === false, 'Verwijzing zonder paginanaam blijft op deze pagina');
338 check($kistLinks['bas']['broken'] === true && $kistLinks['bas']['page'] === null && $kistLinks['bas']['text'] === 'bas', 'Een nog ontbrekende pagina is een zichtbare kapotte verwijzing');
339
340 $bas = createWikiPage([
341 'title' => 'Bas',
342 'category' => 'vriendjes',
343 'content' => "## Wie hij is\n\nBas speelt op het [[oude-plein|oude plein]] en kent [[#samen-spelen]] en de [[speelgoedkist#deksel|kist]].\n\n<script>alert(1)</script> [[geen-pagina]] [[javascript:alert(1)]] [[bas#bestaat-niet]] [[bas|<img src=x onerror=alert(1)>]]\n\nZie [[half\n\n## Samen spelen\n\nZe tellen.",
344 ]);
345 check($bas['slug'] === 'bas' && $bas['category']['slug'] === 'vriendjes', 'Paginatitel wordt de slug en de categorie blijft bewaard');
346 check(array_column($bas['chapters'], 'anchor') === ['wie-hij-is', 'samen-spelen'], 'Hoofdstuktitels worden ankers');
347 $basLinks = [];
348 foreach (wikiLinks($bas) as $link) $basLinks[$link['text']] = $link;
349 check($basLinks['oude plein']['broken'] === false && $basLinks['oude plein']['page'] === 'oude-plein' && $basLinks['oude plein']['anchor'] === null, 'Verwijzing naar een andere pagina');
350 check($basLinks['Samen spelen']['page'] === 'bas' && $basLinks['Samen spelen']['anchor'] === 'samen-spelen' && $basLinks['Samen spelen']['broken'] === false, 'Verwijzing naar een hoofdstuk op dezelfde pagina gebruikt de hoofdstuktitel');
351 check($basLinks['kist']['page'] === 'speelgoedkist' && $basLinks['kist']['anchor'] === 'deksel' && $basLinks['kist']['text'] === 'kist', 'Verwijzing naar een hoofdstuk op een andere pagina');
352 check($basLinks['geen-pagina']['broken'] === true && $basLinks['javascript:alert(1)']['broken'] === true && $basLinks['javascript:alert(1)']['page'] === null, 'Een ongeldig doel wordt geen link');
353 check($basLinks['bas#bestaat-niet']['broken'] === true && $basLinks['<img src=x onerror=alert(1)>']['broken'] === false && $basLinks['<img src=x onerror=alert(1)>']['page'] === 'bas', 'Een ontbrekend anker is kapot en HTML in de tekst blijft tekst');
354 $flat = '';
355 foreach ($bas['chapters'] as $chapter) {
356 foreach ($chapter['blocks'] as $block) {
357 foreach ($block['inlines'] as $inline) {
358 check(in_array($inline['type'], ['text', 'link'], true), 'Alleen tekst en verwijzingen, geen HTML-knoop');
359 if ($inline['type'] === 'text') $flat .= $inline['text'];
360 }
361 }
362 }
363 check(str_contains($flat, '<script>alert(1)</script>') && str_contains($flat, '[[half'), 'Script en een open verwijzing blijven letterlijke tekst');
364 check(!isset(listWikiPages(null, null)[0]['content']), 'De paginalijst geeft de lopende tekst niet terug');
365 check(array_column(listWikiPages(null, 'TOUW'), 'slug') === ['speelgoedkist'], 'Zoeken kijkt in de tekst en negeert hoofdletters');
366 check(array_column(listWikiPages('vriendjes', 'bas'), 'slug') === ['bas'], 'Zoeken kan binnen één categorie');
367 check(listWikiPages('vriendjes', 'touw') === [], 'Categorie en zoekterm gelden allebei');
368 check(array_column(listWikiPages('speeltjes', null), 'slug') === ['speelgoedkist'], 'Filter op categorie');
369 rejects(fn() => listWikiPages('Geen slug', null), 422, 'Categoriefilter moet een slug zijn');
370 rejects(fn() => listWikiPages('onbekend', null), 404, 'Onbekende categorie');
371 rejects(fn() => createWikiPage(['title' => 'X', 'category' => 'nee', 'content' => '']), 404, 'Pagina in een onbekende categorie');
372 rejects(fn() => createWikiPage(['title' => 'X', 'category' => 'vriendjes', 'content' => "##\n\nJa"]), 422, 'Leeg hoofdstuk');
373 rejects(fn() => createWikiPage(['title' => 'Nieuw', 'slug' => 'nieuw', 'category' => 'vriendjes', 'content' => '']), 422, 'Gereserveerde paginaslug');
374 rejects(fn() => createWikiPage(['title' => 'Nog een bas', 'slug' => 'bas', 'category' => 'vriendjes', 'content' => '']), 409, 'Bezette paginaslug');
375 rejects(fn() => updateWikiPage('bas', []), 422, 'Lege paginawijziging');
376 rejects(fn() => loadWikiPage('geen-pagina'), 404, 'Onbekende pagina');
377
378 $een = createWikiPage(['title' => 'Één boom', 'category' => 'plekken', 'content' => '']);
379 check($een['slug'] === 'een-boom' && $een['chapters'] === [], 'Accenten in de titel worden een slug');
380 deleteWikiPage('een-boom');
381 $gek = createWikiPage(['title' => 'Gek', 'category' => 'speeltjes', 'content' => "## !!!\n\nJa."]);
382 check($gek['chapters'][0]['anchor'] === 'hoofdstuk', 'Een hoofdstuk zonder letters heet hoofdstuk');
383 deleteWikiPage($gek['slug']);
384 rejects(fn() => createWikiPage(['title' => 'X', 'category' => 'vriendjes', 'content' => "a\x00b"]), 422, 'Nulbyte in de tekst');
385
386 $renamed = updateWikiPage('bas', ['title' => 'Bas de vriend']);
387 check($renamed['title'] === 'Bas de vriend' && $renamed['slug'] === 'bas' && $renamed['chapters'][1]['anchor'] === 'samen-spelen', 'Titel wijzigen bewaart slug en ankers');
388 $moved = updateWikiPage('bas', ['category' => 'plekken']);
389 check($moved['category']['slug'] === 'plekken' && loadWikiCategory('vriendjes')['pages'] === [], 'Een pagina verhuist mee naar een andere categorie');
390 updateWikiPage('bas', ['category' => 'vriendjes']);
391 $before = array_column(loadWikiPage('speelgoedkist')['chapters'], 'anchor');
392 updateWikiPage('speelgoedkist', ['content' => "## Deksel\n\nDe deksel klemt nog steeds. Zie [[#bodem]] en [[bas]].\n\n## Bodem\n\nOnderin ligt een touw.\n\n## Deksel\n\nNog een deksel."]);
393 check(array_column(loadWikiPage('speelgoedkist')['chapters'], 'anchor') === $before, 'Ankers blijven gelijk als de hoofdstuktitels gelijk blijven');
394 check(wikiLinks(loadWikiPage('speelgoedkist'))[1]['broken'] === false && wikiLinks(loadWikiPage('speelgoedkist'))[1]['page'] === 'bas', 'Na het aanmaken wijst de verwijzing wel naar Bas');
395 updateWikiPage('oude-plein', ['slug' => 'plein']);
396 check(loadWikiPage('plein')['slug'] === 'plein', 'Een pagina krijgt een nieuwe slug');
397 rejects(fn() => loadWikiPage('oude-plein'), 404, 'De oude slug bestaat niet meer');
398 $brokenPage = wikiLinks(loadWikiPage('bas'))[0];
399 check($brokenPage['text'] === 'oude plein' && $brokenPage['broken'] === true, 'Een verwijzing naar de oude slug wordt zichtbaar kapot');
400
401 rejects(fn() => deleteWikiCategory('vriendjes'), 409, 'Categorie met pagina\'s blijft staan');
402 check(deleteWikiPage('bas') === 'bas' && deleteWikiPage('plein') === 'plein' && deleteWikiPage('speelgoedkist') === 'speelgoedkist', 'Pagina\'s verwijderen');
403 check(deleteWikiCategory('vriendjes') === 'vriendjes', 'Lege categorie verwijderen');
404 check(array_column(listWikiCategories()['categories'], 'slug') === ['plekken', 'speeltjes'], 'Verwijderde categorie is weg, de andere blijven');
405 deleteWikiCategory('plekken');
406 deleteWikiCategory('speeltjes');
407 check(listWikiCategories()['categories'] === [], 'Wiki is weer leeg');
408
293 409 $log = $root.'/php-errors.log';
294 410 check(!is_file($log) || file_get_contents($log) === '', 'Geen PHP-fouten tijdens de domeintests');
295 411 echo "Storybook: $checks assertions passed.\n";
@@ -23,6 +23,17 @@ function rejects(callable $fn, int $status, string $label): void {
23 }
23 }
24 check(false, $label);
24 check(false, $label);
25}
25}
26function wikiLinks(array $page): array {
27 $links = [];
28 foreach ($page['chapters'] as $chapter) {
29 foreach ($chapter['blocks'] as $block) {
30 foreach ($block['inlines'] as $inline) {
31 if (($inline['type'] ?? '') === 'link') $links[] = $inline;
32 }
33 }
34 }
35 return $links;
36}
26function three(string $prefix = 'Verhaal'): array {
37function three(string $prefix = 'Verhaal'): array {
27 return [
38 return [
28 ['title' => $prefix.' een', 'paragraphs' => ['Eerste alinea.', 'Tweede alinea.']],
39 ['title' => $prefix.' een', 'paragraphs' => ['Eerste alinea.', 'Tweede alinea.']],
@@ -290,6 +301,111 @@ check(!in_array('uur', array_column($dots['2026-10-05'], 'name'), true) && !in_a
290check($dots['2026-10-07'] === [['id' => 'auth:2', 'name' => 'sam', 'avatar_url' => null]], 'Een andere dag toont alleen wie díe dag las');
301check($dots['2026-10-07'] === [['id' => 'auth:2', 'name' => 'sam', 'avatar_url' => null]], 'Een andere dag toont alleen wie díe dag las');
291check(friendReadsByDay([['id' => 'auth:1;drop', 'name' => 'x', 'avatar_url' => null]]) === [], 'Een vreemd account-id telt niet');
302check(friendReadsByDay([['id' => 'auth:1;drop', 'name' => 'x', 'avatar_url' => null]]) === [], 'Een vreemd account-id telt niet');
292
303
304check(listWikiCategories() === ['categories' => []], 'Lege wiki');
305check(listWikiPages(null, null) === [], 'Nog geen wikipagina\'s');
306$vriendjes = createWikiCategory(['title' => 'Vriendjes']);
307check($vriendjes['slug'] === 'vriendjes' && $vriendjes['position'] === 1 && $vriendjes['pages'] === [], 'Categorie krijgt een slug uit de titel');
308$plekken = createWikiCategory(['title' => 'Plekken']);
309$speeltjes = createWikiCategory(['title' => 'Speeltjes']);
310check(array_column(listWikiCategories()['categories'], 'slug') === ['vriendjes', 'plekken', 'speeltjes'], 'Categorieën staan op positie');
311rejects(fn() => createWikiCategory(['title' => ' ']), 422, 'Lege categorietitel');
312rejects(fn() => createWikiCategory(['title' => 'Nieuw']), 422, 'Gereserveerde categorieslug uit de titel');
313rejects(fn() => createWikiCategory(['title' => 'Nog eens', 'slug' => 'vriendjes']), 409, 'Bezette categorieslug');
314rejects(fn() => createWikiCategory(['title' => 'X', 'slug' => 'Niet geldig']), 422, 'Ongeldige categorieslug');
315
316$plein = createWikiPage([
317 'title' => 'Het oude plein',
318 'slug' => 'oude-plein',
319 'category' => 'plekken',
320 'content' => "Achter de huizen.\n\n## De boom\n\nEen boom. [[#inleiding|terug]]\n\n## De bank\n\nEen bank.",
321]);
322check(array_column($plein['chapters'], 'anchor') === ['inleiding', 'de-boom', 'de-bank'], 'Inleiding en hoofdstukken krijgen stabiele ankers');
323check($plein['chapters'][0]['title'] === null && $plein['chapters'][1]['title'] === 'De boom', 'De inleiding heeft geen eigen titel');
324check($plein['chapters'][0]['blocks'][0]['inlines'][0]['text'] === 'Achter de huizen.', 'Tekst vóór het eerste hoofdstuk blijft een alinea');
325$terug = wikiLinks($plein)[0];
326check($terug['broken'] === false && $terug['page'] === 'oude-plein' && $terug['anchor'] === 'inleiding' && $terug['text'] === 'terug', 'Verwijzing naar een hoofdstuk op dezelfde pagina');
327
328$kist = createWikiPage([
329 'title' => 'Speelgoedkist',
330 'slug' => 'speelgoedkist',
331 'category' => 'speeltjes',
332 'content' => "## Deksel\n\nDe deksel klemt. Zie [[#bodem]] en [[bas]].\n\n## Bodem\n\nOnderin ligt een touw.\n\n## Deksel\n\nNog een deksel.",
333]);
334check(array_column($kist['chapters'], 'anchor') === ['deksel', 'bodem', 'deksel-2'], 'Een herhaalde hoofdstuktitel krijgt een volgnummer');
335$kistLinks = [];
336foreach (wikiLinks($kist) as $link) $kistLinks[$link['text']] = $link;
337check($kistLinks['Bodem']['page'] === 'speelgoedkist' && $kistLinks['Bodem']['anchor'] === 'bodem' && $kistLinks['Bodem']['broken'] === false, 'Verwijzing zonder paginanaam blijft op deze pagina');
338check($kistLinks['bas']['broken'] === true && $kistLinks['bas']['page'] === null && $kistLinks['bas']['text'] === 'bas', 'Een nog ontbrekende pagina is een zichtbare kapotte verwijzing');
339
340$bas = createWikiPage([
341 'title' => 'Bas',
342 'category' => 'vriendjes',
343 'content' => "## Wie hij is\n\nBas speelt op het [[oude-plein|oude plein]] en kent [[#samen-spelen]] en de [[speelgoedkist#deksel|kist]].\n\n<script>alert(1)</script> [[geen-pagina]] [[javascript:alert(1)]] [[bas#bestaat-niet]] [[bas|<img src=x onerror=alert(1)>]]\n\nZie [[half\n\n## Samen spelen\n\nZe tellen.",
344]);
345check($bas['slug'] === 'bas' && $bas['category']['slug'] === 'vriendjes', 'Paginatitel wordt de slug en de categorie blijft bewaard');
346check(array_column($bas['chapters'], 'anchor') === ['wie-hij-is', 'samen-spelen'], 'Hoofdstuktitels worden ankers');
347$basLinks = [];
348foreach (wikiLinks($bas) as $link) $basLinks[$link['text']] = $link;
349check($basLinks['oude plein']['broken'] === false && $basLinks['oude plein']['page'] === 'oude-plein' && $basLinks['oude plein']['anchor'] === null, 'Verwijzing naar een andere pagina');
350check($basLinks['Samen spelen']['page'] === 'bas' && $basLinks['Samen spelen']['anchor'] === 'samen-spelen' && $basLinks['Samen spelen']['broken'] === false, 'Verwijzing naar een hoofdstuk op dezelfde pagina gebruikt de hoofdstuktitel');
351check($basLinks['kist']['page'] === 'speelgoedkist' && $basLinks['kist']['anchor'] === 'deksel' && $basLinks['kist']['text'] === 'kist', 'Verwijzing naar een hoofdstuk op een andere pagina');
352check($basLinks['geen-pagina']['broken'] === true && $basLinks['javascript:alert(1)']['broken'] === true && $basLinks['javascript:alert(1)']['page'] === null, 'Een ongeldig doel wordt geen link');
353check($basLinks['bas#bestaat-niet']['broken'] === true && $basLinks['<img src=x onerror=alert(1)>']['broken'] === false && $basLinks['<img src=x onerror=alert(1)>']['page'] === 'bas', 'Een ontbrekend anker is kapot en HTML in de tekst blijft tekst');
354$flat = '';
355foreach ($bas['chapters'] as $chapter) {
356 foreach ($chapter['blocks'] as $block) {
357 foreach ($block['inlines'] as $inline) {
358 check(in_array($inline['type'], ['text', 'link'], true), 'Alleen tekst en verwijzingen, geen HTML-knoop');
359 if ($inline['type'] === 'text') $flat .= $inline['text'];
360 }
361 }
362}
363check(str_contains($flat, '<script>alert(1)</script>') && str_contains($flat, '[[half'), 'Script en een open verwijzing blijven letterlijke tekst');
364check(!isset(listWikiPages(null, null)[0]['content']), 'De paginalijst geeft de lopende tekst niet terug');
365check(array_column(listWikiPages(null, 'TOUW'), 'slug') === ['speelgoedkist'], 'Zoeken kijkt in de tekst en negeert hoofdletters');
366check(array_column(listWikiPages('vriendjes', 'bas'), 'slug') === ['bas'], 'Zoeken kan binnen één categorie');
367check(listWikiPages('vriendjes', 'touw') === [], 'Categorie en zoekterm gelden allebei');
368check(array_column(listWikiPages('speeltjes', null), 'slug') === ['speelgoedkist'], 'Filter op categorie');
369rejects(fn() => listWikiPages('Geen slug', null), 422, 'Categoriefilter moet een slug zijn');
370rejects(fn() => listWikiPages('onbekend', null), 404, 'Onbekende categorie');
371rejects(fn() => createWikiPage(['title' => 'X', 'category' => 'nee', 'content' => '']), 404, 'Pagina in een onbekende categorie');
372rejects(fn() => createWikiPage(['title' => 'X', 'category' => 'vriendjes', 'content' => "##\n\nJa"]), 422, 'Leeg hoofdstuk');
373rejects(fn() => createWikiPage(['title' => 'Nieuw', 'slug' => 'nieuw', 'category' => 'vriendjes', 'content' => '']), 422, 'Gereserveerde paginaslug');
374rejects(fn() => createWikiPage(['title' => 'Nog een bas', 'slug' => 'bas', 'category' => 'vriendjes', 'content' => '']), 409, 'Bezette paginaslug');
375rejects(fn() => updateWikiPage('bas', []), 422, 'Lege paginawijziging');
376rejects(fn() => loadWikiPage('geen-pagina'), 404, 'Onbekende pagina');
377
378$een = createWikiPage(['title' => 'Één boom', 'category' => 'plekken', 'content' => '']);
379check($een['slug'] === 'een-boom' && $een['chapters'] === [], 'Accenten in de titel worden een slug');
380deleteWikiPage('een-boom');
381$gek = createWikiPage(['title' => 'Gek', 'category' => 'speeltjes', 'content' => "## !!!\n\nJa."]);
382check($gek['chapters'][0]['anchor'] === 'hoofdstuk', 'Een hoofdstuk zonder letters heet hoofdstuk');
383deleteWikiPage($gek['slug']);
384rejects(fn() => createWikiPage(['title' => 'X', 'category' => 'vriendjes', 'content' => "a\x00b"]), 422, 'Nulbyte in de tekst');
385
386$renamed = updateWikiPage('bas', ['title' => 'Bas de vriend']);
387check($renamed['title'] === 'Bas de vriend' && $renamed['slug'] === 'bas' && $renamed['chapters'][1]['anchor'] === 'samen-spelen', 'Titel wijzigen bewaart slug en ankers');
388$moved = updateWikiPage('bas', ['category' => 'plekken']);
389check($moved['category']['slug'] === 'plekken' && loadWikiCategory('vriendjes')['pages'] === [], 'Een pagina verhuist mee naar een andere categorie');
390updateWikiPage('bas', ['category' => 'vriendjes']);
391$before = array_column(loadWikiPage('speelgoedkist')['chapters'], 'anchor');
392updateWikiPage('speelgoedkist', ['content' => "## Deksel\n\nDe deksel klemt nog steeds. Zie [[#bodem]] en [[bas]].\n\n## Bodem\n\nOnderin ligt een touw.\n\n## Deksel\n\nNog een deksel."]);
393check(array_column(loadWikiPage('speelgoedkist')['chapters'], 'anchor') === $before, 'Ankers blijven gelijk als de hoofdstuktitels gelijk blijven');
394check(wikiLinks(loadWikiPage('speelgoedkist'))[1]['broken'] === false && wikiLinks(loadWikiPage('speelgoedkist'))[1]['page'] === 'bas', 'Na het aanmaken wijst de verwijzing wel naar Bas');
395updateWikiPage('oude-plein', ['slug' => 'plein']);
396check(loadWikiPage('plein')['slug'] === 'plein', 'Een pagina krijgt een nieuwe slug');
397rejects(fn() => loadWikiPage('oude-plein'), 404, 'De oude slug bestaat niet meer');
398$brokenPage = wikiLinks(loadWikiPage('bas'))[0];
399check($brokenPage['text'] === 'oude plein' && $brokenPage['broken'] === true, 'Een verwijzing naar de oude slug wordt zichtbaar kapot');
400
401rejects(fn() => deleteWikiCategory('vriendjes'), 409, 'Categorie met pagina\'s blijft staan');
402check(deleteWikiPage('bas') === 'bas' && deleteWikiPage('plein') === 'plein' && deleteWikiPage('speelgoedkist') === 'speelgoedkist', 'Pagina\'s verwijderen');
403check(deleteWikiCategory('vriendjes') === 'vriendjes', 'Lege categorie verwijderen');
404check(array_column(listWikiCategories()['categories'], 'slug') === ['plekken', 'speeltjes'], 'Verwijderde categorie is weg, de andere blijven');
405deleteWikiCategory('plekken');
406deleteWikiCategory('speeltjes');
407check(listWikiCategories()['categories'] === [], 'Wiki is weer leeg');
408
293$log = $root.'/php-errors.log';
409$log = $root.'/php-errors.log';
294check(!is_file($log) || file_get_contents($log) === '', 'Geen PHP-fouten tijdens de domeintests');
410check(!is_file($log) || file_get_contents($log) === '', 'Geen PHP-fouten tijdens de domeintests');
295echo "Storybook: $checks assertions passed.\n";
411echo "Storybook: $checks assertions passed.\n";