<?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 (DB::iserror($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) {

  require_once('DB.php');

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

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

// 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 (DB::iserror($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 (DB::iserror($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 (DB::iserror($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 (DB::iserror($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) {

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

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

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

function check_restrict ($key, $where) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
  } else {
    $value = $_POST[$htmlkey];
  }
  if ($value != "") {
    if ($where) {
      $where = $where . " AND $key = '$value'";
    } else {
      $where = "WHERE $key = '$value'";
    }
  }
  return $where;
}

function check_ordering ($where) {

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

function button_restrict ($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;
}

function write_table_header ($class, $name, $value, $buttonLink, $ID, $file) {

  $link = "$file" . "?" . $ID['link'] . "&sort=$value";
  if ($buttonLink != "") {
    $link = $link . "&$buttonLink";
  }
  echo "<th class=\"$class\"><a href=\"$link\"> $name </a></th>\n";
}

function write_query_row ($key, $width) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
  } else {
    $value = $_POST[$htmlkey];
  }
  if ($value != "") { 
    echo "<td class=\"list\"> <input type=\"text\" name=\"$key\" size=\"$width\" value=\"$value\"> </td>\n";
  } else {
    echo "<td class=\"list\"> <input type=\"text\" name=\"$key\" size=\"$width\"> </td>\n";
  }
}

function write_table_cell ($class, $link, $value) {
  $myValue = $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']; 
  }

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

?>
