page: catch fatal php errors
[minimedit.git] / page.php
1 <?php
2 error_reporting(E_ALL);
3 ini_set('display_errors', TRUE);
4
5 function fail($error)
6 {
7         http_response_code(500);
8         include_once 'page.inc.php';
9         ob_start();
10         require_once './500.html';
11         print str_replace('[[debug]]', $error, ob_get_clean());
12 }
13 set_exception_handler('fail');
14 register_shutdown_function(function () {
15         # display failure page for fatal exceptions
16         $error = error_get_last();
17         if (!($error['type'] & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR))) return;
18         fail("Fatal: $error[message] in $error[file]:$error[line]");
19 });
20
21 include_once 'auth.inc.php';
22 $Edit = isset($_GET['edit']);
23
24 # distinguish subpage Args from topmost Page script
25
26 $Args = '';
27 $Page = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
28 $Page = urldecode(trim($Page, '/')) ?: 'index';
29 while (TRUE) {
30         if (file_exists("$Page.php")) {
31                 break;
32         }
33
34         $up = strrpos($Page, '/');
35         $Args = substr($Page, $up) . $Args;
36         $Page = substr($Page, 0, $up);
37         if ($up === FALSE) {
38                 break;
39         }
40 }
41
42 # load static contents
43
44 ob_start(); # page body
45 ob_start(); # inner html
46 print '<div class="static">'."\n\n";
47
48 $found = FALSE;
49 if (file_exists("$Page$Args/index.html")) {
50         $found = include "./$Page$Args/index.html";
51 }
52 elseif (file_exists("$Page$Args.html")) {
53         $found = include "./$Page$Args.html";
54 }
55
56 print "</div>\n\n";
57
58 # execute dynamic code
59
60 if ($Page) {
61         $found |= require "./$Page.php";
62 }
63
64 # global html
65
66 include_once 'page.inc.php';
67
68 if (!$found) {
69         # no resulting output
70         if (isset($User) and $User['admin']) {
71                 require './template.html';
72         }
73         else {
74                 http_response_code(404);
75                 ob_start();
76                 require "./404.html";
77                 $url = htmlspecialchars($_SERVER['REQUEST_URI']);
78                 print str_replace('[[url]]', $url, ob_get_clean());
79         }
80 }
81