Repository navigation
Expand file tree
/
Copy pathrewrite.php
More file actions
397 lines (346 loc) · 17.5 KB
/
Copy pathrewrite.php
File metadata and controls
397 lines (346 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
<?php
/**
* phpBB SEO Framework — Lightweight Pre-Bootstrap Inbound Front Controller.
*
* Runs BEFORE phpBB common.php boots.
* Matches inbound SEO URLs using ultra-fast compiled route cache.
* Preserves public SEO REQUEST_URI for canonical checks while normalizing internal
* execution server context so phpBB calculates root asset paths as "./".
*
* Resides exclusively at: ext/phpbbseo/framework/rewrite.php
* Deterministically resolves phpBB root from __DIR__ without requiring root file copies.
*/
define('IN_PHPBB', true);
if (!defined('IN_PHPBB'))
{
exit;
}
// 1. Deterministically resolve phpBB installation root filesystem path from __DIR__
$rawRoot = realpath(__DIR__ . '/../../../');
if ($rawRoot === false || !is_file($rawRoot . '/common.php') || !is_file($rawRoot . '/app.php')) {
http_response_code(500);
file_put_contents('php://output', 'Error: Unable to locate phpBB installation root from SEO rewrite handler.');
return;
}
$phpbbRootPath = rtrim(str_replace('\\', '/', $rawRoot), '/') . '/';
// 2. Ensure current working directory is the phpBB installation root
@chdir($phpbbRootPath);
$phpbb_root_path = './';
$phpEx = 'php';
define('PHPBB_SEO_REWRITE', true);
$cacheFile = __DIR__ . '/store/compiled_routes.php';
// Safe hardcoded target script map (Security rule: user input NEVER reaches include path)
$targetScripts = [
'topic' => 'viewtopic.php',
'forum' => 'viewforum.php',
'member' => 'memberlist.php',
'group' => 'memberlist.php',
'post' => 'viewtopic.php',
];
$routes = null;
if (file_exists($cacheFile)) {
$routes = include $cacheFile;
if (is_array($routes) && isset($routes['__disabled']) && $routes['__disabled'] === true) {
$routes = []; // Extension is disabled: bypass SEO rewrite
}
}
if ($routes === null || (!is_array($routes) && !file_exists($cacheFile))) {
// Fail-safe: Use default routes if cache file is absent
$routes = [
['regex' => '#^/topic/(?P<slug>[^/]+)-(?P<id>[0-9]+)/page/(?P<page>[0-9]+)/?$#u', 'resource' => 'topic', 'is_page' => true],
['regex' => '#^/topic/(?P<slug>[^/]+)-(?P<id>[0-9]+)/page-(?P<page>[0-9]+)/?$#u', 'resource' => 'topic', 'is_page' => true],
['regex' => '#^/topic/(?P<slug>[^/]+)-(?P<id>[0-9]+)/?$#u', 'resource' => 'topic', 'is_page' => false],
['regex' => '#^/forum/(?P<slug>[^/]+)-(?P<id>[0-9]+)/page/(?P<page>[0-9]+)/?$#u', 'resource' => 'forum', 'is_page' => true],
['regex' => '#^/forum/(?P<slug>[^/]+)-(?P<id>[0-9]+)/page-(?P<page>[0-9]+)/?$#u', 'resource' => 'forum', 'is_page' => true],
['regex' => '#^/forum/(?P<slug>[^/]+)-(?P<id>[0-9]+)/?$#u', 'resource' => 'forum', 'is_page' => false],
['regex' => '#^/member/(?P<slug>[^/]+)-(?P<id>[0-9]+)/?$#u', 'resource' => 'member', 'is_page' => false],
['regex' => '#^/group/(?P<slug>[^/]+)-(?P<id>[0-9]+)/?$#u', 'resource' => 'group', 'is_page' => false],
];
$storeDir = __DIR__ . '/store/';
if (!is_dir($storeDir)) {
@mkdir($storeDir, 0755, true);
}
@file_put_contents($cacheFile, "<?php\n// Auto-generated route cache.\ndeclare(strict_types=1);\n\nreturn " . var_export($routes, true) . ";\n");
}
$rawUri = $_SERVER['REQUEST_URI'] ?? '';
$qPos = strpos($rawUri, '?');
if ($qPos === false && preg_match('~^(/.*?)(/)?(?:&|&)(.*)$~i', $rawUri, $ampMatches)) {
$path = $ampMatches[1] . ($ampMatches[2] ?? '');
parse_str($ampMatches[3], $extraGet);
$_GET = array_merge($_GET, $extraGet);
} else {
$path = ($qPos !== false) ? substr($rawUri, 0, $qPos) : $rawUri;
}
$path = rawurldecode($path);
// Determine board web path prefix (e.g. "/phpbb/ext/..." -> "/phpbb", "/ext/..." -> "")
$scriptName = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '');
$extSubPath = '/ext/phpbbseo/framework/rewrite.php';
$pos = strrpos($scriptName, $extSubPath);
$boardDir = ($pos !== false) ? substr($scriptName, 0, $pos) : '';
$boardDir = rtrim($boardDir, '/');
if ($boardDir !== '' && str_starts_with($path, $boardDir . '/')) {
$path = substr($path, strlen($boardDir));
}
// Pre-boot fast path for llms.txt (serves cached Pro file with 0 database queries)
if ($path === '/llms.txt') {
$llmsCacheFile = $phpbbRootPath . 'ext/phpbbseo/pro/store/llms.txt.cache';
if (is_file($llmsCacheFile) && is_readable($llmsCacheFile)) {
header('Content-Type: text/plain; charset=UTF-8');
header('Cache-Control: public, max-age=86400');
readfile($llmsCacheFile);
return;
}
}
// 1. Intercept and route native operational endpoints (e.g. relative resolution from deep SEO URLs)
$nativeScriptMap = [
'adm/index.php' => 'adm/index.php',
'download/file.php' => 'download/file.php',
'file.php' => 'download/file.php',
'posting.php' => 'posting.php',
'mcp.php' => 'mcp.php',
'ucp.php' => 'ucp.php',
'report.php' => 'report.php',
'cron.php' => 'cron.php',
'viewtopic.php' => 'viewtopic.php',
'viewforum.php' => 'viewforum.php',
'memberlist.php' => 'memberlist.php',
'search.php' => 'search.php',
'viewonline.php' => 'viewonline.php',
'index.php' => 'index.php',
];
if (preg_match('#(?:^|/)(adm/index\.php|download/file\.php|file\.php|posting\.php|mcp\.php|ucp\.php|report\.php|cron\.php|viewtopic\.php|viewforum\.php|memberlist\.php|search\.php|viewonline\.php|index\.php)$#i', $path, $nativeMatch)) {
$matchedKey = strtolower($nativeMatch[1]);
if (isset($nativeScriptMap[$matchedKey])) {
$targetScript = $nativeScriptMap[$matchedKey];
$canonicalScript = ($boardDir !== '') ? $boardDir . '/' . $targetScript : '/' . $targetScript;
// If accessed with a deep/relative prefix (e.g. /member/slug-101/adm/index.php or /topic/.../ucp.php),
// redirect immediately to the canonical root script so the browser URL is corrected.
if ($path !== '/' . $targetScript && $targetScript !== 'download/file.php') {
$queryString = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
$statusCode = (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') ? 307 : 301;
header('Cache-Control: no-cache, must-revalidate');
header('Location: ' . $canonicalScript . $queryString, true, $statusCode);
return;
}
if (is_file($phpbbRootPath . $targetScript)) {
$internalScript = $canonicalScript;
$internalQuery = http_build_query($_GET);
$_SERVER['SCRIPT_NAME'] = $internalScript;
$_SERVER['PHP_SELF'] = $internalScript;
$_SERVER['SCRIPT_FILENAME'] = $phpbbRootPath . $targetScript;
$_SERVER['REQUEST_URI'] = $internalScript . ($internalQuery !== '' ? '?' . $internalQuery : '');
$_SERVER['PATH_INFO'] = '';
if ($targetScript === 'download/file.php') {
@chdir($phpbbRootPath . 'download');
} elseif ($targetScript === 'adm/index.php') {
@chdir($phpbbRootPath . 'adm');
}
set_error_handler(static function ($errno, $errstr) {
return str_contains($errstr, 'IN_PHPBB already defined');
});
require $phpbbRootPath . $targetScript;
return;
}
}
}
// 2. Intercept and handle relative static asset requests from deep SEO URL paths
if (preg_match('#(?:^|/)(styles|assets|images|ext)/(.*)$#i', $path, $assetMatch)) {
$assetRelPath = rtrim($assetMatch[1] . '/' . $assetMatch[2], '/');
$fullAssetPath = $phpbbRootPath . $assetRelPath;
if (is_file($fullAssetPath)) {
$realAssetPath = realpath($fullAssetPath);
if ($realAssetPath !== false && str_starts_with(str_replace('\\', '/', $realAssetPath), $phpbbRootPath)) {
$ext = strtolower(pathinfo($realAssetPath, PATHINFO_EXTENSION));
$staticMimes = [
'css' => 'text/css; charset=UTF-8',
'js' => 'application/javascript; charset=UTF-8',
'mjs' => 'application/javascript; charset=UTF-8',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'svg' => 'image/svg+xml',
'webp' => 'image/webp',
'ico' => 'image/x-icon',
'woff' => 'font/woff',
'woff2' => 'font/woff2',
'ttf' => 'font/ttf',
'otf' => 'font/otf',
'eot' => 'application/vnd.ms-fontobject',
'map' => 'application/json',
];
if (isset($staticMimes[$ext])) {
$mtime = filemtime($realAssetPath);
$fileSize = filesize($realAssetPath);
$etag = '"' . dechex((int) $mtime) . '-' . dechex((int) $fileSize) . '"';
header('Content-Type: ' . $staticMimes[$ext]);
header('ETag: ' . $etag);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
header('Cache-Control: public, max-age=31536000, immutable');
header('X-Content-Type-Options: nosniff');
header('Vary: Accept-Encoding');
$ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : null;
$ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : null;
if (($ifNoneMatch !== null && $ifNoneMatch === $etag) || ($ifModifiedSince !== null && $ifModifiedSince >= $mtime)) {
http_response_code(304);
return;
}
$isCompressible = in_array($ext, ['css', 'js', 'mjs', 'svg', 'json', 'map'], true);
$acceptsGzip = isset($_SERVER['HTTP_ACCEPT_ENCODING']) && str_contains($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
$phpAutoGzip = (bool) filter_var(ini_get('zlib.output_compression'), FILTER_VALIDATE_BOOLEAN)
|| in_array('ob_gzhandler', ob_list_handlers(), true)
|| in_array('zlib output compression', ob_list_handlers(), true);
if ($isCompressible && $acceptsGzip && function_exists('gzencode') && !$phpAutoGzip) {
$compressed = gzencode(file_get_contents($realAssetPath), 6);
if ($compressed !== false) {
header('Content-Encoding: gzip');
header('Content-Length: ' . strlen($compressed));
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') {
file_put_contents('php://output', $compressed);
}
return;
}
}
if (!$phpAutoGzip) {
header('Content-Length: ' . $fileSize);
}
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') {
readfile($realAssetPath);
}
return;
}
}
// Fallback: fast 301 redirect preserving query parameters and adding Cache-Control
$targetAssetUrl = ($boardDir !== '') ? $boardDir . '/' . $assetRelPath : '/' . $assetRelPath;
if (!empty($_SERVER['QUERY_STRING'])) {
$targetAssetUrl .= '?' . $_SERVER['QUERY_STRING'];
}
header('Cache-Control: public, max-age=31536000');
header('Location: ' . $targetAssetUrl, true, 301);
return;
}
// Static Asset Fast-Path:
// If the request targets a static asset file extension (images, css, js, fonts, maps)
// inside styles/, assets/, images/, or ext/ and the physical file does NOT exist on disk,
// verify it is NOT a dynamic controller route before fast-failing with 404.
if (preg_match('#\.(?:png|jpe?g|gif|svg|webp|ico|css|js|map|woff2?|ttf|eot|otf)$#i', $assetRelPath)) {
$isDynamicRoute = false;
$matcherFile = $phpbbRootPath . 'cache/production/url_matcher.php';
if (is_file($matcherFile)) {
try {
if (!class_exists('Symfony\\Component\\Routing\\RequestContext', false)) {
require_once $phpbbRootPath . 'vendor/autoload.php';
}
require_once $matcherFile;
$context = new \Symfony\Component\Routing\RequestContext();
$matcher = new \phpbb_url_matcher($context);
try {
$matcher->match('/' . ltrim($path, '/'));
$isDynamicRoute = true;
} catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
try {
$matcher->match('/' . ltrim($assetRelPath, '/'));
$isDynamicRoute = true;
} catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e2) {
$isDynamicRoute = false;
} catch (\Throwable $t2) {
$isDynamicRoute = true;
}
} catch (\Throwable $t) {
$isDynamicRoute = true;
}
} catch (\Throwable $outer) {
$isDynamicRoute = true;
}
}
if (!$isDynamicRoute) {
http_response_code(404);
header('Content-Type: text/plain; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
file_put_contents('php://output', '404 Not Found');
return;
}
}
}
// 2. Inbound SEO URL Route Matching
if (is_array($routes) && !empty($routes)) {
foreach ($routes as $route) {
if (preg_match($route['regex'], $path, $matches)) {
$resource = $route['resource'];
$id = isset($matches['id']) ? (int) $matches['id'] : 0;
$page = isset($matches['page']) ? (int) $matches['page'] : 0;
if ($id > 0 && isset($targetScripts[$resource])) {
$targetScript = $targetScripts[$resource];
// Prepare native request environment
switch ($resource) {
case 'topic':
$_GET['t'] = (string) $id;
$_REQUEST['t'] = (string) $id;
break;
case 'forum':
$_GET['f'] = (string) $id;
$_REQUEST['f'] = (string) $id;
break;
case 'member':
$_GET['mode'] = 'viewprofile';
$_GET['u'] = (string) $id;
$_REQUEST['mode'] = 'viewprofile';
$_REQUEST['u'] = (string) $id;
break;
case 'group':
$_GET['mode'] = 'group';
$_GET['g'] = (string) $id;
$_REQUEST['mode'] = 'group';
$_REQUEST['g'] = (string) $id;
break;
case 'post':
$_GET['p'] = (string) $id;
$_REQUEST['p'] = (string) $id;
break;
}
// Support start offset (e.g. from legacy USU -t123-20.html)
if (isset($matches['start']) && (int) $matches['start'] > 0) {
$startOffset = (int) $matches['start'];
$_GET['start'] = (string) $startOffset;
$_REQUEST['start'] = (string) $startOffset;
}
// Dynamically pass page number without hardcoding pagination offsets
if ($page > 1) {
$_GET['seo_page'] = (string) $page;
$_REQUEST['seo_page'] = (string) $page;
}
// Preserve original public SEO URI for Framework RequestContextFactory & canonical checks
$_SERVER['SEO_PUBLIC_REQUEST_URI'] = $_SERVER['REQUEST_URI'];
// Build internal query string
$internalQuery = http_build_query($_GET);
// Normalize internal phpBB execution context
$internalScript = ($boardDir !== '') ? $boardDir . '/' . $targetScript : '/' . $targetScript;
$_SERVER['SCRIPT_NAME'] = $internalScript;
$_SERVER['PHP_SELF'] = $internalScript;
$_SERVER['SCRIPT_FILENAME'] = $phpbbRootPath . $targetScript;
$_SERVER['REQUEST_URI'] = $internalScript . ($internalQuery !== '' ? '?' . $internalQuery : '');
$_SERVER['PATH_INFO'] = '';
set_error_handler(static function ($errno, $errstr) {
return str_contains($errstr, 'IN_PHPBB already defined');
});
require $phpbbRootPath . $targetScript;
return;
}
}
}
}
// 3. Controller Routes (e.g. extension routes, /sitemap.xml, /app.php/demo, /app.php/help/faq)
$appPath = $path;
if (preg_match('#(?:^|/)app\.php(/.*)?$#i', $path, $appMatch)) {
$appPath = $appMatch[1] ?? '';
}
$appScript = ($boardDir !== '') ? $boardDir . '/app.php' : '/app.php';
$_SERVER['SCRIPT_NAME'] = $appScript;
$_SERVER['PHP_SELF'] = $appScript . ($appPath !== '' ? $appPath : '');
$_SERVER['SCRIPT_FILENAME'] = $phpbbRootPath . 'app.php';
$_SERVER['PATH_INFO'] = $appPath !== '' ? $appPath : '';
set_error_handler(static function ($errno, $errstr) {
return str_contains($errstr, 'IN_PHPBB already defined');
});
require $phpbbRootPath . 'app.php';
return;