<?php
	ob_start("ob_gzhandler"); // Start the output buffer
	date_default_timezone_set("UTC");
    setlocale(LC_ALL, "en_US.utf8");
	
	$cachefile = 'atom-cached.xml';
	// Serve from the cache if it is older than index.html
	if (file_exists($cachefile) && filemtime("../index.html") <= filemtime($cachefile)) {
	    header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($cachefile)) . " GMT");
		header("Content-type: application/atom+xml; charset=utf-8");
	    readfile($cachefile);
	    ob_end_flush(); // Send the output to the browser
	    //header("Content-Length: " . ob_get_length());
	    //ob_end_flush();
	    exit;
	}

	$fileinputs=array(
		"/index.html",
		"/Niall_stuff/vdiary/archives/googleplus/2017.html",
		"/Niall_stuff/vdiary/archives/googleplus/2016.html",
		"/Niall_stuff/vdiary/archives/googleplus/2015.html",
		"/Niall_stuff/vdiary/archives/googleplus/2014.html",
		"/Niall_stuff/vdiary/archives/googleplus/2013.html",
		"/Niall_stuff/vdiary/archives/2013.html",
		"/Niall_stuff/vdiary/archives/googleplus/2012.html",
		"/Niall_stuff/vdiary/archives/2012.html",
		"/Niall_stuff/vdiary/archives/googleplus/2011.html",
		"/Niall_stuff/vdiary/archives/2011.html",
		"/Niall_stuff/vdiary/archives/2010.html",
		"/Niall_stuff/vdiary/archives/september09.html",
		"/Niall_stuff/vdiary/archives/august09.html",
		"/Niall_stuff/vdiary/archives/july09.html",
		"/Niall_stuff/vdiary/archives/june09.html",
		"/Niall_stuff/vdiary/archives/may09.html",
		"/Niall_stuff/vdiary/archives/april09.html",
		"/Niall_stuff/vdiary/archives/march09.html",
		"/Niall_stuff/vdiary/archives/january09.html",
		"/Niall_stuff/vdiary/archives/december08.html",
		"/Niall_stuff/vdiary/archives/october08.html",
		"/Niall_stuff/vdiary/archives/august08.html",
		"/Niall_stuff/vdiary/archives/july08.html",
		"/Niall_stuff/vdiary/archives/june08.html",
		"/Niall_stuff/vdiary/archives/may08.html",
		"/Niall_stuff/vdiary/archives/april08.html",
		"/Niall_stuff/vdiary/archives/march08.html",
		"/Niall_stuff/vdiary/archives/february08.html",
		"/Niall_stuff/vdiary/archives/january08.html",
		"/Niall_stuff/vdiary/archives/december07.html",
		"/Niall_stuff/vdiary/archives/november07.html",
		"/Niall_stuff/vdiary/archives/october07.html",
		"/Niall_stuff/vdiary/archives/august07.html",
		"/Niall_stuff/vdiary/archives/july07.html",
		"/Niall_stuff/vdiary/archives/june07.html",
		"/Niall_stuff/vdiary/archives/may07.html",
		"/Niall_stuff/vdiary/archives/april07.html",
		"/Niall_stuff/vdiary/archives/march07.html",
		"/Niall_stuff/vdiary/archives/february07.html",
		"/Niall_stuff/vdiary/archives/january07.html",
		"/Niall_stuff/vdiary/archives/december06.html",
		"/Niall_stuff/vdiary/archives/november06.html",
		"/Niall_stuff/vdiary/archives/october06.html");
	include("FeedWriter.php");
	//header("Content-type: text/plain; charset=utf-8");
	//header("Content-type: text/xml; charset=utf-8");
	
	//Creating an instance of FeedWriter class. 
	//The constant ATOM is passed to mention the version
	$TestFeed = new FeedWriter(ATOM);

	//Setting the channel elements
	//Use wrapper functions for common elements
	$TestFeed->setTitle('nedprod.com Virtual Diary');
	$TestFeed->setLink('http://www.nedprod.com/atom.xml');
	$TestFeed->setImage('nedprod.com', 'http://www.nedprod.com/favicon.gif', 'http://www.nedprod.com/favicon.gif');
	//$TestFeed->setStylesheet('http://www.nedprod.com/genstyles.css');
	
	//For other channel elements, use setChannelElement() function
	$TestFeed->setChannelElement('updated', date(DATE_ATOM , time()));
	$TestFeed->setChannelElement('author', array('name'=>'Niall Douglas'));

	foreach ($fileinputs as $fileinput) {
		// Load index.html as XML (XHTML)
		//echo "<!-- Processing input file $fileinput -->\n";
		$oldreport=error_reporting(E_ALL&~(E_WARNING));
		$dom = new DOMDocument('1.0', 'UTF-8');
		$dom->loadHTMLFile("..$fileinput") or die("Failed to parse $fileinput");
		error_reporting($oldreport);
		$xml = simplexml_import_dom($dom);
		// Fetch all namespaces 
		$namespaces = $xml->getNamespaces(true); 
	
		// Register them with their prefixes 
		foreach ($namespaces as $prefix => $ns) {
			$xml->registerXPathNamespace($prefix, $ns); 
		}
		
		$underlined=$xml->xpath("//*[@class='underlined']");
		foreach($underlined as $item) {
			if(!isset($item->attributes()->style))
				$item->addAttribute('style', "text-decoration: underline;");
			else
				$item->attributes()->style=$item->attributes()->style." text-decoration: underline;";
		}
		$centered=$xml->xpath("//*[@class='centered']");
		foreach($centered as $item) {
			if(!isset($item->attributes()->style))
				$item->addAttribute('style', "text-align: center;");
			else
				$item->attributes()->style=$item->attributes()->style." text-align:center;";
		}
		$floatleft=$xml->xpath("//*[@class='floatleft']");
		foreach($floatleft as $item) {
			$item->addAttribute('float', "left");
			$item->addAttribute('border', "0");
			$item->addAttribute('hspace', "8");
			if(!isset($item->attributes()->style))
				$item->addAttribute('style', "float: left; border-width: 0px; margin-right: 8px;");
			else
				$item->attributes()->style=$item->attributes()->style." float: left; border-width: 0px; margin-left: 0px; margin-right: 8px;";
		}
		$floatright=$xml->xpath("//*[@class='floatright']");
		foreach($floatright as $item) {
			$item->addAttribute('float', "right");
			$item->addAttribute('border', "0");
			$item->addAttribute('hspace', "8");
			if(!isset($item->attributes()->style))
				$item->addAttribute('style', "float: right; border-width: 0px; margin-left: 8px;");
			else
				$item->attributes()->style=$item->attributes()->style." float: right; border-width: 0px; margin-left: 8px; margin-right: 0px;";
		}
		$nofloat=$xml->xpath("//*[@class='nofloat']");
		foreach($nofloat as $item) {
			$item->addAttribute('float', "middle");
			$item->addAttribute('border', "0");
			if(!isset($item->attributes()->style))
				$item->addAttribute('style', "border-width: 0px; vertical-align: middle;");
			else
				$item->attributes()->style=$item->attributes()->style." border-width: 0px; vertical-align: middle;";
		}
		
		$diaryentries = $xml->xpath("//div[@class='diaryentry']");
		//echo "Found ",count($diaryentries)," entries\n";
		foreach($diaryentries as $diaryentry) {
			$diaryentry->addAttribute('xmlns', "http://www.w3.org/1999/xhtml");
			//echo $diaryentry->asXML();
			$diaryentryasxml=simplexml_load_string($diaryentry->asXML());
			$diaryentryasxml->registerXPathNamespace('default', "http://www.w3.org/1999/xhtml");

			$date=$diaryentryasxml->xpath("//default:time[@itemprop='datePublished']");
			$datetime=0;
			if($date) {
				// datetime="2011-08-11T18:05"
				$datetime=strtotime($date[0]->attributes()->datetime);
			}

			// Extract the date from e.g. <a name="18thJanuary2009">Sunday 18th January 2009:</a>
			$entrylink = $diaryentryasxml->xpath("//default:a[@name]");
			//echo "Found a:names ",count($entrylink),"\n";
			$date=$entrylink[0];
			$date=preg_replace('/\s\s+/', ' ', $date);
   			$name=$date;
			if(substr($name, -1)==':')
				$name=substr($name, 0, -1);
			//echo $diaryentry->asXML()."\n$name:$date\n";
			//echo "$name:$date\n";
			//echo "Date is ",$date," for ",$name,"\n";
			//ereg("^.* (0-9)*)[a-z][a]-z
			list($weekday, $day, $th, $month, $year) = sscanf($date, "%s %d%s %s %d");
			if($datetime==0) $datetime=strtotime(sprintf("%d %s %d", $day, $month, $year));
			//echo "$datetime\n";
			//echo "$date\n";
			//echo "day=",$day," month=",$month," year=",$year," time=",strtotime(sprintf("%d %s %d", $day, $month, $year)),"\n";

			// Fixup any bad links by filling in a full URL
			$baseurl=dirname($fileinput);
			if(!strcmp($baseurl, "/")) $baseurl="";
			$hrefs=$diaryentryasxml->xpath("//*[@href]");
			foreach($hrefs as $item) {
				if(strncmp($item->attributes()->href, "http://", 7) && strncmp($item->attributes()->href, "https://", 8))
					$item->attributes()->href="http://www.nedprod.com$baseurl/".$item->attributes()->href;
			}
			$hrefs=$diaryentryasxml->xpath("//*[@src]");
			foreach($hrefs as $item) {
				if(strncmp($item->attributes()->src, "http://", 7) && strncmp($item->attributes()->src, "https://", 8))
					$item->attributes()->src="http://www.nedprod.com$baseurl/".$item->attributes()->src;
			}
			// Add new FeedItem
			$newItem = $TestFeed->createNewItem();	
			$newItem->setDate($datetime); // needs to be first for sort
			$newItem->setTitle($date);
			$newItem->setLink("http://www.nedprod.com/Niall_stuff/vdiary/archives/".$datetime);
			$doc = new DOMDocument('1.0', 'UTF-8');
			$doc->preserveWhiteSpace = false;
			$doc->loadXML($diaryentryasxml->asXML());
			$doc->formatOutput = true;
			$newItem->setDescription(substr($doc->saveXML(), 22));
			$TestFeed->addItem($newItem);
		}
	}

	// Generate the feed.
	rsort($TestFeed->items);
	$TestFeed->genarateFeed();
	echo "\n<!-- Cached copy, generated ".date('l jS \of F Y h:i:s A', time())." -->\n";

	// Cache the output to a file
	$fp = fopen($cachefile, 'w');
	fwrite($fp, ob_get_contents());
	fclose($fp);
	header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($cachefile)) . " GMT");
	ob_end_flush(); // Send the output to the browser
	//header("Content-Length: " . ob_get_length());
	//ob_end_flush();
?>