<?PHP
include ("/var/www/sites/allsites/.htmachine.inc.php");

#Some general (and not so general) configuration constants so that the process can
#be more easily controlled and updated in this one central spot

#The pages in order for the entire process
define ("PAGES","redo,start,nda1,nda2,nda4,userDetails,userDetails3,userDetails4,snoopy,getcert");
#special names for log, error, and debugging files
#The debuggery should be phased out and the log file should move to what's there.  Right now it just goes to our directory/log.
define("LOGDIR","/var/log/httpd/domains");
#define("LOGFILENAME",LOGDIR."/reliableid.com.log");
define("LOGFILENAME","log");
#define("ERRORFILENAME",LOGDIR."/reliableid.com.errors");
define("ERRORFILENAME","errors");
define("DEBUGGERY","debug");
#mysql connection parameters
define("SERVER","localhost");
define("USER","valid");
define("PASSWORD","F0UNDAT10N");
define("DB","valID");
#application parameters, these can change as we decide what we're doing and where we're doing it.
#the base URL of the application
define("URL","https://www.reliableid.com/level1/");
define("OURLEGALNAME","Reliable ID");
define("OURCEONAME","Wes Kussmaul");
#the parameters for sending email to the enrollee and to the EO (used later for DBC)
define("EMAILFROM","Reliable ID Enrollments<securit@reliableid.com>");
define("EMAILSUBJECT","Enrollment documents");
define("OFFICERSUBJECT","New Enrollee for you");
#for accessing Google Maps to choose an EO (I think Somen might have cancelled the account.)
define("GOOGLEKEY","ABQIAAAAlDqe0fX2HhjnltNo_fB04hQRMg6-gZ96b75SQzwcJL73ESLdJhTMAAgxfQZiGNqNpygFm72gq5UuFw");
define ("RETURNTO","https://www.osmio.org");
/*
#I think the following are relics of the time that the certs might have been made on the reliableid server
#UPLOADDIRECTORY might still be a good place to throw the NCMS data
define("UPLOADDIRECTORY",dirname($_SERVER["SCRIPT_FILENAME"])."/upload");
define("CERTSDIRECTORY",HARDTOGET."webvivos/4/certs");
define("PLAINCERTS",UPLOADDIRECTORY);
#certificate creation parameters
define("OPENSSLDIR","/usr/bin");
define("PROVISIONALDAYS",'8');
define("CACERT",HARDTOGET."webvivos/4/certs/root.pem");
define("CAKEYFILE",HARDTOGET."/webvivos/4/certs/rootkey.pem");
define("CAKEY",'1273!Main');    ##formerly m3m
*/
#For those who wish to write their own NDA's
define("NDANOTTO","phadley@reliableid.com");
define("NDANOTSUBJECT","Another misfit with his own NDA");
define("NDANOTURL",URL."admin/notyet.php");
#A hiding place for alternative NDA's
define("NDASTORAGE",HARDTOGET."ValID/nda");
#accessing the snoopy information from NCMS
define("NCMSURL","https://transactions.everification.net/eipsservices/WrapEVS.aspx");
define("NCMSUSER","1087503461060");
define("NCMSPASSWORD","5Ps7vg3D");
define("NCMSSTORAGE",HARDTOGET."ValID/NCMS");
#For informing a notary of the rejection
define("REJECTTO","phadley@reliableid.com");
define("REJECTSUBJECT","A rejected applicant");
define("REJECTURL",URL."admin/notyet.php");
define("GETCERTURL",URL."getcert.php");

#####################################################################################################
#A few general utility functions stolen from previous work.

