<?php

$config_file = '/etc/telem/config';

/* The common globals used by the telemetry routines
 *
 * _SESSION['state']    : Action / state
 * _SESSION['params']   : List of params to be plotted
 * _SESSION['start']    : Start time
 * _SESSION['stop']     : End time
 * _SESSION['limits']   : Enable/Disable limits
 * _SESSION['title']    : Title graph
 * _SESSION['desc']     : Graph description
 * _SESSION['yaxis']    : Y-Axis Title
 * _SESSION['xaxis']    : X-Axis Title
 * _SESSION['yrange']   : Y-Axis range
 * _SESSION['xrange']   : X-Axis range
 */

function reset_session_parameters()
{
	global $config_file;
	
	$_SESSION['state']  = 'select';
	$_SESSION['config'] = $config_file;
	$_SESSION['params'] = array();
	$_SESSION['start']  = '1 day ago';
	$_SESSION['stop']   = 'now';
	$_SESSION['limits'] = 'on';
	$_SESSION['title']  = 'Telemetry Graph';
	$_SESSION['desc']   = 'Description';
 	$_SESSION['yaxis']  = 'Units';
 	$_SESSION['xaxis']  = 'Time';
 	$_SESSION['yrange'] = 'auto';
 	$_SESSION['xrange'] = 'auto';

	foreach($_SESSION as $key => $value) {
		session_register($_SESSION[$key]);
	}
}

function validate_session()
{
	if (!session_id()) {
		session_start();
	}

	if (!isset($_SESSION['state'])) {
		reset_session_parameters();
	} else {
		/* Check the session is still okay */
	}
}

function print_status()
{
	echo "<pre>\n";
	echo "Session: " . session_id() . "\n";
	echo "State:   " . $_SESSION['state'] . "\n";
	echo "Config:  " . $_SESSION['config'] . "\n";
	foreach($_SESSION['params'] as $key => $value)
		echo 'Params:  ' . $key . ' => ' . $value . "\n";
	echo "Time:    " . $_SESSION['start'] . " until " . $_SESSION['stop'] . "\n";
	echo "Limits:  " . $_SESSION['limits'] . "\n";
	echo "Title:   " . $_SESSION['title'] . "\n";
	echo "Desc:    " . $_SESSION['desc'] . "\n";
	echo "Y-Label: " . $_SESSION['yaxis'] . "\n";
	echo "X-Label: " . $_SESSION['xaxis'] . "\n";
	echo "Y-Range: " . $_SESSION['yrange'] . "\n";
	echo "X-Range: " . $_SESSION['xrange'] . "\n";
	echo "</pre></br\>";
}

function do_page_header()
{
	echo "<head>\n<title>Foo!</title>\n</head>\n\n<body>\n";
}

function do_page_footer()
{
	echo "</body>\n";
}

function report_error($err)
{
	echo '<p>An internal error was encountered: ' . $err . '</p>\n';
}

function sanitise($string)
{
	$len = strlen($string);
	
	/* Only allow a very limited range of characters */
	for ($index = 0; $index < $len; $index ++) {

		$pos = strpos('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_', $string[$index]);

		if ($pos === false)
			$string[$index] = '_';
	};

	return $string;
}

function sanitise_template_name($string)
{
	$len = strlen($string);
	
	/* Only allow a very limited range of characters */
	for ($index = 0; $index < $len; $index ++) {

		$pos = strpos('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_', $string[$index]);

		if ($pos === false)
			$string[$index] = '_';
	};

	return $string;
}

function validate_template_from_name($dir, $name)
{
	$handle = @fopen($dir . '/' . $name, 'r');
	if (!$handle) {
	  echo "Couldn't read $dir/$name";
		return false;
	}
	$list = array();
	
	while(!feof($handle)) {

		$buffer = fgets($handle, 4096);
		
		if (strlen($buffer) == 0)
			continue;

		if ($buffer[0] == '#')
			continue;

		$toks = explode('=', $buffer);

		if (count($toks) != 2)
			continue;

		$list[trim($toks[0])] = trim($toks[1]);
	}
	
	fclose($handle);

	if (count($list) == 0) {
	  echo "No tokens in template $dir/$name";
		return false;
	}

	return $list;
}

