<?php
defined('VSIGN') or die("Sorry, you are not allowed to directly access this page.<br /> Please press the back button in your browser.");

class Debug
{
	public function __construct()
	{
		global $db;
		
		if (!defined('AUDIT'))
		{
			// Get the setting from the DB and define it
			if (Config::GetSetting($db, 'audit') != 'On')
			{
				define('AUDIT', false);
			}
			else
			{
				define('AUDIT', true);
			}
		}
	}
	
	public function ErrorHandler($errno, $errmsg, $filename, $linenum, $vars) {

		global $db;

		// timestamp for the error entry
		$dt = date("Y-m-d H:i:s (T)");

		// define an assoc array of error string
		// in reality the only entries we should
		// consider are E_WARNING, E_NOTICE, E_USER_ERROR,
		// E_USER_WARNING and E_USER_NOTICE
		$errortype = array(E_ERROR => 'Error', E_WARNING => 'Warning', E_PARSE =>
				'Parsing Error', E_NOTICE => 'Notice', E_CORE_ERROR => 'Core Error',
				E_CORE_WARNING => 'Core Warning', E_COMPILE_ERROR => 'Compile Error',
				E_COMPILE_WARNING => 'Compile Warning', E_USER_ERROR => 'User Error',
				E_USER_WARNING => 'User Warning', E_USER_NOTICE => 'User Notice', E_STRICT =>
				'Runtime Notice', E_RECOVERABLE_ERROR => 'Recoverable Error', 8192 => 'Deprecated Call');

		// set of errors for which a var trace will be saved
		$user_errors_halt = array(E_USER_ERROR);
		$user_errors_inline = array(E_USER_WARNING);

		$err = "<errormsg>" . $errmsg . "</errormsg>\n";
		$err .= "<errornum>" . $errno . "</errornum>\n";
		$err .= "<errortype>" . $errortype[$errno] . "</errortype>\n";
		$err .= "<scriptname>" . $filename . "</scriptname>\n";
		$err .= "<scriptlinenum>" . $linenum . "</scriptlinenum>\n";

		// Log everything
		Debug::LogEntry($db, "error", $err);
		
		// Test to see if this is a HALT error or not (we do the same if we are in production or not!)
		if (in_array($errno, $user_errors_halt)) 
		{
			// We have a halt error
			Debug::LogEntry($db, 'audit', 'Creating a Response Manager to deal with the HALT Error.');

			$response = new ResponseManager();
			
			$response->SetError($errmsg);
			$response->Respond();
		}
		
		// Is Debug Enabled? (i.e. Development or Support)
		if (error_reporting() != 0) 
		{
			if (in_array($errno, $user_errors_inline)) 
			{
				// This is an inline error - therefore we really want to pop up a message box with this in it - so we know?
				// For now we treat this like a halt error? Or do we just try and output some javascript to pop up an error
				// surely the javascript idea wont work in ajax?
				// or prehaps we add this to the session errormessage so we see it at a later date?
				echo $errmsg;
				die();
			}
		}
		
		// Must return false
		return false;
	}
	
	/**
	 * Mail an error - currently disabled
	 * @return 
	 * @param $errmsg Object
	 * @param $err Object
	 */
	function MailError($errmsg, $err) 
	{
		global $db;
		
		return true;

		$to = 'info@vs.co.id';
		
		$from = Config::GetSetting($db, "mail_from");
		if ($from == "") return true;
		
		$subject = "Error message from VSign Digital Signage";
		$message = wordwrap("$errmsg\n$err");

		$headers = "From: $from" . "\r\n" . "Reply-To: $from" . "\r\n" .
				"X-Mailer: PHP/" . phpversion();

		if (!mail($to, $subject, $message, $headers)) trigger_error("Mail not accepted", E_USER_NOTICE);
		return true;
	}

	/**
	 * Write an Entry to the Log table
	 * @return 
	 * @param $db Object
	 * @param $type Object
	 * @param $message Object
	 * @param $page Object[optional]
	 * @param $function Object[optional]
	 * @param $logdate Object[optional]
	 * @param $displayid Object[optional]
	 * @param $scheduleID Object[optional]
	 * @param $layoutid Object[optional]
	 * @param $mediaid Object[optional]
	 */	
	static function LogEntry(database $db, $type, $message, $page = "", $function = "", $logdate = "", $displayid = 0, $scheduleID = 0, $layoutid = 0, $mediaid = 0) 
	{
		if ($type == 'audit' && !AUDIT)
		{
			return;
		}

		$currentdate 		= date("Y-m-d H:i:s");
		$requestUri			= Kit::GetParam('REQUEST_URI', $_SERVER, _STRING, 'Not Supplied');
		$requestIp			= Kit::GetParam('REMOTE_ADDR', $_SERVER, _STRING, 'Not Supplied');
		$requestUserAgent   = Kit::GetParam('HTTP_USER_AGENT', $_SERVER, _STRING, 'Not Supplied');
                $requestUserAgent   = substr($requestUserAgent, 0, 253);
		$userid 			= Kit::GetParam('userid', _SESSION, _INT, 0);
		$message			= Kit::ValidateParam($message, _HTMLSTRING);
		
		if ($logdate == "") $logdate = $currentdate;

		//Prepare the variables
		if ($page == "")
		{
			$page = Kit::GetParam('p', _GET, _WORD);
		}

		$SQL = "INSERT INTO log (logdate, type, page, function, message, RequestUri, RemoteAddr, UserAgent, UserID, displayID, scheduleID, layoutID, mediaID) ";
		$SQL .= sprintf("VALUES ('$logdate','$type', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d)", 
					$db->escape_string($page),
					$db->escape_string($function), 
					$db->escape_string($message),
					$db->escape_string($requestUri), 
					$db->escape_string($requestIp), 
					$db->escape_string($requestUserAgent), 
					$userid, $displayid, $scheduleID, $layoutid, $mediaid);

		if (!$db->query($SQL)) 
		{
			// Log the original message
			error_log($message . "\n\n", 3, "./err_log.xml");

			// Log the log failure
			$message = $db->error();
			error_log($message . "\n\n", 3, "./err_log.xml");
		}

		return true;
	}
}
?>