page: ignore failed user setup during errors
[minimedit.git] / page.php
index 9e3388ee0757cc27a3d384066c74799d1f805ade..ed0ec1b9af93772e0b9cbbbc15e1721846ad9ffe 100644 (file)
--- a/page.php
+++ b/page.php
 error_reporting(E_ALL);
 ini_set('display_errors', TRUE);
 
+function abort($body, $status = NULL) {
+       if ($status) header("HTTP/1.1 $status");
+       print "$body\n";
+       exit;
+}
+
+function placeholder_include($name, $params = [])
+{
+       $path = stream_resolve_include_path("widget/$name.php");
+       if (!file_exists($path)) {
+               return '<strong class="warn"><em>'.$name.'</em> ontbreekt</strong>';
+       }
+
+       ob_start();
+       $Page = $GLOBALS['Page'] . $GLOBALS['Args'];
+       $Args = '';
+       $Place = $GLOBALS['Place'];
+       foreach ($params as $param) {
+               if ($set = strpos($param, '=')) {
+                       $Place[ substr($param, 0, $set) ] = substr($param, $set + 1);
+               }
+               elseif (!empty($param)) {
+                       $Args .= '/'.$param;
+               }
+       }
+       try {
+               include "widget/$name.php";
+               return ob_get_clean();
+       }
+       catch (Exception $e) {
+               return sprintf('<strong class="warn">%s</strong>',
+                       "fout in <em>$name</em>: {$e->getMessage()}"
+               );
+       }
+}
+
+function getoutput($blocks = [])
+{
+       $doc = ob_get_clean();
+
+       if (!empty($blocks['warn'])) {
+               $warn = '<p class="warn">[[warn]]</p>';
+               if ($offset = strpos($doc, '</h2>')) {
+                       $doc = substr_replace($doc, "\n\n".$warn, $offset + 5, 0);
+               }
+               else {
+                       $doc = $warn . "\n\n" . $doc;
+               }
+       }
+
+       # keep either login or logout parts depending on user level
+       global $User;
+       $hideclass = $User && property_exists($User, 'login') && $User->login ? 'logout' : 'login';
+       $doc = preg_replace('{\s*<([a-z]+) class="'.$hideclass.'">.*?</\1>}s', '', $doc);
+
+       return preg_replace_callback(
+               '{ (?<! <!--BLOCK: ) \[\[ ([^] ]+) ([^]]*) \]\] }x',
+               function ($sub) use ($blocks) {
+                       list ($placeholder, $name, $params) = $sub;
+                       if (isset($blocks[$name])) {
+                               $html = $blocks[$name];
+                       }
+                       else {
+                               $html = placeholder_include($name, explode(' ', $params));
+                       }
+                       return sprintf('<!--BLOCK:%s-->%s<!--/-->',
+                               is_numeric($name) ? '' : $placeholder, # edit replacement
+                               preg_replace('{<!--[^-]*-->}', '', $html) # contents
+                       );
+               },
+               $doc
+       );
+}
+
+# custom error handling
+
+define('DOCROOT', getcwd());
+set_include_path(implode(PATH_SEPARATOR, [ DOCROOT, __DIR__ ]));
+
 function fail($error)
 {
+       global $User, $Page, $Args;
        http_response_code(500);
+       if (!isset($Article)) {
+               require_once('article.inc.php');
+               $Article = new ArchiveArticle(NULL);
+               $Article->title = 'Fout';
+       }
        include_once 'page.inc.php';
        ob_start();
-       require_once './500.html';
-       print getoutput(['debug' => $error]);
+       require '500.inc.html';
+       print getoutput(['debug' => htmlspecialchars($error)]);
 }
+
 set_exception_handler('fail');
+
+define('E_FATAL', E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR);
+
+set_error_handler(function ($level, $error, $file, $line) {
+       if ($level & E_FATAL) {
+               fail($error);
+               return;
+       }
+       return FALSE;
+});
+
 register_shutdown_function(function () {
        # display failure page for fatal exceptions
        $error = error_get_last();
-       if (!($error['type'] & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR))) return;
+       if (!($error['type'] & E_FATAL)) return;
        fail("Fatal: $error[message] in $error[file]:$error[line]");
 });
 
-include_once 'auth.inc.php';
+error_reporting(error_reporting() & ~E_FATAL);
+
+# user login and control
+
+include_once 'auth.inc.php'; // sets global $User
 $Edit = isset($_GET['edit']);
 