function get_template_dirname_from_config($config)
{
	$td = '';
	
	$handle = fopen($config, 'r');
	
	while(!feof($handle)) {
	  
	  $buffer = fgets($handle, 4096);
	  
	  if (sscanf($buffer, 'TEMPLATE_DIRECTORY=%s', &$td))
	    break;
	}
	
	fclose($handle);
	
	return trim($td,'"');
}

/*
 * get_template_list
 *
 * Returns an array containing the descriptions of valid template files
 * in the specified directory, keyed by the filename.
 *
 * The list is naturally sorted.
 */
function get_template_list($dir)
{
  $list = array();
  
  $dh = @opendir($dir);
  if (!$dh) {
    echo "Unable to open template dir " . $dir;
    return $list;
  }
  
  while(($name = readdir($dh)) !== false) {
    
    /* Skip over . files */
    if ($name[0] == '.')
      continue;
    
    /* Skip over non-files */
    if (!is_file($dir . '/' . $name))
      continue;
    
    /* Check the file is a valid template */
    if (sanitise_template_name($name) != $name)
      continue;
    
    $template = validate_template_from_name($dir, $name);
    
    if (!$template)
      continue;
    
    if (!array_key_exists('desc', $template)) {
      echo "No desc key in $name";
      continue;
    }
    
    /* Add the file to the list */
    $list[$name] = $template['desc'];
  }
  
  closedir($dh);
  
  natsort($list);
  
  return $list;
}

function get_csv_filename_from_config($config)
{
	$csv = '';

	$handle = fopen($config, 'r');

	while(!feof($handle)) {

		$buffer = fgets($handle, 4096);

		if (sscanf($buffer, 'TELEMETRY_DEFINITION_FILE=%s', &$csv))
			break;
	}

	fclose($handle);

	return trim($csv,'"');
}

function get_param_list($csv)
{
	$list = array();

	$handle = fopen($csv, 'r');
	if (!$handle) {
		return $list;
	}

	while(!feof($handle)) {

		$pieces = fgetcsv($handle, 32768);

		/* Check for a valid line */
		if (count($pieces) < 4)
			continue;
		if ($pieces[0] == '#')
			continue;
		if ($pieces[4] == '')
			continue;

		$list[$pieces[4]] = $pieces[4];
	}

	fclose($handle);

	/* Produce a naturally sorted list */
	natsort($list);

	return $list;
}

function show_select_list()
{
	/* Get the name of the CSV file */
	$csv = get_csv_filename_from_config($_SESSION['config']);
	
	if ($csv == '')
		return false;

	$list = get_param_list($csv);

	/* And turn that into options */
	echo '<select name="param_id[]" size="10" multiple="multiple">' . "\n";
	foreach($list as $p) {

		if (array_key_exists($p, $_SESSION['params']))
			echo '<option selected="on">' . $p . '</option>' . "\n";
		else
			echo '<option>' . $p . '</option>' . "\n";
	}
	echo "</select>\n";

	return true;
}

