BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / api.php

api.php

fix: hide an empty wiki from readers
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 5 weeks ago
f4ebf519 History
api.php 9.0 KiB Download Raw
1<?php
2declare(strict_types=1);
3require __DIR__.'/lib/bootstrap.php';
4
5try {
6 $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
7 $route = apiRoute();
8 $actor = authenticate();
9 if ($method !== 'GET' && $method !== 'HEAD') requireCsrf($actor);
10 $readerId = $actor['kind'] === 'user' ? $actor['userId'] : null;
11
12 if ($route === '/me') {
13 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
14 jsonOut([
15 'user' => publicUser($actor['userId']),
16 'csrf' => $actor['kind'] === 'user' ? ($_SESSION['csrf'] ?? null) : null,
17 'local' => localDev(),
18 'auth' => $actor['kind'],
19 'wiki' => wikiVisible(($actor['role'] ?? '') === 'admin'),
20 ]);
21 }
22 if ($route === '/me/settings') {
23 if ($method !== 'PUT') fail('Deze methode is hier niet toegestaan.', 405);
24 requireReader($actor);
25 jsonOut(['user' => saveSettings($actor['userId'], readJson())]);
26 }
27 if ($route === '/me/export') {
28 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
29 requireReader($actor);
30 header('Content-Disposition: attachment; filename="verhalenboek-gegevens.json"');
31 jsonOut(exportUser($actor['userId']));
32 }
33 if ($route === '/session/switch') {
34 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
35 requireReader($actor);
36 if (!localDev()) fail('Niet beschikbaar.', 403);
37 $in = readJson();
38 if (!in_array($in['user'] ?? '', ['test_user_1', 'test_user_2'], true)) throw new AppException('Onbekende testgebruiker.');
39 loginUser('local:'.$in['user'], $in['user']);
40 jsonOut(['ok' => true, 'user' => publicUser($_SESSION['user']), 'csrf' => $_SESSION['csrf']]);
41 }
42 if ($route === '/session/logout') {
43 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
44 requireReader($actor);
45 if (!localDev() && isset($_SESSION['token'])) {
46 try { authRequest('/api/logout', [], (string)$_SESSION['token']); } catch (Throwable $e) { /* lokaal alsnog afmelden */ }
47 }
48 $_SESSION = [];
49 session_destroy();
50 jsonOut(['ok' => true]);
51 }
52 if ($route === '/keys') {
53 requireAdminSession($actor);
54 if ($method === 'GET') jsonOut(['keys' => listApiKeys()]);
55 if ($method === 'POST') {
56 $in = readJson();
57 jsonOut(['key' => createApiKey($actor['userId'], $in['name'] ?? null)], 201);
58 }
59 fail('Deze methode is hier niet toegestaan.', 405);
60 }
61 if ($route === '/users') {
62 requireAdminSession($actor, 'Alleen een beheerder mag gebruikers beheren.', 'users');
63 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
64 jsonOut(['users' => listUsers()]);
65 }
66 if (preg_match('#^/users/([^/]+)$#', $route, $match)) {
67 requireAdminSession($actor, 'Alleen een beheerder mag gebruikers beheren.', 'users');
68 if ($method !== 'PUT') fail('Deze methode is hier niet toegestaan.', 405);
69 $in = readJson();
70 if (!is_bool($in['admin'] ?? null)) throw new AppException('Zeg of deze gebruiker beheerder moet zijn.');
71 jsonOut(['user' => setUserRole($actor['userId'], rawurldecode($match[1]), $in['admin'])]);
72 }
73 if (preg_match('#^/keys/(\d+)$#', $route, $match)) {
74 requireAdminSession($actor);
75 if ($method === 'GET') jsonOut(['key' => revealApiKey((int)$match[1])]);
76 if ($method === 'DELETE') jsonOut(['key' => revokeApiKey((int)$match[1])]);
77 fail('Deze methode is hier niet toegestaan.', 405);
78 }
79 if ($route === '/days') {
80 if ($method === 'GET') {
81 $week = $_GET['week'] ?? null;
82 $today = $_GET['today'] ?? null;
83 if ($week !== null && !is_string($week)) throw new AppException('De week moet een datum zijn.');
84 if ($today !== null && !is_string($today)) throw new AppException('De datum moet de vorm JJJJ-MM-DD hebben.');
85 $listed = listDays($readerId);
86 $focus = overviewWeek($readerId, is_string($week) ? $week : null, is_string($today) ? $today : null);
87 jsonOut([
88 'days' => $listed,
89 'weekDays' => daysInWeek($listed, $focus['week']['start'], $focus['week']['end']),
90 'lastRead' => $focus['lastRead'],
91 'week' => $focus['week'],
92 ]);
93 }
94 if ($method === 'POST') {
95 requireWriter($actor);
96 $in = readJson();
97 if (!is_string($in['date'] ?? null)) throw new AppException('De datum moet de vorm JJJJ-MM-DD hebben.');
98 jsonOut(createDay($in['date'], $in['title'] ?? null, $in['stories'] ?? null), 201);
99 }
100 fail('Deze methode is hier niet toegestaan.', 405);
101 }
102 if ($route === '/days/latest') {
103 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
104 jsonOut(latestWritten());
105 }
106 if ($route === '/days/gaps') {
107 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
108 jsonOut(dayGaps());
109 }
110 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})$#', $route, $match)) {
111 $date = $match[1];
112 if ($method === 'GET') jsonOut(loadDay($date, $readerId));
113 if ($method === 'PUT') {
114 requireWriter($actor);
115 jsonOut(updateDay($date, readJson()));
116 }
117 if ($method === 'DELETE') {
118 requireWriter($actor);
119 jsonOut(['ok' => true, 'date' => deleteDay($date)]);
120 }
121 fail('Deze methode is hier niet toegestaan.', 405);
122 }
123 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/read$#', $route, $match)) {
124 requireReader($actor);
125 if ($method === 'POST') jsonOut(markRead($actor['userId'], $match[1], true));
126 if ($method === 'DELETE') jsonOut(markRead($actor['userId'], $match[1], false));
127 fail('Deze methode is hier niet toegestaan.', 405);
128 }
129 if ($route === '/friend-reads') {
130 requireReader($actor);
131 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
132 $days = friendReadsByDay(sessionFriends($actor['userId']));
133 jsonOut(['days' => $days === [] ? new stdClass() : $days]);
134 }
135 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories$#', $route, $match)) {
136 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
137 requireWriter($actor);
138 jsonOut(addStory($match[1], readJson()), 201);
139 }
140 if ($route === '/wiki/categories') {
141 if ($method === 'GET') jsonOut(listWikiCategories());
142 if ($method === 'POST') {
143 requireWriter($actor);
144 jsonOut(createWikiCategory(readJson()), 201);
145 }
146 fail('Deze methode is hier niet toegestaan.', 405);
147 }
148 if (preg_match('#^/wiki/categories/([a-z0-9]+(?:-[a-z0-9]+)*)$#', $route, $match)) {
149 $slug = $match[1];
150 if ($method === 'GET') jsonOut(loadWikiCategory($slug));
151 if ($method === 'PUT') {
152 requireWriter($actor);
153 jsonOut(updateWikiCategory($slug, readJson()));
154 }
155 if ($method === 'DELETE') {
156 requireWriter($actor);
157 jsonOut(['ok' => true, 'slug' => deleteWikiCategory($slug)]);
158 }
159 fail('Deze methode is hier niet toegestaan.', 405);
160 }
161 if ($route === '/wiki/pages') {
162 if ($method === 'GET') {
163 $category = $_GET['category'] ?? null;
164 $q = $_GET['q'] ?? null;
165 if ($category !== null && !is_string($category)) throw new AppException('De categorie moet een slug zijn.');
166 if ($q !== null && !is_string($q)) throw new AppException('De zoekterm moet tekst zijn.');
167 jsonOut(['pages' => listWikiPages(is_string($category) ? $category : null, is_string($q) ? $q : null)]);
168 }
169 if ($method === 'POST') {
170 requireWriter($actor);
171 jsonOut(createWikiPage(readJson()), 201);
172 }
173 fail('Deze methode is hier niet toegestaan.', 405);
174 }
175 if (preg_match('#^/wiki/pages/([a-z0-9]+(?:-[a-z0-9]+)*)$#', $route, $match)) {
176 $slug = $match[1];
177 if ($method === 'GET') jsonOut(loadWikiPage($slug));
178 if ($method === 'PUT') {
179 requireWriter($actor);
180 jsonOut(updateWikiPage($slug, readJson()));
181 }
182 if ($method === 'DELETE') {
183 requireWriter($actor);
184 jsonOut(['ok' => true, 'slug' => deleteWikiPage($slug)]);
185 }
186 fail('Deze methode is hier niet toegestaan.', 405);
187 }
188 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories/([123])$#', $route, $match)) {
189 requireWriter($actor);
190 if ($method === 'PUT') jsonOut(updateStory($match[1], (int)$match[2], readJson()));
191 if ($method === 'DELETE') jsonOut(deleteStory($match[1], (int)$match[2]));
192 fail('Deze methode is hier niet toegestaan.', 405);
193 }
194 fail('Onbekend pad.', 404);
195} catch (AppException $e) {
196 fail($e->getMessage(), $e->status, $e->auth);
197} catch (Throwable $e) {
198 error_log($e->getMessage());
199 fail('Er ging iets mis.', 500);
200}