BlueGit

projects-timfalken-com verhalenboek

feat: toon vrienden die een dag lazen op de weekkaart

Tot vijf kleine avatars rechtsonder op elke dagkaart, recentste leeshandeling eerst. De vriendenlijst komt van auth en de leesstatus uit reads.

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

timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa

Authored 2026-10-05 · 6 weeks ago

Hash
80e7c59d3efaae6b2b88e3e8b76023b5e4eb13f6
Parent
d0378789
8 files changed +301 −2
README.md +5 −0
@@ -57,6 +57,10 @@ Het overzicht toont één kalenderweek, maandag tot en met zondag. Dagen zonder
57 57
58 58 Op de dagpagina blijven **Vorige dag** en **Volgende dag** de aangrenzende geschreven dagen. Die knoppen springen niet naar een andere week.
59 59
60 Rechtsonder op een dagkaart staan tot vijf kleine rondjes: vrienden die díe dag gelezen hebben. De lijst komt uit `GET /api/friends` op auth.timfalken.com (`id`, `username`, `avatar_url`). De app haalt die lijst server-side op met het bearer-token uit de sessie, dezelfde weg als `/api/me`. Het token komt niet in JavaScript. De browser toont alleen de foto; `avatar_url` mag een pad `/avatar/{id}?v=…` zijn of de absolute URL op `https://auth.timfalken.com`. Een ander adres wordt genegeerd. Zonder foto komt de eerste letter van de naam in een neutraal rondje.
61
62 Een vriend telt voor een dag als het account `auth:{id}` een rij in `reads` heeft voor die dag. Iemand die dit boek nog nooit opende, heeft geen rij en blijft weg. De eigen lezer staat er niet bij. Meer dan vijf vrienden: de vijf met de recentste leeshandeling (`read_at`), en bij een gelijk moment op naam en daarna op id. Lukt de vriendenlijst niet, dan blijven de kaarten gewoon staan, gelezen of ongelezen. Lokaal is er geen auth-lijst; elk ander account in deze database telt dan als vriend, zonder foto.
63
60 64 ## API
61 65
62 66 Schrijven kan met een Bearer-sleutel of, in de browser, als beheerder. Een volledige dag heeft precies drie verhalen, elk met een titel en minstens één alinea. De volgorde in de lijst is plek 1, 2 en 3.
@@ -102,6 +106,7 @@ curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
102 106 | PUT | `/days/JJJJ-MM-DD/stories/1` | Plek 1, 2 of 3 bijwerken. |
103 107 | DELETE | `/days/JJJJ-MM-DD/stories/2` | Eén verhaal weg; de andere plekken blijven. |
104 108 | POST / DELETE | `/days/JJJJ-MM-DD/read` | Alleen een ingelogde lezer. |
109 | GET | `/friend-reads` | Alleen een ingelogde lezer, niet met een API-sleutel. Per datum tot vijf vrienden die die dag lazen: `id`, `name`, `avatar_url`. Recentste leeshandeling eerst. |
105 110 | PUT | `/me/settings` | `theme`: `system`, `light` of `dark`. `font`: `serif`, `sans` of `rounded`. |
106 111 | GET | `/me/export` | Eigen gegevens als JSON. |
107 112
@@ -57,6 +57,10 @@ Het overzicht toont één kalenderweek, maandag tot en met zondag. Dagen zonder
57
57
58Op de dagpagina blijven **Vorige dag** en **Volgende dag** de aangrenzende geschreven dagen. Die knoppen springen niet naar een andere week.
58Op de dagpagina blijven **Vorige dag** en **Volgende dag** de aangrenzende geschreven dagen. Die knoppen springen niet naar een andere week.
59
59
60Rechtsonder op een dagkaart staan tot vijf kleine rondjes: vrienden die díe dag gelezen hebben. De lijst komt uit `GET /api/friends` op auth.timfalken.com (`id`, `username`, `avatar_url`). De app haalt die lijst server-side op met het bearer-token uit de sessie, dezelfde weg als `/api/me`. Het token komt niet in JavaScript. De browser toont alleen de foto; `avatar_url` mag een pad `/avatar/{id}?v=…` zijn of de absolute URL op `https://auth.timfalken.com`. Een ander adres wordt genegeerd. Zonder foto komt de eerste letter van de naam in een neutraal rondje.
61
62Een vriend telt voor een dag als het account `auth:{id}` een rij in `reads` heeft voor die dag. Iemand die dit boek nog nooit opende, heeft geen rij en blijft weg. De eigen lezer staat er niet bij. Meer dan vijf vrienden: de vijf met de recentste leeshandeling (`read_at`), en bij een gelijk moment op naam en daarna op id. Lukt de vriendenlijst niet, dan blijven de kaarten gewoon staan, gelezen of ongelezen. Lokaal is er geen auth-lijst; elk ander account in deze database telt dan als vriend, zonder foto.
63
60## API
64## API
61
65
62Schrijven kan met een Bearer-sleutel of, in de browser, als beheerder. Een volledige dag heeft precies drie verhalen, elk met een titel en minstens één alinea. De volgorde in de lijst is plek 1, 2 en 3.
66Schrijven kan met een Bearer-sleutel of, in de browser, als beheerder. Een volledige dag heeft precies drie verhalen, elk met een titel en minstens één alinea. De volgorde in de lijst is plek 1, 2 en 3.
@@ -102,6 +106,7 @@ curl -sS -H 'Authorization: Bearer vb_JOUW_SLEUTEL' \
102| PUT | `/days/JJJJ-MM-DD/stories/1` | Plek 1, 2 of 3 bijwerken. |
106| PUT | `/days/JJJJ-MM-DD/stories/1` | Plek 1, 2 of 3 bijwerken. |
103| DELETE | `/days/JJJJ-MM-DD/stories/2` | Eén verhaal weg; de andere plekken blijven. |
107| DELETE | `/days/JJJJ-MM-DD/stories/2` | Eén verhaal weg; de andere plekken blijven. |
104| POST / DELETE | `/days/JJJJ-MM-DD/read` | Alleen een ingelogde lezer. |
108| POST / DELETE | `/days/JJJJ-MM-DD/read` | Alleen een ingelogde lezer. |
109| GET | `/friend-reads` | Alleen een ingelogde lezer, niet met een API-sleutel. Per datum tot vijf vrienden die die dag lazen: `id`, `name`, `avatar_url`. Recentste leeshandeling eerst. |
105| PUT | `/me/settings` | `theme`: `system`, `light` of `dark`. `font`: `serif`, `sans` of `rounded`. |
110| PUT | `/me/settings` | `theme`: `system`, `light` of `dark`. `font`: `serif`, `sans` of `rounded`. |
106| GET | `/me/export` | Eigen gegevens als JSON. |
111| GET | `/me/export` | Eigen gegevens als JSON. |
107
112
web/api.php +6 −0
@@ -125,6 +125,12 @@ try {
125 125 if ($method === 'DELETE') jsonOut(markRead($actor['userId'], $match[1], false));
126 126 fail('Deze methode is hier niet toegestaan.', 405);
127 127 }
128 if ($route === '/friend-reads') {
129 requireReader($actor);
130 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
131 $days = friendReadsByDay(sessionFriends($actor['userId']));
132 jsonOut(['days' => $days === [] ? new stdClass() : $days]);
133 }
128 134 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories$#', $route, $match)) {
129 135 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
130 136 requireWriter($actor);
@@ -125,6 +125,12 @@ try {
125 if ($method === 'DELETE') jsonOut(markRead($actor['userId'], $match[1], false));
125 if ($method === 'DELETE') jsonOut(markRead($actor['userId'], $match[1], false));
126 fail('Deze methode is hier niet toegestaan.', 405);
126 fail('Deze methode is hier niet toegestaan.', 405);
127 }
127 }
128 if ($route === '/friend-reads') {
129 requireReader($actor);
130 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
131 $days = friendReadsByDay(sessionFriends($actor['userId']));
132 jsonOut(['days' => $days === [] ? new stdClass() : $days]);
133 }
128 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories$#', $route, $match)) {
134 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories$#', $route, $match)) {
129 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
135 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
130 requireWriter($actor);
136 requireWriter($actor);
web/assets/app.css +37 −0
@@ -158,9 +158,46 @@ button:disabled, .continue:disabled { opacity: 0.55; cursor: default; }
158 158 user-select: none;
159 159 -webkit-touch-callout: none;
160 160 touch-action: pan-y;
161 position: relative;
161 162 }
162 163 .day-link.is-holding { background: color-mix(in srgb, var(--accent) 12%, var(--bg-raised)); }
163 164 .day-link.unread { box-shadow: inset 4px 0 0 var(--accent), var(--shadow); }
165 .day-link.has-friends { padding-bottom: 1.85rem; }
166 .friend-reads {
167 position: absolute;
168 right: 0.72rem;
169 bottom: 0.4rem;
170 display: flex;
171 flex-direction: row;
172 flex-wrap: nowrap;
173 align-items: center;
174 justify-content: flex-end;
175 gap: 0.15rem;
176 }
177 .friend-dot {
178 width: 1.125rem;
179 height: 1.125rem;
180 border-radius: 50%;
181 overflow: hidden;
182 display: inline-flex;
183 align-items: center;
184 justify-content: center;
185 flex: 0 0 auto;
186 font-family: var(--sans);
187 font-size: 0.62rem;
188 font-weight: 600;
189 line-height: 1;
190 letter-spacing: 0;
191 text-transform: uppercase;
192 color: #fffaf3;
193 background: var(--muted);
194 }
195 .friend-dot img {
196 width: 100%;
197 height: 100%;
198 object-fit: cover;
199 display: block;
200 }
164 201 .day-date { color: var(--muted); font-size: 0.92rem; }
165 202 .day-state { font-size: 0.82rem; letter-spacing: 0.04em; text-transform: uppercase; }
166 203 .day-link.unread .day-state { color: var(--accent); }
@@ -158,9 +158,46 @@ button:disabled, .continue:disabled { opacity: 0.55; cursor: default; }
158 user-select: none;
158 user-select: none;
159 -webkit-touch-callout: none;
159 -webkit-touch-callout: none;
160 touch-action: pan-y;
160 touch-action: pan-y;
161 position: relative;
161}
162}
162.day-link.is-holding { background: color-mix(in srgb, var(--accent) 12%, var(--bg-raised)); }
163.day-link.is-holding { background: color-mix(in srgb, var(--accent) 12%, var(--bg-raised)); }
163.day-link.unread { box-shadow: inset 4px 0 0 var(--accent), var(--shadow); }
164.day-link.unread { box-shadow: inset 4px 0 0 var(--accent), var(--shadow); }
165.day-link.has-friends { padding-bottom: 1.85rem; }
166.friend-reads {
167 position: absolute;
168 right: 0.72rem;
169 bottom: 0.4rem;
170 display: flex;
171 flex-direction: row;
172 flex-wrap: nowrap;
173 align-items: center;
174 justify-content: flex-end;
175 gap: 0.15rem;
176}
177.friend-dot {
178 width: 1.125rem;
179 height: 1.125rem;
180 border-radius: 50%;
181 overflow: hidden;
182 display: inline-flex;
183 align-items: center;
184 justify-content: center;
185 flex: 0 0 auto;
186 font-family: var(--sans);
187 font-size: 0.62rem;
188 font-weight: 600;
189 line-height: 1;
190 letter-spacing: 0;
191 text-transform: uppercase;
192 color: #fffaf3;
193 background: var(--muted);
194}
195.friend-dot img {
196 width: 100%;
197 height: 100%;
198 object-fit: cover;
199 display: block;
200}
164.day-date { color: var(--muted); font-size: 0.92rem; }
201.day-date { color: var(--muted); font-size: 0.92rem; }
165.day-state { font-size: 0.82rem; letter-spacing: 0.04em; text-transform: uppercase; }
202.day-state { font-size: 0.82rem; letter-spacing: 0.04em; text-transform: uppercase; }
166.day-link.unread .day-state { color: var(--accent); }
203.day-link.unread .day-state { color: var(--accent); }
web/assets/app.js +64 −1
@@ -188,6 +188,64 @@ function unreadLabel(count) {
188 188 return count + ' dagen ongelezen';
189 189 }
190 190
191 function friendInitial(name) {
192 const trimmed = String(name || '').trim();
193 const first = Array.from(trimmed)[0] || '?';
194 return first.toLocaleUpperCase('nl');
195 }
196
197 function friendColor(id) {
198 const palette = ['#8a624f', '#6d7a62', '#5f6e78', '#7a6558', '#6a5d78', '#8d5346'];
199 const key = String(id || '');
200 let hash = 0;
201 for (let index = 0; index < key.length; index += 1) hash = (hash * 33 + key.charCodeAt(index)) >>> 0;
202 return palette[hash % palette.length];
203 }
204
205 function friendDot(friend) {
206 const label = friend.name || 'Vriend';
207 const dot = el('span', { class: 'friend-dot', title: label });
208 dot.style.background = friendColor(friend.id || label);
209 dot.setAttribute('aria-hidden', 'true');
210 if (friend.avatar_url) {
211 const img = el('img', {
212 src: friend.avatar_url,
213 alt: '',
214 width: '18',
215 height: '18',
216 referrerpolicy: 'no-referrer',
217 });
218 img.addEventListener('error', () => {
219 img.remove();
220 dot.textContent = friendInitial(label);
221 });
222 dot.append(img);
223 } else {
224 dot.textContent = friendInitial(label);
225 }
226 return dot;
227 }
228
229 function friendReadsLabel(readers) {
230 const names = readers.map((friend) => friend.name).filter((name) => name);
231 if (names.length === 1) return 'Gelezen door ' + names[0];
232 return 'Gelezen door ' + names.join(', ');
233 }
234
235 function paintFriendReads(byDay) {
236 document.querySelectorAll('.day-link').forEach((link) => {
237 const existing = link.querySelector('.friend-reads');
238 if (existing) existing.remove();
239 link.classList.remove('has-friends');
240 const date = link.getAttribute('data-date');
241 const readers = date && byDay && byDay[date] ? byDay[date] : [];
242 if (!readers.length) return;
243 const row = el('span', { class: 'friend-reads', 'aria-label': friendReadsLabel(readers) }, readers.slice(0, 5).map(friendDot));
244 link.classList.add('has-friends');
245 link.append(row);
246 });
247 }
248
191 249 function paintOverview(data) {
192 250 const days = data.days || [];
193 251 const visible = data.weekDays || [];
@@ -213,7 +271,7 @@ function paintOverview(data) {
213 271 if (visible.length) {
214 272 const list = el('ol', { class: 'day-list' });
215 273 visible.forEach((day) => {
216 const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date }, [
274 const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date, 'data-date': day.date }, [
217 275 el('span', { class: 'day-date' }, [formatDate(day.date)]),
218 276 el('span', { class: 'day-state' }, [day.read ? 'Gelezen' : 'Ongelezen']),
219 277 el('span', { class: 'day-title' }, [day.title]),
@@ -560,9 +618,14 @@ async function render() {
560 618 try {
561 619 const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/);
562 620 if (path === '/' || path === '' || weekMatch) {
621 const friendsPromise = api('GET', '/friend-reads').catch(() => ({ days: {} }));
563 622 const data = await api('GET', overviewQuery(weekMatch ? weekMatch[1] : null));
564 623 if (token !== renderToken) return;
565 624 paintOverview(data);
625 friendsPromise.then((friends) => {
626 if (token !== renderToken) return;
627 paintFriendReads((friends && friends.days) || {});
628 });
566 629 } else if (path === '/instellingen') {
567 630 paintSettings();
568 631 } else if (path === '/beheer') {
@@ -188,6 +188,64 @@ function unreadLabel(count) {
188 return count + ' dagen ongelezen';
188 return count + ' dagen ongelezen';
189}
189}
190
190
191function friendInitial(name) {
192 const trimmed = String(name || '').trim();
193 const first = Array.from(trimmed)[0] || '?';
194 return first.toLocaleUpperCase('nl');
195}
196
197function friendColor(id) {
198 const palette = ['#8a624f', '#6d7a62', '#5f6e78', '#7a6558', '#6a5d78', '#8d5346'];
199 const key = String(id || '');
200 let hash = 0;
201 for (let index = 0; index < key.length; index += 1) hash = (hash * 33 + key.charCodeAt(index)) >>> 0;
202 return palette[hash % palette.length];
203}
204
205function friendDot(friend) {
206 const label = friend.name || 'Vriend';
207 const dot = el('span', { class: 'friend-dot', title: label });
208 dot.style.background = friendColor(friend.id || label);
209 dot.setAttribute('aria-hidden', 'true');
210 if (friend.avatar_url) {
211 const img = el('img', {
212 src: friend.avatar_url,
213 alt: '',
214 width: '18',
215 height: '18',
216 referrerpolicy: 'no-referrer',
217 });
218 img.addEventListener('error', () => {
219 img.remove();
220 dot.textContent = friendInitial(label);
221 });
222 dot.append(img);
223 } else {
224 dot.textContent = friendInitial(label);
225 }
226 return dot;
227}
228
229function friendReadsLabel(readers) {
230 const names = readers.map((friend) => friend.name).filter((name) => name);
231 if (names.length === 1) return 'Gelezen door ' + names[0];
232 return 'Gelezen door ' + names.join(', ');
233}
234
235function paintFriendReads(byDay) {
236 document.querySelectorAll('.day-link').forEach((link) => {
237 const existing = link.querySelector('.friend-reads');
238 if (existing) existing.remove();
239 link.classList.remove('has-friends');
240 const date = link.getAttribute('data-date');
241 const readers = date && byDay && byDay[date] ? byDay[date] : [];
242 if (!readers.length) return;
243 const row = el('span', { class: 'friend-reads', 'aria-label': friendReadsLabel(readers) }, readers.slice(0, 5).map(friendDot));
244 link.classList.add('has-friends');
245 link.append(row);
246 });
247}
248
191function paintOverview(data) {
249function paintOverview(data) {
192 const days = data.days || [];
250 const days = data.days || [];
193 const visible = data.weekDays || [];
251 const visible = data.weekDays || [];
@@ -213,7 +271,7 @@ function paintOverview(data) {
213 if (visible.length) {
271 if (visible.length) {
214 const list = el('ol', { class: 'day-list' });
272 const list = el('ol', { class: 'day-list' });
215 visible.forEach((day) => {
273 visible.forEach((day) => {
216 const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date }, [
274 const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date, 'data-date': day.date }, [
217 el('span', { class: 'day-date' }, [formatDate(day.date)]),
275 el('span', { class: 'day-date' }, [formatDate(day.date)]),
218 el('span', { class: 'day-state' }, [day.read ? 'Gelezen' : 'Ongelezen']),
276 el('span', { class: 'day-state' }, [day.read ? 'Gelezen' : 'Ongelezen']),
219 el('span', { class: 'day-title' }, [day.title]),
277 el('span', { class: 'day-title' }, [day.title]),
@@ -560,9 +618,14 @@ async function render() {
560 try {
618 try {
561 const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/);
619 const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/);
562 if (path === '/' || path === '' || weekMatch) {
620 if (path === '/' || path === '' || weekMatch) {
621 const friendsPromise = api('GET', '/friend-reads').catch(() => ({ days: {} }));
563 const data = await api('GET', overviewQuery(weekMatch ? weekMatch[1] : null));
622 const data = await api('GET', overviewQuery(weekMatch ? weekMatch[1] : null));
564 if (token !== renderToken) return;
623 if (token !== renderToken) return;
565 paintOverview(data);
624 paintOverview(data);
625 friendsPromise.then((friends) => {
626 if (token !== renderToken) return;
627 paintFriendReads((friends && friends.days) || {});
628 });
566 } else if (path === '/instellingen') {
629 } else if (path === '/instellingen') {
567 paintSettings();
630 paintSettings();
568 } else if (path === '/beheer') {
631 } else if (path === '/beheer') {
web/lib/Storybook.php +136 −0
@@ -342,6 +342,142 @@ function overviewWeek(?string $readerId, ?string $requestedWeek, ?string $today
342 342 return ['lastRead' => $lastRead, 'week' => $bounds];
343 343 }
344 344
345 function knownUserId(mixed $id): bool {
346 return is_string($id) && preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id) === 1;
347 }
348
349 /** Alleen profielfoto's van auth.timfalken.com. Een relatief /avatar/{id}-pad wordt absoluut. */
350 function normalizeAvatarUrl(mixed $value): ?string {
351 if (!is_string($value)) return null;
352 $value = trim($value);
353 if ($value === '' || strlen($value) > 300) return null;
354 $query = '';
355 if (str_starts_with($value, '/')) {
356 $split = strpos($value, '?');
357 if ($split === false) {
358 $path = $value;
359 } else {
360 $path = substr($value, 0, $split);
361 $query = substr($value, $split);
362 }
363 } else {
364 $parts = parse_url($value);
365 if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'https' || strcasecmp((string)($parts['host'] ?? ''), 'auth.timfalken.com') !== 0) return null;
366 if (isset($parts['user']) || isset($parts['pass']) || isset($parts['port'])) return null;
367 $path = (string)($parts['path'] ?? '');
368 if (isset($parts['query'])) $query = '?'.$parts['query'];
369 }
370 if (!preg_match('#^/avatar/([1-9][0-9]{0,17})$#', $path, $match)) return null;
371 if ($query !== '' && !preg_match('/^\?[A-Za-z0-9._~%=&-]{1,200}$/', $query)) return null;
372 return 'https://auth.timfalken.com/avatar/'.$match[1].$query;
373 }
374
375 /** @param array<string,mixed> $payload @return list<array{id:string,name:string,avatar_url:?string}> */
376 function parseAuthFriends(array $payload): array {
377 $list = $payload['friends'] ?? null;
378 if (!is_array($list)) return [];
379 $friends = [];
380 foreach ($list as $friend) {
381 if (!is_array($friend)) continue;
382 $rawId = $friend['id'] ?? null;
383 $numeric = is_int($rawId) || (is_string($rawId) && preg_match('/^[1-9][0-9]{0,17}$/', $rawId));
384 if (!$numeric || (int)$rawId < 1) continue;
385 $id = 'auth:'.(int)$rawId;
386 $name = $friend['username'] ?? null;
387 if (!is_string($name)) continue;
388 $name = trim($name);
389 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) continue;
390 $friends[$id] = [
391 'id' => $id,
392 'name' => $name,
393 'avatar_url' => normalizeAvatarUrl($friend['avatar_url'] ?? null),
394 ];
395 }
396 return array_values($friends);
397 }
398
399 /** @return list<array{id:string,name:string,avatar_url:?string}> */
400 function localFriendProfiles(string $exceptUserId): array {
401 $rows = query('SELECT id, name FROM users WHERE id <> ? ORDER BY name COLLATE NOCASE, id', [$exceptUserId])->fetchAll();
402 $friends = [];
403 foreach ($rows as $row) {
404 if (!knownUserId($row['id'] ?? null) || !is_string($row['name'] ?? null) || $row['name'] === '') continue;
405 $friends[] = ['id' => $row['id'], 'name' => $row['name'], 'avatar_url' => null];
406 }
407 return $friends;
408 }
409
410 /** @return list<array{id:string,name:string,avatar_url:?string}> */
411 function authFriendProfiles(): array {
412 $cachedAt = $_SESSION['friends_cached_at'] ?? 0;
413 $cached = $_SESSION['friends_cache'] ?? null;
414 if (is_int($cachedAt) && is_array($cached) && (time() - $cachedAt) < 60) return $cached;
415 $token = $_SESSION['token'] ?? null;
416 if (!is_string($token) || $token === '') return [];
417 try {
418 $friends = parseAuthFriends(authRequest('/api/friends', null, $token));
419 } catch (Throwable $e) {
420 error_log('Vriendenlijst niet bereikbaar.');
421 return [];
422 }
423 $_SESSION['friends_cache'] = $friends;
424 $_SESSION['friends_cached_at'] = time();
425 return $friends;
426 }
427
428 /** @return list<array{id:string,name:string,avatar_url:?string}> */
429 function sessionFriends(string $userId): array {
430 $friends = localDev() ? localFriendProfiles($userId) : authFriendProfiles();
431 return array_values(array_filter($friends, fn(array $friend): bool => $friend['id'] !== $userId));
432 }
433
434 /**
435 * Vrienden die een dag gelezen hebben, per datum.
436 * Maximaal vijf, de recentste leeshandeling eerst. Bij een gelijk moment telt de naam, daarna het id.
437 *
438 * @param list<array{id:string,name:string,avatar_url:?string}> $friends
439 * @return array<string, list<array{id:string,name:string,avatar_url:?string}>>
440 */
441 function friendReadsByDay(array $friends): array {
442 $byId = [];
443 foreach ($friends as $friend) {
444 if (!is_array($friend) || !knownUserId($friend['id'] ?? null)) continue;
445 $name = $friend['name'] ?? '';
446 if (!is_string($name) || $name === '') continue;
447 $byId[$friend['id']] = [
448 'id' => $friend['id'],
449 'name' => $name,
450 'avatar_url' => normalizeAvatarUrl($friend['avatar_url'] ?? null),
451 ];
452 }
453 if ($byId === []) return [];
454 $ids = array_keys($byId);
455 $placeholders = implode(',', array_fill(0, count($ids), '?'));
456 $rows = query(
457 'SELECT d.date AS date, r.user_id AS user_id, r.read_at AS read_at, u.name AS stored_name
458 FROM reads r
459 JOIN days d ON d.id = r.day_id
460 JOIN users u ON u.id = r.user_id
461 WHERE r.user_id IN ('.$placeholders.')
462 ORDER BY d.date ASC, r.read_at DESC, u.name COLLATE NOCASE ASC, r.user_id ASC',
463 $ids
464 )->fetchAll();
465 $days = [];
466 foreach ($rows as $row) {
467 $date = $row['date'];
468 if (!isset($days[$date])) $days[$date] = [];
469 if (count($days[$date]) >= 5) continue;
470 $friend = $byId[$row['user_id']];
471 $stored = $row['stored_name'];
472 $days[$date][] = [
473 'id' => $friend['id'],
474 'name' => is_string($stored) && $stored !== '' ? $stored : $friend['name'],
475 'avatar_url' => $friend['avatar_url'],
476 ];
477 }
478 return $days;
479 }
480
345 481 function markRead(string $userId, string $date, bool $read): array {
346 482 $day = dayRow($date);
347 483 if ($read) {
@@ -342,6 +342,142 @@ function overviewWeek(?string $readerId, ?string $requestedWeek, ?string $today
342 return ['lastRead' => $lastRead, 'week' => $bounds];
342 return ['lastRead' => $lastRead, 'week' => $bounds];
343}
343}
344
344
345function knownUserId(mixed $id): bool {
346 return is_string($id) && preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id) === 1;
347}
348
349/** Alleen profielfoto's van auth.timfalken.com. Een relatief /avatar/{id}-pad wordt absoluut. */
350function normalizeAvatarUrl(mixed $value): ?string {
351 if (!is_string($value)) return null;
352 $value = trim($value);
353 if ($value === '' || strlen($value) > 300) return null;
354 $query = '';
355 if (str_starts_with($value, '/')) {
356 $split = strpos($value, '?');
357 if ($split === false) {
358 $path = $value;
359 } else {
360 $path = substr($value, 0, $split);
361 $query = substr($value, $split);
362 }
363 } else {
364 $parts = parse_url($value);
365 if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'https' || strcasecmp((string)($parts['host'] ?? ''), 'auth.timfalken.com') !== 0) return null;
366 if (isset($parts['user']) || isset($parts['pass']) || isset($parts['port'])) return null;
367 $path = (string)($parts['path'] ?? '');
368 if (isset($parts['query'])) $query = '?'.$parts['query'];
369 }
370 if (!preg_match('#^/avatar/([1-9][0-9]{0,17})$#', $path, $match)) return null;
371 if ($query !== '' && !preg_match('/^\?[A-Za-z0-9._~%=&-]{1,200}$/', $query)) return null;
372 return 'https://auth.timfalken.com/avatar/'.$match[1].$query;
373}
374
375/** @param array<string,mixed> $payload @return list<array{id:string,name:string,avatar_url:?string}> */
376function parseAuthFriends(array $payload): array {
377 $list = $payload['friends'] ?? null;
378 if (!is_array($list)) return [];
379 $friends = [];
380 foreach ($list as $friend) {
381 if (!is_array($friend)) continue;
382 $rawId = $friend['id'] ?? null;
383 $numeric = is_int($rawId) || (is_string($rawId) && preg_match('/^[1-9][0-9]{0,17}$/', $rawId));
384 if (!$numeric || (int)$rawId < 1) continue;
385 $id = 'auth:'.(int)$rawId;
386 $name = $friend['username'] ?? null;
387 if (!is_string($name)) continue;
388 $name = trim($name);
389 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) continue;
390 $friends[$id] = [
391 'id' => $id,
392 'name' => $name,
393 'avatar_url' => normalizeAvatarUrl($friend['avatar_url'] ?? null),
394 ];
395 }
396 return array_values($friends);
397}
398
399/** @return list<array{id:string,name:string,avatar_url:?string}> */
400function localFriendProfiles(string $exceptUserId): array {
401 $rows = query('SELECT id, name FROM users WHERE id <> ? ORDER BY name COLLATE NOCASE, id', [$exceptUserId])->fetchAll();
402 $friends = [];
403 foreach ($rows as $row) {
404 if (!knownUserId($row['id'] ?? null) || !is_string($row['name'] ?? null) || $row['name'] === '') continue;
405 $friends[] = ['id' => $row['id'], 'name' => $row['name'], 'avatar_url' => null];
406 }
407 return $friends;
408}
409
410/** @return list<array{id:string,name:string,avatar_url:?string}> */
411function authFriendProfiles(): array {
412 $cachedAt = $_SESSION['friends_cached_at'] ?? 0;
413 $cached = $_SESSION['friends_cache'] ?? null;
414 if (is_int($cachedAt) && is_array($cached) && (time() - $cachedAt) < 60) return $cached;
415 $token = $_SESSION['token'] ?? null;
416 if (!is_string($token) || $token === '') return [];
417 try {
418 $friends = parseAuthFriends(authRequest('/api/friends', null, $token));
419 } catch (Throwable $e) {
420 error_log('Vriendenlijst niet bereikbaar.');
421 return [];
422 }
423 $_SESSION['friends_cache'] = $friends;
424 $_SESSION['friends_cached_at'] = time();
425 return $friends;
426}
427
428/** @return list<array{id:string,name:string,avatar_url:?string}> */
429function sessionFriends(string $userId): array {
430 $friends = localDev() ? localFriendProfiles($userId) : authFriendProfiles();
431 return array_values(array_filter($friends, fn(array $friend): bool => $friend['id'] !== $userId));
432}
433
434/**
435 * Vrienden die een dag gelezen hebben, per datum.
436 * Maximaal vijf, de recentste leeshandeling eerst. Bij een gelijk moment telt de naam, daarna het id.
437 *
438 * @param list<array{id:string,name:string,avatar_url:?string}> $friends
439 * @return array<string, list<array{id:string,name:string,avatar_url:?string}>>
440 */
441function friendReadsByDay(array $friends): array {
442 $byId = [];
443 foreach ($friends as $friend) {
444 if (!is_array($friend) || !knownUserId($friend['id'] ?? null)) continue;
445 $name = $friend['name'] ?? '';
446 if (!is_string($name) || $name === '') continue;
447 $byId[$friend['id']] = [
448 'id' => $friend['id'],
449 'name' => $name,
450 'avatar_url' => normalizeAvatarUrl($friend['avatar_url'] ?? null),
451 ];
452 }
453 if ($byId === []) return [];
454 $ids = array_keys($byId);
455 $placeholders = implode(',', array_fill(0, count($ids), '?'));
456 $rows = query(
457 'SELECT d.date AS date, r.user_id AS user_id, r.read_at AS read_at, u.name AS stored_name
458 FROM reads r
459 JOIN days d ON d.id = r.day_id
460 JOIN users u ON u.id = r.user_id
461 WHERE r.user_id IN ('.$placeholders.')
462 ORDER BY d.date ASC, r.read_at DESC, u.name COLLATE NOCASE ASC, r.user_id ASC',
463 $ids
464 )->fetchAll();
465 $days = [];
466 foreach ($rows as $row) {
467 $date = $row['date'];
468 if (!isset($days[$date])) $days[$date] = [];
469 if (count($days[$date]) >= 5) continue;
470 $friend = $byId[$row['user_id']];
471 $stored = $row['stored_name'];
472 $days[$date][] = [
473 'id' => $friend['id'],
474 'name' => is_string($stored) && $stored !== '' ? $stored : $friend['name'],
475 'avatar_url' => $friend['avatar_url'],
476 ];
477 }
478 return $days;
479}
480
345function markRead(string $userId, string $date, bool $read): array {
481function markRead(string $userId, string $date, bool $read): array {
346 $day = dayRow($date);
482 $day = dayRow($date);
347 if ($read) {
483 if ($read) {
web/lib/bootstrap.php +1 −1
@@ -6,7 +6,7 @@ ini_set('log_errors', '1');
6 6 ini_set('error_log', dataDir().'/php-errors.log');
7 7 header('X-Content-Type-Options: nosniff');
8 8 header('Referrer-Policy: same-origin');
9 header("Content-Security-Policy: default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
9 header("Content-Security-Policy: default-src 'self'; img-src 'self' https://auth.timfalken.com; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
10 10 header('Cache-Control: no-store');
11 11
12 12 function dataDir(): string {
@@ -6,7 +6,7 @@ ini_set('log_errors', '1');
6ini_set('error_log', dataDir().'/php-errors.log');
6ini_set('error_log', dataDir().'/php-errors.log');
7header('X-Content-Type-Options: nosniff');
7header('X-Content-Type-Options: nosniff');
8header('Referrer-Policy: same-origin');
8header('Referrer-Policy: same-origin');
9header("Content-Security-Policy: default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
9header("Content-Security-Policy: default-src 'self'; img-src 'self' https://auth.timfalken.com; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
10header('Cache-Control: no-store');
10header('Cache-Control: no-store');
11
11
12function dataDir(): string {
12function dataDir(): string {
web/tests/integration.py +7 −0
@@ -230,6 +230,12 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
230 230 check(next(day for day in reader_days if day['date'] == '2026-05-01')['read'] is True, 'Overzicht van de lezer toont gelezen')
231 231 check(next(day for day in admin_days if day['date'] == '2026-05-01')['read'] is False, 'De andere gebruiker heeft die dag niet gelezen')
232 232 check(reader_overview['lastRead'] == '2026-05-01' and admin_overview['lastRead'] is None, 'lastRead hoort bij de lezer die de dag opende')
233 friend_dots = admin.request('GET', '/friend-reads')['days']
234 check(friend_dots.get('2026-05-01') == [{'id': 'local:test_user_2', 'name': 'test_user_2', 'avatar_url': None}], 'Het vriendrondje toont de andere lokale lezer op de gelezen dag')
235 check('2026-05-04' not in friend_dots, 'Een dag die de vriend niet las krijgt geen rondje')
236 check(reader.request('GET', '/friend-reads')['days'] == {}, 'Zonder leesrecord van de ander blijft de rij leeg')
237 bearer.request('GET', '/friend-reads', expected=403)
238 reader.request('POST', '/friend-reads', {}, expected=405)
233 239 check(reader_overview['week']['start'] == '2026-04-27' and reader_overview['week']['end'] == '2026-05-03' and reader_overview['week']['label'] == '27 april – 3 mei 2026', 'Standaardweek is de week van de laatst gelezen dag')
234 240 check(reader_overview['week']['hasPrevious'] is False and reader_overview['week']['hasNext'] is True and reader_overview['week']['previous'] == '2026-04-20', 'De eerste week verbergt vorige week en houdt de datum van die week')
235 241 check([day['date'] for day in reader_overview['weekDays']] == ['2026-05-01'], 'De zichtbare week laat dagen buiten maandag–zondag weg')
@@ -248,6 +254,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
248 254 reader.request('GET', '/days?week=2026-02-31', expected=422)
249 255 check(admin_overview['week']['start'] == '2026-05-04', 'Zonder leesgeschiedenis de week van de nieuwste dag, niet today')
250 256 check(reader.request('DELETE', '/days/2026-05-01/read')['read'] is False, 'Handmatig ongelezen')
257 check('2026-05-01' not in admin.request('GET', '/friend-reads')['days'], 'Ongelezen haalt het vriendrondje weg')
251 258 after_unread = reader.request('GET', '/days?today=2030-01-01')
252 259 check(after_unread['lastRead'] is None and after_unread['week']['start'] == '2026-05-04', 'Na het wissen van de enige leeshandeling geldt de nieuwste dag')
253 260 bearer.request('POST', '/days', {'date': '2026-06-01', 'title': 'Voor het gat', 'stories': stories('Juni')}, expected=201)
@@ -230,6 +230,12 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
230 check(next(day for day in reader_days if day['date'] == '2026-05-01')['read'] is True, 'Overzicht van de lezer toont gelezen')
230 check(next(day for day in reader_days if day['date'] == '2026-05-01')['read'] is True, 'Overzicht van de lezer toont gelezen')
231 check(next(day for day in admin_days if day['date'] == '2026-05-01')['read'] is False, 'De andere gebruiker heeft die dag niet gelezen')
231 check(next(day for day in admin_days if day['date'] == '2026-05-01')['read'] is False, 'De andere gebruiker heeft die dag niet gelezen')
232 check(reader_overview['lastRead'] == '2026-05-01' and admin_overview['lastRead'] is None, 'lastRead hoort bij de lezer die de dag opende')
232 check(reader_overview['lastRead'] == '2026-05-01' and admin_overview['lastRead'] is None, 'lastRead hoort bij de lezer die de dag opende')
233 friend_dots = admin.request('GET', '/friend-reads')['days']
234 check(friend_dots.get('2026-05-01') == [{'id': 'local:test_user_2', 'name': 'test_user_2', 'avatar_url': None}], 'Het vriendrondje toont de andere lokale lezer op de gelezen dag')
235 check('2026-05-04' not in friend_dots, 'Een dag die de vriend niet las krijgt geen rondje')
236 check(reader.request('GET', '/friend-reads')['days'] == {}, 'Zonder leesrecord van de ander blijft de rij leeg')
237 bearer.request('GET', '/friend-reads', expected=403)
238 reader.request('POST', '/friend-reads', {}, expected=405)
233 check(reader_overview['week']['start'] == '2026-04-27' and reader_overview['week']['end'] == '2026-05-03' and reader_overview['week']['label'] == '27 april – 3 mei 2026', 'Standaardweek is de week van de laatst gelezen dag')
239 check(reader_overview['week']['start'] == '2026-04-27' and reader_overview['week']['end'] == '2026-05-03' and reader_overview['week']['label'] == '27 april – 3 mei 2026', 'Standaardweek is de week van de laatst gelezen dag')
234 check(reader_overview['week']['hasPrevious'] is False and reader_overview['week']['hasNext'] is True and reader_overview['week']['previous'] == '2026-04-20', 'De eerste week verbergt vorige week en houdt de datum van die week')
240 check(reader_overview['week']['hasPrevious'] is False and reader_overview['week']['hasNext'] is True and reader_overview['week']['previous'] == '2026-04-20', 'De eerste week verbergt vorige week en houdt de datum van die week')
235 check([day['date'] for day in reader_overview['weekDays']] == ['2026-05-01'], 'De zichtbare week laat dagen buiten maandag–zondag weg')
241 check([day['date'] for day in reader_overview['weekDays']] == ['2026-05-01'], 'De zichtbare week laat dagen buiten maandag–zondag weg')
@@ -248,6 +254,7 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
248 reader.request('GET', '/days?week=2026-02-31', expected=422)
254 reader.request('GET', '/days?week=2026-02-31', expected=422)
249 check(admin_overview['week']['start'] == '2026-05-04', 'Zonder leesgeschiedenis de week van de nieuwste dag, niet today')
255 check(admin_overview['week']['start'] == '2026-05-04', 'Zonder leesgeschiedenis de week van de nieuwste dag, niet today')
250 check(reader.request('DELETE', '/days/2026-05-01/read')['read'] is False, 'Handmatig ongelezen')
256 check(reader.request('DELETE', '/days/2026-05-01/read')['read'] is False, 'Handmatig ongelezen')
257 check('2026-05-01' not in admin.request('GET', '/friend-reads')['days'], 'Ongelezen haalt het vriendrondje weg')
251 after_unread = reader.request('GET', '/days?today=2030-01-01')
258 after_unread = reader.request('GET', '/days?today=2030-01-01')
252 check(after_unread['lastRead'] is None and after_unread['week']['start'] == '2026-05-04', 'Na het wissen van de enige leeshandeling geldt de nieuwste dag')
259 check(after_unread['lastRead'] is None and after_unread['week']['start'] == '2026-05-04', 'Na het wissen van de enige leeshandeling geldt de nieuwste dag')
253 bearer.request('POST', '/days', {'date': '2026-06-01', 'title': 'Voor het gat', 'stories': stories('Juni')}, expected=201)
260 bearer.request('POST', '/days', {'date': '2026-06-01', 'title': 'Voor het gat', 'stories': stories('Juni')}, expected=201)
web/tests/storybook.php +45 −0
@@ -229,6 +229,51 @@ check(loadDay('2026-10-19', null)['storyCount'] === 0 && overviewWeek('auth:2',
229 229 check(weekHasDays('2026-04-20', '2026-04-26') === false && weekHasDays('2026-04-27', '2026-05-03') === true, 'Alleen de maandag tot en met zondag van die week telt');
230 230 rejects(fn() => weekHasDays('2026-02-31', '2026-03-01'), 422, 'Weekknoppen eisen echte datums');
231 231
232 $avatars = parseAuthFriends([
233 'friends' => [
234 ['id' => 4, 'username' => 'noor', 'avatar_url' => '/avatar/4?v=abc'],
235 ['id' => '5', 'username' => 'bas', 'avatar_url' => 'https://auth.timfalken.com/avatar/5?v=2'],
236 ['id' => 6, 'username' => 'ies', 'avatar_url' => 'https://evil.example/avatar/6'],
237 ['id' => 7, 'username' => 'zonder'],
238 ['id' => 0, 'username' => 'nul', 'avatar_url' => '/avatar/1'],
239 ['id' => 8, 'username' => "regel\nbreuk"],
240 'kapot',
241 ],
242 ]);
243 check(count($avatars) === 4 && $avatars[0]['id'] === 'auth:4' && $avatars[0]['avatar_url'] === 'https://auth.timfalken.com/avatar/4?v=abc', 'Een relatief avatarpad wordt de auth-URL');
244 check($avatars[1]['avatar_url'] === 'https://auth.timfalken.com/avatar/5?v=2', 'Een absolute auth-avatar blijft');
245 check($avatars[2]['id'] === 'auth:6' && $avatars[2]['avatar_url'] === null && $avatars[3]['avatar_url'] === null, 'Een vreemd adres of een ontbrekende foto valt terug op geen avatar');
246 check(normalizeAvatarUrl('https://auth.timfalken.com.evil/avatar/4') === null && normalizeAvatarUrl('/avatar/4/../5') === null, 'Avatar-URL blijft op het avatar-pad van auth');
247 check(friendReadsByDay([]) === [], 'Zonder vrienden geen leesrondjes');
248
249 foreach (['auth:3' => 'cim', 'auth:4' => 'noor', 'auth:5' => 'bas', 'auth:6' => 'ies', 'auth:8' => 'pim', 'auth:9' => 'uur', 'auth:10' => 'eva'] as $friendId => $friendName) {
250 loginUser($friendId, $friendName);
251 }
252 $friendList = [
253 ['id' => 'auth:4', 'name' => 'noor', 'avatar_url' => 'https://auth.timfalken.com/avatar/4?v=abc'],
254 ['id' => 'auth:3', 'name' => 'cim', 'avatar_url' => null],
255 ['id' => 'auth:5', 'name' => 'bas', 'avatar_url' => 'javascript:alert(1)'],
256 ['id' => 'auth:6', 'name' => 'ies', 'avatar_url' => null],
257 ['id' => 'auth:8', 'name' => 'pim', 'avatar_url' => null],
258 ['id' => 'auth:9', 'name' => 'uur', 'avatar_url' => null],
259 ['id' => 'auth:10', 'name' => 'eva', 'avatar_url' => null],
260 ['id' => 'auth:2', 'name' => 'sam', 'avatar_url' => null],
261 ['id' => 'drop table', 'name' => 'nee', 'avatar_url' => null],
262 ];
263 foreach (['auth:4', 'auth:3', 'auth:5', 'auth:6', 'auth:8', 'auth:9'] as $friendId) markRead($friendId, '2026-10-05', true);
264 markRead('auth:1', '2026-10-05', true);
265 markRead('auth:2', '2026-10-07', true);
266 $stamps = ['auth:4' => 500, 'auth:3' => 400, 'auth:5' => 400, 'auth:6' => 300, 'auth:8' => 200, 'auth:9' => 100, 'auth:1' => 900];
267 foreach ($stamps as $friendId => $stamp) {
268 query('UPDATE reads SET read_at=? WHERE user_id=? AND day_id=(SELECT id FROM days WHERE date=?)', [$stamp, $friendId, '2026-10-05']);
269 }
270 $dots = friendReadsByDay($friendList);
271 check(array_column($dots['2026-10-05'], 'name') === ['noor', 'bas', 'cim', 'ies', 'pim'], 'Hoogstens vijf vrienden, recentste leeshandeling eerst en bij gelijk moment op naam');
272 check($dots['2026-10-05'][0]['avatar_url'] === 'https://auth.timfalken.com/avatar/4?v=abc' && $dots['2026-10-05'][1]['avatar_url'] === null, 'Alleen een auth-avatar gaat mee naar de kaart');
273 check(!in_array('uur', array_column($dots['2026-10-05'], 'name'), true) && !in_array('tim', array_column($dots['2026-10-05'], 'name'), true) && !in_array('eva', array_column($dots['2026-10-05'], 'name'), true), 'De zesde, een niet-vriend en een vriend zonder leesrecord blijven weg');
274 check($dots['2026-10-07'] === [['id' => 'auth:2', 'name' => 'sam', 'avatar_url' => null]], 'Een andere dag toont alleen wie díe dag las');
275 check(friendReadsByDay([['id' => 'auth:1;drop', 'name' => 'x', 'avatar_url' => null]]) === [], 'Een vreemd account-id telt niet');
276
232 277 $log = $root.'/php-errors.log';
233 278 check(!is_file($log) || file_get_contents($log) === '', 'Geen PHP-fouten tijdens de domeintests');
234 279 echo "Storybook: $checks assertions passed.\n";
@@ -229,6 +229,51 @@ check(loadDay('2026-10-19', null)['storyCount'] === 0 && overviewWeek('auth:2',
229check(weekHasDays('2026-04-20', '2026-04-26') === false && weekHasDays('2026-04-27', '2026-05-03') === true, 'Alleen de maandag tot en met zondag van die week telt');
229check(weekHasDays('2026-04-20', '2026-04-26') === false && weekHasDays('2026-04-27', '2026-05-03') === true, 'Alleen de maandag tot en met zondag van die week telt');
230rejects(fn() => weekHasDays('2026-02-31', '2026-03-01'), 422, 'Weekknoppen eisen echte datums');
230rejects(fn() => weekHasDays('2026-02-31', '2026-03-01'), 422, 'Weekknoppen eisen echte datums');
231
231
232$avatars = parseAuthFriends([
233 'friends' => [
234 ['id' => 4, 'username' => 'noor', 'avatar_url' => '/avatar/4?v=abc'],
235 ['id' => '5', 'username' => 'bas', 'avatar_url' => 'https://auth.timfalken.com/avatar/5?v=2'],
236 ['id' => 6, 'username' => 'ies', 'avatar_url' => 'https://evil.example/avatar/6'],
237 ['id' => 7, 'username' => 'zonder'],
238 ['id' => 0, 'username' => 'nul', 'avatar_url' => '/avatar/1'],
239 ['id' => 8, 'username' => "regel\nbreuk"],
240 'kapot',
241 ],
242]);
243check(count($avatars) === 4 && $avatars[0]['id'] === 'auth:4' && $avatars[0]['avatar_url'] === 'https://auth.timfalken.com/avatar/4?v=abc', 'Een relatief avatarpad wordt de auth-URL');
244check($avatars[1]['avatar_url'] === 'https://auth.timfalken.com/avatar/5?v=2', 'Een absolute auth-avatar blijft');
245check($avatars[2]['id'] === 'auth:6' && $avatars[2]['avatar_url'] === null && $avatars[3]['avatar_url'] === null, 'Een vreemd adres of een ontbrekende foto valt terug op geen avatar');
246check(normalizeAvatarUrl('https://auth.timfalken.com.evil/avatar/4') === null && normalizeAvatarUrl('/avatar/4/../5') === null, 'Avatar-URL blijft op het avatar-pad van auth');
247check(friendReadsByDay([]) === [], 'Zonder vrienden geen leesrondjes');
248
249foreach (['auth:3' => 'cim', 'auth:4' => 'noor', 'auth:5' => 'bas', 'auth:6' => 'ies', 'auth:8' => 'pim', 'auth:9' => 'uur', 'auth:10' => 'eva'] as $friendId => $friendName) {
250 loginUser($friendId, $friendName);
251}
252$friendList = [
253 ['id' => 'auth:4', 'name' => 'noor', 'avatar_url' => 'https://auth.timfalken.com/avatar/4?v=abc'],
254 ['id' => 'auth:3', 'name' => 'cim', 'avatar_url' => null],
255 ['id' => 'auth:5', 'name' => 'bas', 'avatar_url' => 'javascript:alert(1)'],
256 ['id' => 'auth:6', 'name' => 'ies', 'avatar_url' => null],
257 ['id' => 'auth:8', 'name' => 'pim', 'avatar_url' => null],
258 ['id' => 'auth:9', 'name' => 'uur', 'avatar_url' => null],
259 ['id' => 'auth:10', 'name' => 'eva', 'avatar_url' => null],
260 ['id' => 'auth:2', 'name' => 'sam', 'avatar_url' => null],
261 ['id' => 'drop table', 'name' => 'nee', 'avatar_url' => null],
262];
263foreach (['auth:4', 'auth:3', 'auth:5', 'auth:6', 'auth:8', 'auth:9'] as $friendId) markRead($friendId, '2026-10-05', true);
264markRead('auth:1', '2026-10-05', true);
265markRead('auth:2', '2026-10-07', true);
266$stamps = ['auth:4' => 500, 'auth:3' => 400, 'auth:5' => 400, 'auth:6' => 300, 'auth:8' => 200, 'auth:9' => 100, 'auth:1' => 900];
267foreach ($stamps as $friendId => $stamp) {
268 query('UPDATE reads SET read_at=? WHERE user_id=? AND day_id=(SELECT id FROM days WHERE date=?)', [$stamp, $friendId, '2026-10-05']);
269}
270$dots = friendReadsByDay($friendList);
271check(array_column($dots['2026-10-05'], 'name') === ['noor', 'bas', 'cim', 'ies', 'pim'], 'Hoogstens vijf vrienden, recentste leeshandeling eerst en bij gelijk moment op naam');
272check($dots['2026-10-05'][0]['avatar_url'] === 'https://auth.timfalken.com/avatar/4?v=abc' && $dots['2026-10-05'][1]['avatar_url'] === null, 'Alleen een auth-avatar gaat mee naar de kaart');
273check(!in_array('uur', array_column($dots['2026-10-05'], 'name'), true) && !in_array('tim', array_column($dots['2026-10-05'], 'name'), true) && !in_array('eva', array_column($dots['2026-10-05'], 'name'), true), 'De zesde, een niet-vriend en een vriend zonder leesrecord blijven weg');
274check($dots['2026-10-07'] === [['id' => 'auth:2', 'name' => 'sam', 'avatar_url' => null]], 'Een andere dag toont alleen wie díe dag las');
275check(friendReadsByDay([['id' => 'auth:1;drop', 'name' => 'x', 'avatar_url' => null]]) === [], 'Een vreemd account-id telt niet');
276
232$log = $root.'/php-errors.log';
277$log = $root.'/php-errors.log';
233check(!is_file($log) || file_get_contents($log) === '', 'Geen PHP-fouten tijdens de domeintests');
278check(!is_file($log) || file_get_contents($log) === '', 'Geen PHP-fouten tijdens de domeintests');
234echo "Storybook: $checks assertions passed.\n";
279echo "Storybook: $checks assertions passed.\n";