<?php

$debug = 0;
$dTABLE = 80;
include 'site.php';

function logintext () {
  echo '<p>Welcome to the IPP status pages.<br><br>', "\n";
  echo 'From these pages, you may examine summary information about the IPP processing results.<br>', "\n";
  echo 'In order to continue, it is necessary to login as an authorized IPP user.</p>', "\n\n";
}

function loginform ($username) { 
  echo '<form action="Login.php" method="POST">', "\n";
  if ($username) {
    echo "Username: <input type=\"text\" name=\"username\" value=\"$username\"><br>\n";
  } else {
    echo "Username: <input type=\"text\" name=\"username\"><br>\n";
  }
  echo 'Password: <input type="password" name="password"><br>', "\n";
  echo '<input type="submit" name="login" value="login">', "\n";
  echo '</form>', "\n\n";
}

function projectform ($ID) {

  menu ('ipp.menu.dat', 'Select Project', 'ipp.css', $ID['link'], $ID['proj']);
  if ($_GET['new'] && $_GET['proj']) {
    echo "<p> Project is now <b>" . $_GET['proj'] . "</b></p>\n";
  }
  echo "<p> Please select the project of interest </p>\n";
  // echo "<form action=\"SelectProject.php\" method=\"POST\">\n";
  // echo "Project: <input type=\"text\" name=\"proj\"><br>\n";
  // echo "<input type=\"submit\" name=\"project\">\n";

  $pass = $ID['pass'];
  // echo "<input type=\"hidden\" name=\"pass\" value=\"$pass\">\n";
  // echo "</form>\n";

  $db = dbconnect('ippadmin');

  // make this a DB lookup
  $sql = "SELECT projname FROM projects order by projname";

  $qry = $db->query($sql);
  if (dberror($db)) {
    echo "<b>error reading project list</b><br>\n";
    menu_end();
  }
  
  echo "<table class=select>\n";
  echo "<tr class=select><th class=select> projects </th></tr>\n";
  while (dbFetchInto($qry, $row)) {
    // add a link here to set the database
    $tmp_proj = $row[0];
    $tmp_link = "pass=$pass";
    echo "<tr class=select><td class=select><a class=\"menutop\" href=\"SelectProject.php?$tmp_link&proj=$tmp_proj&new=1\"> $row[0] </a></td></tr>\n";
    // echo "<tr class=select><td class=select> $row[0] </td></tr>\n";
  } 
  echo "</table>\n";

  menu_end ();
}

function dbFetchInto ($qry, &$result) {
  global $DBI;

  if ($DBI == "MDB2") {
    $result = $qry->fetchRow();
    if ($result == NULL) {
      $success = 0;
    } else {
      $success = 1;
    }
  }
  if ($DBI == "DB") {
    $success = $qry->fetchInto($result);
  }
  return $success;
}

function dbconnect ($database) {

  // these are set in 'site.php'
  global $DBI;
  global $DBHOST;
  global $DBUSER;
  global $DBPASS;
  global $CZARDBNAME;
  global $CZARDBHOST;

  $success = 0;
  if ($DBI == "MDB2") {
    $success = include_once('MDB2.php');
  }
  if ($DBI == "DB") {
    $success = include_once('DB.php');
  }
  if ($success != 1) {
    echo "<b>installation error: php file for $DBI not found.</b><br>\n";
    echo "<b>please consult the IPP Wiki for install help (get $DBI.php via Pear)</b><br>\n";
    menu_end();
    return 0;
  }

  // connect to the database
  if ($database == $CZARDBNAME) {
    $dsn = "mysql://$DBUSER:$DBPASS@$CZARDBHOST/$database";
    $dsnerr = "mysql://$DBUSER:XXX@$CZARDBHOST/$database"; // only used to report the error
  } else {
    $dsn = "mysql://$DBUSER:$DBPASS@$DBHOST/$database";
    $dsnerr = "mysql://$DBUSER:XXX@$DBHOST/$database"; // only used to report the error
  }
  if ($DBI == "DB") {
    $db = DB::connect($dsn);
  }
  if ($DBI == "MDB2") {
    $db = MDB2::connect($dsn);
  }

  if (dberror($db)) {
    echo "<b>error accessing database</b><br>\n";
    echo "<b>tried $dsnerr</b><br>\n";
    $result = $db->getMessage();
    echo "$result<br>";
    menu_end();
  }
  return $db;
}