#user_agent parses the user agent string to determine what operating system and browser are in use.
#it returns an array so it should be called as list($os,$br,$opsys,$browser)=user_agent();
# $os and $br are two-letter abbreviations for the operating system and browser, $opsys and $browser are
#their names spelled out as in (wi ff Windows Firefox)
#The caller will usually make $osbr=$os.$br for use in the osbr subdirectory which handles specific clients
if (!function_exists('user_agent'))
{
function user_agent()
{
	$agent=" ".$_SERVER["HTTP_USER_AGENT"];
	if (strpos($agent,"Konqueror") > 0) {$browser="Konqueror";$br="ko";}
	else if (strpos($agent,"MSIE 7.0") > 0) {$browser="InternetExplorer 7";$br="e7";}
	else if (strpos($agent,"MSIE") > 0) {$browser="InternetExplorer";$br="ie";}
	else if (strpos($agent,"Firefox") > 0) {$browser="Firefox";$br="ff";}
	else if (strpos($agent,"Mozilla") > 0) {$browser="Mozilla";$br="mo";}
	else if (strpos($agent,"Safari") > 0) {$browser="Safari";$br="sf";}
	else
	{
		PKH_log("Could not figure out browser from $agent.");
		$browser="dn";
	}

	if (strpos($agent,"Linux") > 0) {$opsys="Linux";$os="li";}
	else if (strpos($agent,"FreeBSD") > 0) {$opsys="Free BSD";$os="fr";}
	else if (strpos($agent,"Windows NT 6.0") > 0) {$opsys="Windows Vista";$os="vi";}
	else if (strpos($agent,"Windows") > 0) {$opsys="Windows";$os="wi";}
	else if (strpos($agent,"Macintosh") > 0) {$opsys="Macintosh";$os="ma";}
	else
	{
		PKH_log("Could not find operating system from $agent.");
		$os="ig";
	}

	return array($os,$br,$opsys,$browser);
}
}

function reporterror($where,$query="")
{
	$a="Error in $where";
	if (strlen($query)>0)
	{
		$a.=" with a query of<BR>$query";
		$a.="<BR>The reported error condition is<BR>".mysql_error();
	}
	$b=str_replace("<BR>","\n",$a);
	shell_exec("echo \"".date("j F Y-G:i:s")."$b\" >>".ERRORFILENAME);
	return $a;
}

function baderror($line,$what,$query="")
{
	global $script;
	$a=date("j F Y-G:i:s")."-$script-line $line-$what";
	if (strlen($query)>0)
	{
		$a.=" with a query of<BR>$query";
		$a.="<BR>The reported error condition is<BR>".mysql_error();
	}
	$cmd="echo \"".str_replace("<BR>","\n",$a)."\" >> ".ERRORFILENAME;
	shell_exec($cmd);
}

function loggywoggy($msg)
{
  $cmd="echo ".date("j F Y-G:i:s")."-$msg>>".LOGFILENAME;
  #echo "<BR>Attempting to log the message $msg at ".LOGFILENAME." using the command<BR>$cmd"
	shell_exec($cmd);
	return;
}

function buggywuggy($line,$msg)
{
  global $script;
  $cmd="echo ".date("j F Y-G:i:s")."-$script at $line-$msg>>".DEBUGGERY;
  shell_exec($cmd);
	#echo "<BR>$msg";
}

#########################################################################################
#These next ones are dangerous utilities for looking at the database from investigate.php

function show_fields($table)		#Might want to echo <PRE> around it.
{
  $result = mysql_query("SHOW COLUMNS FROM $table");
	if (!$result)
	{
	    return 'Could not run query to show columns of the $table table: ' . mysql_error();
	}
	$a="";
	if (mysql_num_rows($result) > 0)
	{
		while ($row = mysql_fetch_assoc($result))
		{
			$a.=print_r($row,TRUE);
		}
	}
	return $a;
}

function spill_query_results($query,$title,$border=1,$limit=60)
{
	$res=mysql_query($query);
	if (!$res)
	{
		return reporterror("showing query results",$query);
	}
	$a="<H4>$title</H4><TABLE border=$border><TR>";
	$nf=mysql_num_fields($res);
	for ($i=0;$i<$nf;$i++) $a.="<TH>".mysql_field_name($res,$i)."</TH>";
	echo "</TR>";
	while ($row=mysql_fetch_array($res))
	{
		$a.="<TR>";
		for ($i=0;$i<$nf;$i++) $a.="<TD>".$row[$i]."</TD>";
		$a.="</TR>";
	}
	$a.="</TABLE>";
	return $a;
}

