<?php

$dTABLE = 10;

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 () { 
  echo '<form action="Login.php" method="POST">', "\n";
  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']);
    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)) {
      echo "<tr class=select><td class=select> $row[0] </td></tr>\n";
    }
    echo "</table>\n";

    menu_end ();
}

function dbconnect ($database) {

  // connect to the database
  // these should be set on installation
  require_once('DB.php');
  $password = "ipp";
  $username = "ipp";
  $hostname = "alala";
  $db = DB::connect("mysql://$username:$password@$hostname/$database");
  if (DB::iserror($db)) {
    echo "<b>error accessing database</b><br>\n";
    echo "<b>tried mysql://$username:$password@$hostname/$database</b><br>\n";
    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];

  $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)) {
    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');

  // make this a DB lookup
  $pass = $ID['pass'];
  $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 = (($username == "eugene") && ($password == "test"));
  $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 check_restrict ($key, $where) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  if ($_SERVER[REQUEST_METHOD] == 'GET') { 
    $value = $_GET[$htmlkey]; 
    // echo "using GET: $value<br>\n";
  } else {
    $value = $_POST[$htmlkey];
    // echo "using POST: $value<br>\n";
  }
  // echo "value: $value<br>\n";
  if ($value != "") {
    if ($where) {
      $where = $where . " AND $key = '$value'";
      // echo "where 1: $where<br>\n";
    } else {
      $where = "$key = '$value'";
      // echo "where 2: $where<br>\n";
    }
  }
  return $where;
}

function write_query_row ($key, $width) {
  $htmlkey = preg_replace ('|\.|', '_', $key);
  $value = $_POST[$htmlkey];
  if (($_SERVER[REQUEST_METHOD] == 'POST') && $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";
  }
}

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

?>