function dberror ($db) {
  global $DBI;

  if ($DBI == "MDB2") {
    $dberr = PEAR::isError($db);
  }
  if ($DBI == "DB") {
    $dberr = DB::isError($db);
  }

  return $dberr;
}

// there are three pieces of data that are used to define a user:
// - name (the username: available somewhere: db table?)
// - proj (defines which database is being used)
// - pass (NOT the same as the user password: randomly generated for the session and given a timeout) 

// have this function take the current menu and style?
function checkLogin () {

  $username = $_POST['username'];
  $password = $_POST['password'];

  // if password is not specified, keep username and ask again
  if ($password == "") {
    menu ('ipp.menu.dat', 'Login', 'ipp.css', '', '');
    loginform ($username);
    menu_end ();
  }

  $db = dbconnect('ippadmin');

  // get the users from the DB
  $sql = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
  $qry = $db->query($sql);

  if (dberror($db)) {
    menu ('ipp.menu.dat', 'Login', 'ipp.css', '', '');
    echo "<b>error reading users table</b><br>\n";
    echo "Login Failed, please try again<br>\n";
    loginform ("");
    menu_end();
  }

  $success = dbFetchInto($qry, $row);
  if (!$success) {  
    menu ('ipp.menu.dat', 'Login', 'ipp.css', '', '');
    echo "Login Failed, please try again<br>\n";
    loginform ("");
    menu_end ();
    exit ();
  }
  
  // generate an random ephemeral ID
  $ID['name'] = $username;
  $ID['proj'] = "";

  // generate a cookie for the user
  $sql = "SELECT username,cookie FROM cookies WHERE username = '$username'";
  $qry = $db->query($sql);
  if (dberror($db)) {
    echo "Cookie Failed, please try again<br>\n";
    menu_end();
  }

  if (dbFetchInto($qry, $row)) {
    $ID['pass'] = $row[1];
  } else {
    $cookie = rand(0,100000);
    $ID['pass'] = $cookie;
    $sql = "INSERT into cookies (username, cookie) values ('$username', '$cookie')";
    $qry = $db->query($sql);
    if (dberror($db)) {
      echo "Cookie Failed, please try again<br>\n";
      menu_end();
    }
  }

  // the link is attached to every nav link
  $ID['link'] = "pass=" . $ID['pass'];
  if ($ID['proj']) {
    $ID['link'] = $link . "&proj=" . $ID['proj'];
  }

  return $ID;
}

function checkID () {
  $VERBOSE = 0;
  if ($VERBOSE > 1) {
      phpinfo(32);
  }

  // check for valid server method
  if (($_SERVER['REQUEST_METHOD'] != 'POST') && ($_SERVER['REQUEST_METHOD'] != 'GET')) {
    menu ('ipp.menu.dat', 'Login', 'ipp.css', '', '');
    echo "Invalid Client Request<br>\n";
    menu_end ();
    exit ();
  }

  // look for pass & proj in appropriate location
  if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    $ID['pass'] = array_key_exists('pass', $_GET) ? $_GET['pass'] : "";
    $ID['proj'] = array_key_exists('proj', $_GET) ? $_GET['proj'] : "";
    $ID['menu'] = array_key_exists('menu', $_GET) ? $_GET['menu'] : "";
    $ID['from'] = array_key_exists('from', $_GET) ? $_GET['from'] : "";

    if ($VERBOSE) {
      echo "using GET: ", $ID['pass'], $ID['proj'], "<br>\n";
      echo "GET list<br>\n";
      foreach ($_GET as $key => $value) {
	echo "$key : $value<br>\n";
      }
    }
  }
  if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
    $ID['pass'] = array_key_exists('pass', $_POST) ? $_POST['pass'] : "";
    $ID['proj'] = array_key_exists('proj', $_POST) ? $_POST['proj'] : "";
    $ID['menu'] = array_key_exists('menu', $_POST) ? $_POST['menu'] : "";
    $ID['from'] = array_key_exists('from', $_POST) ? $_POST['from'] : "";

    if ($VERBOSE) {
      echo "using POST: ", $ID['pass'], $ID['proj'], "<br>\n";
      echo "POST list<br>\n";
      foreach ($_POST as $key => $value) {
	echo "$key : $value<br>\n";
      }
    }
  }

  // user is not logged in at all
  if ($ID['pass'] == "") {
    menu('ipp.menu.dat', 'Login', 'ipp.css', '', '');
    logintext ();    
    loginform ("");
    menu_end ();
  }

  $db = dbconnect ('ippadmin');

  $pass = $ID['pass'];

  // search for password
  $sql = "SELECT username FROM cookies WHERE cookie = '$pass'";
  $qry = $db->query($sql);
  if (dberror($db)) {
    echo "<b>error reading users table</b><br>\n";
    echo "Login Failed, please try again<br>\n";
    loginform ("");
    menu_end();
  }
  
  $success = dbFetchInto($qry,$row);
  if (! $success) {
    menu('ipp.menu.dat', 'Login', 'ipp.css', '', '');
    echo "unknown user, please login again<br>\n";
    loginform ("");
    menu_end ();
  }
  // use the pass value to find the corresponding user
  $ID['name'] = $row[0];

  // $link is attached to every nav link
  $ID['link'] = "pass=" . $ID['pass'];
  if ($ID['proj']) {
    $ID['link'] = $ID['link'] . "&proj=" . $ID['proj'];
  }
  
  return $ID;
}

