<?php
/*
 * Project: NodeMap2.0
 * File: KMLHandler.class.php
 * Purpose: Creating of editing KML files
 */

class KMLFile {
	private $template = '
		<kml xmlns="http://www.opengis.net/kml/2.2">
			<Document>
				<name>Wireless Leiden Interactive Nodemap 2.0</name>
				<open>1</open>
				<description>Wireless Leiden Interactive Nodemap 2.0</description>
				<Style id="greenArrowIcon">
					<IconStyle>
						<Icon>
							<href>%NODE_GREEN%</href>
						</Icon>
					</IconStyle>
				</Style>
				<Style id="orangeArrowIcon">
					<IconStyle>
						<Icon>
							<href>%NODE_ORANGE%</href>
						</Icon>
					</IconStyle>
				</Style>
				<Style id="redArrowIcon">
					<IconStyle>
						<Icon>
							<href>%NODE_RED%</href>
						</Icon>
					</IconStyle>
				</Style>
				<Style id="blackLine"> 
					<LineStyle>
						<color>%LINE_BLACK%</color>
						<width>3</width>
					</LineStyle>
				</Style>
				<Folder id="nodes">
					<name>Nodes</name>
					<description>Nodes from the Wireless Leiden network</description>
					<LookAt>
						<longitude>4.490153</longitude>
						<latitude>52.161087</latitude>
						<altitude>5</altitude>
						<heading>0</heading>
						<tilt>0</tilt>
						<range>500</range>
					</LookAt>
					%NODESCONTENT%
				</Folder>
				<Folder id="lines">
					<name>Lines</name>
					<description>Lines from nodes to nodes from the Wireless Leiden network</description>
					<LookAt>
						<longitude>4.490153</longitude>
						<latitude>52.161087</latitude>
						<altitude>5</altitude>
						<heading>0</heading>
						<tilt>0</tilt>
						<range>500</range>
					</LookAt>
					%LINESCONTENT%
				</Folder>
				</Document>
		</kml>';

	// First line of the status file must be like this:
	static $fileFirst = 'type,host_name,has_been_checked,check_execution_time,current_state,last_hard_state,last_check,problem_has_been_acknowledged';
	// Every following line will be checked using these functions
	private $fileContent = array('string', 'string', 'int', 'double', 'int', 'int', 'int', 'int');

	private $KMLNodes;
	private $KMLLines;
	
	/*
	 * Function: __construct (constructor)
	 * Description: Creating a new KMLFile
	 * Parameters: -
	 * Returns: -
	 */
	public function __construct() {
		$this->KMLNodes = array();
		$this->KMLLines = array();
	}

	/*
	 * Function: addNode
	 * Description: Add a node to the local node array
	 * Parameters: KMLNode $node
	 * Returns: -
	 */
	public function addNode(KMLNode $node) {
		$this->KMLNodes[] = $node;
	}

	/*
	 * Function: addLIne
	 * Description: Add a line to the local line array
	 * Parameters: KMLLine $line
	 * Returns: -
	 */
	public function addLine(KMLLine $line) {
		$this->KMLLines[] = $line;
	}

	/*
	 * Function: toString
	 * Description: Converts the content of this file and the placemarks to a KML valid string
	 * Parameters: -
	 * Returns: KML valid string
	 */
	public function toString() {
		global $config;

		$toString = $this->template;

		$nodeString = '';
		$nodeCount = count($this->KMLNodes);
		for ($i = 0; $i < $nodeCount; $i++) {
			$nodeString .= $this->KMLNodes[$i]->toString();
		}

		$lineString = '';
		$lineCount = count($this->KMLLines);
		for ($i = 0; $i < $lineCount; $i++) {
			$lineString .= $this->KMLLines[$i]->toString();
		}

		$toString = str_replace('%NODE_GREEN%', $config['node_green'], $toString);
		$toString = str_replace('%NODE_ORANGE%', $config['node_orange'], $toString);
		$toString = str_replace('%NODE_RED%', $config['node_red'], $toString);
		$toString = str_replace('%LINE_BLACK%', $config['line_black'], $toString);
		$toString = str_replace('%NODESCONTENT%', $nodeString, $toString);
		$toString = str_replace('%LINESCONTENT%', $lineString, $toString);
		
		return $toString;
	}

