<?php
if(!defined('IN_DJCMS')) {
	exit('Access Denied');
}
$nextRunCfg = "./cron/lock/cronnextrun.config";
$timestamp = times("");

function getNextRunTime($mHas, $dHas, $hHas, $nHas){
	$Y=date('Y');$M=date('n');$D=date('j'); ;$H=date('G');$N=date('i');
	$dAry=array(0,31,ifthen($Y % 4 <>0,28,29),31,30,31,30,31,31,30,31,30,31);$nAry=array(0,0,0,0);
	if (trim($mHas)=="" || trim($dHas)=="" || trim($hHas)=="" || trim($nHas)==""){ return "N/A";}
	$mHas = explode(",",$mHas);$dHas = explode(",",$dHas);$hHas = explode(",",$hHas);$nHas = explode(",",$nHas);

	for ($i = 0;$i < count($nHas);$i++) {
		if ($nHas[$i]>$N){ $nAry[0]=$nHas[$i];break;}
    }
	if ($nAry[0]==0){$nAry[0]=$nHas[0];}else{$H=$H-1;}
    
	for ($i = 0;$i < count($hHas);$i++) {
		if ($hHas[$i]>$H){ $nAry[1]=$hHas[$i];break;}
    }
	if ($nAry[1]==0){$nAry[1]=$hHas[0];}else{$D=$D-1;}
    
	for ($i = 0;$i < count($dHas);$i++) {
		if ($dHas[$i]>$D){ $nAry[2]=$dHas[$i];break;}
    }
	if ($nAry[2]==0 || $dAry[$M]<$nAry[2]){$nAry[2]=$dHas[0];}else{$M=$M-1;}
	
	for ($i = 0;$i < count($mHas);$i++) {
		if ($mHas[$i] > $M){ $nAry[3]=$mHas[$i];break;}
    }
	if ($nAry[3]==0){ $nAry[3]=$mHas[0];$Y=$Y+1;}
	return $Y."-".$nAry[3]."-".$nAry[2]." ".$nAry[1].":".$nAry[0].":00";
}

function times($time) {
	if (empty($time)){ return time();}
    $dt_elements = @explode(" ",$time);       // 将字符串分解成2部分－日期、时间
    $date_elements = @explode("-",$dt_elements[0]);           // 分解日期
    $time_elements = @explode(":",$dt_elements[1]);           // 分解时间
    $unixtime = @mktime ($time_elements [0], $time_elements[ 1], $time_elements[ 2], $date_elements[1], $date_elements[2], $date_elements[0]);
    return $unixtime;
}

function computenext($cronid) {
	global $timestamp;
	$cron = DB::fetch_first("SELECT months,days,hours,minutes FROM ".DB::table('crons')." WHERE cronid='$cronid'");
	if (is_array($cron)) {
	    $nextrun = getNextRunTime($cron["months"],$cron["days"],$cron["hours"],$cron["minutes"]);
	    $nextrun = times($nextrun);
	    $setarr = array(
		    'lastrun' => $timestamp,
		    'nextrun' => $nextrun,
	    );
	    if($nextrun <= $timestamp) {
		    $setarr['available'] = 0;
	    }
	    DB::update('crons', $setarr, array('cronid'=>$cronid));
	}
}

function nextConfig() {
	global $nextRunCfg;
	$nextrun = NULL;
	$query = DB::query("SELECT nextrun FROM ".DB::table('crons')." WHERE available>'0' ORDER BY nextrun LIMIT 1");
	if($cron = DB::fetch($query)) { $nextrun = $cron["nextrun"];}
	$nextrun = ifthen($nextrun==NULL,0,$nextrun);
	createTextFile($nextrun,$nextRunCfg);
}

function runcron($cronid = 0) {
	global $timestamp;
	$where = $cronid ? "cronid='$cronid'" : "available>'0' AND nextrun<='$timestamp'";
	$query = DB::query("SELECT * FROM ".DB::table('crons')." WHERE $where ORDER BY nextrun ASC LIMIT 1");//只运行一个
	if ($cron = DB::fetch($query)) {
		$lockfile = './cron/lock/runcron_'.$cron['cronid'].'.lock';
		$cronfile = '/cron/execute/'.$cron['filename']."?".$cron['paramets'];
		if (is_writable(DJ_ROOT.$lockfile)) {
			$locktime =  filemtime(DJ_ROOT.$lockfile);
			if ($locktime>$timestamp - 30){//30秒
				return NULL;
	        }
	    } else {
			createTextFile($timestamp,$lockfile);
			if ($cron['available'] == 1) {
				DB::update('crons', array('available' => 0),array('cronid' => $cron['cronid']));
			}
	    }
		computenext($cron['cronid']);nextConfig();
		rinclude($cronfile);
    }
}

function rinclude($url){
	$t = getForm("op","both");
	if (empty($t)) {
		header("Location:".$url);
	} else {
		echo "<img src=\"".$url."\" width=\"0\" height=\"0\" style=\"display:none\" />";
	}
}
?>