<?php

define("HTTP_TIMEOUT", 1.0);

$curl_is_enabled = in_array('curl', get_loaded_extensions());

/**
 * Set timeout for ATP communication
 */
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 0
    )
));

if (!defined("HOST")) define("HOST", "http://" . htmlentities($_SERVER["HTTP_HOST"]));

if(isset($_POST["action"]) && !empty($_POST["action"])) {
	$action = getPost("action");
	switch($action) {
		case 'alertProcessor' :
			$alertString = htmlentities(getPost("alert"));
			echo alertProcessor($alertString);
			break;
		case 'clearEventLogs' :
			echo clearEventLogs();
			break;
		case 'deleteConfiguration' :
			$filename = htmlentities(getPost("filename"));
			deleteConfiguration($filename);
			break;
		case 'getServerMillis' :
			echo getServerMillis();
			break;
		case 'queryProcessor' :
			$queryString = htmlentities(getPost("query"));
			echo queryProcessor($queryString);
			break;
		case 'setPageDefs' :
			$display = htmlentities(getPost("display"));
			setPageDefs($display);
			break;
		case 'updateSession' :
			$variableName = htmlentities(getPost("variable"));
			$variableValue = htmlentities(getPost("value"));
			session_start();
			$_SESSION[$variableName] = $variableValue;
			break;

		case 'queryBFD':
        {
            try
            {
                $bfdAddressString = htmlentities(getPost("bfdAddress"));
                $queryString = htmlentities(getPost("query"));

			    echo queryBFD($bfdAddressString, $queryString);
            }
            catch (RuntimeException $e)
            {
                echo "";

                exit;
            }

			break;
        }
	}
}

function file_get_contents_curl($url, $curlTimeout = 1, $curlConnectTimeout = 5) {
	$ch = curl_init();

	// Set cURL options
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// Don't check peer certificate, we know it's us
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	// Response timeout
	curl_setopt($ch, CURLOPT_TIMEOUT, $curlTimeout);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curlConnectTimeout);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Connection: close'));

	$response = curl_exec($ch);
	if (curl_errno($ch))
		$error_msg = curl_error($ch);
		
	curl_close($ch);

	if (isset($error_msg))
		throw new RuntimeException($error_msg, 1000);
	else
		return $response;
}

/**
 * Convert from decimal degrees to degrees and decimal minutes
 * @param string $decDeg String representation of position in decimal degrees
 * @param string $orientation Latitude or Longitude
 **/
function decimalDegreesToDecimalMinutes($decDeg, $orientation) {
	
	if ( filter_var($decDeg, FILTER_VALIDATE_FLOAT) === false ) {
		return array("Unknown");
	}

	if ($orientation == "Latitude") {
		$direction = ( intval($decDeg) <=> 1)? "N" : "S";
	} else if ($orientation == "Longitude") {
		$direction = ( intval($decDeg) <=> 1 )? "E" : "W";
	} else {
		$direction = "";
	}

	$decDeg = explode('.', $decDeg);
	$degrees = number_format(intval($decDeg[0]), 0);
	$decMins = floatval("0." . intval($decDeg[1]));
	$minutes = number_format($decMins * 60.0, 3);
	
	return array($degrees, $minutes, $direction);
}

/**
 * Shorthand to get a $_POST field if it exists
 * @param string $field The key to look for
 **/
function getPost($field) {
	return isset($_POST[$field])?($_POST[$field]):"";
}

/**
 * Send update message to processor
 * @param string category The category of field to update
 **/
function alertProcessor($category)
{
	global $ctx;

	try
	{	
		return file_get_contents(HOST . ":8080?DatabaseUpdated=" . $category, false, $ctx);
	}
	catch (Exception $e)
	{
		// This doesn't work because file_get_contents raises a warning not an exception...
		header('HTTP/1.1 500 Internal Server Error');
		header('Content-Type: application/json; charset=UTF-8');
		die(json_encode(array('message' => 'ERROR')));
	}
}

/**
 * Clear all files in the logs\EventLogs folder
 **/
function clearEventLogs() {
	return json_encode(array_map('unlink', glob('logs/EventLogs/*')));
}

/**
 * Delete a configuration file
 * @param string $filename relative to www\
 **/
function deleteConfiguration($filename) {
	unlink($filename);
}

function queryProcessor($queryString) {
	return file_get_contents(HOST . ":8080?" . str_replace(" ", "%20", $queryString));
}

function getServerMillis() {
	return round(microtime(true) * 1000);
}

function setPageDefs($display) {
	file_get_contents(HOST . ":8080?DisplayChange=PageDef&Display=" . htmlspecialchars($display));
}

function queryBFD($bfdAddressString, $queryString) {
	
	global $curl_is_enabled;
	$url = $bfdAddressString . ":8080?" . str_replace(" ", "%20", $queryString);
	$timeout = 3;
	
	if ($curl_is_enabled)
		return file_get_contents_curl($url, $timeout);

	$ctx = stream_context_create(array( 'http' => array('timeout' => $timeout)));
	return file_get_contents($url, false, $ctx);
}

?>