function head ($title) {
  echo "<head>\n";
  echo "  <title> $title </title>\n";
  /* JavaScript code */
  echo "  <script type=\"text/javascript\">\n";
  echo "  function changeCell(cellId, newContent){\n";
  echo "    document.getElementById(cellId).innerHTML=newContent;\n";
  echo "  }\n";
  echo "  </script>\n";
  echo "</head>\n\n";
}

function menu ($source, $title, $sheet, $append, $project) {

  $root = "/ippMonitor";
  if (! $project) { $project = "none"; }

  $bodyclass = "default";
  if ("$project" == "gpc1") { $bodyclass = "gpc1"; }
  if ("$project" == "gpc2") { $bodyclass = "gpc2"; }

  $tblclass = "page";
  if ("$project" == "gpc1") { $tblclass = "page_gpc1"; }
  if ("$project" == "gpc2") { $tblclass = "page_gpc2"; }

  echo "<html>\n";
  head($title);
  echo "<link rel=\"STYLESHEET\" HREF=\"$sheet\">\n";
  echo "<body class=$bodyclass>\n";

  // these are defined in site.php
  global $DBHOST;
  global $WWWHOST;

  echo "<p style=\"font-size:50%\">host: $WWWHOST, db: $DBHOST</p>\n";
  echo "<table class=$tblclass cellspacing=10px><tr><td valign=top>\n";
  echo "<table class=menu cellspacing=0px>\n";

  menulines ($source, $root, $append, $project);

  echo '</table></td><td class="body" valign=top>', "\n\n";
}

function menulines ($source, $root, $append, $project) {

  $file = fopen ($source, "r");

  // loop over the lines in the file and generate lines in the menu
  while ($line = fgetcsv ($file, 1024, "|")) {
    if (preg_match ('^[:blank:]*#', $line[0])) continue;
    if (count($line) < 2) continue;

    if (count($line) == 2) {
      $value = trim($line[0]);
      if ($value == "input") {
        $value = trim($line[1]);
        menulines ($value, $root, $append, $project);
      }
      continue;
    }
    if (count($line) != 5) continue;

    $type = trim($line[2]);
    $name = trim($line[3]);
    $base = trim($line[4]);

    if (preg_match ('|\$PROJECT|', $name)) {
      $name = preg_replace ('|\$PROJECT|', $project, $name);
    }

    if ($append) {
      $link = $base . "?" . $append;
    } else {
      $link = $base;
    }
	
    $thisname = $_SERVER['SCRIPT_NAME']; 
    $page = "$root/" . $base;
    if ($page == $thisname) {
      $style = trim($line[1]);
    } else { 
      $style = trim($line[0]);
    }       

    switch ($type) { 
    case 'plain':
      echo "<tr><td class=\"$style\"> $name </td></tr>\n";  
      break;
    case 'picture':
      echo "<tr><td class=\"$style\"> <img src=\"$name\"> </td></tr>\n";     
      break;
    case 'piclink':
      echo "<tr><td class=\"$style\"> <a class=\"$style\" href=\"$link\"> <img class=\"$style\" src=\"$name\"> </a></td></tr>\n";     
      break;
    default:
      echo "<tr><td class=\"$style\"> <a class=\"$style\" href=\"$link\"> $name </a></td></tr>\n";     
      break;
    } 
  }
  fclose ($file);
}