	/*
	 * Function: write
	 * Description: Write KMLFile to a KML file
	 * Parameters: string $filename
	 * Returns: true if we can write to the file, otherwise false
	 */
	public function write($filename) {
		// TODO: David: Needs to be placed in FileHandler.class.php. Here we just want to call our file handler.

		trigger_log(SYSLOG_DEBUG, 'Opening the file "' . $filename . '"', __FILE__, __LINE__);
		$file = new FileHandler($filename, 'w')
			or trigger_log(SYSLOG_ERR, 'Opening the file "' . $filename . '"', __FILE__, __LINE__);

		trigger_log(SYSLOG_DEBUG, 'Writing file "' . $filename . '"', __FILE__, __LINE__);
		$file->write($file,$this->toString());

		trigger_log(SYSLOG_DEBUG, 'Closing file "' . $filename . '"', __FILE__, __LINE__);
		fclose($file);
	}

	/*
	 * Function: getNodeByName
	 * Description: Find the first KMLNode with the name $name and return its position. If not found, return false
	 * Parameters: string $name
	 * Returns: Position of node in our array, if not found false
	 */
	public function getNodeByName($name) {
		$nodesCount = count($this->KMLNodes);
		for ($i = 0; $i < $nodesCount; $i++) {
			if ($this->KMLNodes[$i]->getName() == $name) {
				return $i;
			}
		}

		return false;
	}

