<?php

$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="text" 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";

  $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 ($qry->fetchInto($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 dbconnect ($database) {

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

  $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 ($DBI == "DB") {
    $db = DB::connect("mysql://$DBUSER:$DBPASS@$DBHOST/$database");
  }
  if ($DBI == "MDB2") {
    $db = MDB2::connect("mysql://$DBUSER:$DBPASS@$DBHOST/$database");
  }

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

function dberror ($db) {
  global $DBI;

  if ($DBI == "MDB2") {
    $dberr = MDB2::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 = $qry->fetchInto($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 ($qry->fetchInto($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;

  // 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'] = $_GET[pass];
    $ID['proj'] = $_GET[proj];
    $ID['menu'] = $_GET[menu];
    $ID['from'] = $_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'] = $_POST[pass];
    $ID['proj'] = $_POST[proj];
    $ID['menu'] = $_POST[menu];
    $ID['from'] = $_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 = $qry->fetchInto($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 menu ($source, $title, $sheet, $append, $project) {

  echo "<html><head><title> $title </title></head>\n\n";
  echo "<link rel=\"STYLESHEET\" HREF=\"$sheet\">\n";
  echo "<body>\n";

  $root = "/ippMonitor";

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

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

  echo "<table class=page cellspacing=10px><tr><td valign=top>\n";
  echo "<table class=menu cellspacing=0px>\n";

  while ($line = fgetcsv ($file, 1024, "|")) {
    if (count($line) != 5) continue;
    if (ereg ('^[:blank:]*#', $line[0])) 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);
  echo '</table></td><td class="body" valign=top>', "\n\n";
}

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
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $sortVal = $_GET['sort']; 
  } else {
    $sortVal = $_POST['sort'];
  }
  if ($sortVal != "") {
    $sortKey = "&sort=" . $sortVal;
  }
  // try sort reverse
  if ($sortKey == "") {
    if ($_SERVER[REQUEST_METHOD] == 'GET') { 
      $sortKey = $_GET['rsort']; 
    } else {
      $sortKey = $_POST['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) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  if ($mode == 'min') {
    $htmlkey = $htmlkey . "_min";
  }
  if ($mode == 'max') {
    $htmlkey = $htmlkey . "_max";
  }

  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
  } else {
    $value = $_POST[$htmlkey];
  }
  if ($value == "") { return $where; }
  if ($where) { 
    $where = $where . " AND"; 
  } else {
    $where = "WHERE";
  }

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

  return $where;
}

function check_ordering ($groups, $where) {

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

  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET['sort']; 
  } else {
    $value = $_POST['sort'];
  }
  if ($value != "") {
    $where = $where . " ORDER BY $value";
    return $where;
  }
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET['rsort']; 
  } else {
    $value = $_POST['rsort'];
  }
  if ($value != "") {
    $where = $where . " ORDER BY $value DESC";
    return $where;
  }
  return $where;
}

// 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);
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
  } else {
    $value = $_POST[$htmlkey];
  }
  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';
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
  } else {
    $value = $_POST[$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';
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
  } else {
    $value = $_POST[$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   = $_GET['rsort']; 
    $down = $_GET['sort']; 
    $from = $_GET['from']; 
  } else {
    $up   = $_POST['rsort']; 
    $down = $_POST['sort']; 
    $from = $_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";
  }
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
  } else {
    $value = $_POST[$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\">";
  } 
  echo "</td>\n";
}

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

  if ($format == '%T') {
    $format = '%s';
  }
  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) {

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

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

  if ($basename && $camera && $rule) {
    echo "<img src=\"getimage.php?name=$basename&rule=$rule&camera=$camera&class_id=$class_id\">\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 = $_GET['basename']; 
    $class_id = $_GET['class']; 
    $camera   = $_GET['camera']; 
  } else {
    $basename = $_POST['basename']; 
    $class_id = $_POST['class']; 
    $camera   = $_POST['camera']; 
  }

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

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

  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 $BINDIR;
    global $SITE;

    putenv("PERL5LIB=$PERLLIB:");
    $PATH = getenv("PATH");
    putenv("PATH=$BINDIR:$PATH");

    // be careful of the definition of PATH in SITE: cannot contain HOME
    echo "<br>ipp_filename.pl --site=$SITE --basename $basename --filerule $filerule --camera $camera --class_id $class_id<br>\n";
    exec ("ipp_filename.pl --site=$SITE --basename $basename --filerule $filerule --camera $camera --class_id $class_id", $output, $status);

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

    $filename = $output[0];
    if ($status) {
      echo "log file ($filerule, $basename) not found<br>\n";
      return;
    }

    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) {

  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $name = $_GET[$key]; 
  } else {
    $name = $_POST[$key]; 
  }

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

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

?>
