page: predetermine static html include
[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 set_include_path(implode(PATH_SEPARATOR, [ DOCROOT, __DIR__ ]));
71
72 function fail($error)
73 {
74         http_response_code(500);
75         include_once 'page.inc.php';
76         ob_start();
77         require_once '500.html';
78         print getoutput(['debug' => $error]);
79 }
80
81 set_exception_handler('fail');
82
83 define('E_FATAL', E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
84
85 set_error_handler(function ($level, $error, $file, $line) {
86         if ($level & E_FATAL) {
87                 fail($error);
88                 return;
89         }
90         return FALSE;
91 });
92
93 register_shutdown_function(function () {
94         # display failure page for fatal exceptions
95         $error = error_get_last();
96         if (!($error['type'] & E_FATAL)) return;
97         fail("Fatal: $error[message] in $error[file]:$error[line]");
98 });
99
100 error_reporting(error_reporting() & ~E_FATAL);
101
102 # user login and control
103
104 include_once 'auth.inc.php';
105 $Edit = isset($_GET['edit']);
106
107 # distinguish subpage Args from topmost Page script
108
109 $Args = '';
110 $Page = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
111 $Page = urldecode(trim($Page, '/')) ?: 'index';
112 while (TRUE) {
113         if (file_exists("$Page/.private")) {
114                 # access restriction
115                 if (empty($User)) {
116                         http_response_code(303);
117                         $target = urlencode($_SERVER['REQUEST_URI']);
118                         header("Location: /login?goto=$target");
119                         exit;
120                 }
121                 $PageAccess = $Page;
122         }
123
124         if (file_exists("$Page/index.php")) {
125                 break;
126         }
127
128         $up = strrpos($Page, '/');
129         $Args = substr($Page, $up) . $Args;
130         $Page = substr($Page, 0, $up);
131         if ($up === FALSE) {
132                 break;
133         }
134 }
135
136 $staticpage = NULL;
137 if (file_exists("$Page$Args.html")) {
138         $staticpage = "$Page$Args.html";
139 }
140 elseif (file_exists("$Page$Args/index.html")) {
141         $staticpage = "$Page$Args/index.html";
142 }
143 elseif (!empty($User['admin'])) {
144         $staticpage = (file_exists("$Page/template.html") ? "$Page/template.html" : 'template.html');
145 }
146
147 # load static contents
148
149 ob_start(); # page body
150 ob_start(); # inner html
151 print '<div class="static">'."\n\n";
152
153 $found = FALSE;
154 if (isset($staticpage)) {
155         $found = include "./$staticpage";
156 }
157
158 print "</div>\n\n";
159
160 # execute dynamic code
161
162 $Place = [];
163
164 if ($Page) {
165         $found |= require "./$Page/index.php";
166 }
167
168 $Place += [
169         'user'  => empty($User) ? '' : $User['name'],
170         'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
171 ];
172
173 # global html
174
175 if (!$found) {
176         # no resulting output
177         http_response_code(404);
178         @require '404.html';
179 }
180
181 include_once 'page.inc.php';
182