function menu_end () { 
  echo "</td></tr></table>\n";
  echo "</body></html>\n\n";
  exit ();
}

function navigate_buttons ($rowStart, $rowLast, $dTABLE, $rowTotal, $buttonLink, $ID, $file) {

  // add a sort key?
  $sortKey = "";
  // try sort forward
  $sortVal = get_htmlkey_value ('sort');
  if ($sortVal != "") {
    $sortKey = "&sort=" . $sortVal;
  }
  // try sort reverse
  if ($sortKey == "") {
    $sortVal = get_htmlkey_value ('rsort');
    if ($sortVal != "") {
      $sortKey = "&rsort=" . $sortVal;
    }
  }

  if ($rowStart > 0) {
    $value = 0;
    $link = "$file" . "?" . $ID['link'] . "&from=$value";
    if ($buttonLink != "") {
      $link = $link . "&$buttonLink";
    }
    $link = $link . $sortKey;
    echo "<a width=10 class=\"button\" href=\"$link\"><img src=\"left.png\"><img src=\"left.png\"></a>\n";
  } else {
    echo "<img src=\"left_sel.png\"><img src=\"left_sel.png\">\n";
  }
  if ($rowStart >= $dTABLE) {
    $value = $rowStart - $dTABLE;
    $link = "$file" . "?" . $ID['link'] . "&from=$value";
    if ($buttonLink != "") {
      $link = $link . "&$buttonLink";
    }
    $link = $link . $sortKey;
    echo "<a class=\"button\" href=\"$link\"><img src=\"left.png\"></a>\n";
  } else {
    echo "<img src=\"left_sel.png\">\n";
  }

  if ($rowLast < $rowTotal) {
    $value = $rowStart + $dTABLE;
    $link = "$file" . "?" . $ID['link'] . "&from=$value";
    if ($buttonLink != "") {
      $link = $link . "&$buttonLink";
    }
    $link = $link . $sortKey;
    echo "<a class=\"button\" href=\"$link\"><img src=\"right.png\"></a>\n";
  } else {
    echo "<img src=\"right_sel.png\">\n";
  }

  if ($rowLast < $rowTotal) {
    $value = $rowTotal - $dTABLE;
    $link = "$file" . "?" . $ID['link'] . "&from=$value";
    if ($buttonLink != "") {
      $link = $link . "&$buttonLink";
    }
    $link = $link . $sortKey;
    echo "<a class=\"button\" href=\"$link\"><img src=\"right.png\"><img src=\"right.png\"></a>\n";
  } else {
    echo "<img src=\"right_sel.png\"><img src=\"right_sel.png\">\n";
  }
}

function check_restrict ($key, $where, $mode, $scale) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  if ($mode == 'min') {
    $htmlkey = $htmlkey . "_min";
  }
  if ($mode == 'max') {
    $htmlkey = $htmlkey . "_max";
  }

  if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    $value = array_key_exists($htmlkey, $_GET) ? $_GET[$htmlkey] : ""; 
  } else {
    $value = array_key_exists($htmlkey, $_POST) ? $_POST[$htmlkey] : ""; 
  }
  if ($value == "") { return $where; }

  global $restricted;
  $restricted = 1;

  if ($where) { 
    $where = $where . " AND"; 
  } else {
    $where = "WHERE";
  }

  if ($scale != 1.0) {
    $fvalue = $value * $scale;
  } else {
    $fvalue = $value;
  }

  if ($mode == 'string') {
    // can we pass the '%' through the html?
    $where = $where . " $key like '$value'";
  } 
  if ($mode == 'value') {
    // can we pass the '%' through the html?
    $where = $where . " $key = '$value'";
  } 
  if ($mode == 'min') {
    // can we pass the '%' through the html?
    $where = $where . " $key >= '$fvalue'";
  } 
  if ($mode == 'max') {
    // can we pass the '%' through the html?
    $where = $where . " $key <= '$fvalue'";
  } 

  return $where;
}

