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

define('NODE_STATUS_UP', 0);
define('NODE_STATUS_ERROR', 1);
define('NODE_STATUS_UNREACHABLE', 2);

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>
				<LookAt>
					<longitude>%OVERALL_LONGITUDE%</longitude>
					<latitude>%OVERALL_LATITUDE%</latitude>
					<altitude>%OVERALL_ALTITUDE%</altitude>
					<heading>%OVERALL_HEADING%</heading>
					<tilt>%OVERALL_TILT%</tilt>
					<range>%OVERALL_RANGE%</range>
				</LookAt>
				<Style id="blackLine"> 
					<LineStyle>
						<color>%LINE_BLACK%</color>
						<width>3</width>
					</LineStyle>
				</Style>
				<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>
				<Folder id="nodes">
					<name>Nodes</name>
					<description>Nodes from the Wireless Leiden network</description>
					<LookAt>
						<longitude>%OVERALL_LONGITUDE%</longitude>
						<latitude>%OVERALL_LATITUDE%</latitude>
						<altitude>%OVERALL_ALTITUDE%</altitude>
						<heading>%OVERALL_HEADING%</heading>
						<tilt>%OVERALL_TILT%</tilt>
						<range>%OVERALL_RANGE%</range>
					</LookAt>
					%NODESCONTENT%
				</Folder>
				<Folder id="lines">
					<name>Lines</name>
					<description>Lines from nodes to nodes from the Wireless Leiden network</description>
					<LookAt>
						<longitude>%OVERALL_LONGITUDE%</longitude>
						<latitude>%OVERALL_LATITUDE%</latitude>
						<altitude>%OVERALL_ALTITUDE%</altitude>
						<heading>%OVERALL_HEADING%</heading>
						<tilt>%OVERALL_TILT%</tilt>
						<range>%OVERALL_RANGE%</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;
	private $NetworkList;

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

	/*
	 * 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;

		// Add all nodes to the string
		$nodeString = '';
		$nodeCount = count($this->KMLNodes);
		for ($i = 0; $i < $nodeCount; $i++) {
			$nodeString .= $this->KMLNodes[$i]->toString();
		}

		// Add all connected lines to the string
		$lineString = '';
		$lineCount = count($this->KMLLines);
		for ($i = 0; $i < $lineCount; $i++) {
			// If longitude2 and latitude2 aren't set, ignore the lines
			// This happens with all the connections that don't connect 2 nodes
			if ($this->KMLLines[$i]->isConnected()) {
				$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);

		$toString = str_replace('%OVERALL_LONGITUDE%', $config['overall_longitude'], $toString);
		$toString = str_replace('%OVERALL_LATITUDE%', $config['overall_latitude'], $toString);
		$toString = str_replace('%OVERALL_ALTITUDE%', $config['overall_altitude'], $toString);
		$toString = str_replace('%OVERALL_HEADING%', $config['overall_heading'], $toString);
		$toString = str_replace('%OVERALL_TILT%', $config['overall_tilt'], $toString);
		$toString = str_replace('%OVERALL_RANGE%', $config['overall_range'], $toString);

		return $toString;
	}

	/*
	 * 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) {
		// We want to find all the nodes in the location file and store information of the nodes...
		$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
			$dataLocation = '
				<Data name="location">
					<value>
						<![CDATA[
							' . $location . '
						]]>
					</value>
				</Data>
				<Data name="status">
					<value>' . $status . '</value>
				</Data>
				<Data name="interfaces">
					<value>' . $interfaces . '</value>
				</Data>
				<Data name="masterIP">
					<value>' . $masterip . '</value>
				</Data>
				<Data name="nodeType">
					<value>' . $nodetype . '</value>
				</Data>';

			if ($placemarkPosition = $this->getNodeByName($name)) {
				// Updating an excisting placemark
				$this->KMLNodes[$placemarkPosition]->setDataLocation($dataLocation);
				$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->setDataLocation($dataLocation);
				$placemark->setLongitude($longitude);
				$placemark->setLatitude($latitude);
				$this->addNode($placemark);
			}

			// Now let's find all interlinks with this node
			$position = $nodes[0][$i][1];
			while (($position = strpos($file, 'ip=', $position + 1)) && (isset($nodes[0][$i + 1][1]) && $position < $nodes[0][$i + 1][1])) {
				$ipAddress = $this->findInLocationFile($file, 'ip=', $position);
				$posSlash = strpos($ipAddress, '/');
				$ip = substr($ipAddress, 0, $posSlash);
				$netmask = substr($ipAddress, $posSlash + 1);

				$posNetwork = $this->NetworkList->find($ip);
				if ($posNetwork) {
					// Network already excists in list, just need to add longitude2 en latitude2 to KMLLine
					// and add the node name to the name of the line.
					// Position in network equals position in KMLLine array :-)

					$this->KMLLines[$posNetwork]->setName($this->KMLLines[$posNetwork]->getName() . $name);
					$this->KMLLines[$posNetwork]->setLongitude2($longitude);
					$this->KMLLines[$posNetwork]->setLatitude2($latitude);
				} else {
					// Network doesn't excist. We create a new network and a new line.

					$network = new Network($ip, $netmask);
					$this->NetworkList->add($network);

					// TODO: For this project we'll use random numbers.
					// In a following project this can be adjusted 
					$bandwithMax = rand(0, 200);
					$bandwithUsage = rand(0, $bandwithMax);
					
					$data =	'
						<Data name="netmaskDecimal">
							<value>' . $network->netmaskDecimal . '</value>
						</Data>
						<Data name="netmaskBinary">
							<value>' . $network->netmaskBinary . '</value>
						</Data>
						<Data name="wildcardDecimal">
							<value>' . $network->wildcardDecimal . '</value>
						</Data>
						<Data name="wildcardBinary">
							<value>' . $network->wildcardBinary . '</value>
						</Data>
						<Data name="networkDecimal">
							<value>' . $network->networkDecimal . '</value>
						</Data>
						<Data name="networkBinary">
							<value>' . $network->networkBinary . '</value>
						</Data>
						<Data name="broadcastDecimal">
							<value>' . $network->broadcastDecimal . '</value>
						</Data>
						<Data name="broadcastBinary">
							<value>' . $network->broadcastBinary . '</value>
						</Data>
						<Data name="hostMinDecimal">
							<value>' . $network->hostminDecimal . '</value>
						</Data>
						<Data name="hostMinBinary">
							<value>' . $network->hostminBinary . '</value>
						</Data>
						<Data name="hostMaxDecimal">
							<value>' . $network->hostmaxDecimal . '</value>
						</Data>
						<Data name="hostMaxBinary">
							<value>' . $network->hostmaxBinary . '</value>
						</Data>
						<Data name="hosts">
							<value>' . $network->numberHosts . '</value>
						</Data>
						<Data name="bandwidthMax">
							<value>' . $bandwithMax . '</value>
						</Data>
						<Data name="bandwidthUsage">
							<value>' . $bandwithUsage . '</value>
						</Data>';

					$line = new KMLLine();
					$line->setID(str_replace('.', '', $network->networkDecimal));
					$line->setName('Link: Van ' . $name . ' naar ');
					$line->setData($data);
					$line->setLongitude1($longitude);
					$line->setLatitude1($latitude);
					$this->KMLLines[] = $line;
				}
			}
		}
	}

	/*
	 * 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]);

			// Names in the status file are in the format "CNode%NAME%".
			// We need to remove the CNode so it matches the location file.
			$lineContent[1] = str_replace('CNode', '', $lineContent[1]);

			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
			$dataStatus = '
				<Data name="type">
					<value>' . $lineContent[0] . '</value>
				</Data>
				<Data name="hostName">
					<value>' . $lineContent[1] . '</value>
				</Data>
				<Data name="hasBeenChecked">
					<value>' . $lineContent[2] . '</value>
				</Data>
				<Data name="checkExecutionTime">
					<value>' . $lineContent[3] . '</value>
				</Data>
				<Data name="currentState">
					<value>' . $lineContent[4] . '</value>
				</Data>
				<Data name="lastHardState">
					<value>' . $lineContent[5] . '</value>
				</Data>
				<Data name="lastCheck">
					<value>' . $lineContent[6] . '</value>
				</Data>
				<Data name="problemHasBeenAcknowledged">
					<value>' . $lineContent[7] . '</value>
				</Data>';

			$style = NODE_RED;
			if ($lineContent[4] == NODE_STATUS_ERROR) {
				$style = NODE_ORANGE;
			} elseif ($lineContent[4] == NODE_STATUS_UP) {
				$style = NODE_GREEN;
			}

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