function sanitise_any_request()
{
  if (count($_REQUEST) == 1)
    return;
  
  /* If we're not doing actions, we're all done */
  if (!array_key_exists("action", $_REQUEST))
    return;
  
  /* Ensure that the request is properly cleaned up */
  switch($_REQUEST['action']) {
    
  case 'Reset Template':
    break;
    
  case 'Add To Template':
    {	
      /* Zap any requests we aren't expecting */
      $valid_requests = array('action', 'param_id', 'PHPSESSID', 'template');
      
      foreach($_REQUEST as $key => $value) {
	if (!in_array($key, $valid_requests))
	  unset($_REQUEST[$key]);
      }
      
      if (count($_REQUEST['param_id']) == 0) {
	$_REQUEST['action'] = 'error';
	return;
      }
      
      foreach($_REQUEST['param_id'] as $key => $value)
	$_REQUEST['param_id'][$key] = sanitise($value);
      
      break;
    }
    
  case 'Remove From Template':
    {
      /* Zap any requests we aren't expecting */
      $valid_requests = array('action', 'param_id', 'PHPSESSID', 'template');
      
      foreach($_REQUEST as $key => $value) {
	if (!in_array($key, $valid_requests))
	  unset($_REQUEST[$key]);
      }
      
      if (count($_REQUEST['param_id']) == 0) {
	$_REQUEST['action'] = 'error';
	return;
      }
      
      foreach($_REQUEST['param_id'] as $key => $value)
	$_REQUEST['param_id'][$key] = sanitise($value);
      
      break;
    }
    
  case 'Create Template':
    break;
    
  case 'Template Details':
    break;
    
  case 'Delete Template':
    break;
    
  case 'View Template':
    {		
      if (count($_REQUEST['template']) != 1) {
	$_REQUEST['action'] = 'error';
	return;
      }
      
      $_REQUEST['template'] = sanitise_template_name($_REQUEST['template']);
      
      /* Read the directory name from the config file */
      $dirname = get_template_dirname_from_config($_SESSION['config']);
      if (!$dirname) {
	$_REQUEST['action'] = 'error';
	return;
      }
      
      $templates = get_template_list($dirname);
      if (count($templates) == 0) {
	$_REQUEST['action'] = 'error';
	return;
      }
      
      if (!array_key_exists($_REQUEST['template'], $templates)) {
	$_REQUEST['action'] = 'error';
	return;
      }
      
      break;
    }

  case 'Get Data':
    {
      /* Zap any requests we aren't expecting */
      $valid_requests = array('action', 'param', 'ts', 'te', 'PHPSESSID', 'type');
      foreach($_REQUEST as $key => $value) {
	if (!in_array($key, $valid_requests))
	  unset($_REQUEST[$key]);
	else
	  //$_REQUEST[$key] = sanitise($value);
	  false;
      }
      break;
    }
    
  case 'Make Graph':
    {
      /* Zap any requests we aren't expecting */
      $valid_requests = array('action', 'param', 'param0', 'param1', 'param2', 'param3', 'param4', 'param5', 'param6', 'param7', 'param8', 'param9', 'param10', 'param11', 'param12', 'param13', 'param14', 'param15', 'ts', 'te', 'ymax', 'ymin', 'w', 'h', 'v', 'PHPSESSID', 'wt', 'raw', 'type', 'project' );
      foreach($_REQUEST as $key => $value) {
	if (!in_array($key, $valid_requests))
	  unset($_REQUEST[$key]);
	else
	  //$_REQUEST[$key] = sanitise($value);
	  false;
      }

      /* Check if project is set */
      if (array_key_exists('project', $_REQUEST)) {
	/* Check we are a valid project */
        $valid_projects = array('smei', 'dept');
        if (!in_array($_REQUEST['project'] , $valid_projects)) {
	  $_REQUEST['project'] = 'smei';
        }
      }
      
      break;
    }
    
  default:
    foreach($_REQUEST as $key => $value)
      unset($_REQUEST[$key]);
    break;
  }
  
  return;
}

function verify_selected_params()
{
	/* Get the name of the CSV file */
	$csv = get_csv_filename_from_config($_SESSION['config']);
	
	if ($csv == '')
		return false;
	
	$list = get_param_list($csv);
	
	foreach($_SESSION['params'] as $key => $value) {

		if (!array_key_exists($key, $list))
			unset($_SESSION['params'][$key]);
	}
}

