page: move placeholder_include() to widget method
[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         # keep either login or logout parts depending on user level
26         global $User;
27         $hideclass = $User && property_exists($User, 'login') && $User->login ? 'logout' : 'login';
28         $doc = preg_replace('{\s*<([a-z]+) class="'.$hideclass.'">.*?</\1>}s', '', $doc);
29
30         return preg_replace_callback(
31                 '{ \[\[ ([^] ]+) ([^]]*) \]\] }x',
32                 function ($sub) use ($blocks) {
33                         list ($placeholder, $name, $params) = $sub;
34                         $html = $blocks[$name] ??
35                                 placeholder_include($name, explode(' ', $params));
36                         if (empty($html) or $html[0] != '<') {
37                                 $html = "<span>$html</span>";
38                         }
39                         $attr = sprintf(' data-dyn="%s"', is_numeric($name) ? '' : $name.$params);
40                         # contents with identifier in first tag
41                         return preg_replace( '/(?=>)/', $attr, $html, 1);
42                 },
43                 $doc
44         );
45 }
46
47 # custom error handling
48
49 define('DOCROOT', getcwd());
50 set_include_path(implode(PATH_SEPARATOR, [ DOCROOT, __DIR__ ]));
51
52 function fail($error)
53 {
54         global $User, $Page;
55         http_response_code(500);
56         if (!isset($Page)) {
57                 require_once('article.inc.php');
58                 $Page = new ArchiveArticle(NULL);
59                 $Page->title = 'Fout';
60         }
61         include_once 'page.inc.php';
62         ob_start();
63         require '500.inc.html';
64         print getoutput(['debug' => htmlspecialchars($error)]);
65 }
66
67 set_exception_handler('fail');
68
69 define('E_FATAL', E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
70
71 set_error_handler(function ($level, $error, $file, $line) {
72         if ($level & E_FATAL) {
73                 fail($error);
74                 return;
75         }
76         return FALSE;
77 });
78
79 register_shutdown_function(function () {
80         # display failure page for fatal exceptions
81         $error = error_get_last();
82         if (!($error['type'] & E_FATAL)) return;
83         fail("Fatal: $error[message] in $error[file]:$error[line]");
84 });
85
86 error_reporting(error_reporting() & ~E_FATAL);
87
88 # user login and control
89
90 include_once 'auth.inc.php'; // sets global $User
91 $Edit = isset($_GET['edit']);
92
93 # setup requested page
94
95 $request = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
96 $request = urldecode(trim($request, '/')) ?: 'index';
97
98 $staticpage = "$request.html";
99 if (file_exists($staticpage)) {
100         if (is_link($staticpage)) {
101                 $target = preg_replace('/\.html$/', '', readlink($staticpage));
102                 header("HTTP/1.1 302 Shorthand");
103                 header("Location: $target");
104                 exit;
105         }
106 }
107 elseif (file_exists("$request/index.html")) {
108         $staticpage = "$request/index.html";
109 }
110
111 require_once('article.inc.php');
112 $Page = new ArchiveArticle($staticpage);
113
114 if ($Page->restricted) {
115         # access restriction
116         if (!$User->login) {
117                 http_response_code(303);
118                 $target = urlencode($Page->link);
119                 header("Location: /login?goto=$target");
120                 exit;
121         }
122 }
123
124 # prepare page contents
125
126 header(sprintf('Content-Security-Policy: %s', implode('; ', [
127         "default-src 'self' 'unsafe-inline' http://cdn.ckeditor.com", # some overrides remain
128         "img-src 'self' data: http://cdn.ckeditor.com", # inline svg (in css)
129         "base-uri 'self'", # only local pages
130         "frame-ancestors 'none'", # prevent malicious embedding
131 ])));
132
133 ob_start(); # page body
134 $Place = [
135         'user'  => $User->login ?: '',
136         'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
137 ];
138
139 if (!isset($Page->raw) and $User->admin("edit {$Page->link}")) {
140         # open bottom template as initial contents
141         $template = 'template.inc.html';
142         if ($Page->handler and file_exists("{$Page->handler}/$template")) {
143                 $template = "{$Page->handler}/$template";
144         }
145         $Page->raw($template);
146         $Page->meta['article:published_time'] = date('Y-m-d h:i:s O');
147         $Page->meta['article:author'] = '/' . $User->dir;
148 }
149
150 if (isset($Page->raw)) {
151         if ($User->admin("edit {$Page->link}")) {
152                 # restore meta tags in static contents for editing
153                 foreach (array_reverse($Page->meta) as $metaprop => $val) {
154                         $Page->raw = sprintf(
155                                 '<meta property="%s" content="%s">'."\n",
156                                 $metaprop, $val
157                         ) . $Page->raw;
158                 }
159         }
160         $Page->raw = '<div class="static">'."\n\n".$Page->raw."</div>\n\n";
161 }
162
163 # output dynamic and/or static html
164
165 if (!$Page->handler or require("./{$Page->handler}/index.php")) {
166         # static contents
167         if (isset($Page->raw)) {
168                 print $Page->raw;
169         }
170         else {
171                 # no resulting output
172                 http_response_code(404);
173                 @require '404.inc.html';
174         }
175 }
176
177 include_once 'page.inc.php';
178