<?php
/*==================================================

index.php

RefDB Web Interface

This file provides a web-based interface for RefDB. It supports all basic operations: 
e.g query, edit/update and delete.

The same file (with includes, stylesheets and related files) is used for all operations 
and pages.

This version was written more or less from scratch by by Daniel Paul O'Donnell and 
Dominik Reusser. Some sections were adapted from the previous RefDB web interface.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

===================================================*/

/*-----------------------------------------------------------------------

Part 1: Some initialisation

This section prepares initial values and variables, and calls essential includes, functions, 
and objects

-------------------------------------------------------------------------*/

// First start session (see http://ca.php.net/session_start). This allows variables to be kept alive as long as the browser is engaged. 
session_start();

// Set the error reporting (http://ca.php.net/error-reporting and http://ca.php.net/manual/en/ref.errorfunc.php). E_ALL for debugging, E_ERROR for publication
error_reporting(E_ALL); // debugging error level
//error_reporting(E_ERROR); // publication error level

// Load refdb interface
require_once "includes/refdblib.inc.php";

// Load functions
require_once "includes/functions.inc.php";

//Set session variables
// Note: it is not clear this is necessary $refdbc="refdbc", etc., maybe enough 
// This is also where path names are set during install.
    
$_SESSION["refdbc"]="/usr/local/bin/refdbc";
$_SESSION["refdba"]="/usr/local/bin/refdba";
$_SESSION["path"]="/usr/local/bin";
$refdbc=$_SESSION["refdbc"];
$refdba=$_SESSION["refdba"];

/*=================================================

PART 2: Check for cookies from previous session

The login screen allows users to "remember me on this computer". If the "remember
me button is checked, user name, database, and password are stored in cookies.

This section checks whether the cookies exist and are complete. If they are it uses 
their values to establish the session; otherwise it directs the user to the login screen.

This section could be cleaned up:

1) There is probably a better (more secure) way of handling Login information
2) The database cookie is odd: it is set to "remember me" whatever the user does

=================================================*/

/* Username and password Cookie (refdb) */
// Check for availability and completeness of the existing refdb session cookie
// A complete cookie has values for both $name and $passwd.
if (isset($_COOKIE['refdb'])) {
  // If either is missing or set to null, kill the session.
  if (!isset($_COOKIE['refdb']['name'])||!isset($_COOKIE['refdb']['passwd'])) {
    // Delete any remaining parts of the cookie array by setting the components to more than one year in the past.
    setcookie('refdb[name]', "", time() - 3600 * 24 * 400);
    setcookie('refdb[passwd]', "", time() - 3600 * 24 * 400);
    setcookie('database', "", time() - 3600 * 24 * 400);

    // Now destroy the PHP $_SESSION variables: see the comments in http://ca.php.net/manual/en/function.session-unset.php
    /* Note: Removed session_unset following advice at http://ca.php.net/manual/en/function.session-destroy.php: 
                "Note:  Only use session_unset() for older deprecated code that does not use $_SESSION.") */
    $_SESSION=array();
    session_destroy();
            
    // Now start the session again, because we'll need it to be started before we log on
    session_start();
    // Set a warning for use on the login page indicating what we have done
    $warning="There was a problem closing your last session.<br/>Please re-enter your username and password.";
  }
  //If the refdb cookie has values for both $username and $passwd, use the cookie values to set the session variables
  else {
    $_SESSION['passwd']=$_COOKIE['refdb']['passwd'];
    $_SESSION['name']=$_COOKIE['refdb']['name'];
  }
}
// If the refdb cookie is missing or incomplete, there may be input from the login screen, or we may need 
// to go to the login screen for the first time
else {
  // Case 1: We have come here from the login form
  // Check if there is input from the login form use that we can use
  if (isset($_POST['name'])&&isset($_POST['passwd'])) {
    // If both name and passwd are set, check whether they both have values other than ""
    if (($_POST['name']!="")&&($_POST['passwd']!="")) {

      //this is an attempt at a validity checker. It doesn't work though: even if you pass, you end up at the login screen
      /*        $username=escapeshellarg($_POST['name']);
        $passwd=escapeshellarg($_POST['passwd']);
                $testcmd="$refdbc -u $username -w $passwd -C listdb -c cat";
                exec($testcmd,$lines,$exit_state);
                switch ($exit_state) {
                            case 0:
                                $login="true";
                            case 1:
                                $login="false";
                        }
                if ($login=="true") { */
      $_SESSION["passwd"]=$_POST['passwd'];
      $_SESSION["name"]=$_POST['name'];
      // Establish new refdb cookie 
      // Check if the remember me box was checked
      if (isset($_POST['rememberMe'])) {
	// if yes, set $duration to 1 year for the cookie
	$duration=time() + 3600 * 24 * 365;
      } 
      else {
	// otherwise set the duration for this session only (i.e. null)
	$duration=0;
      }
      // Now set new cookies using form data we have just converted to session data
      setcookie ("refdb[name]", $_SESSION['name'], $duration);
      setcookie ("refdb[passwd]", $_SESSION['passwd'], $duration);
    }
    // if one or both of the $username and $passwd variables are not set, set a warning for use on the login form
    else {
      $warning="Please supply a valid username and password";
    }
  }
  // Case 2: The user has not been here before as far as we can tell and is going to be sent to the login screen
  // Set the warning for use on the login form
  else {
    $warning="Please supply a username and password";
  }
}

// This checks whether the database has been selected on the form
// If it has, it sets a new cookie.
if (isset($_POST['selectedDatabase'])){
  $_SESSION['database']=$_POST['selectedDatabase'];
  //remember database for one year anyway . It is not checked if name and password do not exist
  setcookie ("database", $_SESSION['database'],time() + 3600 * 24 * 365);
}
        
/* Database Cookie (database) */ 
//Does a database cookie already exist? If so, use its values
if (isset($_COOKIE['database'])) {
  $_SESSION['database']=stripQuotes($_COOKIE['database']);
}
                                               
/*=================================================

PART 3 Decide where to go

Now we check whether after all this, we have a session name and passwd. If we do not, we go
to the login form. If we do, we check to see whether we have a $thisPage variable.
    
The two usual choices for a first hit on the URL are Login (if nothing is set) or Search (if
the session variables are set but not the $thisPage).
After the first search or login, the $thisPage variable becomes more common. 

=================================================*/

// First we check whether session name or password variables have been set above.
if (!isset($_SESSION['name'])||!isset($_SESSION['passwd'])) {
  // If either has not been set, then we set this page to Login, since we will need to login
  $thisPage="Login";
}
// If both session variables have been set, then we are logged in. 
else {
  //First let's escape the $passwd and $username variables so the can be passed to the shell from here on
  /* SECURITY note: $_SESSION['name'] and $_SESSION['passwd'] should not be used hereafter. */
  $username=escapeshellarg($_SESSION['name']);
  $passwd=escapeshellarg($_SESSION['passwd']);
        
  $my_refdba = new RefDB($username, $passwd, "", "", $refdba);
  $my_refdbc = new RefDB($username, $passwd, "", "", $refdbc);

  $operation="";
  $ID="";
  // If $sendQuery is set we are being sent an operation. Check if it is set.
  if(isset($_POST['sendQuery'])) {
    $sendQuery=$_POST['sendQuery'];
    // Three types of $sendQuery (edit, delete, and display) require extraction of an ID number from the variable value; check if that's what we are looking at.
    if (substr($sendQuery,0,4)=="edit") {
      $operation="edit";
      $ID=substr($sendQuery,5);
    }
    elseif (substr($sendQuery,0,6)=="delete") {
      $operation="delete";
      $ID=substr($sendQuery,7);
    }
    elseif (substr($sendQuery,0,7)=="display") {
      $operation="display";
      $citekey=substr($sendQuery,8);
    }
    //Check if $sendQuery is a legal value
    elseif ($sendQuery=="Login"||
            $sendQuery=="Confirm deletion"||
            $sendQuery=="Cancel deletion"||
            $sendQuery=="Add reference"||
            $sendQuery=="Send File"||
            $sendQuery=="Search") {
      $operation=$sendQuery;
    }
    // if $sendQuery is none of the above, then it is illegal and needs to be cleaned out 
    else {
      unset($sendQuery);
      $operation="Illegal operation";
    }
  }




  // Now let's check whether thisPage has been set: if it has, we are responding to a user request; if it is not,
  // we are supposed to go to the default (Search) page.
  if(isset($_REQUEST['thisPage'])) {
    $thisPage=$_REQUEST['thisPage'];
    // SECURITY: compare $thisPage to a list of legal values; if it doesn't match, change it to the default (Search)
    if ($thisPage=="Search"||
	$thisPage=="Search results"||
	$thisPage=="Index results"||
	$thisPage=="Confirm"||                
	$thisPage=="Logout"||
	$thisPage=="Login"||
	$thisPage=="Search indices"||
	$thisPage=="Add-Edit-Delete"||
	$thisPage=="Upload"||
	$thisPage=="External databases"||
	$thisPage=="Preferences"||
	$thisPage=="Help") {
      $thisPage=$thisPage;
    }
    else {
      $thisPage="Search";
    }
  }
  else {
    $thisPage="Search";
  }
}

// Now we need to act on the $thisPage variable:
// If $thisPage is "logout"--i.e. the user has requested to logout, we need to kill the cookies and everything before anything
// is sent to the browser

