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