forked from perdedora/nicochan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.php
390 lines (323 loc) · 13.7 KB
/
mod.php
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
<?php
/*
* Copyright (c) 2010-2024 Tinyboard Development Group
*/
require_once 'inc/bootstrap.php';
require_once 'inc/mod/pages.php';
/**
* Class Router
*
* Handles HTTP request routing.
*/
class Router {
/** @var array $pages Array of URL patterns and their corresponding handlers */
private array $pages;
/** @var string $query The query string from the HTTP request */
private string $query;
/** @var mixed $mod Mod information for the current user session */
private mixed $mod;
/** @var array $config Configuration settings for the application */
private array $config;
/** @var bool $securePostOnly Indicates if the current handler requires a secure POST request */
private bool $securePostOnly = false;
/**
* Router constructor.
*
* @param array $config Configuration settings for the application
* @param mixed|null $mod Mod information for the current user session
*/
public function __construct(array $config, mixed $mod = null) {
$this->config = $config;
$this->mod = $mod;
$this->query = isset($_SERVER['QUERY_STRING']) ? rawurldecode($_SERVER['QUERY_STRING']) : '';
$this->initializePages();
}
/**
* Initializes the array of pages and their handlers.
*
* This method sets up the routing table for various endpoints.
*/
private function initializePages(): void {
$this->pages = [
'' => ':?/', // redirect to dashboard
'/' => 'dashboard', // dashboard
'/confirm/(.+)' => 'confirm', // confirm action (if javascript didn't work)
'/logout' => 'secure logout', // logout
'/users' => 'users', // manage users
'/users/(\d+)/(promote|demote)' => 'secure user_promote', // promote/demote user
'/users/(\d+)' => 'secure_POST user', // edit user
'/users/new' => 'secure_POST user_new', // create a new user
'/new_PM/([^/]+)' => 'secure_POST new_pm', // create a new pm
'/PM/(\d+)(/reply)?' => 'pm', // read a pm
'/inbox' => 'inbox', // pm inbox
'/log' => 'log', // modlog
'/log/(\d+)' => 'log', // modlog
'/log:([^/:]+)' => 'user_log', // user log
'/log:([^/:]+)/(\d+)' => 'user_log', // user log
'/log:b:([^/]+)' => 'board_log', // board log
'/log:b:([^/]+)/(\d+)' => 'board_log', // board log
'/edit_news' => 'secure_POST news', // view news
'/edit_news/(\d+)' => 'secure_POST news', // view news
'/edit_news/delete/(\d+)' => 'secure news_delete', // delete from news
'/banners/(\%b)' => 'secure_POST banners', // view/upload banners
'/edit_pages(?:/?(\%b)?)' => 'secure_POST pages', // edit static pages from board
'/edit_page/(\d+)' => 'secure_POST edit_page', // edit site-wide static pages
'/edit_pages/delete/([a-z0-9]+)' => 'secure delete_page', // delete site-wide static pages
'/edit_pages/delete/([a-z0-9]+)/(\%b)' => 'secure delete_page_board', // delete static pages from board
'/wl_region' => 'whitelist_region', // view whitelist
'/change_wl(/([\w.:]+))?' => 'secure_POST change_whitelist', // modify whitelist
'/hashlist' => 'hashlist', // view hashban list
'/hashlist/(\d+)' => 'secure_POST change_hashlist', // modify hashban list
'/noticeboard' => 'secure_POST noticeboard', // view noticeboard
'/noticeboard/(\d+)' => 'secure_POST noticeboard', // view noticeboard
'/noticeboard/thread/(\d+)' => 'secure_POST noticeboard_view', // view noticeboard thread
'/noticeboard/delete/(\d+)' => 'secure noticeboard_delete', // delete from noticeboard
'/edit/(\%b)' => 'secure_POST edit_board', // edit board details
'/new-board' => 'secure_POST new_board', // create a new board
'/rebuild' => 'secure_POST rebuild', // rebuild
'/reports' => 'reports', // report queue
'/reports/(\d+)/dismiss(&all|&post)?' => 'secure report_dismiss', // dismiss a report
'/IP/([\w.:]+)/page/(\d+)' => 'secure_POST ip', // view ip address
'/IP/([\w.:]+)/remove_note/(\d+)' => 'secure ip_remove_note', // remove note from ip address
'/(\%b)/bantz/(\d+)' => 'secure_POST bantz_post', // issue bantz for post
'/(\%b)/warning(&delete)?/(\d+)' => 'secure_POST warning_post', // issue warning
'/(\%b)/nicenotice/(\d+)' => 'secure_POST nicenotice_post', // issue nicenotice
'/ban-cookie' => 'secure_POST ban_cookie', // ban cookie
'/ban' => 'secure_POST ban', // new ban
'/bans' => 'secure_POST bans', // ban list
'/bans.json' => 'secure bans_json', // ban list json
'/edit_ban/(\d+)' => 'secure_POST edit_ban', // edit ban
'/ban-appeals' => 'secure_POST ban_appeals', // view ban appeals
'/recent(_shadow)?/(\d+)' => 'recent_posts', // view recent posts
'/search' => 'search_redirect', // search
'/search/(posts|IP_notes|bans|log)/(.+)/(\d+)' => 'search', // search
'/search/(posts|IP_notes|bans|log)/(.+)' => 'search', // search
'/statistics' => 'view_statistics', // view site post statistics
'/(\%b)/statistics' => 'view_board_statistics', // view site post statistics for given board
'/(\%b)/archive/' => 'secure_POST view_archive', // view archive
'/(\%b)/featured/' => 'secure_POST view_archive_featured', // view featured archive
'/(\%b)/mod_archive/' => 'secure_POST view_archive_mod_archive', // view mod archive
'/shadow_recent_post/(\d+)' => 'recent_shadow_posts', // view recent posts shadow deleted
'/(\%b)/shadow_view/(\d+)' => 'view_shadow_thread', // view shadow deleted thread
'/(\%b)/shadow_restore/(\d+)/(\d+)' => 'secure_POST shadow_restore_post', // restore shadow deleted post
'/(\%b)/shadow_delete/(\d+)' => 'secure_POST shadow_delete_post', // permanent delete shadow deleted post
'/(\%b)/ban(&delete|&deletebyip)?/(\d+)' => 'secure_POST ban_post', // ban poster
'/(\%b)/hash/(\d+)/(\d+)' => 'secure_POST ban_hash', // hashban a file
'/(\%b)/move/(\d+)' => 'secure_POST move', // move thread
'/(\%b)/move_reply/(\d+)' => 'secure_POST move_reply', // move reply
'/(\%b)/merge/(\d+)' => 'secure_POST merge', // merge a post
'/(\%b)/edit(_raw)?/(\d+)' => 'secure_POST edit_post', // edit post
'/(\%b)/delete(_shadow)?/(\d+)' => 'secure delete', // delete post
'/(\%b)/deletefile/(\d+)/(\d+)' => 'secure deletefile', // delete file from post
'/(\%b+)/(un)?spoiler/(\d+)/(\d+)' => 'secure spoiler_image', // spoiler file
'/(\%b)/deletebyip(&global)?/(\d+)' => 'secure deletebyip', // delete all posts by IP address
'/(\%b)/(un)?lock/(\d+)' => 'secure lock', // lock thread
'/(\%b)/(un)?sticky/(\d+)' => 'secure sticky', // sticky thread
'/(\%b)/(un)?cycle/(\d+)' => 'secure cycle', // cycle thread
'/(\%b)/(un)?hideid/(\d+)' => 'secure hideid', // hide poster ID on thread
'/(\%b)/bump(un)?lock/(\d+)' => 'secure bumplock', // bumplock thread
'/(\%b)/archive_thread/(\d+)' => 'secure archive_thread', // send thread to archive
'/themes' => 'themes_list', // manage themes
'/themes/(\w+)' => 'secure_POST theme_configure', // configure/reconfigure theme
'/themes/(\w+)/rebuild' => 'secure theme_rebuild', // rebuild theme
'/themes/(\w+)/uninstall' => 'secure theme_uninstall', // uninstall theme
'/config' => 'secure_POST config', // config editor
'/config/(\%b)' => 'secure_POST config', // board config editor
// This should always be at the end:
'/(\%b)/' => 'view_board',
'/(\%b)/' . preg_quote($this->config['file_index'], '!') => 'view_board',
'/(\%b)/' . str_replace('%d', '(\d+)',
preg_quote($this->config['file_page'], '!')) => 'view_board',
'/(\%b)/' . preg_quote($this->config['catalog_link'], '!') => 'view_catalog',
'/(\%b)/' . preg_quote($this->config['dir']['res'], '!') .
str_replace('%d', '(\d+)',
preg_quote($this->config['file_page50'], '!')) => 'view_thread50',
'/(\%b)/' . preg_quote($this->config['dir']['res'], '!') .
str_replace('%d', '(\d+)',
preg_quote($this->config['file_page'], '!')) => 'view_thread',
// slug
'/(\%b)/' . preg_quote($this->config['dir']['res'], '!') .
str_replace(['%d','%s'], ['(\d+)', '[a-z0-9-]+'],
preg_quote($this->config['file_page50_slug'], '!')) => 'view_thread50',
'/(\%b)/' . preg_quote($this->config['dir']['res'], '!') .
str_replace(['%d','%s'], ['(\d+)', '[a-z0-9-]+'],
preg_quote($this->config['file_page_slug'], '!')) => 'view_thread',
];
if ($this->config['debug']) {
$this->addDebugPages();
}
if (!$this->mod) {
$this->pages = ['!^(.+)?$!' => 'login'];
}
if (isset($this->config['mod']['custom_pages'])) {
$this->pages = array_merge($this->pages, $this->config['mod']['custom_pages']);
}
$this->prepareRoutes();
}
/**
* Adds debugging pages to the routing table if debugging is enabled.
*/
private function addDebugPages(): void {
$this->pages = array_merge_recursive($this->pages, [
'/debug/antispam' => 'debug_antispam',
'/debug/recent' => 'debug_recent_posts',
'/debug/apcu' => 'debug_apcu',
'/debug/sql' => 'secure_POST debug_sql',
]);
}
/**
* Prepares routes by processing page patterns into regex patterns and updating the pages array.
*/
private function prepareRoutes(): void {
$new_pages = [];
foreach ($this->pages as $key => $callback) {
if (is_string($callback) && preg_match('/^secure /', $callback)) {
$key .= '(/(?P<token>[a-f0-9]{8}))?';
}
$key = str_replace('\%b', '?P<board>' . sprintf(substr($this->config['board_path'], 0, -1), $this->config['board_regex']), $key);
$new_pages[strpos($key, '!') === 0 ? $key : '!^' . $key . '(?:&[^&=]+=[^&]*)*$!u'] = $callback;
}
$this->pages = $new_pages;
}
/**
* Handles the incoming request by matching the query string to a route and executing the corresponding handler.
*/
public function handleRequest(): void {
foreach ($this->pages as $uri => $handler) {
if (preg_match($uri, $this->query, $matches)) {
$matches = array_slice($matches, 1);
$this->processBoard($matches);
if (is_string($handler) && preg_match('/^secure(_POST)? /', $handler, $m)) {
$this->securePostOnly = isset($m[1]);
$this->processSecureHandler($matches);
$handler = $this->processHandler($handler);
}
$this->logDebugInfo($uri, $handler);
$matches = array_values($matches);
$this->executeHandler($handler, $matches);
exit;
}
}
$this->error($this->config['error']['404']);
}
/**
* Processes the handler name, removing security prefixes.
*
* @param string $handler The handler name
* @return string The processed handler name
*/
private function processHandler(string $handler): string {
return preg_replace('/^secure(_POST)? /', '', $handler);
}
/**
* Processes the board information from the route matches.
*
* @param array &$matches The array of route matches
*/
private function processBoard(array &$matches): void {
if (isset($matches['board'])) {
$board_match = $matches['board'];
unset($matches['board']);
$key = array_search($board_match, $matches);
if (preg_match('/^' . sprintf(substr($this->config['board_path'], 0, -1), '(' . $this->config['board_regex'] . ')') . '$/u', $matches[$key], $board_match)) {
$matches[$key] = $board_match[1];
}
}
}
/**
* Processes POST secure handlers, validating CSRF tokens.
*
* @param array &$matches The array of route matches
*/
private function processSecureHandler(array &$matches): void {
if (!$this->securePostOnly || $_SERVER['REQUEST_METHOD'] === 'POST') {
$token = $this->getToken($matches);
// CSRF-protected page; validate security token
$actual_query = preg_replace('!/([a-f0-9]{8})$!', '', $this->query);
if ($token !== make_secure_link_token(substr($actual_query, 1))) {
$this->error($this->config['error']['csrf']);
}
}
}
/**
* Retrieves the CSRF token from the route matches or POST data.
*
* @param array &$matches The array of route matches
* @return string|null The CSRF token, or null if not found
*/
private function getToken(array &$matches): ?string {
if (isset($matches['token'])) {
return $matches['token'];
} elseif (isset($_POST['token'])) {
return $_POST['token'];
} else {
if ($this->securePostOnly) {
$this->error($this->config['error']['csrf']);
} else {
mod_confirm(substr($this->query, 1));
exit;
}
}
return null;
}
/**
* Logs debug information, if enabled, about the current request.
*
* @param string $uri The matched URI pattern
* @param string $handler The handler name
*/
private function logDebugInfo(string $uri, string $handler): void {
global $debug, $parse_start_time;
if ($this->config['debug']) {
$debug['mod_page'] = [
'req' => $this->query,
'match' => $uri,
'handler' => $handler,
'type' => gettype($handler),
'secure' => $this->securePostOnly ? 'true' : 'false'
];
$debug['time']['parse_mod_req'] = '~' . round((microtime(true) - $parse_start_time) * 1000, 2) . 'ms';
}
}
/**
* Executes the matched handler with the provided matches.
*
* @param string $handler The handler to execute
* @param array $matches The route matches to pass to the handler
*/
private function executeHandler(string $handler, array $matches): void {
if (is_string($handler)) {
if ($handler[0] === ':') {
$this->safeRedirect(substr($handler, 1));
} elseif (is_callable("mod_$handler")) {
call_user_func_array("mod_$handler", $matches);
} else {
$this->error("Mod page '$handler' not found!");
}
} elseif (is_callable($handler)) {
call_user_func_array($handler, $matches);
} else {
$this->error("Mod page '$handler' not a string, and not callable!");
}
}
/**
* Safely redirects to the specified location.
*
* @param string $location The URL to redirect to
*/
private function safeRedirect(string $location): void {
header('Location: ' . $location, true, $this->config['redirect_http']);
exit;
}
/**
* Triggers an error with the specified message.
*
* @param string $message The error message
*/
private function error(string $message): void {
error($message);
}
}
check_login(true);
$router = new Router($config, $mod);
$router->handleRequest();