page: replace global variables by $Page object
[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 = clone $GLOBALS['Page'];
20         $Page->handler = $Page->handler . $Page->path; // .= with explicit getter
21         $Page->path = '';
22         $Place = $GLOBALS['Place'];
23         foreach ($params as $param) {
24                 if ($set = strpos($param, '=')) {
25                         $Place[ substr($param, 0, $set) ] = substr($param, $set + 1);
26                 }
27                 elseif (!empty($param)) {
28                         $Page->path .= '/'.$param;
29                 }
30         }
31         $Page->link .= $Page->path;
32         try {
33                 include "widget/$name.php";
34                 return ob_get_clean();
35         }
36         catch (Exception $e) {
37                 return sprintf('<strong class="warn">%s</strong>',
38                         "fout in <em>$name</em>: {$e->getMessage()}"
39                 );
40         }
41 }
42
43 function getoutput($blocks = [])
44 {
45         $doc = ob_get_clean();
46
47         if (!empty($blocks['warn'])) {
48                 $warn = '<p class="warn">[[warn]]</p>';
49                 if ($offset = strpos($doc, '</h2>')) {
50                         $doc = substr_replace($doc, "\n\n".$warn, $offset + 5, 0);
51                 }
52                 else {
53                         $doc = $warn . "\n\n" . $doc;
54                 }
55         }
56
57         # keep either login or logout parts depending on user level
58         global $User;
59         $hideclass = $User && property_exists($User, 'login') && $User->login ? 'logout' : 'login';
60         $doc = preg_replace('{\s*<([a-z]+) class="'.$hideclass.'">.*?</\1>}s', '', $doc);
61
62         return preg_replace_callback(
63                 '{ \[\[ ([^] ]+) ([^]]*) \]\] }x',
64                 function ($sub) use ($blocks) {
65                         list ($placeholder, $name, $params) = $sub;
66                         $html = $blocks[$name] ??
67                                 placeholder_include($name, explode(' ', $params));
68                         if (empty($html) or $html[0] != '<') {
69                                 $html = "<span>$html</span>";
70                         }
71                         $attr = sprintf(' data-dyn="%s"', is_numeric($name) ? '' : $name.$params);
72                         # contents with identifier in first tag
73                         return preg_replace( '/(?=>)/', $attr, $html, 1);
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;
87         http_response_code(500);
88         if (!isset($Page)) {
89                 require_once('article.inc.php');
90                 $Page = new ArchiveArticle(NULL);
91                 $Page->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 $request = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
128 $request = urldecode(trim($request, '/')) ?: 'index';
129
130 $staticpage = "$request.html";
131 if (file_exists($staticpage)) {
132         if (is_link($staticpage)) {
133                 $target = preg_replace('/\.html$/', '', readlink($staticpage));
134                 header("HTTP/1.1 302 Shorthand");
135                 header("Location: $target");
136                 exit;
137         }
138 }
139 elseif (file_exists("$request/index.html")) {
140         $staticpage = "$request/index.html";
141 }
142
143 require_once('article.inc.php');
144 $Page = new ArchiveArticle($staticpage);
145
146 if ($Page->restricted) {
147         # access restriction
148         if (!$User->login) {
149                 http_response_code(303);
150                 $target = urlencode($Page->link);
151                 header("Location: /login?goto=$target");
152                 exit;
153         }
154 }
155
156 # prepare page contents
157
158 header(sprintf('Content-Security-Policy: %s', implode('; ', [
159         "default-src 'self' 'unsafe-inline' http://cdn.ckeditor.com", # some overrides remain
160         "img-src 'self' data: http://cdn.ckeditor.com", # inline svg (in css)
161         "base-uri 'self'", # only local pages
162         "frame-ancestors 'none'", # prevent malicious embedding
163 ])));
164
165 ob_start(); # page body
166 $Place = [
167         'user'  => $User->login ?: '',
168         'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
169 ];
170
171 if (!isset($Page->raw) and $User->admin("edit {$Page->link}")) {
172         # open bottom template as initial contents
173         $template = 'template.inc.html';
174         if ($Page->handler and file_exists("{$Page->handler}/$template")) {
175                 $template = "{$Page->handler}/$template";
176         }
177         $Page->raw($template);
178         $Page->meta['article:published_time'] = date('Y-m-d h:i:s O');
179         $Page->meta['article:author'] = '/' . $User->dir;
180 }
181
182 if (isset($Page->raw)) {
183         if ($User->admin("edit {$Page->link}")) {
184                 # restore meta tags in static contents for editing
185                 foreach (array_reverse($Page->meta) as $metaprop => $val) {
186                         $Page->raw = sprintf(
187                                 '<meta property="%s" content="%s">'."\n",
188                                 $metaprop, $val
189                         ) . $Page->raw;
190                 }
191         }
192         $Page->raw = '<div class="static">'."\n\n".$Page->raw."</div>\n\n";
193 }
194
195 # output dynamic and/or static html
196
197 if (!$Page->handler or require("./{$Page->handler}/index.php")) {
198         # static contents
199         if (isset($Page->raw)) {
200                 print $Page->raw;
201         }
202         else {
203                 # no resulting output
204                 http_response_code(404);
205                 @require '404.inc.html';
206         }
207 }
208
209 include_once 'page.inc.php';
210