function spill_table($table,$border=1,$limit=4)
{
	$query="select * from $table limit $limit";
	return spill_query_results($query,"$table table",$border,$limit);
}

#Get a variable from the $_REQUEST array or return NULL.
#This one avoids filling the ssl_error_log with notices of reference to non-existent indexes.
function fromRequest($name)
{
	if (array_key_exists($name,$_REQUEST)) return $_REQUEST[$name];
	else return NULL;
}

#A cleaner way to designate the default for a dropdown list.
function if_selected($test)
{
	if ($test) return " SELECTED >";
	else return ">";
}

#Create all the options of a dropdown list from rows returned by $query run on $link.
#$value is the name of the field with the value chosen
#$display is the name of the field which is shown to designate $value
#$default is the value of $value which starts off preselected
function spew_options($link,$query,$value,$display,$default)
{
	$res=mysql_query($query,$link);
	$a="";
	while ($row=mysql_fetch_array($res))
		$a.="<OPTION value=".$row[$value].if_selected($row[$value] == $default).$row[$display]."</OPTION>";
	return $a;
}

#Some functions to create text input boxes for the information gathering forms.
#This is easier than repeating the stuff many times per page
function inputBox($name)
{
	$a="<input name=\"$name\" type=\"text\" ";
	if (array_key_exists($name,$_REQUEST))
		$a.= "value=\"".$_REQUEST[$name]."\" ";
	else
	{
		global $$name;
		if (isset($$name)) $a.= "value=\"".$$name."\" ";
	}
	$a.="/>";
	return $a;
}

function inputCells($label,$name)
{
  $a="<td height=\"30\" align=\"left\" valign=\"top\" class=\"browseEventContents\">$label:</td>"
    ."<td height=\"30\" align=\"left\" valign=\"top\">".inputBox($name)."</td>";
  return $a;
}

##Easier database access#####################################################################
#A steal from the pgsql (Postgres) interface, it gets the first row returned by the query
#It is assumed that there will be only one row but it returns the first row regardless
#If the query is bad or the result is empty, it returns NULL.
function mysql_getRow($query)
{
	$res=mysql_query($query);
	if (!$res) return NULL;
	if (is_null($res)) return NULL;
	if (mysql_num_rows($res) == 0) return NULL;
	$row=mysql_fetch_array($res);
	return $row;
}

#A steal from the pgsql (Postgres) interface, it gets the first element of the first row returned by the query
#It is assumed that there will be only one row but it returns the first value of the first row regardless
#If the query is bad or the result is empty, it returns NULL.
function mysql_getOne($query)
{
	$row=mysql_getRow($query);
	if (is_null($row)) return NULL;
	return $row[0];
}

##getStateId will get the id for the state named state_name in country $country_id
##or insert a new line in the state table and return the id for that new line.
function getStateId($state_name,$country_id)
{
  if (strlen($state_name) > 0)
  {
    $stname=mysql_escape_string($state_name);
    $state_sql="select * from state where (state_name = '$stname' or state_code = '$stname') and country_id=$country_id";
    $state=mysql_getRow($state_sql);
    if (!state || is_null($state))
    {
      $state_sql="select * from state where (state_name like '%$stname%' or state_code like '%$stname%') and country_id=$country_id";
      $state=mysql_getRow($state_sql);
    }
    if (!$state || is_null($state))
    {
      $state_sql="insert into state set state_name='$stname',country_id=$country_id";
      if (mysql_query($state_sql))
      {
        $state_id=mysql_insert_id();
        return $state_id;
      }
      else
      {
        reporterror("inserting a new state",$query);
        return 0;
      }
    }
    else  #is_null($state)
      return $state["state_id"];
  }
  else    #strlen($state_name) > 0
    return 0;
}

