BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / bootstrap.php

bootstrap.php

bootstrap.php 20.6 KiB Download Raw
1<?php
2declare(strict_types=1);
3require_once __DIR__.'/Storybook.php';
4require_once __DIR__.'/Wiki.php';
5require_once __DIR__.'/Feed.php';
6ini_set('display_errors', '0');
7ini_set('log_errors', '1');
8ini_set('error_log', dataDir().'/php-errors.log');
9header('X-Content-Type-Options: nosniff');
10header('Referrer-Policy: same-origin');
11header("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'");
12header('Cache-Control: no-store');
13
14function dataDir(): string {
15 $env = getenv('VERHALENBOEK_DATA_DIR');
16 if (is_string($env) && $env !== '') return rtrim($env, '/');
17 return dirname(__DIR__).'/data';
18}
19
20function db(): PDO {
21 static $db;
22 if ($db) return $db;
23 $dir = dataDir();
24 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) throw new RuntimeException('De datamap moet bestaan en schrijfbaar zijn.');
25 $db = new PDO('sqlite:'.$dir.'/verhalenboek.sqlite', null, null, [
26 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
27 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
28 ]);
29 $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
30 $db->exec('CREATE TABLE IF NOT EXISTS users (
31 id TEXT PRIMARY KEY,
32 name TEXT NOT NULL,
33 role TEXT NOT NULL DEFAULT \'user\' CHECK(role IN (\'admin\',\'user\')),
34 theme TEXT NOT NULL DEFAULT \'system\' CHECK(theme IN (\'system\',\'light\',\'dark\')),
35 font TEXT NOT NULL DEFAULT \'serif\' CHECK(font IN (\'serif\',\'sans\',\'rounded\')),
36 created INTEGER NOT NULL
37 );
38 CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);
39 CREATE TABLE IF NOT EXISTS days (
40 id INTEGER PRIMARY KEY AUTOINCREMENT,
41 date TEXT NOT NULL UNIQUE,
42 title TEXT NOT NULL,
43 created INTEGER NOT NULL,
44 updated INTEGER NOT NULL
45 );
46 CREATE TABLE IF NOT EXISTS stories (
47 id INTEGER PRIMARY KEY AUTOINCREMENT,
48 day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
49 position INTEGER NOT NULL CHECK(position BETWEEN 1 AND 3),
50 title TEXT NOT NULL,
51 created INTEGER NOT NULL,
52 updated INTEGER NOT NULL,
53 UNIQUE(day_id, position)
54 );
55 CREATE TABLE IF NOT EXISTS paragraphs (
56 id INTEGER PRIMARY KEY AUTOINCREMENT,
57 story_id INTEGER NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
58 position INTEGER NOT NULL CHECK(position >= 1),
59 body TEXT NOT NULL,
60 UNIQUE(story_id, position)
61 );
62 CREATE TABLE IF NOT EXISTS reads (
63 user_id TEXT NOT NULL REFERENCES users(id),
64 day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
65 read_at INTEGER NOT NULL,
66 PRIMARY KEY(user_id, day_id)
67 );
68 CREATE TABLE IF NOT EXISTS api_keys (
69 id INTEGER PRIMARY KEY AUTOINCREMENT,
70 user_id TEXT NOT NULL REFERENCES users(id),
71 name TEXT NOT NULL,
72 token_hash TEXT NOT NULL UNIQUE,
73 token_prefix TEXT NOT NULL,
74 token_cipher TEXT NOT NULL DEFAULT \'\',
75 created INTEGER NOT NULL,
76 revoked INTEGER
77 );
78 CREATE TABLE IF NOT EXISTS wiki_categories (
79 id INTEGER PRIMARY KEY AUTOINCREMENT,
80 slug TEXT NOT NULL UNIQUE,
81 title TEXT NOT NULL,
82 position INTEGER NOT NULL,
83 created INTEGER NOT NULL,
84 updated INTEGER NOT NULL
85 );
86 CREATE TABLE IF NOT EXISTS wiki_pages (
87 id INTEGER PRIMARY KEY AUTOINCREMENT,
88 category_id INTEGER NOT NULL REFERENCES wiki_categories(id),
89 slug TEXT NOT NULL UNIQUE,
90 title TEXT NOT NULL,
91 content TEXT NOT NULL,
92 position INTEGER NOT NULL,
93 created INTEGER NOT NULL,
94 updated INTEGER NOT NULL
95 );
96 CREATE INDEX IF NOT EXISTS wiki_pages_category ON wiki_pages(category_id, position);
97 CREATE TABLE IF NOT EXISTS app_settings (
98 name TEXT PRIMARY KEY,
99 value TEXT NOT NULL,
100 updated INTEGER NOT NULL
101 );
102 CREATE TABLE IF NOT EXISTS feed_tokens (
103 user_id TEXT PRIMARY KEY REFERENCES users(id),
104 token_hash TEXT NOT NULL UNIQUE,
105 token_prefix TEXT NOT NULL,
106 token_cipher TEXT NOT NULL,
107 created INTEGER NOT NULL
108 );');
109 $columns = array_column($db->query('PRAGMA table_info(api_keys)')->fetchAll(), 'name');
110 if (!in_array('token_cipher', $columns, true)) {
111 $db->exec("ALTER TABLE api_keys ADD COLUMN token_cipher TEXT NOT NULL DEFAULT ''");
112 }
113 return $db;
114}
115
116function query(string $sql, array $args = []): PDOStatement {
117 $statement = db()->prepare($sql);
118 $statement->execute($args);
119 return $statement;
120}
121
122final class DatabaseSessions implements SessionHandlerInterface {
123 public function open(string $path, string $name): bool { return true; }
124 public function close(): bool { return true; }
125 public function read(string $id): string|false {
126 return query('SELECT payload FROM sessions WHERE id=? AND expires>?', [$id, time()])->fetchColumn() ?: '';
127 }
128 public function write(string $id, string $data): bool {
129 query('INSERT OR REPLACE INTO sessions (id, payload, expires) VALUES (?,?,?)', [$id, $data, time() + 86400]);
130 return true;
131 }
132 public function destroy(string $id): bool {
133 query('DELETE FROM sessions WHERE id=?', [$id]);
134 return true;
135 }
136 public function gc(int $max_lifetime): int|false {
137 return query('DELETE FROM sessions WHERE expires<?', [time()])->rowCount();
138 }
139}
140
141function localDev(): bool {
142 $host = parse_url('http://'.($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
143 return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
144 && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
145}
146
147function config(): array {
148 $dir = dataDir();
149 $path = $dir.'/config.php';
150 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
151 $lock = fopen($dir.'/config.lock', 'c');
152 if ($lock === false) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
153 try {
154 if (!flock($lock, LOCK_EX)) throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
155 if (!file_exists($path)) {
156 $secret = bin2hex(random_bytes(32));
157 $template = <<<PHP
158<?php
159// Vul deze waarden op deze server in. Lege velden gebruiken omgevingsvariabelen.
160// Productie-URL: https://projects.timfalken.com/verhaaltjesboek
161// client_id is het geregistreerde domein, meestal projects.timfalken.com.
162// Het geheim komt uit https://auth.timfalken.com/admin en hoort alleen in dit bestand.
163// key_secret versleutelt API-sleutels zodat een beheerder ze opnieuw kan tonen. Laat die staan.
164return [
165 'base_url' => '',
166 'client_id' => '',
167 'client_secret' => '',
168 'key_secret' => '$secret',
169];
170
171PHP;
172 if (file_put_contents($path, $template) !== strlen($template)) throw new RuntimeException('data/config.php kon niet worden gemaakt.');
173 }
174 $values = require $path;
175 if (!is_array($values)) throw new RuntimeException('data/config.php moet een array teruggeven.');
176 $values = ensureKeySecret($path, $values);
177 } finally {
178 flock($lock, LOCK_UN);
179 fclose($lock);
180 }
181 foreach (['base_url' => 'VERHALENBOEK_BASE_URL', 'client_id' => 'VERHALENBOEK_CLIENT_ID', 'client_secret' => 'VERHALENBOEK_CLIENT_SECRET'] as $key => $env) {
182 if (($values[$key] ?? '') === '') $values[$key] = getenv($env) ?: '';
183 }
184 return $values;
185}
186
187function ensureKeySecret(string $path, array $values): array {
188 $secret = $values['key_secret'] ?? '';
189 if (is_string($secret) && preg_match('/^[a-f0-9]{64}$/', $secret)) return $values;
190 $secret = bin2hex(random_bytes(32));
191 $values['key_secret'] = $secret;
192 $raw = file_get_contents($path);
193 if (!is_string($raw)) throw new RuntimeException('data/config.php kon niet worden gelezen.');
194 if (preg_match("/'key_secret'\\s*=>\\s*'[^']*'/", $raw)) {
195 $updated = preg_replace("/'key_secret'\\s*=>\\s*'[^']*'/", "'key_secret' => '".$secret."'", $raw, 1);
196 } else {
197 $updated = preg_replace("/(\\r?\\n)(\\];)/", "$1 'key_secret' => '".$secret."',$1$2", $raw, 1);
198 }
199 if (!is_string($updated) || !str_contains($updated, $secret) || file_put_contents($path, $updated) !== strlen($updated)) {
200 throw new RuntimeException('key_secret kon niet in data/config.php worden gezet.');
201 }
202 return $values;
203}
204
205function authPublicBase(): string {
206 if (localDev()) return baseUrl();
207 $base = rtrim((string)(config()['base_url'] ?? ''), '/');
208 if (str_starts_with($base, 'https://')) return $base;
209 $env = getenv('VERHALENBOEK_BASE_URL');
210 if (is_string($env) && str_starts_with($env = rtrim($env, '/'), 'https://')) return $env;
211 return '';
212}
213
214function authHint(string $kind): string {
215 $base = authPublicBase();
216 $beheer = ($base !== '' ? $base : '').'/#/beheer';
217 $docs = ($base !== '' ? $base.'/' : '').'docs.php';
218 $how = 'Stuur de header Authorization: Bearer vb_… met een API-sleutel. Een beheerder maakt sleutels aan onder Beheer op '.$beheer.'. Uitleg: '.$docs;
219 return match ($kind) {
220 'missing' => 'Er is geen Authorization-header. '.$how,
221 'format' => 'De Authorization-header heeft het verkeerde formaat. Gebruik Bearer, gevolgd door vb_ en 64 hexadecimale tekens. '.$how,
222 'rejected' => 'Deze API-sleutel is onbekend of ingetrokken. '.$how,
223 'writer' => 'Dit mag alleen met een API-sleutel of als beheerder. '.$how,
224 'admin' => 'Sleutels beheren kan alleen als ingelogde beheerder, niet met een API-sleutel. Open Beheer op '.$beheer.'. Uitleg: '.$docs,
225 'users' => 'Gebruikers beheren kan alleen als ingelogde beheerder, niet met een API-sleutel. Open Beheer op '.$beheer.'. Uitleg: '.$docs,
226 default => $how,
227 };
228}
229
230function baseUrl(): string {
231 if (localDev()) {
232 $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
233 if ($dir === '/' || $dir === '.') $dir = '';
234 return 'http://'.$_SERVER['HTTP_HOST'].$dir;
235 }
236 $base = rtrim((string)config()['base_url'], '/');
237 if (!str_starts_with($base, 'https://')) throw new RuntimeException("Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie, of zet VERHALENBOEK_BASE_URL. De datamap wordt niet meegedeployed.");
238 return $base;
239}
240
241function assetVersion(): string {
242 static $version;
243 if ($version !== null) return $version;
244 $file = dirname(__DIR__).'/asset-version.txt';
245 if (is_readable($file)) {
246 $hash = trim((string)file_get_contents($file));
247 if ($hash !== '' && preg_match('/^[0-9a-f]{7,64}$/i', $hash)) return $version = $hash;
248 }
249 $env = getenv('CI_COMMIT_SHA') ?: getenv('VERHALENBOEK_ASSET_VERSION') ?: '';
250 if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i', trim($env))) return $version = trim($env);
251 $git = dirname(__DIR__, 2).'/.git';
252 if (is_dir($git)) {
253 $out = @shell_exec('git -C '.escapeshellarg(dirname($git)).' rev-parse HEAD 2>/dev/null');
254 if (is_string($out) && preg_match('/^[0-9a-f]{7,64}$/i', trim($out))) return $version = trim($out);
255 }
256 $js = dirname(__DIR__).'/assets/app.js';
257 return $version = is_file($js) ? (string)filemtime($js) : '0';
258}
259
260function assetUrl(string $path): string {
261 $path = ltrim($path, '/');
262 $version = rawurlencode(assetVersion());
263 return str_contains($path, '?') ? $path.'&v='.$version : $path.'?v='.$version;
264}
265
266function pwaHead(): void {
267 $icon = htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES);
268 $png32 = htmlspecialchars(assetUrl('assets/favicon-32.png'), ENT_QUOTES);
269 $png16 = htmlspecialchars(assetUrl('assets/favicon-16.png'), ENT_QUOTES);
270 $mask = htmlspecialchars(assetUrl('assets/mask-icon.svg'), ENT_QUOTES);
271 $script = htmlspecialchars(assetUrl('assets/pwa.js'), ENT_QUOTES);
272 echo <<<HTML
273<link rel="icon" href="{$icon}" type="image/svg+xml" sizes="any">
274<link rel="icon" href="{$png32}" type="image/png" sizes="32x32">
275<link rel="icon" href="{$png16}" type="image/png" sizes="16x16">
276<link rel="apple-touch-icon" href="assets/apple-touch-icon.png" sizes="180x180">
277<link rel="manifest" href="manifest.webmanifest">
278<link rel="mask-icon" href="{$mask}" color="#3a5fc8">
279<meta name="mobile-web-app-capable" content="yes">
280<meta name="apple-mobile-web-app-capable" content="yes">
281<meta name="apple-mobile-web-app-title" content="Verhalenboek">
282<meta name="apple-mobile-web-app-status-bar-style" content="default">
283<script src="{$script}"></script>
284
285HTML;
286}
287
288function authRequest(string $path, ?array $form = null, ?string $token = null): array {
289 $ch=curl_init('https://auth.timfalken.com'.$path);
290 $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
291 if ($token) $headers[] = 'Authorization: Bearer '.$token;
292 curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => $headers]);
293 if ($form !== null) curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
294 $body = curl_exec($ch);
295 $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
296 curl_close($ch);
297 $data = is_string($body) ? json_decode($body, true) : null;
298 if ($status !== 200 || !is_array($data)) throw new RuntimeException('De authenticatiedienst is niet bereikbaar of de sessie is verlopen. Log opnieuw in.');
299 return $data;
300}
301
302/** @return array{0:string,1:string} */
303function authIdentity(array $profile): array {
304 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
305 throw new RuntimeException('Het accountantwoord mist een id of gebruikersnaam.');
306 }
307 $raw = $profile['id'];
308 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
309 if (!$numeric || (int)$raw < 1) throw new RuntimeException('Ongeldig account-id.');
310 return ['auth:'.(int)$raw, $profile['username']];
311}
312
313function loginUser(string $id, string $name): void {
314 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) throw new RuntimeException('Ongeldig account.');
315 $name = trim($name);
316 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) throw new RuntimeException('Ongeldige gebruikersnaam.');
317 transaction(function () use ($id, $name): void {
318 $existing = query('SELECT id FROM users WHERE id=?', [$id])->fetch();
319 if ($existing) {
320 query('UPDATE users SET name=? WHERE id=?', [$name, $id]);
321 return;
322 }
323 $count = (int)query('SELECT COUNT(*) FROM users')->fetchColumn();
324 query('INSERT INTO users (id, name, role, theme, font, created) VALUES (?,?,?,?,?,?)', [
325 $id, $name, $count === 0 ? 'admin' : 'user', 'system', 'serif', time(),
326 ]);
327 });
328 session_regenerate_id(true);
329 $_SESSION['user'] = $id;
330 $_SESSION['csrf'] = bin2hex(random_bytes(24));
331}
332
333config();
334if (defined('VERHALENBOEK_NO_SESSION')) return;
335session_name('verhalenboek_session');
336ini_set('session.use_strict_mode', '1');
337$sessionLifetime = 86400;
338$sessionPath = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/').'/';
339if ($sessionPath === '//') $sessionPath = '/';
340$sessionSecure = !localDev();
341session_set_cookie_params(['lifetime' => $sessionLifetime, 'path' => $sessionPath, 'secure' => $sessionSecure, 'httponly' => true, 'samesite' => 'Lax']);
342session_set_save_handler(new DatabaseSessions(), true);
343session_start();
344if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
345 setcookie(session_name(), session_id(), [
346 'expires' => time() + $sessionLifetime,
347 'path' => $sessionPath,
348 'secure' => $sessionSecure,
349 'httponly' => true,
350 'samesite' => 'Lax',
351 ]);
352}
353if (localDev() && !in_array($_SESSION['user'] ?? '', ['local:test_user_1', 'local:test_user_2'], true)) {
354 unset($_SESSION['token'], $_SESSION['expires'], $_SESSION['validated']);
355 loginUser('local:test_user_1', 'test_user_1');
356}
357
358function user(): string {
359 if (!isset($_SESSION['user'])) fail('Log in om verder te gaan.', 401, 'missing');
360 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
361 unset($_SESSION['user']);
362 fail('Je sessie is verlopen. Log opnieuw in.', 401, 'missing');
363 }
364 return $_SESSION['user'];
365}
366
367function fail(string $message, int $status = 400, ?string $auth = null): never {
368 http_response_code($status);
369 header('Content-Type: application/json; charset=utf-8');
370 $body = ['error' => $message];
371 if ($auth !== null) {
372 $body['how_to_authenticate'] = authHint($auth);
373 $body['hint'] = $body['how_to_authenticate'];
374 if ($status === 401) header('WWW-Authenticate: Bearer');
375 }
376 echo json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
377 exit;
378}
379
380function jsonOut(mixed $data, int $status = 200): never {
381 http_response_code($status);
382 header('Content-Type: application/json; charset=utf-8');
383 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
384 exit;
385}
386
387function bearerToken(): ?string {
388 $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
389 if ($header === '' && function_exists('getallheaders')) {
390 $headers = getallheaders();
391 if (is_array($headers)) {
392 foreach ($headers as $name => $value) {
393 if (strcasecmp((string)$name, 'Authorization') === 0) { $header = (string)$value; break; }
394 }
395 }
396 }
397 if ($header === '') return null;
398 if (preg_match('/^Bearer\s+(\S+)\s*$/i', $header, $match)) return $match[1];
399 throw new AppException('De Authorization-header heeft het verkeerde formaat.', 401, 'format');
400}
401
402function authenticate(): array {
403 $token = bearerToken();
404 if ($token !== null) return actorFromToken($token);
405 $id = user();
406 if (!localDev() && time() - ($_SESSION['validated'] ?? 0) > 60) {
407 try {
408 authRequest('/api/me', null, (string)($_SESSION['token'] ?? ''));
409 if (($_SESSION['expires'] ?? 0) - time() < 900) {
410 $extended = authRequest('/api/session/extend', [], (string)$_SESSION['token']);
411 $_SESSION['expires'] = time() + (int)$extended['expires_in'];
412 }
413 $_SESSION['validated'] = time();
414 } catch (Throwable $e) {
415 unset($_SESSION['user']);
416 fail('Log opnieuw in.', 401, 'missing');
417 }
418 }
419 $row = query('SELECT id, role FROM users WHERE id=?', [$id])->fetch();
420 if (!$row) fail('Log opnieuw in.', 401, 'missing');
421 return ['kind' => 'user', 'userId' => $row['id'], 'role' => $row['role']];
422}
423
424function requireCsrf(array $actor): void {
425 if ($actor['kind'] === 'token') return;
426 $sent = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
427 $expected = $_SESSION['csrf'] ?? '';
428 if (!is_string($sent) || !is_string($expected) || $expected === '' || !hash_equals($expected, $sent)) {
429 fail('Ongeldige sessie. Laad de pagina opnieuw.', 403);
430 }
431}
432
433function requireWriter(array $actor): void {
434 if ($actor['kind'] === 'token') return;
435 if (($actor['role'] ?? '') !== 'admin') fail('Alleen een beheerder mag dit wijzigen.', 403, 'writer');
436}
437
438function requireAdminSession(array $actor, string $message = 'Alleen een beheerder mag sleutels beheren.', string $auth = 'admin'): void {
439 if ($actor['kind'] !== 'user' || ($actor['role'] ?? '') !== 'admin') fail($message, 403, $auth);
440}
441
442function requireReader(array $actor): void {
443 if ($actor['kind'] !== 'user') fail('Leesstatus hoort bij een ingelogde lezer.', 403);
444}
445
446function readJson(): array {
447 $raw = file_get_contents('php://input');
448 if ($raw === false || trim($raw) === '') throw new AppException('De aanvraag heeft een JSON-object nodig.');
449 try {
450 $data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
451 } catch (JsonException) {
452 throw new AppException('De JSON is ongeldig.');
453 }
454 if (!is_array($data) || array_is_list($data)) throw new AppException('De JSON moet een object zijn.');
455 return $data;
456}
457
458function apiRoute(): string {
459 $candidates = [];
460 $info = $_SERVER['PATH_INFO'] ?? '';
461 if (is_string($info) && $info !== '') $candidates[] = $info;
462 $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
463 if (preg_match('#/api\.php(/.*)$#', $uri, $match)) $candidates[] = $match[1];
464 foreach ($candidates as $candidate) {
465 $candidate = '/'.trim((string)$candidate, '/');
466 if ($candidate !== '/') return $candidate;
467 }
468 return '/';
469}