function check_ordering ($groups, $where) {

  if ($groups != "") {
    $where = $where . " GROUP BY $groups";
  }

  $value = get_htmlkey_value ('sort');
  if ($value != "") {
    $where = $where . " ORDER BY $value";
    return $where;
  }
  $value = get_htmlkey_value ('rsort');
  if ($value != "") {
    $where = $where . " ORDER BY $value DESC";
    return $where;
  }
  return $where;
}

function get_htmlkey_value ($htmlkey) {
  if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    $value = array_key_exists($htmlkey, $_GET) ? $_GET[$htmlkey] : ""; 
  } else {
    $value = array_key_exists($htmlkey, $_POST) ? $_POST[$htmlkey] : ""; 
  }
  return $value;
}

// if we have a restriction for a string-valued field, supply it to outgoing links
function button_restrict_string ($key, $line) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  $value = get_htmlkey_value ($htmlkey);

  # a search restriction may include an SQL wild-card.  we have to mangle these so that the http 
  # does not get converted to a special character
  $value = preg_replace ('|%|', '%25', $value);
  if ($value != "") {
    if ($line) {
      $line = $line . "&$key=$value";
    } else {
      $line = "$key=$value";
    }
  }
  return $line;
}

// for numerical fields, test for both 'min' and plain values
function button_restrict_min ($key, $line) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  $htmlkey = $htmlkey . '_min';
  $value = get_htmlkey_value ($htmlkey);
  if ($value != "") {
    if ($line) {
      $line = $line . "&$htmlkey=$value";
    } else {
      $line = "$htmlkey=$value";
    }
  }
  return $line;
}

// for numerical fields, test for both 'min' and 'max' values
function button_restrict_max ($key, $line) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  $htmlkey = $htmlkey . '_max';
  $value = get_htmlkey_value ($htmlkey);
  if ($value != "") {
    if ($line) {
      $line = $line . "&$htmlkey=$value";
    } else {
      $line = "$htmlkey=$value";
    }
  }
  return $line;
}

// 
function button_restrict_checkbox ($key, $line) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  $value = get_htmlkey_value ($htmlkey);
  if ($value != "") {
    if ($line) {
      $line = $line . "&$htmlkey=$value";
    } else {
      $line = "$htmlkey=$value";
    }
  }
  return $line;
}

// 
function button_restrict_radio ($key, $line) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  $value = get_htmlkey_value ($htmlkey);
  if ($value != "") {
    if ($line) {
      $line = $line . "&$htmlkey=$value";
    } else {
      $line = "$htmlkey=$value";
    }
  }
  return $line;
}

function write_header_cell ($class, $name) {
  echo "<th class=\"$class\">$name</th>\n";
}

// write a table cell with the up and down sort arrows
function write_sort_cell ($class, $value, $buttonLink, $ID, $file) {
  
  echo "<td>";

  // base link
  $baselink = "$file" . "?" . $ID['link'];
  if ($buttonLink != "") {
    $baselink = $baselink . "&$buttonLink";
  }

  if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    $up   = array_key_exists('rsort', $_GET) ? $_GET['rsort'] : "";
    $down = array_key_exists('sort',  $_GET) ? $_GET['sort'] : "";
    $from = array_key_exists('from',  $_GET) ? $_GET['from'] : "";
  } else {
    $up   = array_key_exists('rsort', $_POST) ? $_POST['rsort'] : "";
    $down = array_key_exists('sort',  $_POST) ? $_POST['sort'] : "";
    $from = array_key_exists('from',  $_POST) ? $_POST['from'] : "";
  }

  // down button link
  $link = "$baselink" . "&sort=$value";
  if ($from != "") {
    $link = $link . "&from=$from";
  }
  if ($down == $value) {
    echo "<a href=\"$link\"><img src=\"down_sel.png\"></a>";
  } else {
    echo "<a href=\"$link\"><img src=\"down.png\"></a>";
  }

  // up button link
  $link = "$baselink" . "&rsort=$value";
  if ($from != "") {
    $link = $link . "&from=$from";
  }
  if ($up == $value) {
    echo "<a href=\"$link\"><img src=\"up_sel.png\"></a>";
  } else {
    echo "<a href=\"$link\"><img src=\"up.png\"></a>";
  }

  echo "</td>\n";
}