function show_existing_templates()
{
  echo '<div class="set">' . "\n";
  
  /* Read the directory name from the config file */
  $dirname = get_template_dirname_from_config($_SESSION['config']);
  if (!$dirname) {
    echo "No template dirname found in the configuration file!<br>\n";
    return;
  }
  
  $templates = get_template_list($dirname);
  if (count($templates) == 0) {
    echo '<hr><p>No current templates in ' . "$dirname" . '</p>.' . "\n";
    return;
  }
  
  echo '<hr><p>Currently existing templates are:</p>' . "\n";
  
  echo '<form>' . "\n";
  echo '<table>' . "\n";
  echo '<tr><th>ID</th><th></th><th>Description</th></tr>' . "\n";
  
  foreach($templates as $key => $value) {
    
    echo '<tr>';
    echo '<td align="center">' . $key . '</td>';
    echo '<td align="center"><input type="radio" name="template" value="' . $key .'"></td>';
    echo '<td>' . $value . '</td>';
    echo '</tr>' . "\n";
  }
  
  echo '<tr><td><input type="submit" name="action" value="Template Details"></td>' . "\n";
  echo '    <td><input type="submit" name="action" value="Delete Template"></td>' . "\n";
  echo '    <td><input type="submit" name="action" value="View Template"></td></tr>' . "\n";
  
  echo '</table>' . "\n";
  echo '</form>' . "\n";
  echo '</div>' . "\n";
}

function show_new_template()
{
	/* key / description for the session parameters */
	$options = array('title'  => 'Graph Title',
			 'desc'   => 'Description',
			 'start'  => 'Start Time',
			 'stop'   => 'End Time',
			 'yaxis'  => 'Y-Axis Lable',
			 'xaxis'  => 'X-Axis Lable',
			 'yrange' => 'Y-Axis Range',
			 'xrange' => 'X-Axis Range'); 

	echo '<hr>';

	echo '<p>New template configuration:</p>' . "\n";

        echo '<form>' . "\n";
        echo '<table>' . "\n";
        echo '<tr><th><input type="submit" name="action" value="Reset Template"></th>' . "\n";
        echo '    <th><input type="submit" name="action" value="Add To Template"></th>' . "\n";
        echo '    <th><input type="submit" name="action" value="Remove From Template"></th>' . "\n";
        echo '    <th><input type="submit" name="action" value="Create Template"></th></tr>' . "\n";
	echo '<tr><th>TelemID</th><th>Option</th><th colspan="2">Setting</th></tr>' . "\n";
        echo '<tr><td rowspan="' . count($options) . '">';
        show_select_list();
        echo '</td>';

	$open = 1;

	foreach($options as $key => $desc) {

		if ($open == 0)
			echo '<tr>';
		else
			$open = 0;

		echo '<td>' . $desc . '</td><td colspan="2"><input name="'. $key . '" value="' . $_SESSION[$key] . '"></td></tr>' . "\n";
	}
	
        echo '</table>' . "\n";
        echo '</form>' . "\n";

	echo '<hr>';
}

function view_template($template)
{
  /* Read the directory name from the config file */
  $dirname = get_template_dirname_from_config($_SESSION['config']);
  if (!$dirname) {
    echo "No dirname found!<br>\n";
    return;
  }
  
  $templates = get_template_list($dirname);
  if (count($templates) == 0) {
    echo '<hr><p>No current templates in ' . "$dirname" . '</p>.' . "\n";
    return;
  }
  
  echo '<hr><p>Template :</p>' . "\n";
  
  echo '<form>' . "\n";
  echo '<table>' . "\n";
  echo '<tr><th>ID</th><th></th><th>Description</th></tr>' . "\n";
  
  foreach($templates as $key => $value) {
    
    echo '<tr>';
    echo '<td align="center">' . $key . '</td>';
    echo '<td align="center"><input type="radio" name="template" value="' . $key .'"></td>';
    echo '<td>' . $value . '</td>';
    echo '</tr>' . "\n";
  }
  
  echo '<tr><td><input type="submit" name="action" value="Template Details"></td>' . "\n";
  echo '    <td><input type="submit" name="action" value="Delete Template"></td>' . "\n";
  echo '    <td><input type="submit" name="action" value="View Template"></td></tr>' . "\n";
  
  echo '</table>' . "\n";
  echo '</form>' . "\n";
}

function load_template()
{
}

function create_new_template()
{ 
}

?>
