page: catch exceptions in placeholder scripts
[minimedit.git] / page.php
1 <?php
2 error_reporting(E_ALL);
3 ini_set('display_errors', TRUE);
4
5 function abort($body, $status = NULL) {
6         if ($status) header("HTTP/1.1 $status");
7         print "$body\n";
8         exit;
9 }
10
11 function getoutput($blocks = [])
12 {
13         $doc = ob_get_clean();
14
15         if (!empty($blocks['warn'])) {
16                 $warn = '<p class="warn">[[warn]]</p>';
17                 if ($offset = strpos($doc, '</h2>')) {
18                         $doc = substr_replace($doc, "\n\n".$warn, $offset + 5, 0);
19                 }
20                 else {
21                         $doc = $warn . "\n\n" . $doc;
22                 }
23         }
24
25         return preg_replace_callback(
26                 '< \[\[ ([^] ]+) ([^]]*) \]\] >x',
27                 function ($sub) use ($blocks) {
28                         list ($placeholder, $name, $params) = $sub;
29                         if (isset($blocks[$name])) {
30                                 $html = $blocks[$name];
31                         }
32                         elseif (file_exists("$name.php")) {
33                                 ob_start();
34                                 $Page = $GLOBALS['Page'] . $GLOBALS['Args'];
35                                 $Args = '';
36                                 $Place = $GLOBALS['Place'];
37                                 foreach (explode(' ', $params) as $param) {
38                                         if ($set = strpos($param, '=')) {
39                                                 $Place[ substr($param, 0, $set) ] = substr($param, $set + 1);
40                                         }
41                                         elseif (!empty($param)) {
42                                                 $Args .= '/'.$param;
43                                         }
44                                 }
45                                 try {
46                                         include "$name.php";
47                                         $html = ob_get_clean();
48                                 }
49                                 catch (Exception $e) {
50                                         $html = sprintf('<strong class="warn">%s</strong>',
51                                                 "fout in <em>$name</em>: {$e->getMessage()}"
52                                         );
53                                 }
54                         }
55                         else {
56                                 $html = '<strong class="warn"><em>'.$name.'</em> ontbreekt</strong>';
57                         }
58                         return sprintf('<!--BLOCK:%s-->%s<!--/-->',
59                                 is_numeric($name) ? '' : $placeholder, # edit replacement
60                                 preg_replace('{<!--[^-]*-->}', '', $html) # contents
61                         );
62                 },
63                 $doc
64         );
65 }
66
67 # custom error handling
68
69 define('DOCROOT', getcwd().'/');
70
71 function fail($error)
72 {
73         http_response_code(500);
74         include_once 'page.inc.php';
75         ob_start();
76         require_once DOCROOT.'500.html';
77         print getoutput(['debug' => $error]);
78 }
79
80 set_exception_handler('fail');
81
82 define('E_FATAL', E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
83
84 set_error_handler(function ($level, $error, $file, $line) {
85         if ($level & E_FATAL) {
86                 fail($error);
87                 return;
88         }
89         return FALSE;
90 });
91
92 register_shutdown_function(function () {
93         # display failure page for fatal exceptions
94         $error = error_get_last();
95         if (!($error['type'] & E_FATAL)) return;
96         fail("Fatal: $error[message] in $error[file]:$error[line]");
97 });
98
99 error_reporting(error_reporting() & ~E_FATAL);
100
101 # user login and control
102
103 include_once 'auth.inc.php';
104 $Edit = isset($_GET['edit']);
105
106 # distinguish subpage Args from topmost Page script
107
108 $Args = '';
109 $Page = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
110 $Page = urldecode(trim($Page, '/')) ?: 'index';
111 while (TRUE) {
112         if (file_exists("$Page/.private")) {
113                 # access restriction
114                 if (empty($User)) {
115                         http_response_code(303);
116                         $target = urlencode($_SERVER['REQUEST_URI']);
117                         header("Location: /login?goto=$target");
118                         exit;
119                 }
120                 $PageAccess = $Page;
121         }
122
123         if (file_exists("$Page/index.php")) {
124                 break;
125         }
126
127         $up = strrpos($Page, '/');
128         $Args = substr($Page, $up) . $Args;
129         $Page = substr($Page, 0, $up);
130         if ($up === FALSE) {
131                 break;
132         }
133 }
134
135 # load static contents
136
137 ob_start(); # page body
138 ob_start(); # inner html
139 print '<div class="static">'."\n\n";
140
141 $found = FALSE;
142 if (file_exists("$Page$Args.html")) {
143         $found = include "./$Page$Args.html";
144 }
145 elseif (file_exists("$Page$Args/index.html")) {
146         $found = include "./$Page$Args/index.html";
147 }
148 elseif (!empty($User['admin'])) {
149         $found = include (file_exists("$Page/template.html") ? "$Page/template.html" : './template.html');
150 }
151
152 print "</div>\n\n";
153
154 # execute dynamic code
155
156 $Place = [];
157
158 if ($Page) {
159         $found |= require "./$Page/index.php";
160 }
161
162 $Place += [
163         'user'  => empty($User) ? '' : $User['name'],
164         'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
165 ];
166
167 # global html
168
169 if (!$found) {
170         # no resulting output
171         http_response_code(404);
172         @require "./404.html";
173 }
174
175 include_once 'page.inc.php';
176