if ($thisPage=="Logout") {
  // First delete the cookie array by setting the components to more than one year in the past.
  setcookie('refdb[name]', "", time() - 3600 * 24 * 400);
  setcookie('refdb[passwd]', "", time() - 3600 * 24 * 400);
  setcookie('database', "", time() - 3600 * 24 * 400);
  // Then destroy the PHP $_SESSION variables: see the comments in http://ca.php.net/manual/en/function.session-unset.php
  // (note Removed session_unset following advice at http://ca.php.net/manual/en/function.session-destroy.php: 
  // "Note:  Only use session_unset() for older deprecated code that does not use $_SESSION.")
  $_SESSION=array();
  session_destroy();        
}

// No  matter what happens next, we are going to need a doctype and head
// include_once('php/logo.inc.php');
echo "<!DOCTYPE html SYSTEM \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
echo "    <head>\n";
echo "        <title>Refdb: " . $thisPage . "</title>\n";
echo "        <link href=\"css/main.css\" type=\"text/css\" rel=\"stylesheet\"/>\n";
echo "        <link href=\"css/navigationlist.css\" type=\"text/css\" rel=\"stylesheet\"/>\n";        
echo "        <link href=\"css/refdb-frequency.css\" type=\"text/css\" rel=\"stylesheet\" title=\"RefDB frequency\"/>\n";
echo "        <link href=\"css/refdb.css\" type=\"text/css\" rel=\"alternate stylesheet\" title=\"RefDB\"/>\n";
echo "        <meta http-equiv=\"content-type\" content=\"text-html; charset=utf-8\"/>";
echo "    </head>\n";
echo "    <body>\n";    
echo "        <div id=\"header\">\n";
echo "            <div id=\"status\">\n";
//check if there is a session name set; if there is, get the user name from it for the status box
//  echo "<p>DEBUG: session db went to:".$_SESSION['database'].".username went to:".$username."thisPage went to:".$thisPage."</p>";
if (isset($username) && !($thisPage=="Logout")) { 
  echo "                    <form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">\n";
  echo "                        <p>You are logged in as <strong>" .htmlentities($username)."</strong>.<br/>\n";
  echo "                            Database:"; 
  echo "                                <select name=\"selectedDatabase\" onchange=\"this.form.submit();\">\n";
  $_SESSION['databases']=$my_refdbc->listdb("");

  // I cannot infer from the code nor find out by "echo" debugging where those extra single quotes come from. Running just about anything through stripQuotes solves the "invalid database" error message though (MH)
  if(!isset($_SESSION['database'])) {
    $_SESSION['database']=stripQuotes($_SESSION['databases'][0]); 
  }
  $selected = FALSE;
  foreach($_SESSION['databases'] as $aDatabase) {
    echo "<option value=\"".htmlentities(stripQuotes($aDatabase))."\"";
    //Mark the selected database as selected in the list
    if(stripQuotes($_SESSION['database']) == $aDatabase) {
      $selected=TRUE;
      $_SESSION['database'] = stripQuotes($aDatabase);
      echo " selected=\"selected\"";
    }
    echo">".htmlentities(stripQuotes($aDatabase))."</option>\n";
  }
  echo "                                </select><br/>\n";
  if(!$selected){
    echo" <p> Selected Database ".  $_SESSION['database'].  " is not valid, using ".  $_SESSION['databases'][0].  " instead";
    $_SESSION['database']=stripQuotes($_SESSION['databases'][0]); 

  }
  /*echo "                                <input type=\"submit\" name=\"sendQuery\" value=\"change\"/><br/>\n";*/
  echo "                                <a href=\"index.php?thisPage=Logout\">Switch User/Logout</a><br/>\n";
  echo "                    </form>\n";
  //SECURITY: Escaping database here, do not use from
  //SESSION herafter
  //We also made sure, the database really exists.
  $database=escapeshellarg($_SESSION['database']);
}
// If the session name has not been set, indicate that we are not logged in.
else {
  echo "                    <strong>Not logged in.</strong>\n";
}

// The getversion() function does not require a valid username/password combo so we'll just create a fake client. The 'real' clients may not yet be available if we're still on the login screen
$my_fakeclient = new RefDB("", "", "", "", $refdba);
$version = $my_fakeclient->getversion();
$version=$version[0];
$version=str_replace("markus@mhoenicka.de","",$version);
$version=str_replace("refdba ","",$version);
echo "        </div>\n";
echo "       <div id=\"logo\">\n";
echo "            <p>\n";
echo "                <a href=\"http://refdb.sourceforge.net\">\n";
echo "                    <img src=\"images/refdb.png\" alt=\"Refdb Logo.\" id=\"main_logo\"/>\n";
echo "                </a>\n";
//echo "                Reference manager and bibliography tool. Version $version";
echo "            </p>\n";
echo "        </div>\n";
echo "     </div>\n";

