-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathRouteHandler.class.php
More file actions
397 lines (339 loc) · 11.4 KB
/
RouteHandler.class.php
File metadata and controls
397 lines (339 loc) · 11.4 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
namespace wcf\system\request;
use wcf\system\event\EventHandler;
use wcf\system\exception\SystemException;
use wcf\system\request\route\DynamicRequestRoute;
use wcf\system\request\route\IRequestRoute;
use wcf\system\request\route\LookupRequestRoute;
use wcf\system\SingletonFactory;
use wcf\util\FileUtil;
/**
* Handles routes for HTTP requests.
*
* Inspired by routing mechanism used by ASP.NET MVC and released under the terms of
* the Microsoft Public License (MS-PL) http://www.opensource.org/licenses/ms-pl.html
*
* @author Alexander Ebert
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
*/
final class RouteHandler extends SingletonFactory
{
/**
* current host and protocol
*/
private static string $host = '';
/**
* current absolute path
*/
private static string $path = '';
/**
* current path info component
*/
private static string $pathInfo;
/**
* HTTP protocol, either 'http://' or 'https://'
*/
private static string $protocol = '';
/**
* HTTP encryption
*/
private static bool $secure;
/**
* true if the default controller is used (support for custom landing page)
*/
private bool $isDefaultController = false;
/**
* true if the controller was renamed and has already been transformed
*/
private bool $isRenamedController = false;
/**
* list of available routes
* @var IRequestRoute[]
*/
private array $routes = [];
/**
* parsed route data
* @var array<string, mixed>
*/
private array $routeData;
/**
* Sets default routes.
*/
protected function init()
{
$route = new DynamicRequestRoute();
$route->setIsACP(true);
$this->addRoute($route);
$route = new DynamicRequestRoute();
$this->addRoute($route);
$route = new LookupRequestRoute();
$this->addRoute($route);
// fire event
EventHandler::getInstance()->fireAction($this, 'didInit');
}
/**
* Adds a new route to the beginning of all routes.
*
* @param IRequestRoute $route
*/
public function addRoute(IRequestRoute $route): void
{
\array_unshift($this->routes, $route);
}
/**
* Returns all registered routes.
*
* @return IRequestRoute[]
**/
public function getRoutes(): array
{
return $this->routes;
}
/**
* Returns true if a route matches. Please bear in mind, that the
* first route that is able to consume all path components is used,
* even if other routes may fit better. Route order is crucial!
*/
public function matches(): bool
{
foreach ($this->routes as $route) {
if (RequestHandler::getInstance()->isACPRequest() != $route->isACP()) {
continue;
}
if ($route->matches(self::getPathInfo())) {
$this->routeData = $route->getRouteData();
$this->isDefaultController = $this->routeData['isDefaultController'];
unset($this->routeData['isDefaultController']);
$hasController = isset($this->routeData['controller']) && $this->routeData['controller'] !== '';
if (
($hasController && $this->isDefaultController())
|| (!$hasController && !$this->isDefaultController())
) {
throw new \DomainException(\sprintf(
"Route implementation '%s' is buggy: Matched route must either be the default controller or a controller must be returned.",
$route::class
));
}
if (isset($this->routeData['isRenamedController'])) {
$this->isRenamedController = $this->routeData['isRenamedController'];
unset($this->routeData['isRenamedController']);
}
$this->registerRouteData();
return true;
}
}
return false;
}
/**
* Returns true if route uses default controller.
*/
public function isDefaultController(): bool
{
return $this->isDefaultController;
}
/**
* Returns true if the controller was renamed and has already been transformed.
*/
public function isRenamedController(): bool
{
return $this->isRenamedController;
}
/**
* Returns parsed route data
*
* @return array<string, mixed>
*/
public function getRouteData(): array
{
return $this->routeData;
}
/**
* Registers route data within $_GET and $_REQUEST.
*/
private function registerRouteData(): void
{
foreach ($this->routeData as $key => $value) {
$_GET[$key] = $value;
$_REQUEST[$key] = $value;
}
}
/**
* Builds a route based upon route components, this is nothing
* but a reverse lookup.
*
* @param array<string, mixed> $components
* @throws SystemException
*/
public function buildRoute(string $application, array $components, ?bool $isACP = null): string
{
if ($isACP === null) {
$isACP = RequestHandler::getInstance()->isACPRequest();
}
$components['application'] = $application;
foreach ($this->routes as $route) {
if ($isACP != $route->isACP()) {
continue;
}
if ($route->canHandle($components)) {
return $route->buildLink($components);
}
}
throw new SystemException("Unable to build route, no available route is satisfied.");
}
/**
* Returns true if `$customUrl` contains only the letters a-z/A-Z, numbers, dashes,
* underscores and forward slashes.
*
* All other characters including those from the unicode range are potentially unsafe,
* especially when dealing with url rewriting and resulting encoding issues with some
* webservers.
*
* This heavily limits the abilities for end-users to define appealing urls, but at
* the same time this ensures a sufficient level of stability.
*
* @param string $customUrl url to perform sanity checks on
* @return bool true if `$customUrl` passes the sanity check
* @since 3.0
*/
public static function isValidCustomUrl($customUrl): bool
{
return \preg_match('~^[a-z0-9\-_/]+$~', $customUrl) === 1;
}
/**
* Returns true if this is a secure connection.
*/
public static function secureConnection(): bool
{
if (!isset(self::$secure)) {
self::$secure = false;
if (
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
|| $_SERVER['SERVER_PORT'] == 443
|| (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
) {
self::$secure = true;
}
}
return self::$secure;
}
/**
* Returns true if the current environment is treated as a secure context by
* browsers.
*
* @see https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#when_is_a_context_considered_secure
* @since 6.1
*/
public static function secureContext(): bool
{
static $secureContext = null;
if ($secureContext === null) {
$secureContext = self::secureConnection();
// The connection is considered as secure if it is encrypted with
// TLS, or if the target host is a local address.
if (!$secureContext) {
$host = $_SERVER['HTTP_HOST'];
// @see https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-let-localhost-be-localhost-02
if ($host === '127.0.0.1' || $host === 'localhost' || \str_ends_with($host, '.localhost')) {
$secureContext = true;
}
}
}
return $secureContext;
}
/**
* Returns HTTP protocol, either 'http://' or 'https://'.
*/
public static function getProtocol(): string
{
if (empty(self::$protocol)) {
self::$protocol = 'http' . (self::secureConnection() ? 's' : '') . '://';
}
return self::$protocol;
}
/**
* Returns protocol and domain name.
*/
public static function getHost(): string
{
if (empty(self::$host)) {
self::$host = self::getProtocol() . $_SERVER['HTTP_HOST'];
}
return self::$host;
}
/**
* Returns absolute domain path.
*
* @param string[] $removeComponents
*/
public static function getPath(array $removeComponents = []): string
{
if (empty(self::$path)) {
// dirname return a single backslash on Windows if there are no parent directories
$dir = \dirname($_SERVER['SCRIPT_NAME']);
self::$path = ($dir === '\\') ? '/' : FileUtil::addTrailingSlash($dir);
}
if (!empty($removeComponents)) {
$path = \explode('/', self::$path);
foreach ($path as $index => $component) {
if (empty($path[$index])) {
unset($path[$index]);
}
if (\in_array($component, $removeComponents)) {
unset($path[$index]);
}
}
return FileUtil::addTrailingSlash('/' . \implode('/', $path));
}
return self::$path;
}
/**
* Returns current path info component.
*/
public static function getPathInfo(): string
{
if (!isset(self::$pathInfo)) {
self::$pathInfo = '';
if (!empty($_SERVER['QUERY_STRING'])) {
// don't use parse_str as it replaces dots with underscores
$components = \explode('&', $_SERVER['QUERY_STRING']);
for ($i = 0, $length = \count($components); $i < $length; $i++) {
$component = $components[$i];
$pos = \mb_strpos($component, '=');
if ($pos !== false && $pos + 1 === \mb_strlen($component)) {
$component = \mb_substr($component, 0, -1);
$pos = false;
}
if ($pos === false) {
self::$pathInfo = \urldecode($component);
break;
}
}
}
// translate legacy controller names
if (\preg_match('~^(?P<controller>(?:[A-Z]+[a-z0-9]+)+)(?:/|$)~', self::$pathInfo, $matches)) {
$parts = \preg_split(
'~([A-Z]+[a-z0-9]+)~',
$matches['controller'],
-1,
\PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY
);
$parts = \array_map('strtolower', $parts);
self::$pathInfo = \implode('-', $parts) . \mb_substr(
self::$pathInfo,
\mb_strlen($matches['controller'])
);
}
}
return self::$pathInfo;
}
/**
* Overrides the path info as part of the smart URL rewriting feature.
*
* @since 6.2
*/
public static function overridePathInfo(string $pathInfo): void
{
self::$pathInfo = $pathInfo;
}
}