// there are two query rows: for strings, only the first is set; for numbers, the first = min, the second = max
// mode == string, min, max
function write_query_row ($key, $width, $mode) {
  $htmlkey = preg_replace ('|\.|', '_', $key);

  // optional bits by mode
  if ($mode == 'min') {
    $htmlkey = $htmlkey . "_min";
  }
  if ($mode == 'max') {
    $htmlkey = $htmlkey . "_max";
  }
  $value = get_htmlkey_value ($htmlkey);

  // full table element includes optionally the <= or >= words
  echo "<td class=\"list\"> <input type=\"text\" name=\"$htmlkey\" size=\"$width\"";
  if ($value != "") { 
    echo "value=\"$value\">";
  } else {
    echo ">";
  }
  echo "</td>\n";
}

// checkbox
function write_query_checkbox ($key, $comment) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  $value = get_htmlkey_value ($htmlkey);

  echo "<td> <input type=\"checkbox\" name=\"$htmlkey\"";
  if ($value == "on") { 
    echo " checked>";
  } else {
    echo ">";
  }
  echo "$comment ($htmlkey/$value)</td>\n";
}

// checkbox
function write_query_radio ($value, $key) {
  $htmlkey = preg_replace ('| |', '_', $key);
  $htmlvalue = preg_replace ('|\.|', '_', $value);

  $value = get_htmlkey_value ($htmlkey);
  if ($htmlvalue == get_value_from_key($htmlkey, TRUE)) {
    $checked = "checked";
  } else {
    $checked = "";
  }
  echo "<td> <input type=\"radio\" name=\"$htmlkey\" value=\"$htmlvalue\" $checked/>";
  echo "$key ($htmlkey/$htmlvalue)</td>\n";
}

function write_table_cell ($class, $format, $link, $value) {

  if ($format == '%T') {
    $format = '%s';
  }
  if ($format == '%C') {
    $format = '%10.6f';
  }
  if ($format == '%t') {
    $format = '%s';
    if ($value == 0) { 
      $value = 'N'; 
    } else {
      $value = 'Y';
    }
  }

  $myValue = sprintf ($format, $value);
  if ($myValue == "") { $myValue = "&nbsp;"; }

  if ($link) {
    echo "<td class=\"$class\"><a href=\"$link\"> $myValue </a></td>\n";
  } else {
    echo "<td class=\"$class\"> $myValue </td>\n";
  }
}

// expect image supplied with key=name
// this function should define matching hidden inputs in the form
function insert_image ($rule, $size) {

  if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    $basename = array_key_exists('basename', $_GET) ? $_GET['basename'] : "";
    $class_id = array_key_exists('class',    $_GET) ? $_GET['class']    : "";
    $camera   = array_key_exists('camera',   $_GET) ? $_GET['camera']   : "";
  } else {
    $basename = array_key_exists('basename', $_POST) ? $_POST['basename'] : "";
    $class_id = array_key_exists('class',    $_POST) ? $_POST['class']    : "";
    $camera   = array_key_exists('camera',   $_POST) ? $_POST['camera']   : "";
  }

  if (! $class_id) { $class_id = "NONE"; }

  if ($basename && $camera && $rule) {
    echo "<a href=\"showimage.php?name=$basename&rule=$rule&camera=$camera&class_id=$class_id\">\n";
    echo "<img $size src=\"getimage.php?name=$basename&rule=$rule&camera=$camera&class_id=$class_id\">\n";
    echo "</a>\n";
  }
}

