<?php

/******************************************************************************
@owner: SVSi
@author: Arthur Johnson/Dan Nagle
@function: Panel Builder check and initialization, makes sure user
...........is logged in, then fetches data and initializes script editor
...........dropdowns
*******************************************************************************/

	//error_reporting(E_ALL); ini_set('display_errors', 1);

	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $online = 0;
	else $online = 1;

	if ($online){
	
		if (!isset($_SESSION)) session_start(); //if no active session we start a new one

		if (file_exists("php_includes/Common.php")) 
			include_once "php_includes/Common.php";
		else if (file_exists("../php_includes/Common.php"))
			include_once "../php_includes/Common.php";
		else {
			echo 'Fatal error: Could not find php_includes/Common.php';
			exit;
		}

		include_once $php_includes . "/Connect.php";
		include_once $php_includes . "/Authenticate.php";
		include_once $php_includes . "/GetAllUnitsRX.php";
		include_once $php_includes . "/GetAllUnitsTX.php";
		include_once $php_includes . "/GetAllUnitsDVR.php";
		include_once $php_includes . "/GetSerialCommands.php";
		include_once $php_includes . "/TabletFunctions.php";
		include_once $php_includes . "/ScriptFunctions.php";
		include_once $php_includes . "/Get_DVR_PlayList.php";
		include_once $php_includes . "/GetRXLP.php";
		include_once $php_includes . "/GetTXHP.php";
		include_once $php_includes . "/GetGroups.php";

		if (isset($_GET['localexecute'])){

			if ($_SERVER['HTTP_HOST'] != '127.0.0.1' ){
				echo 'You are not a local service.';
				exit;
			}

			if (isset($_GET['wpcommand']) && isset($_GET['ip'])){
			
				$ip = trim($_GET['ip']);
				syslog(LOG_INFO, __FILE__.":".__LINE__.":wpcommand: ". $_GET['wpcommand']." to " .$_GET['ip']);

				if (filter_var($ip, FILTER_VALIDATE_IP)){
					SendCommand($_GET['wpcommand'], $ip);
					exit;
				} 
				else {
				
					$unit = macIsWP($ip);
					
					if ($unit != false){
						syslog(LOG_INFO, __FILE__.":".__LINE__.":wpcommand: ". $_GET['wpcommand']." to " .$unit['ipaddr']);
						SendCommand($_GET['wpcommand'], $unit['ipaddr']);
						exit;
					}	  
				}

				exit;
			}

			$segments = explode(" ", trim($_GET['localexecute']));

			if (strtolower($segments[0]) == "help" || strtolower($segments[0]) == "?"){
				$response = getAsciiHelp(trim(strtolower($_GET['localexecute'])));
			} 
			else {
				if (is_numeric($_GET['localexecute'])){
					$response = trim(ParseScript($_GET['localexecute']));  
				} 
				else {
				  $response = trim(ParseScript($_GET['localexecute'],true));
				}
			}

			$verbose = false;
			if (isset($_GET['verbose'])){
				if ($_GET['verbose'] == 1) $verbose = true;
			}

			if (stripos($segments[0], "getstatus") === 0){
				$response = getAsciiStatus(trim(strtolower($_GET['localexecute'])));
				$verbose = true;
			}

			if (stripos($segments[0], "help") === 0){
				$verbose = true;
			}

			if (stripos($segments[0], "?") === 0){
				$verbose = true;
			}

			if (isset($_GET['saveresponse'])){
				if ($_GET['saveresponse'] && $verbose){
					
					echo "BEGINERESPONSE\n";
				  
					if ($response == "") echo 'Command not found.';
					else echo $response;

				}
			}
			
			exit;
			
		}

		// get all units
		if (isset($_REQUEST['fetchimagedata'])){
			OutputButton($_REQUEST['fetchimagedata']);
			exit;
		}

		if (isset($_REQUEST['fetchgeneratedimagedata'])){
			OutputButton($_REQUEST['fetchgeneratedimagedata'], "generatedimage");
			exit;
		}

		if (isset($_REQUEST['fetchcustomimagedata'])){
			OutputButton($_REQUEST['fetchcustomimagedata'], "customimage");
			exit;
		}



		if (isset($_REQUEST['dvrplaylist'])){

			$playlist = $_REQUEST['dvrplaylist'];

			if(filter_var($playlist, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
				$playlist = getMACfromIP($playlist);

			$PlayLists = array_reverse(Get_DVR_PlayList($playlist));

			echo "\n<select id=\"selectDVRPlaylist\">";
			echo "\n<option value='latest'>Latest recording / file currently recorded</option>";
			
			foreach ($PlayLists as $PlayList) {
				if (!is_array($PlayList)) continue;
				echo "\n<option value='".$PlayList['fileName']."'>".date("[M d, Y h:i:sA] ",strtotime ($PlayList['recordDate'])).$PlayList['description']." (".$PlayList['durationFormat'].")</option>";
			}

			echo "\n</select>";

			echo "<span id='loopplaybackspan'><input id='loopplayback' type='checkbox' name='loopplayback' value='loop' /> Loop</span>";

			if(!is_array($PlayLists) || count($PlayLists) < 1)
				echo "<br><i>No playlists found or couldn't connect to DVR.</i>";

			exit;

		}



		if (isset($_REQUEST['rxtxlocalplaylist'])){

			$rxtxlocalplaylist = $_REQUEST['rxtxlocalplaylist'];

			$quicktest = str_replace("_2", "", $rxtxlocalplaylist, $secondstream);
				//is this an IP address instead of MAC?
			if (filter_var($quicktest, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)){
				$rxtxlocalplaylist = getMACfromIP($quicktest);
				if ($secondstream > 0) $rxtxlocalplaylist = $rxtxlocalplaylist ."_2";
			}

			if (MACisValid($rxtxlocalplaylist)){
				$unit = getUnitNumFromMAC($rxtxlocalplaylist);
			}
			else {
				echo 'Invalid MAC';
				exit;
			}

			if ($unit['unitType'] == "tx"){
				$PlayLists = GetTXHP($rxtxlocalplaylist);
			} 
			elseif ($unit['unitType'] == "rx"){
				$PlayLists = GetRXLP($rxtxlocalplaylist);
			} 
			else {
				echo 'Invalid unit';
				exit;
			}

			echo "\n<select id=\"selectPlaylist\">";
			foreach ($PlayLists as $key => $PlayList){
				switch ($key) {
				  case "hp0":
				  case "lp0":
					echo "\n<option value='1'>".$PlayList."</option>";		
					break;
				  case "hp1":
				  case "lp1":
					echo "\n<option value='2'>".$PlayList."</option>";		
					break;
				  case "hp2":
				  case "lp2":
					echo "\n<option value='3'>".$PlayList."</option>";		
					break;
				  case "hp3":
				  case "lp3":
					echo "\n<option value='4'>".$PlayList."</option>";		
					break;
				  case "hp4":
				  case "lp4":
					echo "\n<option value='5'>".$PlayList."</option>";		
					break;
				  case "hp5":
				  case "lp5":
					echo "\n<option value='6'>".$PlayList."</option>";		
					break;
				  case "hp6":
				  case "lp6":
					echo "\n<option value='7'>".$PlayList."</option>";		
					break;
				  case "hp7":
				  case "lp7":
					echo "\n<option value='8'>".$PlayList."</option>";		
					break;
				}	
			}

			echo "\n</select>";

			if(!is_array($PlayLists) || count($PlayLists) < 1){
				echo "<br><i>No playlists found.</i>";
			}

			exit;

		}

		if (isset($_REQUEST['fetchscriptimage'])){
			//if ($_SESSION['UserData']['IsAdmin'] != 1) exit;		  

			$script = GetScripts(pg_escape_string($_REQUEST['id']));

			if (strpos($script['buttonimage'],"uploads") === false)
				echo  "images/scriptimg/defaultbutton.png";  
			else
				echo "?fetchcustomimagedata={$_REQUEST['id']}";

			exit;
		}


		if (isset($_REQUEST['fetchscript'])){
			//if ($_SESSION['UserData']['IsAdmin'] != 1) exit;

			$script = GetScripts(pg_escape_string($_REQUEST['id']));
			echo trim($script['script']);
			exit;
		}

		if (isset($_POST['savescript']) && isset($_POST['script']) && isset($_POST['name'])){
		
			//if ($_SESSION['UserData']['IsAdmin'] != 1){
			//	echo 'Only admin allowed.';
			//	exit;
			//}

			$savescript = array();
			$savescript['script'] = pg_escape_string(trim($_POST['script']));
			$savescript['name'] = pg_escape_string(trim($_POST['name']));
			$savescript['useimage'] = pg_escape_string(trim($_POST['useimage']));
			$savescript['labelText'] = pg_escape_string(trim($_POST['labelText']));
			$savescript['labelSize'] = pg_escape_string(trim($_POST['labelSize']));
			$savescript['labelColor'] = RGBToHex(trim($_POST['labelColor']));
			$savescript['customimage'] = pg_escape_string(trim($_POST['customimage']));

			if (!is_numeric($savescript['useimage'])) $savescript['useimage'] = 0;

			if (isset($_POST['id'])) {
				if ($_POST['id'] == "null" || $_POST['id'] == "false" || $_POST['id'] == false ){
					$savescript['id'] = null; 
				}
				else{
					$savescript['id'] = pg_escape_string(trim($_POST['id']));
				}
			} 
			else{
				$savescript['id'] = null;
			}

			if (isset($_POST['customimage'])){
				$savescript['customimage'] = $_POST['customimage'];
			}
			else{
				$savescript['customimage'] = "images/scriptimg/defaultbutton.png";
			}

			if (isset($_POST['buttonimage'])){
				$savescript['buttonimage'] = $_POST['buttonimage'];
			} 
			else{
				copy('button_blank_blue.png', 'images/scriptimg/button_blank_blue.png');
				$savescript['buttonimage'] = "images/scriptimg/button_blank_blue.png";
			}

			//clean up CSS url
			if(strpos($savescript['buttonimage'], "url") !== false){

				//  url("http://192.168.1.36/scripts/button_blank_blue.png")

				$buttonimage = str_ireplace("(", "", trim($savescript['buttonimage'])); //trim css syntax
				$buttonimage = str_ireplace(")", "", $buttonimage); //trim css syntax
				$buttonimage = str_ireplace("\"", "", $buttonimage); //trim css syntax
				$buttonimage = str_ireplace("'", "", $buttonimage); //trim css syntax
				$buttonimage = str_ireplace(";", "", $buttonimage); //trim css syntax
				$tempArray = explode( "/", trim($buttonimage)); //break at file name.

				$buttonimage = $tempArray[count($tempArray) - 1];
			}

			$savescript['buttonimage'] = trim($buttonimage);

			//fix possible submission quirks, like absolute paths, nulls, and double slashes

			if ($savescript['id'] != null){
				echo 'Overwrote script.';
			} 
			else{
				echo 'Saved new script.';
			}

			$rowid = SaveScript($savescript['script'], $savescript['name'], $savescript['id'],  $savescript['buttonimage'],
			$savescript['useimage'], $savescript['labelText'], $savescript['labelColor'], $savescript['labelSize'], $savescript['customimage']);

			echo $rowid;

			exit;
			
		}

		if (isset($_POST['executescript'])){
		
			//if ($_SESSION['UserData']['IsAdmin'] != 1){
			//	echo 'Only admin allowed.';
			//	exit;
			//}
			
			if (is_numeric($_POST['script']))
				ParseScript($_POST['script']);
			else
				ParseScript($_POST['script'], true);	
			
			exit;
			
		}

		if (isset($_POST['deletescript'])){
		
			//if ($_SESSION['UserData']['IsAdmin'] != 1){
			//	echo 'Only admin allowed.';
			//	exit;
			//}

			if (is_numeric($_POST['id']))
				CoreInsert("delete from scripts where id = '".$_POST['id']."'");		
			
			exit;
			
		}

		if (isset($_POST['savescript'])){
		
			echo "invalid command\n\n";
			print_r($_POST);
		  
			exit;
			
		}


		if (isset($_REQUEST['id'])){
			if ($_REQUEST['id'] != "new"){
				$script = GetScripts(pg_escape_string($_REQUEST['id']));
			}
		}

		$UnitsRX = GetAllUnitsRX($_SESSION['UserData']['UserId'], $_SESSION['UserData']['IsAdmin']);
		$UnitsTX = GetAllUnitsTX($_SESSION['UserData']['UserId'], $_SESSION['UserData']['IsAdmin']);
		$UnitsDVR = GetAllUnitsDVR($_SESSION['UserData']['UserId'], $_SESSION['UserData']['IsAdmin']);
		$UnitsWP = getAllWP();
		$UnitsATR = getAllATR();
		$SerialCmds = GetSerialCommands();
		$Scripts = GetScripts();
		$tablets = GetTablets();

		if(!isset($UnitsRX[0]['mac']))
			$UnitsRX = false;
		if(!isset($UnitsTX[0]['mac']))
			$UnitsTX = false;
		if(!isset($UnitsDVR[0]['mac']))
			$UnitsDVR = false;

		if(!isset($UnitsWP[0]['mac']))
			$UnitsWP = false;

		if(!isset($UnitsATR[0]['mac']))
			$UnitsATR = false;
		
	}
?>