<?php

function html5_header($common, $page) {
  print "<!DOCTYPE html>\n";
  print "<html>\n";
  print " <head>\n";
  foreach (array($common, $page) as $headers) {
    foreach ($headers as $h) {
# simplexml closes empty tags with <tag /> and not <tag></tag> which
# is harmful for <script>
      print sprintf(" %s\n",
                    preg_replace('/<script(.*)\/>/', '<script$1></script>', $h->asXML())
                    );
    };
  };
  print " </head>\n";
  print " <body>\n";
};

function html5_footer() {
  print " </body>\n";
  print "</html>\n";
};

function html5_menu($xml, $path) {
  $pages = $xml->page;

  print "<div id=\"menu\">\n";
  print " <ul>\n";
  foreach($pages as $p) {
    if ($p['name']) {
      if ($p['menu'] != "0") {
        $name = $p['name'];
        $title = $p->title;
        print sprintf(" <li><a href=\"index?q=%s%s\">%s</a></li>\n", $path, $name, $title);
      }
    }
  }
  print " </ul>\n";
  print "</div>\n";
  print "\n";

  $categories = $xml->category;
  foreach($categories as $c) {
    $name = $p['name'];
    html5_menu($c, $name);
  }
};

$query = $_GET['q'];
if ($query == "") {
  $query = "index";
}
/* $page = $_SERVER['QUERY_STRING']; */

$xml = simplexml_load_file("uphp.xml");

$common = $xml->xpath("/uphp/page");
$result = $xml->xpath("/uphp/page[@name='$query']");
if (count($result) > 0) {
  $page = $result[0];
  $common = $common[0];

  if ($page['driver'] == "html") {
    session_start();

    html5_header($common->children(), $page->children());

    include 'includes/header.php';

    html5_menu($xml, "");

    print " <div id=\"content\">\n";
    readfile(sprintf('html/%s.html', $query));
    print " </div>\n";

    include 'includes/footer.php';

    html5_footer();
    exit(0);
  }
}
else {
  # Does not work
  header("HTTP/1.0 404 Not Found"); 
  /* header("Status: 404 Not Found"); */
}

?>