-# distinguish subpage Args from topmost Page script
+# setup requested page
 
 $Args = '';
-$Page = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
+$Page = preg_replace('/\?.*/', '', @$_SERVER['PATH_INFO'] ?: $_SERVER['REQUEST_URI']);
 $Page = urldecode(trim($Page, '/')) ?: 'index';
-while (TRUE) {
-       if (file_exists("$Page.php")) {
-               break;
-       }
 
-       $up = strrpos($Page, '/');
-       $Args = substr($Page, $up) . $Args;
-       $Page = substr($Page, 0, $up);
-       if ($up === FALSE) {
-               break;
+$staticpage = "$Page.html";
+if (file_exists($staticpage)) {
+       if (is_link($staticpage)) {
+               $target = preg_replace('/\.html$/', '', readlink($staticpage));
+               header("HTTP/1.1 302 Shorthand");
+               header("Location: $target");
+               exit;
        }
 }
+elseif (file_exists("$Page/index.html")) {
+       $staticpage = "$Page/index.html";
+}
 
-# load static contents
+require_once('article.inc.php');
+$Article = new ArchiveArticle($staticpage);
 
-ob_start(); # page body
-ob_start(); # inner html
-print '<div class="static">'."\n\n";
+$Page = $Article->handler;
+$Args = $Article->path;
 
-$found = FALSE;
-if (file_exists("$Page$Args/index.html")) {
-       $found = include "./$Page$Args/index.html";
-}
-elseif (file_exists("$Page$Args.html")) {
-       $found = include "./$Page$Args.html";
+if ($PageAccess = $Article->restricted) {
+       # access restriction
+       if (!$User->login) {
+               http_response_code(303);
+               $target = urlencode($Article->link);
+               header("Location: /login?goto=$target");
+               exit;
+       }
 }
 
-print "</div>\n\n";
+# prepare page contents
 
-# execute dynamic code
+header(sprintf('Content-Security-Policy: %s', implode('; ', [
+       "default-src 'self' 'unsafe-inline' http://cdn.ckeditor.com", # some overrides remain
+       "img-src 'self' data: http://cdn.ckeditor.com", # inline svg (in css)
+       "base-uri 'self'", # only local pages
+       "frame-ancestors 'none'", # prevent malicious embedding
+])));
 
-if ($Page) {
-       function getoutput($blocks = [])
-       {
-               $rep = [];
-               foreach ($blocks as $name => $html) {
-                       $rep["[[$name]]"] = "<!--BLOCK $name-->$html<!--/-->";
+ob_start(); # page body
+$Place = [
+       'user'  => $User->login ?: '',
+       'url'   => htmlspecialchars($_SERVER['REQUEST_URI']),
+];
+
+if (isset($Article->raw)) {
+       if ($User->admin("edit $Page$Args")) {
+               # restore meta tags in static contents for editing
+               foreach (array_reverse($Article->meta) as $metaprop => $val) {
+                       $Article->raw = sprintf(
+                               '<meta property="%s" content="%s" />'."\n",
+                               $metaprop, $val
+                       ) . $Article->raw;
                }
-               return str_replace(array_keys($rep), array_values($rep), ob_get_clean());
        }
-
-       $found |= require "./$Page.php";
+}
+elseif ($User->admin("edit {$Article->link}")) {
+       $Article->raw(file_exists("$Page/template.inc.html") ? "$Page/template.inc.html" : 'template.inc.html');
+}
+if (isset($Article->raw)) {
+       $Article->raw = '<div class="static">'."\n\n".$Article->raw."</div>\n\n";
 }
 
-# global html
-
-include_once 'page.inc.php';
+# output dynamic and/or static html
 
-if (!$found) {
-       # no resulting output
-       if (isset($User) and $User['admin']) {
-               require './template.html';
+if (!$Page or require("./$Page/index.php")) {
+       # static contents
+       if (isset($Article->raw)) {
+               print $Article->raw;
        }
        else {
+               # no resulting output
                http_response_code(404);
-               ob_start();
-               require "./404.html";
-               print getoutput([ 'url' => htmlspecialchars($_SERVER['REQUEST_URI']) ]);
+               @require '404.inc.html';
        }
 }
 
+include_once 'page.inc.php';
+