// If this page is neither Login nor Logout, add a navigation list
if ($thisPage!="Logout"&&$thisPage!="Login") {
  /* todo: is there a better place? */
  $my_refdbc->selectdb($database);
            
  // if $thisPage is not login, add navigation list as well
  //include_once('php/navigationlist.inc.php');
  echo "             <div id=\"navigationlist\">\n";
  echo "                <ul>\n";
  echo "                    <li";
  //check to see if $thisPage is matches any of the tabs and set the tab to current if it does
  /* NOTE: Not all $thisPage values match tabs: result screens, edit screens, and confirmation screens don't because a user cannot logically 
                        to these navigate these pages directly */ 
  if ($thisPage=="Search") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php\">Search records</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Search indices") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Search indices\">Search indices</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Add-Edit-Delete") {
    // The Add-Edit-Delete Page has three functions; you can only navigate to it if you want to add a new entry to
    // the database; if you are editing or deleting an entry you are sent there as a result of your action on another 
    // form. For this reason we need to check whether the $operation was set to either "edit" or "delete." If either is, then no
    // "currentpage" is set; if neither is, then we have got here by selecting the "Add an Entry" tab and currentpage should be set
    if ($operation != "edit"
	&& $operation != "delete"
	&& $operation != "display") {
      echo " id=\"currentpage\"";
    }
  }
  echo "><a href=\"index.php?thisPage=Add-Edit-Delete\">Add Reference</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Upload") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Upload\">Upload from local file</a></li>\n";
  echo "                    <li";
  if ($thisPage=="External databases") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=External databases\">External databases</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Preferences") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Preferences\">Preferences</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Help") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Help\">Help</a></li>\n";
  echo "                </ul>\n";
  echo "            </div>\n";
}
// No matter what $thisPage was, we are going to need body text. Add appropriate content based on the nature of the $thisPage variable
switch($thisPage) {
  /***************************************************************************************************************
                
                LOGOUT
                
  ****************************************************************************************************************/
 case('Logout'):
   // if $thisPage is Logout, we have already run the scripts to kill the session. This content informs the user of this fact.
   echo "<div id=\"login\">";
   echo "    <h1>Logout</h1>";
   echo "    <p>You have successfully logged out.<br/>You will need to log in again to access Refdb.</p>";
   echo "    <p><a href=\"index.php?thisPage=Login\">Return to Login Screen</a></p>";
   echo "</div>";
   break;
   /***************************************************************************************************************
                
                LOGIN
                
   ****************************************************************************************************************/
 case('Login'):
   // If $thisPage is Login, just add login form at this point
   echo "<div id=\"login\">\n";
   echo "    <h1>Login</h1>\n";
   echo "    <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Search\" method=\"post\" enctype=\"multipart/form-data\">\n";
   //Add any warnings collected above
   if (isset($warning)) {
     echo "<div class=\"warning\"><p><strong class=\"warning\">" . $warning . "</strong></p></div>\n";
     unset($warning);
   }
   echo "        <p>Username:<br/><input type=\"text\" name=\"name\" size=\"16\" maxlength=\"16\"/></p>\n";
   echo "        <p>Password:<br/><input type=\"password\" name=\"passwd\" size=\"16\" maxlength=\"16\"/></p>\n";
   echo "        <p>Remember me on this computer <input type=\"checkbox\" name=\"rememberMe\" value=\"rememberMe\"/></p>\n";
   echo "        <p><input id=\"loginbutton\" type=\"submit\" name=\"sendQuery\" value=\"Login\"/></p>\n";
   echo "    </form>\n";
   echo "</div>\n";
   break;
   /***************************************************************************************************************
                
                ADD-EDIT-DELETE
                
                Add-Edit-Delete all use the same form. But different content and operations are used depending on which  we want
                As a result we need to treat each operation separately in this section depending on the value of $operation:
                
                1) if $operation=="delete" go to delete
                2) if $operation=="edit" go to edit
                3) otherwise, go to add
                
   ****************************************************************************************************************/
 case('Add-Edit-Delete'):

   /*-------------------------------------------------------------------------------------------------------
                    Delete

                    If $operation=="delete" we come here.
                    This page pulls the entry that is to be deleted from refdb, presents it and the refdb delete command to the user and asks them
                    to confirm that this is what they want to do.
                    -------------------------------------------------------------------------------------------------------*/
   if ($operation=="delete") {

     // define variables
     $searchcmd=$_POST['searchcmd'];
     $searchdelTerms=":ID:=$ID";
     $searchdelcmd=$corecmd . $searchdelTerms;
     $delTerms=" -C deleteref $ID";
     $delcmd=$ID;
     $displaydelcmd = $displaycmd . $delTerms;
                
     // search refdb for entry that is to be deleted
     $lines = $my_refdbc->getref("risx", "ALL", "", "", "", "", "", "", $searchdelTerms);

     // print form
     echo "        <div id=\"content\">\n";
     echo "            <h2>Confirm deletion</h2>\n";
     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Confirm\" method=\"POST\" enctype=\"multipart/form-data\">\n";
     echo "                <h3 class=\"warning\"><strong>Warning! This operation cannot be undone</strong></h3>\n";
     echo "                <p>You have requested that Refdb delete the following reference. This operation cannot be undone.</p>\n";
     echo "                <div style=\"margin-left:1em;margin-right:1em;border:thin gray solid;font-size:70%;\">\n";
                        
     // print entry that is to be deleted; "false" refers to whether or not we need buttons to appear in this area (we don't)
     risx_xhtmlprocessor($lines,"false");
     echo "                <p>If you are sure you want this entry to be deleted permanently from your bibliography, select <strong>Delete!</strong>.";
     echo "                    Otherwise choose <strong>Cancel!</strong> or use your browser's back button.</p>\n";
     echo "                <p>(If you select <strong>Delete!</strong>, the following command will be sent to the server:" . $displaydelcmd . ").</p>\n";
     echo "                <p><button type=\"submit\" name=\"sendQuery\" value=\"Confirm deletion\">Delete!</button>&#x00A0;";
     echo "                    <button type=\"submit\" name=\"sendQuery\" value=\"Cancel deletion\">Cancel!</button></p>\n"; 
     echo "                <p class=\"hidden\"><input type=\"hidden\" name=\"delcmd\" value=\"" . $ID . "\"/>\n";
     echo "                    <input type=\"hidden\" name=\"searchcmd\" value=\"" . $searchcmd . "\"/>\n";
     echo "                 </p>\n";
     echo "            </form>\n";
     echo "        </div>\n";
     unset($operation);
   }

   /*--------------------------------------------------------------

          display: display a dataset in a particular format

--------------------------------------------------------------------*/

   else if ($operation == "display") {
     // search refdb for entry that is to be edited
     $format = $_REQUEST["format$citekey"];
     //     echo "<p>format went to $format, id went to $ID</p>";
     $lines = $my_refdbc->getref($format, "ALL", "", "", "", "", "", "", ":CK:=$citekey");
     $formats = array("ris" => "RIS",
		 "risx" => "risx",
		 "mods" => "MODS",
		 "bibtex" => "bibtex",
		 "db31" => "DocBook SGML",
		 "db31x" => "DocBook 4 XML",
		 "db50x" => "DocBook 5 XML",
		 "teix" => "TEI P4",
		 "tei5x" => "TEI P5");
     $my_format = $formats[$format];
     echo "        <div id=\"content\">\n";
     echo "            <h2>Display dataset <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$citekey\">$citekey</a> as $my_format</h2>\n";
     echo "            <pre>";
     foreach ($lines as $line) {
       // postprocess lines, e.g. substitute <>
       $fixed_line = str_replace(array("<", ">"), array("&lt;", "&gt;"), $line);
       echo "<p>$fixed_line</p>";
     }
     echo "            </pre>";
     echo "         </div>";
     unset($operation);
   }

   /*-------------------------------------------------------------------------------------------------------
                    Edit and Add

                    If $operation!="delete" we come here.

                    -------------------------------------------------------------------------------------------------------*/
   else {
     $fields = array("ID", "sec_primary","AU","TI","N2","KW","sec_secondary",
		     "A2", "JF", "JO", "J1", "J2", "T2", "sec_tertiary",
		     "A3", "T3", "sec_publication", "VL", "IS", "CY",
		     "PB", "SN", "AD", "PY", "Y2", "SP", "EP", "N1",
		     "sec_shelf", "RP", "AV", "UR", "L1", "U1", "U2", "U3",
		     "U4", "U5", "M1", "M2", "M3");
     $dateFields = array( "PY", "Y2");
     $datePartFields= array( "PYyear", "PYmonth", "PYday", "PYother", "Y2year", "Y2month", "Y2day", "Y2other");
     $allFields= array_merge($fields, $datePartFields);
     $auFields= array("AU", "A2", "A3", "KW");
     $reverseAuFields = array_flip($auFields);
     //Entries in the Form
     $formfields=array();
     //Checked Fields
     $myFields=array();
     //Checked Array Fields
     $arrayFields=array();

     /*--------------------------------------------------------------------------------------------------- 
                        Case 2a $operation=="edit"
                        -----------------------------------------------------------------------------------------------------*/
     if ($operation=="edit") {
       // search refdb for entry that is to be edited
       $lines = $my_refdbc->getref("ris", "ALL", "", "", "", "", "", "", ":ID:=$ID");
       // Parse RIS for form

       $myFields=parseRSS ($lines);
       //ToDO remove the line below once we are only using checked fields in myField for creation of the form --DR
       $formfields=$myFields;
       //extract($RIS,EXTR_OVERWRITE);
     } 
     /*--------------------------------------------------------------------------------------------------- 
                        Case 2b default (="Add")
                        
                        If $thisPage=="Add-Edit-Delete, but $operation has not been set, we end up here
                        -----------------------------------------------------------------------------------------------------*/
     else {
       $sendQuery="";
       if(isset($_POST['formTY'])){
	 $formfields['TY'] = $_POST['formTY'];
       } 
       else {
	 $formfields['TY'] = "";
       }
       //Sequence defines also execution sequence for import and Form
       //We can check the entire field for an entry (invalidText) and replace it by some alternative text altText
       $invalidText = array( "PYyear" => "YYYY" , 
			     "PYmonth" => "NoMonth" , 
			     "PYday" => "NoDay" , 
			     "PYother" => "Other:",
			     "Y2year" => "YYYY" , 
			     "Y2month" => "NoMonth" , 
			     "Y2day" => "NoDay" , 
			     "Y2other" => "Other:"
			     );
       $altText = array("PYyear" => "", 
			"PYmonth" =>"" , 
			"PYday" =>""  , 
			"PYother" =>"",
			"Y2year" => "", 
			"Y2month" =>"" , 
			"Y2day" =>""  , 
			"Y2other" =>""
			);
       //We can also search for any number regular expressions and replace those field         first  s    repl  second  s    repl
       $searchReplaceText = array("AU" => array(array(", ", ","), array( "; ", ";")),
				  "A2" => array(array(", ", ","), array( "; ", ";")),
				  "A3" => array(array(", ", ","), array( "; ", ";")),
				  "KW" => array(array(", ", ",")),
				  "TY" => array(array("short", ""))  //short entries just have different forms (treated in $referencetype)
				  );
       foreach($allFields as $field){
	 $name='form'.$field;
	 if (isset($_POST[$name])) {
	   //Initialize all fields to avoid undefined fields $myFields[$field] = "";
	   $formfields[$field] = $_POST[$name]; //Replaces formXX
	   //include checks here for security reasons. All fields should be checked in the end
	   if(isset($invalidText[$field]) && $formfields[$field]==$invalidText[$field] ){
	     $formfields[$field]=$altText[$field];
	   }
	   if(isset($searchReplaceText[$field])){
	     foreach($searchReplaceText[$field] as $searchRepl){
	       $formfields[$field] = str_replace($searchRepl[0], $searchRepl[1],  $formfields[$field]);
	     }
	   }
	   //later on we check wheter the ID comes from RefDB or from the Form itself based on the fact whether myFields['ID'] exists
	   //if($field!="ID"){
	   $myFields[$field] = $formfields[$field]; //$XX is replaced my myFields['XX'];
	   //}
	 }
       }
       //compile publication year from multiple fields
       foreach($dateFields as $dateField){
	 if(isset($formfields[$dateField.'year'])){
	   $myFields[$dateField]=$formfields[$dateField.'year'];
	   if(isset($formfields[$dateField.'month'])){
	     $myFields[$dateField].= "/" . $formfields[$dateField.'month'];
	     if(isset($formfields[$dateField.'day'])){
	       $myFields[$dateField].="/" . $formfields[$dateField.'day'];
	       if(isset($formfields[$dateField.'other'])){
		 $myFields[$dateField].="/" . $formfields[$dateField.'other'];// Publication Year: YYYY/MM/DD/Otherinfo
	       }
	     }
	   }
	 }
       }
       //clear up formAU~A3
       foreach($auFields as $field){
	 $separator=";";
	 if(isset($formfields[$field])){
	   //$$ arrayFields is a multidimensional array. Each key, e.g. "KW", has a value consisting of an array of all KW entries
	   $arrayFields[$field] = explode($separator,$formfields[$field]);
	 }
       }
     } // end if ($operation=="edit")

     if ($operation=="Add reference") {
       $entry=""; // initialise entry text
       //Debugging output:
       //echo "<div type=\"content\">\n";

       /*
       echo "<p> dumping fields: \n";
       var_dump($fields);
       echo "</p><p> dumping arrayFields: \n";
       var_dump($arrayFields);
       echo "</p><p> dumping myFields: \n";
       var_dump($myFields);
       echo "</p><p> dumping formfields: \n";
       var_dump($formfields);
       echo "</p>";
       */

       // before adding the data to the database, we need to reverse-translate
       // whatever htmlentities() did to the data
       $un_htmlentities = get_html_translation_table(HTML_ENTITIES);
       $rev_un_htmlentities = array_flip($un_htmlentities);

       //ToDo Change code such that the following is not necessary anymore
       //$myFields['ID']=$ID;
       $tempfield =  str_replace("short", "", $formfields['TY']);
       $myFields['TY']=$tempfield;

       // write out the tag lines. Avoid empty tags
       foreach(array_merge(array("TY"),$fields) as $field){
	 //For authors and keywords add each element

	 if(array_key_exists($field, $reverseAuFields)){
	   foreach($arrayFields[$field] as $author){
	     if (isset($author) && strlen($author) > 0) {
	       $entry.= $field."  - ".trim(stripslashes(strtr($author, $rev_un_htmlentities)))."\n";
	     }
	   }
	 } 
	 else {
	   //for nonauthor and nonkeyword fields add field as is
	   if(isset($myFields[$field]) && strlen($myFields[$field]) > 0){
	     $entry.= $field."  - ".stripslashes(strtr($myFields[$field], $rev_un_htmlentities))."\n";
	   }
	 }
       }
       // terminate the RIS dataset
       $entry .= "ER  - \n";

       // currently the reference data are written to a temporary file and imported from that
       // todo: make this workaround unnecessary, needs work in refdblib.inc.php

       $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique - we may not be alone
       $fh=fopen($tempFile, 'w') or die("can't open file");
       fwrite($fh, htmlentities($entry));
       fclose($fh);
       
       // if the ID field is set to an alphanumeric value, we're supposed to update, else add
       $lines = array(); // initialize as empty array
       if(isset($myFields["ID"]) && preg_match('/^[^0-9]+/', $myFields["ID"])){
	 $lines = $my_refdbc->updateref_from_file("", $tempFile, "ris", "");
       }
       else {
	 $lines = $my_refdbc->addref_from_file("", $tempFile, "ris", "");
       }
       unlink($tempFile); // clean up our trash

       $num_success = 0;
       $num_failed = 0;
       $my_citekey = "";

       foreach ($lines as $line) {
	 $resultfields = explode(':', $line);
	 $status = $resultfields[0];

	 // store citekey for later use. urlencoding $citekey should not be required as refdbd strips off offending characters anyway
	 if ($status == "406") {
	   $my_citekey = $resultfields[2];
	 }
	 if ($status == "408") {
	   $num_success++;
	 }
	 else if ($status == "413") {
	   $num_success++;
	 }
	 else if ($status == "414") {
	   $num_failed++;
	 }
       }

       if ($num_success > 0) {
	 // print form
	 echo "        <div id=\"content\">\n";
	 if(isset($myFields["ID"]) && preg_match('/^[^0-9]+/', $myFields["ID"])){
	   echo "            <h2>Successfully updated</h2>\n";
	   echo "                <p>The following entry has been successfully updated in your database as <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$my_citekey\">$my_citekey</a>:</p>\n<p>";
	 }
	 else {
	   echo "            <h2>Successfully added</h2>\n";
	   echo "                <p>The following entry has been successfully added to your database as <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$my_citekey\">$my_citekey</a>:</p>\n<p>";
	 }
	 echo "                <div style=\"margin-left:1em;margin-right:1em;border:thin gray solid;font-size:70%;\">\n"; 
	 echo "                    <pre>" . $entry . "</pre>";
	 echo "        </div>\n";
       } 
       else {
	 echo "        <div id=\"content\">\n";
	 echo "            <h2>Error while adding new entry</h2>\n";
	 echo "                <p>The following entry has <b>not</b> been successfully added to your database.</p>\n<p>";
	 echo "                <div style=\"margin-left:1em;margin-right:1em;border:thin gray solid;font-size:70%;\">\n"; 
	 echo "                    <pre>" . $entry . "</pre>";
	 echo "        </div>\n";
       }
     } 
     else {
       // print form
       echo "        <div id=\"content\">\n";
       $addeditWarning="<br/><strong>Do not use any markup (e.g. html &lt;b&gt;) in your entries</strong>.";
       if ($operation=="edit") {
	 echo "            <h2><a id=\"simple\" name=\"simple\">";
	 echo "Edit reference";
	 echo "</a></h2>\n";
	 echo "            <p>This form allows you to edit pre-existing entries in the database. $addeditWarning</p>\n";
       }
       else {
	 echo "            <h2><a id=\"simple\" name=\"simple\">";
	 echo "Add reference";
	 echo "</a></h2>\n";
	 echo "            <p>This form allows you to add new references to the database. $addeditWarning</p>\n";
       }
       echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Add-Edit-Delete\" method=\"POST\" enctype=\"multipart/form-data\">\n";
       echo "                \n<!-- Supplied by REFDB BOX -->\n";
       echo "                <div id=\"identification\" class=\"bibliographicform\" style=\"background:#DAE0D2;\">\n";
       echo "                    <h3>Citation Identification</h3>\n";
       echo "                                                            <p><strong>Citation Key:</strong>&#x00A0;<input class=\"searchText\" type=\"text\" name=\"formID\""; 
       if (isset($formfields['ID'])&&$formfields['ID']!="") {
	 echo " value=\"".$formfields['ID']."\"";
       }
       echo " size=\"20\" style=\"background: #C0C0C0;color:inherit;\"/>";
       if (isset($formfields['ID'])&&$formfields['ID']!="") {
	 echo "                            &#x00A0;<strong>(RefDB ID:</strong> <strong>#$ID</strong>)</strong>\n";
       }
       echo "<br/>(To be set by RefDB. Only expert users should edit this box. Mistakes may corrupt your data)\n";
       echo "                            </p>\n";
       echo "                </div>\n";
       echo "                <div id=\"formTY\" class=\"bibliographicform\">\n";
       echo "                    <h3>Reference Type</h3>\n";
       echo "                    <table>\n";
       echo "                        \n<!-- Reference Type -->\n";
       echo "                        <tr>\n";
       echo "                            <td class=\"formlabel\"><strong>Reference type</strong>:</td>\n"; 
       echo "                            <td class=\"forminput\">\n";
       form_selection($formfields['TY']);
       echo "                            </td>\n";
       echo "                        </tr>\n";
       echo "                    </table>\n";
       echo "                </div>\n";                        
       //***********************************************************************************************
       //Shorter way to create form!!!!!!!!!!!!!!
       //Here I would include the $fields later on
       foreach($fields as $theField){
	 if($theField == "ID"){
	   // A very dirty hack because ID-field is so far generated separately above. But needs to
	   // be in list in order to be read. TODO: Fixme
	 } 
	 else {
	   //Date fields require an array of defaults
	   if(in_array($theField, $dateFields)) {
	     if(isset($formfields[$theField.'year'])){
	       $defaultValue['year']=$formfields[$theField.'year'];
	     } 
	     else {
	       $defaultValue['year']="";
	     }
	     if(isset($formfields[$theField.'month'])){
	       $defaultValue['month']= $formfields[$theField.'month'];
	     } 
	     else {
	       $defaultValue['month']="";
	     }
	     if(isset($formfields[$theField.'day'])){
	       $defaultValue['day']= $formfields[$theField.'day'];
	     } 
	     else {
	       $defaultValue['day']="";
	     }
	     if(isset($formfields[$theField.'other'])){
	       $defaultValue['other']=$formfields[$theField.'other'];
	     } 
	     else {
	       $defaultValue['other']="";
	     }
	   } 
	   elseif(isset($myFields[$theField])){
	     $defaultValue = $myFields[$theField];
	   } 
	   else {
	     $defaultValue = "";
	   }
	   generateFormPart($formfields['TY'],$theField, $defaultValue);
	 }
       }
       echo "                </table>\n";
       echo "            </div>\n";
       echo "            <p id=\"addReference\"><button type=\"submit\" name=\"sendQuery\" value=\"Add reference\">";
       if ($operation=="edit") {
	 echo "Update reference";
       }
       else {
	 echo "Add reference";
       }
       echo "</button></p>\n";
       echo "        </form>\n";
       echo "    </div>\n";
       if (isset($operation)) {
	 unset($operation);
       }
     }
   }
   break;

   /*========================================================================

          Upload 
                    
                    This page is used to upload files for inclusion in a database
                    
                    ========================================================================*/
 case('Upload'):
   echo "<div id=\"content\">\n";
   echo "<form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Confirm\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   echo "<h2><a id=\"simple\" name=\"simple\">Import references</a></h2>\n";
   echo "<p>Add references from a file here. The following file types are recognized automatically:</p>\n<ul>";

   // dynamically create a list of supported input data formats

   // these are supported by default
   echo "<li>RIS</li>\n<li>risx</li>\n";

   // these need converters provided by refdb
   if (!is_null(nwhich("bib2ris-utf8"))) {
     echo "<li>BibTeX</li>\n";
   }

   // temporarily disabled as we cannot distinguish it from "good" RIS
   //   if (!is_null(nwhich("en2ris"))) {
   //     echo "<li>EndNote (tagged)</li>\n";
   //   }

   if (!is_null(nwhich("marc2ris"))) {
     echo "<li>MARC21 and UNIMARC</li>\n";
   }

   if (!is_null(nwhich("med2ris"))) {
     echo "<li>Pubmed (tagged and XML)</li>\n";
   }

   // these need bibutils. xml2ris is required for all of these converters
   if (!is_null(nwhich("xml2ris"))) {
     echo "<li>MODS</li>\n";
     if (!is_null(nwhich("copac2xml"))) {
       echo "<li>COPAC</li>\n";
     }
     if (!is_null(nwhich("endx2xml"))) {
       echo "<li>EndNote XML</li>\n";
     }
     if (!is_null(nwhich("isi2xml"))) {
       echo "<li>ISI</li>\n";
     }
   }

   // RIS, risx, and exports from the web of science</p>\n";
   echo "</ul>\n";
   echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"3000000\">\n";
   echo "File to import: <input name=\"userfile\" type=\"file\">\n";
   echo "<input type=\"submit\" name=\"sendQuery\" value=\"Send File\"/>\n";
   break;
   /*========================================================================
                    
                    Confirm

                    You come to this page from the Delete page after selecting confirming or canceling a deletion process. This page reports on
                    the results.

                    ========================================================================*/
 case('Confirm'):
   // define variables
   if (isset($_REQUEST['searchcmd'])) {
     $searchcmd=$_REQUEST['searchcmd'];
   }
   if (isset($_REQUEST['delcmd'])) {
     $delcmd=$_REQUEST['delcmd'];
   }
   echo "        <div id=\"content\">\n";
   // do whatever was selected
   if ($sendQuery=="Confirm deletion") {
     $lines = $my_refdbc->deleteref($delcmd);
     echo "<h2>Entry has been deleted</h2>\n";
     echo "<p>The requested entry has been permanently deleted from your database using the following";
   }
   elseif ($sendQuery=='Cancel deletion') {
     echo "<h2>Requested deletion has been cancelled</h2>\n";
     echo "<p>Your request has been cancelled. The entry has <strong>not</strong> been deleted.</p>\n";
   }
   elseif($sendQuery=='Send File') {
     if (!isset($_FILES['userfile'])
	 || !isset($_FILES['userfile']['name'])
	 || strlen($_FILES['userfile']['name']) == 0) {
       echo "Error: no file was specified";
     }
     else {
       $uploaddir='/tmp/';
       $filename=$uploaddir . $_FILES['userfile']['name'];
       echo "<pre>\n";
       if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filename)) {
	 echo "File is valid, and was successfully uploaded.  Here's some more debugging info:\n";
       } 
       else {
	 echo "Error while uploading file! Error:\n";
	 print($_FILES['userfile']['error']."\n");
	 echo "<a href=\"http://de.php.net/manual/de/features.file-upload.errors.php\" target=\"_blank\">error codes</a>\n";
       }
       echo "</pre>\n";
       importFile($filename, $my_refdbc);
     }
   }
   else {
     echo "<h2>Undefined error</h2>\n";
     echo "<p>Something has gone wrong, but we're not sure what it is.</p>\n";
   }
   echo "<p><a href=\"index.php\">Return to search form</a></p>\n";
   break;

   /*========================================================================
                    
                    Search results
                    
                    This page displays search results. You get here from the search screen after a successful search. Like all output forms, 
                    this page does not have an associated tab in the navigation list. This is because you cannot navigate to it--i.e. it is produced 
                    by refdb and the php. Moreover, as a user, you want to be able to select an arbitrary form from this point, including the 
                    form that produced these results. 
                    
                    ========================================================================*/
 case('Search results'):
   //This array is used to build the query that will be sent to the getref command for the advanced search on the query page
   $fields=array("anyauthor"=>":AX:",
		 "anytitle"=>":TX:",
		 "anyjournal"=>":JX:",
		 "author"=>":A1:",
		 "editor"=>":A2:", 
		 "seditor"=>":A3:", 
		 "title"=>":TI:",
		 "booktitle"=>":T2:",
		 "seriestitle"=>":T3:",
		 "journaltitle"=>":JF:",
		 "shortjournaltitle"=>":JO:",
		 "publicationyear"=>":PY:",
		 "keyword"=>":KW:",
		 "Notes"=>":N1:",
		 "Abstract"=>":N2:",
		 "Address"=>":AD:",
		 "Reprint"=>":RP:",
		 "ISSN"=>":SN:",
		 "URL"=>":UR:",
		 "Publisher"=>":PB:",
		 "City"=>":CY:",
		 "U1"=>":U1:",
		 "U2"=>":U2:",
		 "U3"=>":U3:",
		 "U4"=>":U4:",
		 "U5"=>":U5:",
 		 "M1"=>":M1:",
 		 "M2"=>":M2:",
 		 "M3"=>":M3:"
		 );

   //These are the logical operators used in the advanced search
   $ops=array("and"=>"AND",
	      "or"=>"OR",
	      "not"=>"NOT"
	      );

   $equals=array("exact"=>"=",
		 "contains"=>"~",
		 "beginswith"=> "=^",
		 "endswith"=> "=$"
		 );

   // build base refdbc command

   if(isset($_POST['query'])){
     // for expert queries, currently not used
     $terms =$_POST['query'];
   } 
   elseif(isset($_POST['simplequery']) && $_POST['simplequery'] != "") {
     // search string in all fields
     $query="'".$_POST['simplequery']."'";
     $terms="";
     if (is_numeric($query)) {
       $terms=":AX:~$query OR :TX:~$query OR :KW:~$query OR :UR:~$query OR :L1:~$query OR :L2:~$query OR :L3:~$query OR :L4:~$query OR :JX:~$query OR :RP:~$query OR :N1:~$query OR :AV:~$query OR :TY:~$query OR :PY:=$query OR :Y2:=$query OR :ID:=$query OR :CK:~$query OR :SN:~$query OR :N2:~$query OR :SP:~$query OR :EP:~$query OR :VL:~$query OR :IS:~$query OR :AD:~$query OR :CY:~$query OR :PB:~$query OR :U1:~$query OR :U2:~$query OR :U3:~$query OR :U4:~$query OR :U5:~$query OR :TO:~$query OR :AR:~$query OR :OS:~$query OR :DG:~$query OR :RT:~$query OR :CI:~$query OR :CU:~$query OR :SE:~$query OR :RE:~$query OR :MT:~$query OR :NV:~$query OR :EI:~$query OR :CO:~$query OR :CF:~$query OR :RN:~$query OR :CL:~$query OR :SC:~$query OR :PN:~$query OR :CN:~$query";
     }
     else {
       $terms=":AX:~$query OR :TX:~$query OR :KW:~$query OR :UR:~$query OR :L1:~$query OR :L2:~$query OR :L3:~$query OR :L4:~$query OR :JX:~$query OR :RP:~$query OR :N1:~$query OR :AV:~$query OR :TY:~$query OR :CK:~$query OR :SN:~$query OR :N2:~$query OR :SP:~$query OR :EP:~$query OR :VL:~$query OR :IS:~$query OR :AD:~$query OR :CY:~$query OR :PB:~$query OR :U1:~$query OR :U2:~$query OR :U3:~$query OR :U4:~$query OR :U5:~$query OR :TO:~$query OR :AR:~$query OR :OS:~$query OR :DG:~$query OR :RT:~$query OR :CI:~$query OR :CU:~$query OR :SE:~$query OR :RE:~$query OR :MT:~$query OR :NV:~$query OR :EI:~$query OR :CO:~$query OR :CF:~$query OR :RN:~$query OR :CL:~$query OR :SC:~$query OR :PN:~$query OR :CN:~$query";
     }	 
   }
   elseif((isset($_POST['citationkey']) && $_POST['citationkey'] != "")
	  || (isset($_POST['doi']) && $_POST['doi'] != "")) {
     $citationkey=$_POST['citationkey'];
     $doi=$_POST['doi'];
     $terms="";
     if ($citationkey!="") {
       $terms = ":CK:="."$citationkey";
     }
     else if ($doi != "") {
       $terms = ":DO:="."$doi";
     }
   }
   elseif(isset($_POST['simplequery1'])) {
     $simplequery1=$_POST['simplequery1'];
     $simplequery2=$_POST['simplequery2'];
     $simplequery3=$_POST['simplequery3'];
     $simplequery4=$_POST['simplequery4'];
     $simplequery5=$_POST['simplequery5'];
     $simplequery6=$_POST['simplequery6'];
     $simplequery7=$_POST['simplequery7'];
     $simplequery8=$_POST['simplequery8'];
     $advancedquery1=$_POST['advancedquery1'];
     $advancedquery2=$_POST['advancedquery2'];
     $advancedquery3=$_POST['advancedquery3'];
     $advancedquery4=$_POST['advancedquery4'];
     $advancedquery1equals=$_POST['advancedquery1equals'];
     $advancedquery2equals=$_POST['advancedquery2equals'];
     $advancedquery3equals=$_POST['advancedquery3equals'];
     $advancedquery4equals=$_POST['advancedquery4equals'];
     $advancedquery1op=$_POST['advancedquery1op'];
     $advancedquery2op=$_POST['advancedquery2op'];
     $advancedquery3op=$_POST['advancedquery3op'];
     $advancedquery1field=$_POST['advancedquery1field'];
     $advancedquery2field=$_POST['advancedquery2field'];
     $advancedquery3field=$_POST['advancedquery3equals'];
     $advancedquery4field=$_POST['advancedquery4field'];
     //set search terms to NULL in order to begin building search
     $terms="";
     //build simple search. This assigns a variable that we will use to try to figure out if a field is to be used or not
     $first=true;
     //check if simplequeryAX is empty
     if ($simplequery1!="") {
       //add search terms acquired from this field
       $terms=":AX:~"."$simplequery1"." ";
       //set $first to false so that we won't treat any additional fields that way
       $first=false;
     }
     if ($simplequery2!="") {
       //add search terms acquired from this field
       if ($first) {
	 $terms=$terms.":PY:=".$simplequery2." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".":PY:"."=".$simplequery2." ";
       }
     }
     if ($simplequery3!="") {
       //add search terms acquired from this field
       if ($first) {
	 $terms=$terms.":TX:"."~".$simplequery3." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".":TX:"."~".$simplequery3." ";
       }
     }
     if ($simplequery4!="") {
       //add search terms acquired from this field
       if ($first) {
	 $terms=$terms.":JX:"."~".$simplequery4." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".":JX:"."~".$simplequery4." ";
       }
     }
     if ($simplequery5!="") {
       //add search terms acquired from this field
       if ($first) {
	 $terms=$terms.":VL:"."~".$simplequery5." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".":VL:"."~".$simplequery5." ";
       }
     }
     if ($simplequery6!="") {
       //add search terms acquired from this field
       if ($first) {
	 $terms=$terms.":IS:"."~".$simplequery6." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".":IS:"."~".$simplequery6." ";
       }
     }
     if ($simplequery7!="") {
       //add search terms acquired from this field
       if ($first) {
	 $terms=$terms.":SP:"."~".$simplequery7." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".":SP:"."~".$simplequery7." ";
       }
     }
     if ($simplequery8!="") {
       //add search terms acquired from this field
       if ($first) {
	 $terms=$terms.":KW:"."~".$simplequery5." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".":KW:"."~".$simplequery5." ";
       }
     }
     if ($advancedquery1!="") {
       //we should rewrite these so that a date choice has EQUALS as the $equals field, no matter what the user has chosen.
       $field1=$fields[$advancedquery1field];
       $equals1=$equals[$advancedquery1equals];
       if ($first) {
	 $terms=$terms.$field1.$equals1.$advancedquery1." ";
	 $first=false;
       }
       else {
	 $terms=$terms."AND"." ".$field1.$equals1.$advancedquery1." ";
       }
     }
     if ($advancedquery2!="") {
       $field2=$fields[$advancedquery2field];
       $equals2=$equals[$advancedquery2equals];
       if ($first) {
	 $terms=$terms.$field2.$equals2.$advancedquery2." ";
	 $first=false;
       }
       else {
	 $op1=$ops[$advancedquery1op];
	 $terms=$terms.$op1." ".$field2.$equals2.$advancedquery2." ";
       }
     }
     if ($advancedquery3!="") {
       $field3=$fields[$advancedquery3field];
       $equals3=$equals[$advancedquery3equals];
       if ($first) {
	 $terms=$terms.$field3.$equals3.$advancedquery3." ";
	 $first=false;
       }
       else {
	 $op2=$ops[$advancedquery2op];
	 $terms=$terms.$op2." ".$field3.$equals3.$advancedquery3." ";
       }
     }
     if ($advancedquery4!="") {
       $field4=$fields[$advancedquery4field];
       $equals4=$equals[$advancedquery4equals];
       if ($first) {
	 $terms=$terms.$field4.$equals4.$advancedquery4." ";
	 $first=false;
       }
       else {
	 $op3=$ops[$advancedquery3op];
	 $terms=$terms.$op3." ".$field4.$equals4.$advancedquery4." ";
       }
     }
     /*                        // Build the commandline query --> removed because it wasn't working
                        elseif($sendQuery=="Send command line query" ) {
                            $cmd=$commandlinequery;
                            $terms=$terms;
                        } */
     /*                        //  Query terms if you've returned from a search
                        elseif ($sendQuery=="Return to Search Results" ) {
                            $terms=$return;
                        } */
   } 
      elseif (isset($_REQUEST['query'])) {
        $raw_terms=$_REQUEST['query'];

     // escape regexp special characters
        $in_array = array('[', ']', '(', ')', '{', '}', '^', '$', '.', '+', '*', '?', '|');
        $out_array = array('\\[', '\\]', '\\(', '\\)', '\\{', '\\}', '\\^', '\\$', '\\.', '\\+', '\\*', '\\?', '\\|');
        $terms=str_replace($in_array, $out_array, $raw_terms);
        $terms = "'$terms'";
      }
   //   else {
     //No valid query, branching to Search
     //TODO This does not work yet. Work with include later on
   //     $thisPage = "Search";
   //     echo "<div id=\"content\">";
   //     echo "    <p>Sorry! Your request was an invalid search</p>";
   //     echo "</div>";
   //     break;
   //   }
   // Build final command by adding terms we have constructed to command built earlier. 
   //check if the database has been set. If not give warning
   if ($database=="") {
     echo "        <div id=\"content\">\n";
     echo "            <h2>Database error</h2>\n";
     echo "            <p>Please select a database.</p>";
     echo "        </div>";
   }
   else {
     $lines = $my_refdbc->getref("risx", "", "", "", "", "", "", "1", $terms);

     //Report on results
     //first set hits variable to hold count
     $hits="";
     $str=str_replace("<entry", "entry", $lines, $count);
     $hits=$count;
     //If count is 0, indicate there were no hits
     if ($hits<1) {
       $hits="no";
       $resultsnumber="results";
     }
     // Otherwise make $hits equal to the number of hits
     elseif ($hits==1) {
       $resultsnumber="result";
     }
     else {
       $resultsnumber="results";
     }
     echo "        <div id=\"content\">\n";
     echo "            <h2>Matching References</h2>\n";
     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Add-Edit-Delete\" method=\"POST\" enctype=\"multipart/form-data\">\n"; 
     /* echo "                <p><!-- removed for the moment because I don't know how to process arbitrary numbers of checkboxes ";
                        echo "                    <input type=\"submit\" value=\"Delete selected references\" name=\"sendQuery\"/>&#00A0;";
                        echo "                    <input type=\"submit\" value=\"Add selected references to Personal List\" name=\"sendQuery\"/>&#X00A0;";
                        echo "                    <input type=\"submit\" value=\"Remove selected references from Personal List\" name=\"sendQuery\"/>--></p>\n"; */
     echo "                <p>Your search for <strong>" .$terms . "</strong> generated <strong>" . $hits . "</strong> " . $resultsnumber . ".<br/>\n";
     //     echo "                    (RefDB command: <code>" . $displaysearchcmd . "</code>)</p>\n";
     echo "                <p>Back to <a href=\"index.php\">Search screen</a>.</p>\n"; 
     // If the search had results, display them:
     $lineNumber=1;
     $checkboxNumber=risx_xhtmlprocessor ($lines,"true");
     echo "                <p class=\"hidden\"><input type=\"hidden\" name=\"terms\" value=\"" . $terms . "\"/>\n";
     // echo "                <input type=\"hidden\" name=\"scope\" value=\"" . $scope . "\"/>\n";
     //     echo "                <input type=\"hidden\" name=\"searchcmd\" value=\"" . $searchcmd . "\"/>\n";
     echo "                <input type=\"hidden\" name=\"numberOfCheckBoxes\" value=\"" . $checkboxNumber . "\"/></p>\n";
     echo "            </form>\n";
     echo "        </div>\n";
   }
   break;
   /*========================================================================
                
                Help
                
                ========================================================================*/
 case('Help'):
   echo "    <div id=\"content\">\n";
   echo "           <h2>Help and Manuals</h2>\n";
   echo "           <p>The help function and manual for this version of PHP_RefDB is not yet complete. In the mean time, here are links to manuals and instructions for the command line engine.</p>\n";
   echo "           <ul>\n";
   echo "           <li><a href=\"http://refdb.sourceforge.net/manual/index.html\"><em>RefDB Handbook</em></a>: A comprehensive manual to the RefDB suite.</li>\n";
   echo "           <li><a href=\"http://refdb.sourceforge.net/tutorial/book1.html\"><em>RefDB Tutorial</em></a>: A users manual aimed at the needs of clients rather than administrators.</li>\n";
   echo "           </ul>\n";
   echo "   </div>\n";
   break;
   /*========================================================================

                Preferences
                
                ========================================================================*/
 case('Preferences'):
   echo "<div id=\"content\">";
   echo "    <h2>Sorry! Not yet implemented</h2>";
   echo "    <p>This feature will allow you to set various parametres for your use of RefDB.</p>";
   echo "</div>";
   break;
   /*========================================================================
                
                Index Results
                
                ========================================================================*/
 case('Index results'):
   //if field is not set go to the form
   if (!isset($_POST['kajqueryfield'])||!isset($_POST['kajquery'])){
     $thisPage ='Search indices'; 
   }
   // Otherwise show results
   else{ 
     //build the command
     $kajqueryfield = $_POST['kajqueryfield'];
     $kajquery = $_POST['kajquery'];
     $short = selectTag($_POST['kajqueryfield']);
                        
     $in_array = array('[', ']', '(', ')', '{', '}', '^', '$', '.', '+', '*', '?', '|');
     $out_array = array('\\[', '\\]', '\\(', '\\)', '\\{', '\\}', '\\^', '\\$', '\\.', '\\+', '\\*', '\\?', '\\|');
     $terms=str_replace($in_array, $out_array, $kajquery);
     $terms = "'$terms'";

     echo "<div id=\"content\">
                            <h2>Results</h2>
                            <h3>Matching matches for <strong><em>" . $kajquery . "</em></strong> in <strong><em>". $kajqueryfield ."</em></strong></h3>";

     switch($_POST['kajqueryfield']) {
     case "keyword":
       $lines = $my_refdbc->getkw("", "relfreq", $terms);
       break;
     case "author":
       $lines = $my_refdbc->getau("", "relfreq", $terms);
       break;
     case "editor":
       $lines = $my_refdbc->geted("", "relfreq", $terms);
       break;
     case "seditor":
       $lines = $my_refdbc->getas("", "relfreq", $terms);
       break;
     case "journalfull":
       $lines = $my_refdbc->getjf("f", "", "relfreq", $terms);
       break;
     case "journalabbrev":
       $lines = $my_refdbc->getjo("f", "", "relfreq", $terms);
       break;
     case "journalabbrev1":
       $lines = $my_refdbc->getj1("f", "", "relfreq", $terms);
       break;
     case "journalabbrev2":
       $lines = $my_refdbc->getj2("f", "", "relfreq", $terms);
       break;
     }

     if ($lines) {
       foreach($lines as $line) {
	 list($relfreq, $item) = explode(":", $line);
	 echo "<p class='result relfreq$relfreq'>
                                    <a href=index.php?thisPage=Search%20results&query=".$short."~".urlencode("".$item."")." >" . 
	   str_replace(",", ", ", $item) . "
				  </a>
			       </p>\n";
       }
     }
     else {
       echo "<p>Sorry, there were no results.</p>";
     }
     echo "</div>";
   } 
   break;

   /*========================================================================

                Search indices
                
                ========================================================================*/
 case('Search indices'):
   // include_once('php/searchIndices.inc.php');
   echo "    <div id=\"content\">\n";
   echo "        <h2>Search Indices</h2>\n";
   echo "        <p>Use this form to search Refdb's pre-compiled indices.</p>";
   echo "        <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Index results\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   //echo "        <form action=\"kajresult.php\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   echo "	    <p>\n";
   echo "	        <input type=\"text\" name=\"kajquery\"/> in ";
   echo "                <select name=\"kajqueryfield\">\n";
   echo "                    <option value=\"keyword\">keywords</option>\n";
   echo "	            <option value=\"author\">authors</option>\n";
   echo "	            <option value=\"editor\">editors</option>\n";
   echo "	            <option value=\"seditor\">series editors</option>\n";
   echo "	            <option value=\"journalfull\">journal (full)</option>\n";
   echo "	            <option value=\"journalabbrev\">journal (abbrev.)</option>\n";
   echo "	            <option value=\"journalcustabbrev1\">journal (custom abbrev. 1)</option>\n";
   echo "	            <option value=\"journalcustabbrev2\">journal (custom abbrev. 2)</option>\n";
   echo "	        </select>\n";
   echo "	    </p>\n";
   echo "	    <p>\n";
   echo "	        <input type=\"submit\" value=\"Send query\"/>\n";
   echo "	        <input type=\"reset\" value=\"Reset form\"/>\n";
   echo "	    </p>\n";
   echo "        </form>\n";
   echo "    </div>\n";        
   break;
   /*========================================================================

                External databases

                ========================================================================*/
 case('External databases'):
                
   if (function_exists('yaz_connect')) {

   
     function display_record($rec, $xslfile) {
       $xml = new DOMDocument;
       $xml->loadXML($rec);

       $xsl = new DOMDocument;
       $xsl ->load($xslfile);

       // Configure the transformer
       $proc = new XSLTProcessor;
       $proc->registerPHPFunctions();
       $proc->importStyleSheet($xsl); // attach the xsl rules

       echo $proc->transformToXML($xml);
     }

     /*
$processor = xslt_create();
    $parms = array('/_xml' => $rec);
    $res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
    xslt_free($processor);
    $res = preg_replace("'</?html[^>]*>'", '', $res);
    print $res;
} */

     echo "<div id=\"content\">";
     echo "<h2>Search external resources</h2>";
     echo "<p>This search engine uses <a href=\"http://www.indexdata.dk/yaz/\">yaz</a> and <a href=\"http://www.indexdata.dk/phpyaz/\">phpyaz</a> to search selected Z39.50 servers. It is still very rudimentary, but it does allow you to search external sources.</p>";
                    
     // This adds  subtracts slashes from in front of apostrophes as requires by the PHP server's "magic quotes" status 
     function myAddSlashes( $string ) {
       if (get_magic_quotes_gpc()==1) {
	 return ( $string );
       }
       else {
	 return ( addslashes ( $string ) );
       }
     }
     $host="";
     $term="";
     if (isset($_POST['host'])) {
       $host=$_POST['host'];
     }
     if (isset($_POST['term'])) {                    
       $term=$_POST['term'];
     }
     $num_hosts=count($host);
     //The following checks the status of the term input and the number of hosts open. If either is null, then it displays the search field.

     echo " <form method=\"POST\">\n";
     echo "  <h2>Search</h2>\n";
     echo "  <p><input type=\"text\" size=\"30\" name=\"term\"/";
     if ($term) {
       echo " value=\"$term\"";
     }
     echo "> <input type=\"submit\" name=\"action\" value=\"Search\"/></p>\n";
     echo "  <p>Supported CCL fields: ti (title), au (author), ab (abstract), date, isbn and issn. You can combine fields using operators <code>and</code> and <code>or</code>: e.g. <code>ti=submarine and au=parrish thomas</code>.</p>";
     echo " <p><strong>Databases:</strong> <input type=\"checkbox\" checked=\"1\" name=\"host[]\" value=\"melvyl.cdlib.org/CDL90\"/>\n";
     echo "  MELVYL (University of California) \n";
     echo " <input type=\"checkbox\" checked=\"1\" echo\"  name=\"host[]\" value=\"z3950.loc.gov:7090/voyager\"/>\n";
     echo "  Library of Congress</p>&nbsp;";
     if (!empty($term)&&count($host)!=0) {
       //Define each property of bibl1 (todo: add year)
       $bib1["term"]="u=1016 s=pw t=l,r";
       $bib1["ti"]="u=4 s=pw t=l,r";
       $bib1["au"]="u=1003";
       $bib1["ab"]="u=62 s=pw t=l,r";
       $bib1["isbn"]="u=7 s=pw";
       $bib1["issn"]="u=8 s=pw";
       $bib1["date"]="u=30 r=o";
       // Repeat search terms back to user; htmlspecialchars ensures that things like & in input are rendered &amp;.
       // See http://ca3.php.net/htmlspecialchars
       echo "<hr/>";
       echo "<h2>Results</h2>";
       echo '<p>You searched for <strong>' . htmlspecialchars($term) . '</strong> <button type=\"submit\" name=\"thisPage\" value=\"External databases\"/>Clear results</button></p>';
       //Assigns ids to hosts: 1) begin with i=0, as long as i < that the num_hosts (defined above) keep adding 1 
       for ($i=0; $i < $num_hosts; $i++) {
	 //for each host assign an index id
	 $id[]=yaz_connect($host[$i]);
	 // Mapping CCL terms to RPN as defined above (bib1) for each search 
	 yaz_ccl_conf($id[$i], $bib1);
	 // Parse input against yaz_ccl_conf; if error report message; defines cclresult as output of parsing
	 if (!yaz_ccl_parse($id[$i], $term, &$cclresult)) {
	   echo '<p>Error: ' . $cclresult["errorstring"] . '</p><p><a href=\"index.php?thisPage=External databases\">Clear results</a></p>';
	   continue;
	 }
	 //Specify z39.50 preferred syntax for retrieval from the server 
	 yaz_syntax($id[$i],"usmarc");
	 //Prepare search (excuted by yaz_wait). Attributes are (resource id, string type [must be "rpn", string query). 
	 // cclresult is produced by yaz_ccl_parse above.
	 yaz_search($id[$i],"rpn",$cclresult["rpn"]);
	 // Specify number of records to be retrieved. (Should be called befiore yaz_search: http://www.php.net/manual/en/function.yaz-range.php). This is replaced below.
	 yaz_range($id[$i], 0, 0);
       }
       //Allows searches to be executed: returns when server completes or aborts.
       yaz_wait();
       //run through each host for counts
       for ($i=0; $i < $num_hosts; $i++) {
	 $count=yaz_hits($id[$i]);
	 //sets yaz_range in response to number of hits
	 if ($count >=4) {
	   $count=4;
	   yaz_range($id[$i], 1, $count);
	   //prepares for retrieval of number of records specified in yaz_range above
	   yaz_present($id[$i]);
	 }
	 //Allows searches to be executed: returns when server completes or aborts.
	 yaz_wait();
	 for ($i=0;  $i <$num_hosts; $i++) {
	   //add line, indicate the host
	   echo '<hr/>' . $host[$i] . ":";
	   //define error variable
	   $error=yaz_error($id[$i]);
	   //if there is an error, report it.
	   if (!empty($error)) {
	     echo "<p>Error: $error (<a href=\"index.php?thisPage=External databases\">Clear results</a>)</p>";
	   } 
	   //Otherwise report the number of hits
	   else {
	     $hits=yaz_hits($id[$i]);
	     echo "<p>Result Count $hits (<a href=\"index.php?thisPage=External databases\">Clear results</a>)</p>";
	   }
                                    
                                    
	   // Now present the output
	   echo '<ul>';
	   //Restrict following to 20 records
	   for ($p=1; $p <=20; $p++) {
	     // present record of idx in position p, in format "string"; convert marc-8 to utf-8
	     $rec=yaz_record($id[$i],$p,"xml; charset=marc-8,utf-8");
                                        
                                        
                                        
	     //if the record is empty go on to the next host?
	     if (empty($rec)) continue;
	     //Print the position number
	     echo "<p><strong>$p</strong>";
                                        
	     $xslfile="xsl/MARC21slim2English.xsl";
                                        
	     display_record($rec, $xslfile);
	     /* //Go through each record looking for \n and replacing it with html:br element
                                        echo ereg_replace("\n", "<br/>\n",$rec); */
	     echo "</p>";
	   }
	   echo '</ul>';
	 }
       }
     }
   }                            else {echo "<div id=\"content\">";
   echo "    <h2>Not available</h2>";
   echo "    <p>This feature requires the installation of <a href=\"http://www.indexdata.dk/yaz/\">yaz</a> and <a href=\"http://www.indexdata.dk/phpyaz/\">phpyaz</a>. Please install (or ask your system adminitrator to install) this software.</p>";
   echo "</div>";
   // include_once('php/externalsearchengine.inc.php');
   }
   echo "</div>";                
                
   break;
   /*========================================================================

                Search

                ========================================================================*/
   //                case('Search'):
 default :
   // include_once('php/searchform.inc.php');
   echo "    <div id=\"content\">\n";
   echo "        <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Search results\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   echo "            <div class=\"searchform\">\n";
   echo "                <h2><a id=\"simple\" name=\"simple\">Simple search</a></h2>\n";
   echo "                <p>This form performs a simple search for a string in all fields</p>\n";
   echo "                <strong>Find this</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery\"/><br/>\n";  
   echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "            </div>\n";
   echo "            <div class=\"searchform\">\n";
   echo "                <h2><a id=\"findid\" name=\"findid\">Search by unique identifier</a></h2>\n";
   echo "                <p>Use this form to retrieve a particular dataset with a known unique identifier, either the citation key <strong>or</strong> the Digital Objects Identifier (DOI).</p>\n";
   echo "                <strong>Citation key</strong>: <input class=\"searchText\" type=\"text\" name=\"citationkey\"/> ";  
   echo "                <strong>DOI</strong>: <input class=\"searchText\" type=\"text\" name=\"doi\"/><br/>\n";  
   echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "            </div>\n";
   echo "            <div class=\"searchform\">";
   echo "                <h2><a id=\"simplefield\" name=\"simplefield\">Simple field-based search</a></h2>\n";
   echo "                <p>This form allows you to search the most common fields. Enter as many or as few search terms as you wish. The search is case-insensitive. Multiple fields are combined using \"AND\" (i.e. filling in <strong>author</strong> and <strong>publication year</strong> will result in a search for <em>author <strong>AND</strong> publication year</em>."; 
   echo "                        You can also use the <a href=\"#advanced\">Advanced query</a> <!-- or the <a href=\"#commandline\">command-line interface</a>--> below.</p>\n";
   echo "                <p>\n";
   echo "                    <strong>Author/Editor/Translator</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery1\"/><br/>\n";  
   echo "                    <strong>Publication Year</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery2\"/><br/>\n";
   echo "                    <strong>Book/Chapter/Article Title</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery3\"/><br/>\n";
   echo "                    <strong>Journal Name or Abbreviation</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery4\"/><br/>\n";
   echo "                    <strong>Volume</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery5\"/> ";
   echo "                    <strong>Issue</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery6\"/> ";
   echo "                    <strong>Start page</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery7\"/><br/>\n";
   echo "                    <strong>Subject</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery8\"/><br/>\n";
   echo "               </p>\n";
   echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "           </div>\n";
   echo "            <div class=\"searchform\">";
   echo "           <h2><a id=\"advanced\" name=\"advanced\">Advanced query</a></h2>\n";
   echo "           <p>This form allows you to search any available field. The search is case-insensitive.";
   echo "                  You can also use the <a href=\"#simple\">simple search</a> above<!-- or the"; 
   echo "                    <a href=\"#commandline\">command-line interface</a> below-->.</p>\n";
   echo "           <p>\n";
   echo "                <select name=\"advancedquery1field\">\n";
   echo "                    <option value=\"anyauthor\" selected=\"selected\">Author/Editor (all)</option>\n";
   echo "                    <option value=\"anytitle\">Title (article/chapter/book/series)</option>\n";
   echo "                    <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                    <option value=\"\">---</option>\n";
   echo "                    <option value=\"author\">Author</option>\n";
   echo "                    <option value=\"editor\">Editor</option>\n";
   echo "                    <option value=\"seditor\">Series editor</option>\n";
   echo "                    <option value=\"title\">Article title</option>\n";
   echo "                    <option value=\"booktitle\">Book title</option>\n";
   echo "                    <option value=\"seriestitle\">Series title</option>\n";
   echo "                    <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                    <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                    <option value=\"publicationyear\">Publication year (EQUALS only)</option>\n";
   echo "                    <option value=\"keyword\">Keyword</option>\n";
   echo "                </select>\n";
   echo "                <select name=\"advancedquery1equals\">\n";
   echo "                    <option value=\"exact\">EQUALS</option>\n";
   echo "                    <option value=\"contains\" selected=\"selected\">INCLUDES</option>\n";
   echo "                    <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                    <option value=\"ends\">ENDS WITH</option>\n";
   echo "                    <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                </select>\n";
   echo "                <input class=\"searchText\" type=\"text\" name=\"advancedquery1\"/>\n"; 
   echo "                <select name=\"advancedquery1op\">\n";
   echo "                    <option value=\"and\" selected=\"selected\">AND</option>\n";
   echo "                    <option value=\"or\">OR</option>\n";
   echo "                    <option value=\"not\">AND NOT</option>\n";
   echo "                 </select>\n";
   echo "            </p>\n";
   echo "            <p>\n";
   echo "                <select name=\"advancedquery2field\">\n";
   echo "                    <option value=\"anyauthor\">Author/Editor (all)</option>\n";
   echo "                    <option value=\"anytitle\">Title (article/chapter/book/series)</option>\n";
   echo "                    <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                    <option value=\"\">---</option>\n";
   echo "                    <option value=\"author\">Author</option>\n";
   echo "                    <option value=\"editor\">Editor</option>\n";
   echo "                    <option value=\"seditor\">Series editor</option>\n";
   echo "                    <option value=\"title\">Article title</option>\n";
   echo "                    <option value=\"booktitle\">Book title</option>\n";
   echo "                    <option value=\"seriestitle\">Series title</option>\n";
   echo "                    <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                    <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                    <option value=\"publicationyear\" selected=\"selected\">Publication year (EQUALS only)</option>\n";
   echo "                    <option value=\"keyword\">Keyword</option>\n";
   echo "                </select>\n"; 
   echo "                <select name=\"advancedquery2equals\">\n";
   echo "                    <option value=\"exact\" selected=\"selected\">EQUALS</option>\n";
   echo "                    <option value=\"contains\">INCLUDES</option>\n";
   echo "                    <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                    <option value=\"ends\">ENDS WITH</option>\n";
   echo "                    <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                </select>\n";
   echo "                <input class=\"searchText\" type=\"text\" name=\"advancedquery2\"/>\n";
   echo "                <select name=\"advancedquery2op\">\n";
   echo "                    <option value=\"and\" selected=\"selected\">AND</option>\n";
   echo "                    <option value=\"or\">OR</option>\n";
   echo "                    <option value=\"not\">AND NOT</option>\n";
   echo "                 </select>\n";
   echo "              </p>\n";
   echo "              <p>\n";
   echo "                 <select name=\"advancedquery3field\">\n";
   echo "                     <option value=\"anyauthor\">Author/Editor (all)</option>\n";
   echo "                     <option value=\"anytitle\" selected=\"selected\">Title (article/chapter/book/series)</option>\n";
   echo "                     <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                     <option value=\"\">---</option>\n";
   echo "                     <option value=\"author\">Author</option>\n";
   echo "                     <option value=\"editor\">Editor</option>\n";
   echo "                     <option value=\"seditor\">Series editor</option>\n";
   echo "                     <option value=\"title\">Article title</option>\n";
   echo "                     <option value=\"booktitle\">Book title</option>\n";
   echo "                     <option value=\"seriestitle\">Series title</option>\n";
   echo "                     <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                     <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                     <option value=\"publicationyear\">Publication year (EQUALS only)</option>\n";
   echo "                     <option value=\"keyword\">Keyword</option>\n";
   echo "                 </select>\n";
   echo "                 <select name=\"advancedquery3equals\">\n";
   echo "                    <option value=\"exact\">EQUALS</option>\n";
   echo "                     <option value=\"contains\" selected=\"selected\">INCLUDES</option>\n";
   echo "                     <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                     <option value=\"ends\">ENDS WITH</option>\n";
   echo "                     <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                 </select>\n";
   echo "                 <input class=\"searchText\" type=\"text\" name=\"advancedquery3\"/>\n";
   echo "                 <select name=\"advancedquery3op\">\n";
   echo "                     <option value=\"and\">AND</option>\n";
   echo "                     <option value=\"or\">OR</option>\n";
   echo "                     <option value=\"not\">AND NOT</option>\n";
   echo "                 </select>\n";
   echo "              </p>\n";
   echo "              <p>\n";
   echo "                 <select name=\"advancedquery4field\">\n";
   echo "                     <option value=\"anyauthor\">Author/Editor (all)</option>\n";
   echo "                     <option value=\"anytitle\">Title (article/chapter/book/series)</option>\n";
   echo "                     <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                     <option value=\"\">---</option>\n";
   echo "                     <option value=\"author\">Author</option>\n";
   echo "                     <option value=\"editor\">Editor</option>\n";
   echo "                     <option value=\"seditor\">Series editor</option>\n";
   echo "                     <option value=\"title\">Article title</option>\n";
   echo "                     <option value=\"booktitle\">Book title</option>\n";
   echo "                     <option value=\"seriestitle\">Series title</option>\n";
   echo "                     <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                     <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                     <option value=\"publicationyear\">Publication year (EQUALS only)</option>\n";
   echo "                     <option value=\"keyword\" selected=\"selected\">Keyword</option>\n";
   echo "                 </select>\n";
   echo "                 <select name=\"advancedquery4equals\">\n";
   echo "                    <option value=\"exact\">EQUALS</option>\n";
   echo "                     <option value=\"contains\" selected=\"selected\">INCLUDES</option>\n";
   echo "                     <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                     <option value=\"ends\">ENDS WITH</option>\n";
   echo "                     <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                 </select>\n";
   echo "                 <input class=\"searchText\" type=\"text\" name=\"advancedquery4\"/>.";
   echo "              </p>\n";
   echo "              <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "           </div>\n";
   /*                 This has been echoed out because I can't get it to work
                    echo "            <div class=\"searchform\">";
                    echo "<!--           <h2><a name=\"commandline\" id=\"commandline\">Command line query</a></h2>\n";
                    echo "               <p>This form allows you to use RefDB command line syntax directly. ";
                    echo "                   You can also use the <a href=\"#simple\">simple search</a> or <a href=\"#form\">advance query</a> forms above.</p>\n";
                    echo "               <p>Query string: <input type=\"text\" name=\"commandlinequery\" size=\"40\" maxlength=\"2048\"/></p>\n";
                    echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Submit command line query\"/></p> -->\n";
                    echo " </div>";
   */
   echo "        </form>\n";
   echo "    </div>\n";
   break;
}

// footer
echo "        <div id=\"footer\">\n";
echo "            <p>Reference manager and bibliography tool. Version $version</p>\n";
echo "        </div>\n";
 
// close out the html
echo "    </body>\n";
echo "</html>\n";
?>
