<?php
/*
* LICENSE
* Do whatever, just keep attribution and tell me if you
* use it for anything cool. (That seems unlikely, though, 
* since it's messy as all hell and hardly efficient. :)
*
* copyright 2005 Sam Angove <sam@rephrase.net>
*/

/*********************** OPTIONS *****************************/

// Raw feed cache-time (in seconds)
$refilter_cache_lifetime = 21600;

// Filtered feed cache-time (in seconds)
$refilter_filtered_cache_lifetime = 21600;

// Clean out old cache files every so long? (in seconds)
$refilter_clean_cache = 21600;

/************************************************************/
// You probably don't need to change anything below this point.

$starttime = array_sum( explode(' ', microtime()) );
$sep = DIRECTORY_SEPARATOR;

$refilter_dir = dirname(__FILE__) . $sep;
$refilter_inc = $refilter_dir . 'includes' . $sep;

// Cache files where?
$refilter_cache_dir = $refilter_dir . 'cache' . $sep;
$refilter_filtered_cache_dir = $refilter_cache_dir;

require_once( $refilter_inc . 'Lite.php');
require_once( $refilter_inc . 'ReFilter.functions.php');

// The poor man's `cron` to clean old cache files.
// 
if ($refilter_clean_cache) {
	$file = $refilter_dir . 'cron.txt';
	$now = time();
	
	// never clean the cache if the cron.txt file isn't there
	if (!$cron = @filemtime($file)) $cron = $now;
	
	if ($now - $cron > $refilter_clean_cache) {
		$options = array( 
			'cacheDir' => $refilter_cache_dir,
			'lifeTime' => $refilter_clean_cache
			);
		$cache = new Cache_Lite($options);
		$cache->clean(false, 'old');		
		
		if (!touch($file)) {
			// A lot of people won't be able to use `touch()`
			// because of file ownership problems, so try this instead.
			// Best to delete the whole lot and use a real cronjob if
			// you can. File locking probably doesn't matter here,
			// but maybe it'll prevent some errors down the track?
			if ($handle = fopen($file, 'wb')) {
				flock($handle, LOCK_EX);
				fwrite($handle, "I am the ReFilter cron file, do not delete me!");
				flock($handle, LOCK_UN);
				fclose($handle);
			}
		}
	}
} 

if (isset($_GET['feed']) && isset($_GET['filter'])) {

	echo get_rss();

} else {
	
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>ReFilter, a simple RSS filter</title>
<link rel="stylesheet" href="./refilter.css" media="screen" type="text/css"/>
</head>
<body>
<div id="refilter">
<h1>ReFilter</h1>

<?php 
	if ($_GET['p'] == 'filters') { 	
		$file = './filters.txt';
	} elseif ($_GET['p'] == 'iaq') { 	
		$file = './iaq.txt';
	} else { 
		$file = './mainform.txt';
	}
	include_once('./includes/markdown.php'); 
	echo markdown(file_get_contents($file));
?>


</div>
</body>
</html>


<?php

}

$endtime = array_sum( explode(' ', microtime()) );
$totaltime = ($endtime - $starttime);
echo "<!--ReFilter: generated in ".$totaltime." seconds.-->"; 
?>