<?php
/*
 * Project: NodeMap2.0
 * File: kml.php
 * Purpose: Creates up-to-date KML if not exists, otherwise redirect to last KML file in KML folder
 */

require_once('config.php');
require_once($config['file_init']);

$time = isset($_GET['time']) ? $_GET['time'] : mktime() - (mktime() % 300);

// Check if the file is already cached
if (!is_link($config['root'] . '/kml/nodemap-' . $time . '.kml')) {
	// No file found, let's create a new cache file

	// First off, we create a new KMLFile object
	$kmlFile = new KMLFile();

	// Let's try to read the node location file
	$nodeLocation = new FileHandler($config['node_location_file'], 'r');
	$kmlFile->parseLocationFile($nodeLocation->read());

	// Let's try to read the node status file
	$nodeStatus = new FileHandler($config['node_status_file'], 'r');
	$kmlFile->parseStatusFile($nodeStatus->read());

	// Write the file to the server
	$file = new FileHandler($config['root'] . '/kml/nodemap-' . $time . '.kml', 'w');
	$file->write($kmlFile->toString());
}

/* Instead of exposing the kml file, one could also argue to hide it at the back
 * so you can can so some dirty hacking and more easy ACL
 * $kmlFile = fopen($config['root'] . '/kml/nodemap-' . $time . '.kml');
 * print $fread($kmlFile);
 * fclose($kmlFile);
 */
echo 'kml/nodemap-' . $time . '.kml';
?>