##getCityId will get the city named $city_name in the state and country given
##or create a new row in the city table and return the id for that new row.
function getCityId($city_name,$state_id,$country_id)
{
  if (strlen($city_name) > 0)   #In future, we can try to deal with abbreviations like St. Peters.
  {
    $ciname=mysql_escape_string($city_name);
    $city_sql="select * from city where city_name = '$ciname' and country_code=$country_id";
    if ($state_id > 0) $city_sql.=" and state_id=$state_id";
    $city=mysql_getRow($city_sql);
    if (!$city || is_null($city))
    {
      $city_sql="select * from city where city_name like '%$ciname%' and country_code=$country_id";
      if ($state_id > 0) $city_sql.=" and state_id=$state_id";
      $city=mysql_getRow($city_sql);
    }
    if (!$city || is_null($city))
    {
      $city_sql="insert into city set state_id=$state_id,	country_code=$country_id,	city_name='$ciname'";
      if (mysql_query($city_sql))
      {
        $city_id=mysql_insert_id();
        return $city_id;
      }
      else
      {
        reporterror("inserting a new city",$query);
        return 0;
      }
    }
    else    #is_null($city)
      return $city["city_id"];
  }
  else    #strlen($city_name) > 0
    return 0;
}

##I assemble a name from the incoming database $row
function makeName($row)
{
  #We should have a line here to capture the common name if it's there.
	$name=$row["first_name"];
	if (strlen($row["middle_name"])> 0) $name.=" ".$row["middle_name"];
	$name.=" ".$row["last_name"];
	return $name;
}

#I assemble an address from the incoming database row in $address
function make_address($address)
{
  $a="";
  if (!is_null($address["street_line_01"]) && (strlen($address["street_line_01"]) > 0))$a.=$address["street_line_01"];
  if (!is_null($address["street_line_02"]) && (strlen($address["street_line_02"]) > 0))$a.="<BR>".$address["street_line_02"];
  if (!is_null($address["street_line_03"]) && (strlen($address["street_line_03"]) > 0))$a.="<BR>".$address["street_line_03"];
  $a.="<BR>".mysql_getOne("select city_name from city where city_id=".$address["city_id"]);
  $a.=", ".mysql_getOne("select state_name from state where state_id=".$address["state_id"]);
  $a.="  ".$address["zipCode"];
  $a.="<BR>".mysql_getOne("select country_name from country where country_id=".$address["country_id"]);
  return $a;
}

##I assemble an address from the incoming database $row.  Other parameters tell me whether to include city, state, zip, and country
function makeAddress($row,$therest=0)
{
	$address=$row["street_line_01"];
	if(strlen($row["street_line_02"]) > 0) $address.="<BR>".$row["street_line_02"];
	if(strlen($row["street_line_03"]) > 0) $address.="<BR>".$row["street_line_03"];
	if ($therest > 0)
	{
		if (($therest & 1) == 1) $address.="<BR>".$row["city"];
		if (($therest & 2) == 2) $address.=", ".$row["state"];
		if (($therest & 4) == 4) $address.="  ".$row["zip_code"];
		if (($therest & 8) == 8) $address.="<BR>".$row["country"];
	}
	return $address;
}

##prettyDate will turn $date from 1948-9-1 to something more human looking.
function prettyDate($date)
{
	return $date;
}

##This presents a uniform way to assemble a message to the user.
##When the caller has the message assembled, it can do a str_replace to make it a list or something else
if (!function_exists('addMessage'))
{
function addMessage($msg)
{
  return "<BR>$msg";
}
}

##getnewby gets the page number of the given page
function getnewby($pagename)
{
  $pages=explode(",",PAGES);
  return array_search($pagename,$pages);
}