// expect image supplied with key=name
// this function should define matching hidden inputs in the form
function insert_log ($filerule) {

  if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
    $basename = array_key_exists('basename', $_GET) ? $_GET['basename'] : "";
    $class_id = array_key_exists('class',    $_GET) ? $_GET['class']    : "";
    $camera   = array_key_exists('camera',   $_GET) ? $_GET['camera']   : "";
    $state    = array_key_exists('state',    $_GET) ? $_GET['state']    : "";
  } else {
    $basename = array_key_exists('basename', $_POST) ? $_POST['basename'] : "";
    $class_id = array_key_exists('class',    $_POST) ? $_POST['class']    : "";
    $camera   = array_key_exists('camera',   $_POST) ? $_POST['camera']   : "";
    $state    = array_key_exists('state',    $_POST) ? $_POST['state']    : "";
  }

  if ($state == 'update') {
    $filerule = "$filerule.UPDATE";
  }

  // echo "<b>insert log</b><br>\n";
  // echo "<b>basename: $basename</b><br>\n";
  // echo "<b>class_id: $class_id</b><br>\n";
  // echo "<b>camera:   $camera</b><br>\n";
  // echo "<b>filerule:   $filerule</b><br>\n";

  if (! $class_id) { $class_id = "NONE"; }

  //SCH: I set a default value for the 'camera' which is based on the
  //'proj' parameter.
  //It's necessary for staticsky logs and it would require to join tables
  //back to the warpRun table
  if (! $camera) { 
    $camera = strtoupper($_GET['proj']); 
  }

  if ($basename && $camera && $filerule) {
    // do I need to do this to the output result as well?
    $basename = escapeshellarg($basename);
    $basename = str_replace ('..','',$basename);

    // these are defined by site.php
    global $PERLLIB;
    global $NEB_SERVER;
    global $BINDIR;
    global $SITE;
    putenv("PERL5LIB=$PERLLIB:");

    $PATH = getenv("PATH");
    putenv("PATH=$BINDIR:$PATH");
    putenv("NEB_SERVER=$NEB_SERVER");

    exec ("ipp_filename.pl --site=$SITE --basename $basename --filerule $filerule --camera $camera --class_id $class_id", $output, $status);

    if (0) {
      echo "PERLLIB: $PERLLIB<br>";
      echo "NEB_SERVER: $NEB_SERVER<br>";
      echo "basename: $basename<br>";
      for ($i = 0; $i < count($output); $i++) {
	echo "output $i: $output[$i]<br>";
      }
      echo "path:     $PATH<br>";
      echo "output:   $output[0]<br>";
      echo "status:   $status<br>";
      echo "filename: $filename<br>";
      // exit ();
    }

    $filename = $output[0];
    if ($status) {
      if ($status == 1) {	
        echo "<b>log file ($filerule, $basename) not found<br></b>\n";
        echo "ipp_filename.pl --site=$SITE --basename $basename --filerule $filerule --camera $camera --class_id $class_id<br>";
        return;
      } else {
        echo "<b>ipp_filename.pl failure, check configuration<br></b>\n";
        echo "ipp_filename.pl --site=$SITE --basename $basename --filerule $filerule --camera $camera --class_id $class_id<br>";
        echo "NEB_SERVER: $NEB_SERVER<br>";
        return;	
      }
    }
    echo "<b>log filename: $filename</b><br>\n";

    echo "<pre>\n";
    $file = fopen ($filename, "r");
    if ($file && !$debug) {
      fpassthru ($file);
    }
    echo "</pre>\n";
  }
}


// expect image supplied with key=name
// this function should define matching hidden inputs in the form
function insert_backref ($page, $key, $link) {

  $name = get_htmlkey_value ($key);

  if ($name) {
    echo "back to <a href=\"$page?$link&$key=$name\"> $name </a><br>\n";
  }
}

// $myPage = $_SERVER[SCRIPT_NAME] . "?pass=$pass";

//////////////////////////////////////////////////////////////////////////
// Return the value associated to the key (GET or POST method)
// If convertKeyToHtmlkey is true, the key is converted to a 
// so-called HTML, i.e. the key where '.' are replaced by '_'
// (e.g. the conversion of 'f.o.o.b_a_r' is 'f_o_o_b_a_r'.
//
function get_value_from_key ($key, $convertKeyToHtmlkey) {
  if ($convertKeyToHtmlkey) {
    $htmlkey = preg_replace ('|\.|', '_', $key);
  } else {
    $htmlkey = $key;
  }
  $value = get_htmlkey_value ($key);
  return $value;
}

//////////////////////////////////////////////////////////////////////////
// Extra filtering parameters array
$filteringParameters = array();

//
// Delete temporary files if they are older than $expire_time minutes
//
function delete_old_tmp_files() {
  global $DELETION_USER;    // defined in raw/site.php.in
  global $DELETION_DELAY;   // defined in raw/site.php.in
  exec("find /tmp -user $DELETION_USER -amin +$DELETION_DELAY", $output, $status);
  foreach ($output as $key => $value) {
    exec("rm -f $value");
    $count++;
  }
}

?>
