page: prefer page template from script root
[minimedit.git] / page.php
1 <?php
2 error_reporting(E_ALL);
3 ini_set('display_errors', TRUE);
4
5 function fail($error)
6 {
7         http_response_code(500);
8         include_once 'page.inc.php';
9         ob_start();
10         require_once './500.html';
11         print getoutput(['debug' => $error]);
12 }
13 set_exception_handler('fail');
14 register_shutdown_function(function () {
15         # display failure page for fatal exceptions
16         $error = error_get_last();
17         if (!($error['type'] & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR))) return;
18         fail("Fatal: $error[message] in $error[file]:$error[line]");
19 });
20
21 include_once 'auth.inc.php';
22 $Edit = isset($_GET['edit']);
23
24 # distinguish subpage Args from topmost Page script
25
26 $Args = '';
27 $Page = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
28 $Page = urldecode(trim($Page, '/')) ?: 'index';
29 while (TRUE) {
30         if (file_exists("$Page.php")) {
31                 break;
32         }
33
34         $up = strrpos($Page, '/');
35         $Args = substr($Page, $up) . $Args;
36         $Page = substr($Page, 0, $up);
37         if ($up === FALSE) {
38                 break;
39         }
40 }
41
42 # load static contents
43
44 ob_start(); # page body
45 ob_start(); # inner html
46 print '<div class="static">'."\n\n";
47
48 $found = FALSE;
49 if (file_exists("$Page$Args/index.html")) {
50         $found = include "./$Page$Args/index.html";
51 }
52 elseif (file_exists("$Page$Args.html")) {
53         $found = include "./$Page$Args.html";
54 }
55 elseif (isset($User) and $User['admin']) {
56         $found = require (file_exists("$Page/template.html") ? "$Page/template.html" : './template.html');
57 }
58
59 print "</div>\n\n";
60
61 # execute dynamic code
62
63 if ($Page) {
64         function getoutput($blocks = [])
65         {
66                 $rep = [];
67                 foreach ($blocks as $name => $html) {
68                         $rep["[[$name]]"] = sprintf('<!--BLOCK:%s-->%s<!--/-->',
69                                 is_numeric($name) ? '' : "[[$name]]", $html
70                         );
71                 }
72                 return str_replace(array_keys($rep), array_values($rep), ob_get_clean());
73         }
74
75         $found |= require "./$Page.php";
76 }
77
78 # global html
79
80 include_once 'page.inc.php';
81
82 if (!$found) {
83         # no resulting output
84         http_response_code(404);
85         ob_start();
86         require "./404.html";
87         print getoutput([ 'url' => htmlspecialchars($_SERVER['REQUEST_URI']) ]);
88 }
89