##gobackto redirects the client to the most recently done page in case he comes to the wrong page
function gobackto($oldby)
{
  $pages=explode (",",PAGES);
  $npages=count($pages);
  if ($oldby>=$npages)
  {
    loggywoggy("Enrollee $enrollee_id tried to go to page $oldby out of the $npages available.");
    header("location:getcert.php");
  }
  header ("location:".$pages[$oldby].".php");
  loggywoggy("Enrollee has been sent to page $oldby which is ".$pages[$oldby].".php.");
  exit();
}

##advancePage updates the enrollee so that activFlag is the next page
function advancePage($enrollee_id,$newby)
{
  $newby++;
  if ($newby < 1) $newby=1;
  $query="update enrollee set activFlag=$newby where enrollee_id=$enrollee_id";
  mysql_query($query);
  loggywoggy("Enrollee $enrollee_id is advancing to page $newby.");
  gobackto($newby);
}

####################################################################################################

##	This redirection to https doesn't work unless variables are exported.
if (!(array_key_exists("HTTPS",$_SERVER)) || ($_SERVER["HTTPS"] != "on"))
{
  header("location:https://".$_SERVER["HTTP_HOST"]."$script");
  loggywoggy("Request from ".$_SERVER["REMOTE_ADDR"]." redirected to secure connection.");
  die("You should have come here with HTTPS, not HTTP.");
}
    
##Connect to the database with parameters defined above
$link=mysql_connect(SERVER,USER,PASSWORD) or die ("Database Connection Error.");	#log in the user
if (!$link)
{
  reporterror("connecting to the database");
  die("We cannot connect to our database, please try again later.");
}
mysql_select_db(DB,$link);								#connect the user to the database, now the default
session_start();

$bugsy="";$errmsgs="";$msgs="";
$redstar="<font color=\"red\"><strong>*</strong></font>";
$script=$_SERVER["PHP_SELF"];
$pagename=basename($script,".php");
$newby=getnewby($pagename);
  buggywuggy(__LINE__,"$pagename with newby=$newby accessed.");
  loggywoggy ("$script accessed from ".$_SERVER["REMOTE_ADDR"].".");
if ($_SESSION["uid"] == "")
{
  if ($newby == 1)
  {
    $query="insert into enrollee set activFlag=1";
    if (mysql_query($query))
    {
      $enrollee_id=mysql_insert_id();
      $_SESSION["uid"]=$enrollee_id;
    }
    else
    {
      reporterror("Adding a new enrollee",$query);
    }
  }
  else
  {
    gobackto(1);
  }
}
else    ##($_SESSION["uid"} == "")
{
  $enrollee_id=$_SESSION["uid"];
  $query="select * from enrollee where enrollee_id=".$_SESSION["uid"];
  $enrollee=mysql_getRow($query);
  if ($enrollee)
  {
    buggywuggy(__LINE__,"Got an enrollee with\n$query");
  }
  else
  {
    reporterror("No enrollee",$query);
  }
  $oldby=intval($enrollee["activFlag"]);
  if ($oldby < $newby)
  {
    loggywoggy("Returning enrollee $enrollee_id to page $oldby.");
    gobackto($oldby);
  }
  else if ($newby < 1)
  {
    #loggywoggy("Enrollee $enrollee_id is using $script again.");
    $fred=43;
  }
  else if ($oldby > $newby)   ##This means he's trying to go back to a page already completed.
  {
    header("location:redo.php?newby=$newby");
    loggywoggy("Subject $enrollee_id is going back to $newby.");
    exit();
  }

  #In case there's a browser specific problem, we determine it now.
  list($os,$br,$opsys,$browser)=user_agent();
  if (isset($_GET))
  {
    if (array_key_exists("os",$_GET)) {$os=$_GET['os'];$_SESSION['os']=$_GET['os'];}
    if (array_key_exists("br",$_GET)) {$br=$_GET['br'];$_SESSION['br']=$_GET['br'];}
  }
  if (array_key_exists("os",$_SESSION)) $os=$_SESSION['os'];
  if (array_key_exists("br",$_SESSION)) $br=$_SESSION['br'];
  $osbr=$os.$br;
}     ##($_SESSION["uid"} == "")
?>