-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathUnityHTTPD.php
More file actions
380 lines (355 loc) · 12.9 KB
/
Copy pathUnityHTTPD.php
File metadata and controls
380 lines (355 loc) · 12.9 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
<?php
namespace UnityWebPortal\lib;
use UnityWebPortal\lib\exceptions\NoDieException;
use UnityWebPortal\lib\exceptions\ArrayKeyException;
use UnityWebPortal\lib\exceptions\UnityHTTPDMessageNotFoundException;
use RuntimeException;
enum UnityHTTPDMessageLevel: string
{
case DEBUG = "debug";
case INFO = "info";
case SUCCESS = "success";
case WARNING = "warning";
case ERROR = "error";
}
class UnityHTTPD
{
public static function die(?string $x = null): never
{
if ($x !== null) {
echo $x;
}
if (CONFIG["site"]["allow_die"]) {
die();
} else {
throw new NoDieException();
}
}
/*
send HTTP header, set HTTP response code,
print a message just in case the browser fails to redirect if PHP is not being run from the CLI,
and then die
*/
public static function redirect(?string $dest = null): never
{
$dest ??= getURL($_SERVER["REQUEST_URI"]);
header("Location: $dest");
http_response_code(302);
if (CONFIG["site"]["enable_redirect_message"]) {
echo "If you're reading this message, then your browser has failed to redirect you " .
"to the proper destination. click <a href='$dest'>here</a> to continue.";
}
self::die();
}
/*
generates a unique error ID, writes to error log, and then:
if "html_errors" is disabled in the PHP config file:
prints a message to stdout and dies
else, if the user is doing an HTTP POST:
registers a message in the user's session and issues a redirect to display that message
else:
prints an HTML message to stdout, sets an HTTP response code, and dies
we can't always do a redirect or else we could risk an infinite loop.
*/
public static function gracefulDie(
string $log_title,
string $log_message,
string $user_message_title,
string $user_message_body,
?\Throwable $error = null,
int $http_response_code = 200,
mixed $data = null,
): never {
$errorid = uniqid();
$suffix = sprintf(
"Please notify a Unity admin at %s. Error ID: %s.",
CONFIG["mail"]["support"],
$errorid,
);
$user_message_title = htmlspecialchars($user_message_title);
$user_message_body = htmlspecialchars($user_message_body);
if (strlen($user_message_body) === 0) {
$user_message_body = $suffix;
} else {
$user_message_body .= " $suffix";
}
self::errorLog($log_title, $log_message, data: $data, error: $error, errorid: $errorid);
if (ini_get("html_errors") !== "1") {
self::die("$user_message_title -- $user_message_body");
} elseif (($_SERVER["REQUEST_METHOD"] ?? "") == "POST") {
self::messageError($user_message_title, $user_message_body);
self::redirect();
} else {
if (!headers_sent()) {
http_response_code($http_response_code);
}
// text may not be shown in the webpage in an obvious way, so make a popup
self::alert("$user_message_title -- $user_message_body");
echo "<h1>$user_message_title</h1><p>$user_message_body</p>";
// display_errors should not be enabled in production
if (
!is_null($error) &&
ini_get("display_errors") === "1" &&
property_exists($error, "xdebug_message")
) {
echo "<table>";
echo $error->xdebug_message;
echo "</table>";
}
self::die();
}
}
// $data must be JSON serializable
public static function errorLog(
string $title,
string $message,
?string $errorid = null,
?\Throwable $error = null,
mixed $data = null,
): void {
if (!CONFIG["site"]["enable_verbose_error_log"]) {
error_log("$title: $message");
return;
}
$output = ["message" => $message];
if (!is_null($data)) {
try {
\jsonEncode($data);
$output["data"] = $data;
} catch (\JsonException $e) {
$output["data"] = "data could not be JSON encoded: " . $e->getMessage();
}
}
if (!is_null($error)) {
$output["error"] = self::throwableToArray($error);
} else {
// newlines are bad for error log, but getTrace() is too verbose
$output["trace"] = explode("\n", (new \Exception())->getTraceAsString());
}
$output["REMOTE_USER"] = $_SERVER["REMOTE_USER"] ?? null;
$output["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? null;
$output["_REQUEST"] = $_REQUEST;
if (!is_null($errorid)) {
$output["errorid"] = $errorid;
}
error_log("$title: " . \jsonEncode($output));
}
// recursive on $t->getPrevious()
private static function throwableToArray(\Throwable $t): array
{
$output = [
"class" => get_class($t),
"msg" => $t->getMessage(),
// newlines are bad for error log, but getTrace() is too verbose
"trace" => explode("\n", $t->getTraceAsString()),
];
$previous = $t->getPrevious();
if (!is_null($previous)) {
$output["previous"] = self::throwableToArray($previous);
}
return $output;
}
public static function badRequest(
string $log_message,
string $user_message = "",
?\Throwable $error = null,
?array $data = null,
): never {
self::gracefulDie(
"bad request",
$log_message,
"Invalid requested action or submitted data.",
$user_message,
error: $error,
http_response_code: 400,
data: $data,
);
}
public static function forbidden(
string $log_message,
string $user_message = "",
?\Throwable $error = null,
?array $data = null,
): never {
self::gracefulDie(
"forbidden",
$log_message,
"Permission denied.",
$user_message,
error: $error,
http_response_code: 403,
data: $data,
);
}
public static function internalServerError(
string $log_message,
string $user_message = "",
?\Throwable $error = null,
?array $data = null,
): never {
self::gracefulDie(
"internal server error",
$log_message,
"An internal server error has occurred.",
$user_message,
error: $error,
http_response_code: 500,
data: $data,
);
}
// https://www.php.net/manual/en/function.set-exception-handler.php
public static function exceptionHandler(\Throwable $e): void
{
// we disable log_errors before we enable this exception handler to avoid duplicate logging
// if this exception handler itself fails, information will be lost unless we re-enable it
ini_set("log_errors", true);
self::internalServerError("", error: $e);
}
public static function errorHandler(int $severity, string $message, string $file, int $line)
{
if (str_contains($message, "Undefined array key")) {
throw new ArrayKeyException($message);
}
return false;
}
public static function getUploadedFileContents(
string $filename,
bool $do_delete_tmpfile_after_read = true,
string $encoding = "UTF-8",
): string {
if (!array_key_exists($filename, $_FILES)) {
self::badRequest("\$_FILES has no array key '$filename'", data: ['$_FILES' => $_FILES]);
}
if (!array_key_exists("tmp_name", $_FILES[$filename])) {
self::badRequest(
"\$_FILES[$filename] has no array key 'tmp_name'",
data: ['$_FILES' => $_FILES],
);
}
$tmpfile_path = $_FILES[$filename]["tmp_name"];
$contents = file_get_contents($tmpfile_path);
if ($contents === false) {
throw new \Exception("Failed to read file: " . $tmpfile_path);
}
if ($do_delete_tmpfile_after_read) {
unlink($tmpfile_path);
}
$old_encoding = mbDetectEncoding($contents);
return mbConvertEncoding($contents, $encoding, $old_encoding);
}
// in firefox, the user can disable alert/confirm/prompt after the 2nd or 3rd popup
// after I disable alerts, if I quit and reopen my browser, the alerts come back
public static function alert(string $message): void
{
// jsonEncode escapes quotes
echo "<script type='text/javascript'>alert(" . \jsonEncode($message) . ");</script>";
}
private static function ensureSessionMessagesSanity()
{
if (!isset($_SESSION)) {
throw new RuntimeException('$_SESSION is unset');
}
if (!array_key_exists("messages", $_SESSION)) {
self::errorLog(
"invalid session messages",
'array key "messages" does not exist for $_SESSION',
data: ['$_SESSION' => $_SESSION],
);
$_SESSION["messages"] = [];
}
if (!is_array($_SESSION["messages"])) {
$type = gettype($_SESSION["messages"]);
self::errorLog(
"invalid session messages",
"\$_SESSION['messages'] is type '$type', not an array",
data: ['$_SESSION' => $_SESSION],
);
$_SESSION["messages"] = [];
}
}
public static function message(string $title, string $body, UnityHTTPDMessageLevel $level)
{
self::ensureSessionMessagesSanity();
array_push($_SESSION["messages"], [$title, $body, $level]);
}
public static function messageDebug(string $title, string $body)
{
return self::message($title, $body, UnityHTTPDMessageLevel::DEBUG);
}
public static function messageInfo(string $title, string $body)
{
return self::message($title, $body, UnityHTTPDMessageLevel::INFO);
}
public static function messageSuccess(string $title, string $body)
{
return self::message($title, $body, UnityHTTPDMessageLevel::SUCCESS);
}
public static function messageWarning(string $title, string $body)
{
return self::message($title, $body, UnityHTTPDMessageLevel::WARNING);
}
public static function messageError(string $title, string $body)
{
return self::message($title, $body, UnityHTTPDMessageLevel::ERROR);
}
public static function getMessages()
{
self::ensureSessionMessagesSanity();
return $_SESSION["messages"];
}
public static function clearMessages()
{
self::ensureSessionMessagesSanity();
$_SESSION["messages"] = [];
}
private static function getMessageIndex(
UnityHTTPDMessageLevel $level,
string $title,
string $body,
) {
$messages = self::getMessages();
$error_msg = sprintf(
"message(level='%s' title='%s' body='%s'), not found. found messages: %s",
$level->value,
$title,
$body,
jsonEncode($messages),
);
foreach ($messages as $i => $message) {
if ($title == $message[0] && $body == $message[1] && $level == $message[2]) {
return $i;
}
}
throw new UnityHTTPDMessageNotFoundException($error_msg);
}
/* returns the 1st message that matches or throws UnityHTTPDMessageNotFoundException */
public static function getMessage(UnityHTTPDMessageLevel $level, string $title, string $body)
{
$index = self::getMessageIndex($level, $title, $body);
return $_SESSION["messages"][$index];
}
/* deletes the 1st message that matches or throws UnityHTTPDMessageNotFoundException */
public static function deleteMessage(UnityHTTPDMessageLevel $level, string $title, string $body)
{
$index = self::getMessageIndex($level, $title, $body);
unset($_SESSION["messages"][$index]);
$_SESSION["messages"] = array_values($_SESSION["messages"]);
}
public static function validatePostCSRFToken(): void
{
if (!CSRFToken::validate($_POST["csrf_token"])) {
$errorid = uniqid();
self::errorLog("csrf failed to validate", "", errorid: $errorid);
self::messageError(
"Invalid Session Token",
"This can happen if you leave your browser open for too long. Error ID: $errorid",
);
self::redirect();
}
}
public static function getCSRFTokenHiddenFormInput(): string
{
$token = htmlspecialchars(CSRFToken::generate());
return "<input type='hidden' name='csrf_token' value='$token'>";
}
}