<?php

/*
 * This script serves up readings from the ESV.  It takes a
 * single parameter "passage=XXX" where XXX is the Bible text
 * to display.
 * 
 * Version 1.0 BPE 29/07/2003
 * Version 2.0 BPE 18/12/2008 Expunge SOAP interface
 *
 */

$local = preg_match('/\.local$/',$_SERVER['SERVER_NAME']);

if ($local) {
    include('anglicise.inc');
}

if(isset($_GET['passage']) && $_GET['passage']) {
    $passage = $_GET['passage'];
} else {
    $passage = 'John 3:16';
}

// -1- Retrieve the passage ------------------------------------ //

$key = 'TEST';
include('../../inc/esv_key.inc'); // defines $key

$xml_content = file_get_contents("http://www.esvapi.org/v2/rest/passageQuery?key=".$key."&passage=".urlencode($passage)."&output-format=crossway-xml-1.0");

// -2- Convert from XML to XHTML ------------------------------- //

if ($xml_content) {

    // I can't get the ESV DTD to work, so define the entities here
    $doctype = <<<EOT
<!DOCTYPE crossway-bible [
<!ENTITY	ldblquot  "&#8220;">
<!ENTITY	rdblquot  "&#8221;">
<!ENTITY	lquot     "&#8216;">
<!ENTITY	rquot     "&#8217;">
<!ENTITY	apos      "'">
<!ENTITY	emdash    "&#8212;">
<!ENTITY	endash    "&#8211;">
<!ENTITY	ellipsis  "&#xa0;.&#xa0;.&#xa0;.">
<!ENTITY	ellipsis4 ".&#xa0;.&#xa0;.&#xa0;.">
]>
EOT;

    $xml_content = $doctype.preg_replace('/<!DOCTYPE.*>/','',$xml_content);

    $xsl_content = implode('',file('esv.xsl'));

    $style = 'grey.css';
    $params = array(
                    'style' => $style
                    );

    $xsl = new DomDocument();
    $xsl->loadXML($xsl_content);

    $xml = new DomDocument();
    $xml->substituteEntities = TRUE;
    $xml->loadXML($xml_content);

    $proc = new XsltProcessor();
    $proc->importStylesheet($xsl);
    $proc->setParameter(null, $params);

    $domout = $proc->transformToDoc($xml);

    $out = $domout->saveXML();

} else {

    $out = '<p>There was a problem getting the passage in XML</p>';

}

// Anglicise the text: but for my local server only: it would violate
// copyright to do this for public access.

if ($local) {
        $out = anglicise($out);
}

// -3- Output the XHTML ---------------------------------------- //

header("Content-Type: text/html; charset=UTF-8");

print $out;

?>