<?php

# The front controller and caching logic for http://peterodding.com/

# Get the request path.
$request_path = '';
if (!empty($_GET['path']))
  $request_path = trim($_GET['path'], '/');

# Show the front page?
if (empty($request_path)) {
  send_content_headers();
  require '/var/www/peterodding.com/code/frontpage/content.php';
  exit;
}

# Open a database connection (it's all we need to serve cached pages).
require_once '/var/www/peterodding.com/code/database.php';

# See if we can serve the page from the cache.
$qpath = mysqli_real_escape_string($DB_CONN, $request_path);
$result_set = mysqli_query($DB_CONN, "SELECT * FROM cache WHERE cache_path = '$qpath'") or die(mysqli_error($DB_CONN));
if (mysqli_num_rows($result_set) == 1) {
  $cache = mysqli_fetch_assoc($result_set);
  $mtime = strtotime($cache['cache_mtime']);
  if ((isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $mtime) ||
      (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) == $cache['cache_etag'])) {
    header('HTTP/1.1 304 Not Modified', true, 304);
  } else {
    send_content_headers();
    send_cache_headers($mtime, $cache['cache_etag']);
    echo $cache['cache_data'];
  }
  exit;
}

# Generate a dynamic page just-in-time using the back-end code.
require '/var/www/peterodding.com/code/includes.php';
send_content_headers();
render_path($request_path);

# Don't want to define these in more than one place :-)

function send_content_headers() {
  header('Content-Type: text/html; charset=utf-8');
  header('Content-Language: en');
}

function send_cache_headers($mtime, $etag) {
  header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
  header('Etag: ' . $etag);
}
