page: localise page variables within template includes
[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                                 include "$name.php";
46                                 $html = ob_get_clean();
47                         }
48                         else {
49                                 $html = '<strong class="warn"><em>'.$name.'</em> ontbreekt</strong>';
50                         }
51                         return sprintf('<!--BLOCK:%s-->%s<!--/-->',
52                                 is_numeric($name) ? '' : $placeholder, # edit replacement
53                                 preg_replace('{<!--[^-]*-->}', '', $html) # contents
54                         );
55                 },
56                 $doc
57         );
58 }
59
60 # custom error handling
61
62 define('DOCROOT', getcwd().'/');
63
64 function fail($error)
65 {
66         http_response_code(500);
67         include_once 'page.inc.php';
68         ob_start();
69         require_once DOCROOT.'500.html';
70         print getoutput(['debug' => $error]);
71 }
72
73 set_exception_handler('fail');
74
75 define('E_FATAL', E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
76
77 set_error_handler(function ($level, $error, $file, $line) {
78         if ($level & E_FATAL) {
79                 fail($error);
80                 return;
81         }
82         return FALSE;
83 });
84
85 register_shutdown_function(function () {
86         # display failure page for fatal exceptions
87         $error = error_get_last();
88         if (!($error['type'] & E_FATAL)) return;
89         fail("Fatal: $error[message] in $error[file]:$error[line]");
90 });
91
92 error_reporting(error_reporting() & ~E_FATAL);
93
94 # user login and control
95
96 include_once 'auth.inc.php';
97 $Edit = isset($_GET['edit']);
98
99 # distinguish subpage Args from topmost Page script
100
101 $Args = '';
102 $Page = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
103 $Page = urldecode(trim($Page, '/')) ?: 'index';
104 while (TRUE) {
105         if (file_exists("$Page/.private")) {
106                 # access restriction
107                 if (empty($User)) {
108                         http_response_code(303);
109                         $target = urlencode($_SERVER['REQUEST_URI']);
110                         header("Location: /login?goto=$target");
111                         exit;
112                 }
113                 $PageAccess = $Page;
114         }
115
116         if (file_exists("$Page/index.php")) {
117                 break;
118         }
119
120         $up = strrpos($Page, '/');
121         $Args = substr($Page, $up) . $Args;
122         $Page = substr($Page, 0, $up);
123         if ($up === FALSE) {
124                 break;
125         }
126 }
127
128 # load static contents
129
130 ob_start(); # page body
131 ob_start(); # inner html
132 print '<div class="static">'."\n\n";
133
134 $found = FALSE;
135 if (file_exists("$Page$Args.html")) {
136         $found = include "./$Page$Args.html";
137 }
138 elseif (file_exists("$Page$Args/index.html")) {
139         $found = include "./$Page$Args/index.html";
140 }
141 elseif (!empty($User['admin'])) {
142         $found = include (file_exists("$Page/template.html") ? "$Page/template.html" : './template.html');
143 }
144
145 print "</div>\n\n";
146
147 # execute dynamic code
148
149 $Place = [];
150
151 if ($Page) {
152         $found |= require "./$Page/index.php";
153 }
154
155 $Place += [
156         'user'  => empty($User) ? '' : $User['name'],
157         'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
158 ];
159
160 # global html
161
162 if (!$found) {
163         # no resulting output
164         http_response_code(404);
165         @require "./404.html";
166 }
167
168 include_once 'page.inc.php';
169