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
|
<?php
require_once __DIR__ . "/common.php";
const TEMPLATE_DIR = SRCDIR . "/pages/";
const STATIC_DIR = SRCDIR . "/static/";
const FALLBACK_FILE = TEMPLATE_DIR . "not_found.php";
const DEFAULT_FILE = TEMPLATE_DIR . "index.php";
const DEFAULT_MIME_TYPE = "application/octet-stream";
$cg_map = [];
$cg_dir = SRCDIR . "/codegen";
foreach (scandir($cg_dir) as $cg_ent) {
$cg_path = $cg_dir . "/" . $cg_ent;
if (
$cg_ent[0] === "." ||
!is_file($cg_path) ||
strtolower(pathinfo($cg_ent, PATHINFO_EXTENSION)) !== "php"
) continue;
$data = include $cg_path;
if (!is_array($data) || count($data) !== 2) {
trigger_error(
"Invalid data returned from codegen script '$cg_ent'",
E_USER_WARNING,
);
continue;
}
$cg_map[$data[0]] = $cg_path;
}
function get_mime(string $filename): string {
static $mime_overrides = [
"css" => "text/css",
"js" => "text/javascript",
];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = strtolower($ext);
$mime = $mime_overrides[$ext] ?? mime_content_type($filename);
if ($mime === false)
$mime = DEFAULT_MIME_TYPE;
return $mime;
}
$name = strtok($_SERVER["REQUEST_URI"], "?");
$is_static = false;
$name = ltrim($name, "/");
if (str_starts_with($name, "static/"))
$is_static = true;
elseif (str_ends_with($name, ".html")) {
$name = preg_replace('/\.html$/', "", $name);
http_response_code(302);
header("Location: /$name");
exit;
} elseif ($name === "favicon.ico" && is_file(SRCDIR . "/favicon.ico")) {
$path = SRCDIR . "/favicon.ico";
$len = filesize($path);
header("Content-Type: image/x-icon");
header("Content-Length: $len");
readfile($path);
exit;
} elseif (isset($cg_map[$name])) {
$data = include $cg_map[$name];
if (!is_array($data) || count($data) !== 2) {
http_response_code(500);
echo "Invalid data returned from codegen script '$cg_ent'\n";
exit;
}
header("Content-Type: " . get_mime($data[0]));
header("Content-Length: " . strlen($data[1]));
echo $data[1];
exit;
}
$include_file = FALLBACK_FILE;
if ($is_static) {
$staticFile = STATIC_DIR . preg_replace(';^static/;', "", $name);
if (!is_file($staticFile)) {
$include_file = FALLBACK_FILE;
http_response_code(404);
} else {
$content_type = get_mime($staticFile);
$content_length = filesize($staticFile);
header("Content-Type: $content_type");
header("Content-Length: $content_length");
readfile($staticFile);
exit;
}
} else {
if ($name === "")
$include_file = DEFAULT_FILE;
else
$include_file = TEMPLATE_DIR . $name . ".php";
}
if (!is_file($include_file)) {
$include_file = FALLBACK_FILE;
http_response_code(404);
}
echo hzcom_expand(file_get_contents($include_file));
|