page: ignore failed user setup during errors
[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 placeholder_include($name, $params = [])
12 {
13         $path = stream_resolve_include_path("widget/$name.php");
14         if (!file_exists($path)) {
15                 return '<strong class="warn"><em>'.$name.'</em> ontbreekt</strong>';
16         }
17
18         ob_start();
19         $Page = $GLOBALS['Page'] . $GLOBALS['Args'];
20         $Args = '';
21         $Place = $GLOBALS['Place'];
22         foreach ($params as $param) {
23                 if ($set = strpos($param, '=')) {
24                         $Place[ substr($param, 0, $set) ] = substr($param, $set + 1);
25                 }
26                 elseif (!empty($param)) {
27                         $Args .= '/'.$param;
28                 }
29         }
30         try {
31                 include "widget/$name.php";
32                 return ob_get_clean();
33         }
34         catch (Exception $e) {
35                 return sprintf('<strong class="warn">%s</strong>',
36                         "fout in <em>$name</em>: {$e->getMessage()}"
37                 );
38         }
39 }
40
41 function getoutput($blocks = [])
42 {
43         $doc = ob_get_clean();
44
45         if (!empty($blocks['warn'])) {
46                 $warn = '<p class="warn">[[warn]]</p>';
47                 if ($offset = strpos($doc, '</h2>')) {
48                         $doc = substr_replace($doc, "\n\n".$warn, $offset + 5, 0);
49                 }
50                 else {
51                         $doc = $warn . "\n\n" . $doc;
52                 }
53         }
54
55         # keep either login or logout parts depending on user level
56         global $User;
57         $hideclass = $User && property_exists($User, 'login') && $User->login ? 'logout' : 'login';
58         $doc = preg_replace('{\s*<([a-z]+) class="'.$hideclass.'">.*?</\1>}s', '', $doc);
59
60         return preg_replace_callback(
61                 '{ (?<! <!--BLOCK: ) \[\[ ([^] ]+) ([^]]*) \]\] }x',
62                 function ($sub) use ($blocks) {
63                         list ($placeholder, $name, $params) = $sub;
64                         if (isset($blocks[$name])) {
65                                 $html = $blocks[$name];
66                         }
67                         else {
68                                 $html = placeholder_include($name, explode(' ', $params));
69                         }
70                         return sprintf('<!--BLOCK:%s-->%s<!--/-->',
71                                 is_numeric($name) ? '' : $placeholder, # edit replacement
72                                 preg_replace('{<!--[^-]*-->}', '', $html) # contents
73                         );
74                 },
75                 $doc
76         );
77 }
78
79 # custom error handling
80
81 define('DOCROOT', getcwd());
82 set_include_path(implode(PATH_SEPARATOR, [ DOCROOT, __DIR__ ]));
83
84 function fail($error)
85 {
86         global $User, $Page, $Args;
87         http_response_code(500);
88         if (!isset($Article)) {
89                 require_once('article.inc.php');
90                 $Article = new ArchiveArticle(NULL);
91                 $Article->title = 'Fout';
92         }
93         include_once 'page.inc.php';
94         ob_start();
95         require '500.inc.html';
96         print getoutput(['debug' => htmlspecialchars($error)]);
97 }
98
99 set_exception_handler('fail');
100
101 define('E_FATAL', E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
102
103 set_error_handler(function ($level, $error, $file, $line) {
104         if ($level & E_FATAL) {
105                 fail($error);
106                 return;
107         }
108         return FALSE;
109 });
110
111 register_shutdown_function(function () {
112         # display failure page for fatal exceptions
113         $error = error_get_last();
114         if (!($error['type'] & E_FATAL)) return;
115         fail("Fatal: $error[message] in $error[file]:$error[line]");
116 });
117
118 error_reporting(error_reporting() & ~E_FATAL);
119
120 # user login and control
121
122 include_once 'auth.inc.php'; // sets global $User
123 $Edit = isset($_GET['edit']);
124
125 # setup requested page
126
127 $Args = '';
128 $Page = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
129 $Page = urldecode(trim($Page, '/')) ?: 'index';
130
131 $staticpage = "$Page.html";
132 if (file_exists($staticpage)) {
133         if (is_link($staticpage)) {
134                 $target = preg_replace('/\.html$/', '', readlink($staticpage));
135                 header("HTTP/1.1 302 Shorthand");
136                 header("Location: $target");
137                 exit;
138         }
139 }
140 elseif (file_exists("$Page/index.html")) {
141         $staticpage = "$Page/index.html";
142 }
143
144 require_once('article.inc.php');
145 $Article = new ArchiveArticle($staticpage);
146
147 $Page = $Article->handler;
148 $Args = $Article->path;
149
150 if ($PageAccess = $Article->restricted) {
151         # access restriction
152         if (!$User->login) {
153                 http_response_code(303);
154                 $target = urlencode($Article->link);
155                 header("Location: /login?goto=$target");
156                 exit;
157         }
158 }
159
160 # prepare page contents
161
162 header(sprintf('Content-Security-Policy: %s', implode('; ', [
163         "default-src 'self' 'unsafe-inline' http://cdn.ckeditor.com", # some overrides remain
164         "img-src 'self' data: http://cdn.ckeditor.com", # inline svg (in css)
165         "base-uri 'self'", # only local pages
166         "frame-ancestors 'none'", # prevent malicious embedding
167 ])));
168
169 ob_start(); # page body
170 $Place = [
171         'user'  => $User->login ?: '',
172         'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
173 ];
174
175 if (isset($Article->raw)) {
176         if ($User->admin("edit $Page$Args")) {
177                 # restore meta tags in static contents for editing
178                 foreach (array_reverse($Article->meta) as $metaprop => $val) {
179                         $Article->raw = sprintf(
180                                 '<meta property="%s" content="%s" />'."\n",
181                                 $metaprop, $val
182                         ) . $Article->raw;
183                 }
184         }
185 }
186 elseif ($User->admin("edit {$Article->link}")) {
187         $Article->raw(file_exists("$Page/template.inc.html") ? "$Page/template.inc.html" : 'template.inc.html');
188 }
189 if (isset($Article->raw)) {
190         $Article->raw = '<div class="static">'."\n\n".$Article->raw."</div>\n\n";
191 }
192
193 # output dynamic and/or static html
194
195 if (!$Page or require("./$Page/index.php")) {
196         # static contents
197         if (isset($Article->raw)) {
198                 print $Article->raw;
199         }
200         else {
201                 # no resulting output
202                 http_response_code(404);
203                 @require '404.inc.html';
204         }
205 }
206
207 include_once 'page.inc.php';
208