page: include partial templates from *.inc.html
[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 = empty($User) ? 'login' : 'logout';
58         $doc = preg_replace('{\s*<(p|li|span) 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         http_response_code(500);
87         include_once 'page.inc.php';
88         ob_start();
89         require_once '500.inc.html';
90         print getoutput(['debug' => $error]);
91 }
92
93 set_exception_handler('fail');
94
95 define('E_FATAL', E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
96
97 set_error_handler(function ($level, $error, $file, $line) {
98         if ($level & E_FATAL) {
99                 fail($error);
100                 return;
101         }
102         return FALSE;
103 });
104
105 register_shutdown_function(function () {
106         # display failure page for fatal exceptions
107         $error = error_get_last();
108         if (!($error['type'] & E_FATAL)) return;
109         fail("Fatal: $error[message] in $error[file]:$error[line]");
110 });
111
112 error_reporting(error_reporting() & ~E_FATAL);
113
114 # user login and control
115
116 $User = NULL;
117 include_once 'auth.inc.php';
118 $Edit = isset($_GET['edit']);
119
120 # distinguish subpage Args from topmost Page script
121
122 $Args = '';
123 $Page = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
124 $Page = urldecode(trim($Page, '/')) ?: 'index';
125 while (TRUE) {
126         if (file_exists("$Page/.private")) {
127                 # access restriction
128                 if (empty($User)) {
129                         http_response_code(303);
130                         $target = urlencode($_SERVER['REQUEST_URI']);
131                         header("Location: /login?goto=$target");
132                         exit;
133                 }
134                 $PageAccess = $Page;
135         }
136
137         if (file_exists("$Page/index.php")) {
138                 break;
139         }
140
141         $up = strrpos($Page, '/');
142         $Args = substr($Page, $up) . $Args;
143         $Page = substr($Page, 0, $up);
144         if ($up === FALSE) {
145                 break;
146         }
147 }
148
149 $staticpage = NULL;
150 if (file_exists("$Page$Args.html")) {
151         $staticpage = "$Page$Args.html";
152         if (is_link($staticpage)) {
153                 $target = preg_replace('/\.html$/', '', readlink($staticpage));
154                 header("HTTP/1.1 302 Shorthand");
155                 header("Location: $target");
156                 exit;
157         }
158 }
159 elseif (file_exists("$Page$Args/index.html")) {
160         $staticpage = "$Page$Args/index.html";
161 }
162 elseif ($User and $User->admin('edit')) {
163         $staticpage = (file_exists("$Page/template.inc.html") ? "$Page/template.inc.html" : 'template.inc.html');
164 }
165
166 # load static contents
167
168 require_once('article.inc.php');
169 $Article = new ArchiveArticle($staticpage);
170
171 ob_start(); # page body
172 ob_start(); # inner html
173 print '<div class="static">'."\n\n";
174
175 $found = FALSE;
176 if (isset($Article->raw)) {
177         print $Article->raw;
178         $found = 1;
179 }
180
181 print "</div>\n\n";
182
183 # execute dynamic code
184
185 $Place = [];
186
187 if ($Page) {
188         $found |= require "./$Page/index.php";
189 }
190
191 $Place += [
192         'user'  => $User ? $User->login : '',
193         'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
194 ];
195
196 # global html
197
198 if (!$found) {
199         # no resulting output
200         http_response_code(404);
201         @require '404.inc.html';
202 }
203
204 include_once 'page.inc.php';
205