	/*
	 * Function: parseLocationFile
	 * Description: Parse the node location file updating or adding KMLNode objects to the current KMLFile object
	 * Parameters: string $file
	 * Returns: true is successfull, otherwise false
	 */
	public function parseLocationFile($file) {
		$nodesCount = preg_match_all('/\[[a-zA-Z0-9]*\]/i', $file, $nodes, PREG_OFFSET_CAPTURE);
		for ($i = 0; $i < $nodesCount; $i++) {
			// Looking for "location" of the node
			if (!$location = $this->findInLocationFile($file, 'location', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "location" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}
			// Looking for "status" of the node
			if (!$status = $this->findInLocationFile($file, 'status', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "status" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}
			// Looking for "latitude" of the node
			if (!$latitude = $this->findInLocationFile($file, 'latitude', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "latitude" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}
			// Looking for "longitude" of the node
			if (!$longitude = $this->findInLocationFile($file, 'longitude', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "longitude" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}
			// Looking for "interfaces" of the node
			if (!$interfaces = $this->findInLocationFile($file, 'interfaces', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "interfaces" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}
			// Looking for "masterip" of the node
			if (!$masterip = $this->findInLocationFile($file, 'masterip', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "masterip" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}
			// Looking for "nodetype" of the node
			if (!$nodetype = $this->findInLocationFile($file, 'nodetype', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "nodetype" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}
			// Looking for "name" of the node
			if (!$name = $this->findInLocationFile($file, 'name', $nodes[0][$i][1])) {
				trigger_log(SYSLOG_WARNING, 'Could not find the "name" of node "' . $i . '", skipping to next', __FILE__, __LINE__);
				continue;
			}

			// Creating a string with the complete description of the node using all data in the location file
			$descriptionLocation = 'Naam: ' . $name . '<br/>Locatie: ' . $location . '<br/>Status: ' . $status . '<br/>Latitude: ' . $latitude . '<br/>Longitude: ' . $longitude . '<br/>Interfaces: ' . $interfaces . '<br/>Master IP: ' . $masterip . '<br/>Node type: ' . $nodetype . '<br/><br/>';

			if ($placemarkPosition = $this->getNodeByName($name)) {
				// Updating an excisting placemark
				$this->KMLNodes[$placemarkPosition]->setDescriptionLocation($descriptionLocation);
				$this->KMLNodes[$placemarkPosition]->setLongitude($longitude);
				$this->KMLNodes[$placemarkPosition]->setLatitude($latitude);
			} else {
				// Adding a new placemark
				$placemark = new KMLNode();
				$placemark->setID($name);
				$placemark->setName($name);
				$placemark->setDescriptionLocation($descriptionLocation);
				$placemark->setLongitude($longitude);
				$placemark->setLatitude($latitude);
				$this->addNode($placemark);
			}
		}
	}

	/*
	 * Function: findInLocationFile
	 * Description: Find the $keyword in $file and return the value of $keyword, starting at $offset
	 * Parameters: string $file, string $keyword, integer $offset
	 * Returns: The value of the keyword if found, otherwise return false
	 */
	private function findInLocationFile($file, $keyword, $offset) {
		$start	= strpos($file, $keyword, $offset) + strlen($keyword . ' = ');
		$end	= strpos($file, "\n", $start);

		if ($start && $end && ($start < $end)) {
			return substr($file, $start, $end - $start);
		} else {
			return false;
		}
	}

	/*
	 * Function: parseStatusFile
	 * Description: Parse the node status file updating or adding KMLNode objects to the current KMLFile object
	 * Parameters: string $file
	 * Returns: true is successfull, otherwise false
	 */
	public function parseStatusFile($file) {
		$fileContents = explode("\r\n", $file);

		if ($fileContents[0] != KMLFile::$fileFirst) {
			trigger_log(SYSLOG_WARNING, 'Contents of file do not match with template of first line', __FILE__, __LINE__);
		}

		// For loop for all the lines in the file. Skipping first line (headers) and last line (blank)
		$linesCount = count($fileContents);
		for ($i = 1; $i < $linesCount - 1; $i++) {
			$lineContent = explode(',', $fileContents[$i]);

			if (count($lineContent) != count($this->fileContent)) {
				trigger_log(LOG_WARNING, 'Contents of the file do not match with template of lines on line "' . $i . '"', __FILE__, __LINE__);
				continue;
			}

			// Checking for valid entries on this line
			for ($j = 0; $j < 8; $j++) {
				try {
					switch ($this->fileContent[$j]) {
						case 'string':
							$lineContent[$j] = (string) $lineContent[$j];
							break;
						case 'int':
							$lineContent[$j] = (int) $lineContent[$j];
							break;
						case 'double':
							$lineContent[$j] = (double) $lineContent[$j];
							break;
						default:
							break;
					}
				} catch (Exception $err) {
					trigger_log(SYSLOG_WARNING, 'The value "' . $j . '" on line "' . $i . '" is not valid, skipping to next line', __FILE__, __LINE__);
					continue;
				}
			}

			// Creating a string with the complete description of the node using all data in the status file
			$descriptionStatus = 'Type: ' . $lineContent[0] . '<br/>Host name: ' . $lineContent[1] . '<br/>Has been checked: ' . $lineContent[2] . '<br/>Check execution time: ' . $lineContent[3] . '<br/>Currenr state: ' . $lineContent[4] . '<br/>Last hard state: ' . $lineContent[5] . '<br/>Last check: ' . $lineContent[6] . '<br/>Problem has been acknowledged: ' . $lineContent[7] . '<br/><br/>';

			if ($placemarkPosition = $this->getNodeByName($lineContent[1])) {
				// Updating an excisting placemark
				$this->KMLNodes[$placemarkPosition]->setDescriptionStatus($descriptionStatus);
			} else {
				// Adding a new placemark
				$placemark = new KMLNode();
				$placemark->setID($lineContent[1]);
				$placemark->setName($lineContent[1]);
				$placemark->setDescriptionStatus($descriptionStatus);
				$this->addNode($placemark);
			}
		}
	}
}
?>