<?php
/**
 * Cron page
 * 
 * This page is called by a real cronjob. It executes application cronjobs stored 
 * in /config/cron/ folder, if needed, by including PHP files.
 * 
 * @package linea21\core\admin
 * @author $Author$ - Simon Georget <simon@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

@set_time_limit(0); // suppression du timeout

// necessary for cron / CLI call
chdir (__DIR__); // directory is '/admin/'

include_once('../config/define.php');
include_once('../languages/' . U_L . '/lang_common.' . CHARSET . '.php');

// if called from command-line (cron)
// Crontab syntax
// * * * * * /usr/bin/php -q /var/www/linea21/admin/cron.php token=mySecretToken
// * * * * * /usr/bin/php /home/simon/www/linea21_dev/admin/cron.php token=6255533e95978ff87c168b71e413frd4
// OR
// * * * * * curl -s http://yourinstall.com/admin/cron.php
// * * * * * /usr/bin/curl http://localhost/linea21_dev/admin/cron.php?token=6255533e95978ff87c168b71e413frd4

if (PHP_SAPI === 'cli') {
	
	// we get the given token
	parse_str($argv[1], $_GET);
	$source = 'cron_call';
	
} else {
	
	$source = $_SERVER["REQUEST_URI"];
	
}
	
// we check if the given token is correct
// else we quit
if(!isset($_GET['token']) || $_GET['token'] != SECRET_KEY) die('Invalid token!');
	

// getting CRON files to parse
$cron_dir = '../config/cron/';
$cron_files = array();

if ($handle = opendir($cron_dir)) {
	while (false !== ($entry = readdir($handle))) {
		if ($entry != "." && $entry != "..") {
			array_push($cron_files, $cron_dir. $entry);
		}
	}
	closedir($handle);
}
// sort alphabetically
sort($cron_files);


$cron_tasks = array();

// we loop on cron files
for($i = 0; $i < count ($cron_files); $i ++) {
	
	$handle = fopen($cron_files[$i], "r");
	
	if ($handle) {
	
		// for each cronjob
		while (($line = fgets($handle)) !== false) {
	
			$msg = '';
			$cronjob = get_cron_job($line);
	
			if(strpos($cronjob['script'], 'http') !== false) die('This is very suspicious ...');
	
			$cron = new Cron\CronExpression($cronjob['date']);
	
			if(!file_exists($cronjob['script'])) $msg .= 'FILE NOT FOUND / ';
	
			if($cron->isDue()) {
					
				if(file_exists($cronjob['script'])) {
					if(in_array($cronjob['script'], $cron_tasks)) {
						$msg .= 'DUPLICATE / EXECUTION CANCELED';
					} else {
						include_once(override($cronjob['script']));
						$msg .= 'EXECUTE';
						array_push($cron_tasks, $cronjob['script']);
					}
				}
					
			} else {
				if(defined('MOD_DEBUG') && MOD_DEBUG == true) {
					$msg .= 'NEXT-RUN : ' . $cron->getNextRunDate()->format('Y-m-d H:i:s');
				}
			}
	
			if(defined('CRONJOBS_LOG_ENABLED') && CRONJOBS_LOG_ENABLED == 1) logfile(LOG_CRONJOBS, array(override($cronjob['script']), $cronjob['date'], '['.$msg.']', $source));
	
		}
		
	} else {
		// error opening the file.
	}
	fclose($handle);
}

exit;
?>