-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.php
379 lines (320 loc) · 13.2 KB
/
router.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
<?php
// @link https://github.com/yus-ham/php-server-router
// env vars
// ALT_SCRIPT=index.php,__app.html,etc... comma separated
namespace Yusham\PhpServerRouter
{
$_SERVER['SERVER_SOFTWARE'] = $_SERVER['SERVER_SOFTWARE'] .' | Apache conf enabled';
class Config
{
const debug = false;
const protected_paths = '~/\.git(\/.*)?$~';
const show_files = true;
}
class Router
{
private static $docRoot;
private static $prevPathInfo;
private static $requestURI;
private static $rewriteURI;
private static $pathInfo = '';
private static $parsedHtaccess = [];
private static $type2Exts = [
'text/html' => 'htm,html',
'text/css' => 'css',
'text/javascript' => 'js,mjs',
'image/svg+xml' => 'svg',
'image/' => 'png,gif,jpg,jpeg,webp',
'audio/' => 'mp3',
'video/' => 'mp4,webm',
'application/json' => 'json,map',
'application/' => 'pdf',
'font/' => 'woff,woff2',
];
// default = index.php,index.html
// @see [getScripts()]
public static $scripts;
public static function setup()
{
$port = ($_SERVER['SERVER_PORT'] != '80') ? ":$_SERVER[SERVER_PORT]" : "";
$_SERVER['SERVER_ADDR'] = "$_SERVER[SERVER_NAME]$port";
if (empty($_SERVER['QUERY_STRING'])) {
$_SERVER['QUERY_STRING'] = "";
}
self::setRequestURI();
}
public static function run()
{
self::setup();
self::maybeFileRequest();
return self::serveURI();
}
protected static function serveURI()
{
$currentUri = self::getFilePath(self::$requestURI);
error_log("REQUEST_URI = $currentUri");
$_SERVER['QUERY_STRING'] === 'phpinfo()' && die(phpinfo());
if (self::isProtected($currentUri)) {
http_response_code(403);
self::showError('HTTP/1.1 403 Forbidden');
}
self::$docRoot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
$path = self::$docRoot . $currentUri;
if (is_dir($path)) {
if (substr($currentUri, -1) !== '/') {
exit(header("Location: $currentUri/"));
}
return self::serveDir($path, $currentUri);
}
if (is_file($path)) {
if (self::isDot('php', $path)) {
return self::serveScript($path, dirname($path));
}
self::readFile($path);
}
$i = 0;
do {
self::$pathInfo = '/'. basename($currentUri) . self::$pathInfo;
$currentUri = rtrim(str_replace('\\', '/', dirname($currentUri)), '/');
$dir = self::$docRoot . $currentUri;
if (false === self::serveIndex($dir, $currentUri)) {
return;
}
} while (($i++ < 20) && ($currentUri && $currentUri !== '/'));
}
protected static function getScripts()
{
if (!self::$scripts) {
self::$scripts = array('index.php', 'index.html');
if ($altScripts = getenv('ALT_SCRIPT')) {
self::$scripts = array_merge(explode(',', $altScripts), self::$scripts);
}
array_unshift(self::$scripts, '.htaccess');
}
return self::$scripts;
}
protected static function serveIndex($dir, $currentUri)
{
foreach (self::getScripts() as $script) {
$script = "$dir/$script";
if (is_file($script)) {
if (self::serveHtaccess($script, $dir, $currentUri) === null) {
continue;
}
self::$pathInfo = preg_replace(':^/'.preg_quote($script).':', '', self::$pathInfo);
return self::serveScript($script, $dir);
}
}
}
private static $redirectNum = 0;
protected static function serveHtaccess($file, $dir, $currentUri)
{
if (!self::isDot('htaccess', $file)) {
return false;
}
if (in_array($file, self::$parsedHtaccess)) {
return;
}
self::$parsedHtaccess[] = $file;
$stopParsing = false;
$lines = file($file);
foreach ($lines as $line) {
@list($command, $args) = explode(' ', trim($line), 2);
if ($command === '#phps-ignore') {
self::runPhpsIgnore($args);
}
}
foreach ($lines as $line) {
@list($command, $args) = explode(' ', trim($line), 2);
if (strpos($command, 'Rewrite') !== 0) {
continue;
}
$args = preg_split('/ +/', trim($args));
if ($command === 'RewriteEngine' && strtolower($args[0]) === 'on') {
self::$rewriteURI = true;
continue;
}
if (!self::$rewriteURI) {
throw new \Exception('Rewrite engine is off');
}
if ($command === 'RewriteCond') {
if ($args[0] === '%{REQUEST_FILENAME}') {
if ($args[1] === '!-d' && is_dir(self::$docRoot . self::$requestURI)) {
return;
}
if ($args[1] === '!-f' && is_file(self::$docRoot . self::$requestURI)) {
return;
}
}
}
if ($command === 'RewriteRule') {
if (self::$redirectNum === 5) {
return;
}
$newURI = preg_replace(':' . ($args[0] === '.' ? '.+' : $args[0]) . ':', $args[1], ltrim(self::$pathInfo, '/'));
self::$prevPathInfo = substr(self::$requestURI, strlen($currentUri));
self::$requestURI = $currentUri . '/' . $newURI;
self::$pathInfo = '';
error_log("\n\n ==============================\nRedirected to: ". self::$requestURI ."\n");
self::$redirectNum++;
return self::serveURI();
}
}
}
protected static function runPhpsIgnore($path)
{
if (preg_match('#'.preg_quote(trim($path)).'#', self::$pathInfo)) {
die(!http_response_code(404));
}
}
protected static function serveDir($dir, $currentUri)
{
$dir = rtrim($dir, '/');
if (false === self::serveIndex($dir, $currentUri)) {
return;
}
http_response_code(404);
if (Config::show_files) {
exit(self::showFiles($dir));
}
}
protected static function serveScript($script, $dir)
{
// PHP Built-in server fails to serve path that contains dot
$hasDotInDir = strpos($dir, '.') !== false;
if (!$hasDotInDir && self::isDot('php', $script) && self::$prevPathInfo === null) {
return false;
}
if (self::$pathInfo !== null or self::$prevPathInfo !== null) {
if (self::$prevPathInfo) {
$_SERVER['SCRIPT_NAME'] = str_replace(self::$prevPathInfo, '', $_SERVER['SCRIPT_NAME']);
}
$baseURI = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$_SERVER['SCRIPT_NAME'] = ($baseURI === '/' ? '' : $baseURI) . substr($script, strlen($dir));
} else {
$_SERVER['SCRIPT_NAME'] .= $script;
}
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
self::includeScript($script);
}
protected static function includeScript($script)
{
chdir(dirname($script));
include $_SERVER['SCRIPT_FILENAME'] = $script;
exit();
}
protected static function getFilePath($url)
{
return explode('?', $url)[0];
}
protected static function setRequestURI()
{
return self::$requestURI = str_replace('//', '/', self::getFilePath($_SERVER['REQUEST_URI']));
}
protected static function showFiles($dir)
{
header('Content-Type: text/html');
$files = array_merge((array) @scandir($dir), []);
sort($files);
echo '<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
<style>body{font: normal 1.4em/1.4em monospace}
a{text-decoration:none} a:hover{background:#B8C7FF}</style></head><body>';
$reqUri = self::$requestURI;
echo "<table>";
$_dirs = [];
$_files = [];
foreach ($files as $file) {
if ($file === '.' or $file === '..') {
continue;
}
@filemtime("$dir/$file");
if (is_dir("$dir/$file")) {
@$_dirs[] = $file;
} else {
@$_files[] = $file;
}
}
$reqUri === '/' OR empty($reqUri) OR print("<tr><td>[+] <a href='$reqUri..'>../</a></td><td></td><td></td></tr>\n");
foreach ((array) @$_dirs as $item) {
$link = "$reqUri$item/";
echo "<tr><td>[+] <a href='$link'>$item/</a></td><td></td><td></td></tr>\n";
}
foreach ((array) @$_files as $file) {
$link = "$reqUri$file";
if (is_file("$dir/$file")) {
$bytes = filesize("$dir/$file");
echo "<tr><td>[•] <a href='$link'>$file</a></td><td><span class=filesize>$bytes</span></td>";
} else {
echo "<tr><td>[•] <s>$file</s></td><td><span class=filesize>0</span></td>";
}
echo "<td><a href='?view=$link'>view</a></td></tr>\n";
}
echo "</table>";
echo "<script src='/?~/global.js'></script></body></html>";
}
protected static function showError($message)
{
$template = "<html><meta name='viewport' content='width=device-width, initial-scale=1'>
<title>$message</title><body>
<p><code>>> $_SERVER[REQUEST_METHOD] " . htmlspecialchars(urldecode($_SERVER['REQUEST_URI'])) . " $_SERVER[SERVER_PROTOCOL]</code></p>
<p><code><< $message</code></p></body>";
exit($template);
}
protected static function isProtected($path)
{
$regex = Config::protected_paths;
if (preg_match($regex, $path)) {
return true;
}
}
protected static function readFile($file, $ext = null)
{
$ext = $ext ?: strtolower(pathinfo($file, PATHINFO_EXTENSION));
foreach (self::$type2Exts as $type => $exts) {
$exts = explode(',', $exts);
if (in_array($ext, $exts)) {
header('content-type: ' . ($type[-1] === '/' ? $type . $ext : $type));
$setMime = true;
break;
}
}
if (empty($setMime)) {
header('content-type: application/octet-stream');
}
header('expires: '. date(DATE_RFC7231, time() + $maxAge = 31536000));
header('cache-control: max-age='. $maxAge);
readfile($file);
exit();
}
protected static function maybeFileRequest()
{
foreach ($_GET as $key => $v) {
if (strpos($key, '~/')) {
$file = substr($key, 1);
break;
}
}
if (empty($file)) {
return;
}
if ($file === '/global.js') {
header('Content-Type: application/javascript');
header('Cache-Control: public, max-age=' . strtotime('6 month'));
die("// @link http://stackoverflow.com/a/20463021\n"
."fileSizeIEC = (a,b,c,d,e) => (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2) +' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')\n"
."document.querySelectorAll('.filesize').forEach((e) => e.innerHTML = fileSizeIEC(e.innerHTML))");
}
$ext = pathinfo($file, PATHINFO_EXTENSION);
$players['mp4'] = fn () => include 'plyr.php';
$players['js'] = fn () => self::readFile(__DIR__ . '/' . $file, $ext);
$players['css'] = $players['js'];
$player = $players[$ext] ?? fn () => 'no viewer for ' . $file;
die($player());
}
public static function isDot($ext, $file)
{
return pathinfo($file, PATHINFO_EXTENSION) === $ext;
}
}
return !!Router::run();
}