<?php
require_once "functions.php";

function PING_IP($db_conn,$ID_C,$URL){
	if (strpos($URL, ":")){ //Si usa un puerto, dividir
		$host = explode(":", $URL)[0];
		$port = explode(":", $URL)[1];
	}else{$host=$URL;}
	$result = isset($port) ? ping($host,$port) : ping($host); //Ping IP with or without port
	return $result; //Returns result
}

function HTTP_CODE($db_conn,$ID_C,$URL,$Param){
	$httpCode = httpCode($URL); //Code

	$code = (int)$Param != 0 ? $Param : 200; //Establish the code test want to see

	if ($httpCode == $code){ //Si es igual
		$ret = 0; //All right
	}else{ //Si no es igual (Incluye false)
		$ret = (int)$httpCode; //Code not 0 (And it's received code)
	}
	return $ret;
}

function DATABASE_CONN($db_conn,$ID_C,$URL){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $URL);
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_TIMEOUT, 4); //timeout in seconds
	$body = curl_exec($ch); //All file
	curl_close($ch);
	$result = htmlentities($body);
	if($result == 'OK'){
		return 0;
	}else{ //Fail if it returns other than "OK".
		return 1;
	}
}


$sites = dbw_query($db_conn,"SELECT * FROM CHECKS");
while ($site = dbw_fetch_array($db_conn,$sites)){
	$try = 0;
	$ID_C= $site['ID_C'];
	do {
		$try++; //This is for avoiding posible "second" problems in some checks that are working but doesn't answer to first time
		set_time_limit (15); //This resets time limit of php, avoids 30 sec limit in some servers
		
		switch ($site['ID_TC']) {
			case '1': //Ping to IP:Port
				$exitC = PING_IP($db_conn,$ID_C,$site['URL']);
			break;

			case '2': //HttpCode
				$exitC = HTTP_CODE($db_conn,$ID_C,$site['URL'],$site['TCParam']);
			break;

			case '4': //MySQL|Database connect
				$exitC = DATABASE_CONN($db_conn,$ID_C,$site['URL']);
			break;
		}
	}while($try <= 2 && $exitC == 1);
	$timestamp = time();
	if ($exitC == 0){ //Check successful
		dbw_query($db_conn, "INSERT INTO `CHKHIST` (`ID_C`,`code`,`timestamp`) VALUES ('$ID_C','0','$timestamp')");
	}else if ($exitC == 1){ //Normal check failed
		dbw_query($db_conn, "INSERT INTO `CHKHIST` (`ID_C`,`code`,`timestamp`) VALUES ('$ID_C','1','$timestamp')");
	}else{ //Other code of check failed
		dbw_query($db_conn, "INSERT INTO `CHKHIST` (`ID_C`,`code`,`errorText`,`timestamp`) VALUES ('$ID_C','1','$exitC','$timestamp')");
	}
	
	
}


//Delete old Checks (Based on time to save, put in secs)
$mintime = time()-(getSystemOpt($db_conn,"maxTimeSave")*24*3600);
dbw_query($db_conn,"DELETE FROM CHKHIST WHERE `timestamp` < $mintime");

//Delete Checks stored for pages that not exist
dbw_query($db_conn, "DELETE FROM CHKHIST WHERE ID_C NOT IN (SELECT ID_C FROM CHECKS)");


?>