edit: restore placeholders on edit
[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
56 print "</div>\n\n";
57
58 # execute dynamic code
59
60 if ($Page) {
61         function getoutput($blocks = [])
62         {
63                 $rep = [];
64                 foreach ($blocks as $name => $html) {
65                         $rep["[[$name]]"] = "<!--BLOCK $name-->$html<!--/-->";
66                 }
67                 return str_replace(array_keys($rep), array_values($rep), ob_get_clean());
68         }
69
70         $found |= require "./$Page.php";
71 }
72
73 # global html
74
75 include_once 'page.inc.php';
76
77 if (!$found) {
78         # no resulting output
79         if (isset($User) and $User['admin']) {
80                 require './template.html';
81         }
82         else {
83                 http_response_code(404);
84                 ob_start();
85                 require "./404.html";
86                 print getoutput([ 'url' => htmlspecialchars($_SERVER['REQUEST_URI']) ]);
87         }
88 }
89