<?php
/* Copyright (c) 2010, Aaron J. Angel.
 * All rights reserved.
 *
 * XHTML to HTML Transformer (XHT)
 *
 * Requires:  PHP, cURL, DOM, XSLT
 *
 * You'll need to redirect non-compliant browsers to this by tweaking
 * your server's configuration.  An example is below.
 *
 * >>>>>>>>>> EXAMPLE >>>>>>>>>>
 * <VirtualHost *>
 * ServerName www.aaronjangel.us
 * DocumentRoot /var/www/html/aaronjangel
 *
 * RewriteEngine On
 * RewriteCond %{HTTP_ACCEPT} !application\/xhtml\+xml [OR]
 * RewriteCode %{HTTP_ACCEPT} application\/xhtml\+xml\s*;\s*q=0\.?0*(\s|,|$)
 * RewriteRule /(.*) /html/$1
 * <<<<<<<<<< EXAMPLE <<<<<<<<<<
 *
 */

$ch curl_init();

if (isset(
$_SERVER["HTTP_IF_NONE_MATCH"])) {
  
$request_etag stripslashes($_SERVER["HTTP_IF_NONE_MATCH"]);
} else {
  
$request_etag "";
}

$scheme = isset($_SERVER['HTTPS']) ? 'https' 'http';
$url sprintf("%s://%s:%s%s",
               
$scheme,
               
$_SERVER['SERVER_NAME'],
               
$_SERVER['SERVER_PORT'],
               
$_SERVER['PATH_INFO']
               );

curl_setopt($chCURLOPT_URL$url);
curl_setopt($chCURLOPT_HEADERtrue);
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);

$cheaders = array(
                  
"Accept: application/xhtml+xml,*/*;q=0.9",
                  
"User-Agent: Mozilla/5.0 (PHP5); XHT by @aaronjangel"
                  
);

if (
$request_etag != "")
  
$cheaders[] = "If-None-Match: $request_etag";

curl_setopt($chCURLOPT_HTTPHEADER$cheaders);
$data curl_exec($ch);

if (
curl_getinfo($chCURLINFO_HTTP_CODE) == 304) {
  if (isset(
$_SERVER["SERVER_PROTOCOL"]))
    
header($_SERVER["SERVER_PROTOCOL"].' 304 Not modified');
  else
    
header('HTTP/1.0 304 Not modified');

  exit(
0);
 }

if (!
$data) {
  
header('Location: /notfound');
  die(
'Could not find resource to transform.');
}

list(
$raw_headers$body) = explode("\r\n\r\n"$data);
$response_etag sha1($body);

$headers explode('\r\n'$raw_headers);
foreach (
$headers as $header) {
  list(
$header$value) = explode(':'$header);
  if (
$header == 'ETag')
    
$respone_etag $value;
}

if (isset (
$_SERVER["HTTP_IF_NONE_MATCH"])) {
  if (
$response_etag === $request_etag) {
    if (isset(
$_SERVER["SERVER_PROTOCOL"]))
      
header($_SERVER["SERVER_PROTOCOL"].' 304 Not modified');
    else
      
header('HTTP/1.0 304 Not modified');
  }
}

header('ETag: "'.$response_etag.'"');
header('Vary: Accept');
    
if (
$response_etag === $request_etag) {
  
header('Connection: Close');
  exit();
}

$type curl_getinfo($chCURLINFO_CONTENT_TYPE); 
if (
$type != "application/xhtml+xml") {
  
header("Content-Type: $type");
  echo 
$body;
} else {
  
$f tempnam(sys_get_temp_dir(), 'html-');
  
file_put_contents($f$body);

  if (
$xml DOMDocument::load($f)) {
    
$xsl = new XSLTProcessor();
    
$xsl->importStyleSheet(DOMDocument::load('2006/style/de-xhtml.xsl'));
    
$html $xsl->transformToXML($xml);
    
header('Content-type: text/html');
    echo 
$html;
  } else {
    include(
$f);
  }

  
unlink($f);
}

?>