<?php
/* PageCookery Framework
*
* Author: Explon
*
* Copyright (C) 2009 Explon <explon@gmail.com>
*/

class Cron
{
	/*
		$cron = array(
			'id' => array(
					'cache_root' => ,
					'distance' => ,
					'script_location' => 
				);
		);
	*/
	
	function __construct($_config = array(), $_global = array())
	{
		@set_time_limit(0);
		
		foreach ($_global AS $vars)
		{
			global $$vars;
		}
		
		foreach ($_config AS $id => $information)
		{
			if ($information['distance'] == 'DAY' OR $information['distance'] == 'WEEK' OR $information['distance'] == 'MONTH')
			{
				$filemtime = @filemtime($information['cache_root'] . 'cron_' . $id . '_tag.db');
				
				if ($filemtime)
				{
					if ($information['distance'] == 'DAY')
					{
						$information['distance'] = 3600 * 24 * 365;
						
						if (Format::Date($filemtime, 'Ymd') != Format::Date(time(), 'Ymd'))
						{
							unlink($information['cache_root'] . 'cron_' . $id . '_tag.db');
						}
					}
					else if ($information['distance'] == 'WEEK')
					{
						$information['distance'] = 3600 * 24 * 365;
						
						if (Format::Date($filemtime, 'YW') != Format::Date(time(), 'YW'))
						{
							unlink($information['cache_root'] . 'cron_' . $id . '_tag.db');
						}
					}
					else if ($information['distance'] == 'MONTH')
					{
						$information['distance'] = 3600 * 24 * 365;
						
						if (Format::Date($filemtime, 'YW') != Format::Date(time(), 'YW'))
						{
							unlink($information['cache_root'] . 'cron_' . $id . '_tag.db');
						}
					}
				}
			}
			
			if (@filemtime($information['cache_root'] . 'cron_' . $id . '_tag.db') < time() - $information['distance'])
			{
				@file_put_contents($information['cache_root'] . 'cron_' . $id . '_tag.db', 'Start at: ' . Format::Date(time()));
				
				require_once($information['script_location']);
				
				@file_put_contents($information['cache_root'] . 'cron_' . $id . '_tag.db', 'Finish at: ' . Format::Date(time()));	
			}
		}
		
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');             // Date in the past
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
		header('Cache-Control: no-cache, must-revalidate');           // HTTP/1.1
		header('Pragma: no-cache');                                   // HTTP/1.0
		header("Content-disposition: inline; filename=clear.gif");
		//header('Content-transfer-encoding: binary');
		//header("Content-Length: " . strlen('R0lGODlhAQABAIAAAMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='));
		//header('Content-type: image/gif');
		echo base64_decode('R0lGODlhAQABAIAAAMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
		exit;
	}
}
