<?PHP
	echo "<BR><BR>We are here<BR><BR>";
	define ("ALLSITES","/var/www/sites/allsites");
	include (ALLSITES."/.htmachine.inc.php");     ##This defines HARDTOGET
	
	#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,index,start,nda1,nda2,nda4,userDetails,userDetails3,snoopy,getcert");
	define ('DEBUGMU',TRUE);
	#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",LOGDIR."/reliableid.com.debug");
	#define("DEBUGGERY","debug");
	define("SESSIONFILE","session");
	
	#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");
	
	#define("OPENIDDIRECTORY",ALLSITES."/openid");
	define("OPENIDDIRECTORY","./openid");
	define("SESSIONTIMEOUT",3600);
	
	define("SNOOPYPASSING",0.8);    ##How many does he have to get right to pass.
	
	#####################################################################################################
	#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);
		}
	}
	
	##Connect to the database with parameters defined above
	function databaseconnect()
	{
		$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
		return $link;
	}
	
	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);
		echo "<BR>Have just written<BR>$a<BR>to ".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);
		echo "<BR>Just wrote<BR>$a<BR>to ".ERRORFILENAME;
	}
	
	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($msg,$line=NULL,$file=NULL)
	{
		if (!DEBUGMU) return;
		global $script;
		$cmd="echo ".date("j F Y-G:i:s");
		if (!is_null($file)) $cmd.="-$file";
		if (!is_null($line)) $cmd.=", line $line";
		$cmd.="-$msg>>".DEBUGGERY;
		shell_exec($cmd);
		echo "<BR>Attempting to write the message $msg at ".DEBUGGERY." using the command<BR>$cmd";
		return;
	}
	
	function progress($file,$line,$msg="")
	{
		buggywuggy($msg,$line,$file);
		return;
	}
	
	#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
	#if the word "noquery" is used as the first parameter, then the second parameter is already an array so it doesn't need a trip to the dtabase.
	function spew_options($link,$query,$value,$display,$default)
	{
		if ($link == "noquery")
		{
			$res=$query;
		}
		else
		{
			$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["zipCode"];
			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);
		$i=array_search($pagename,$pages);
		if ($i === false)
		{
			if ($pagename == "investigate") $i=-1;
		}
		return $i;
	}
	
	##removes the slashes in the openid so that it can play nicely with the file system
	function deslash($str)
	{
		$a=substr($str,8);
		$a=substr($a,0,-1);
		return $a;
	}
	
	##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 tried to go to page $oldby out of the $npages available.");
			header("location:getcert.php");
		}
		else
		{
			header ("location:".$pages[$oldby].".php");
			loggywoggy("Enrollee has been sent to page $oldby which is ".$pages[$oldby].".php.");
		}
		exit();
	}
	
	##advancePage updates the session so that the next page is the current page
	##It then calls gobackto to redirect to that page.
	##It should be called before any output is generated.
	function advancePage($newby)
	{
		buggywuggy("Advancing from page $newby.",__LINE__,__FILE__);
		$newby++;
		if ($newby < 1) $newby=1;
		$_SESSION["newby"]=$newby;
		buggywuggy("Advancing to page $newby.",__LINE__,__FILE__);
		loggywoggy("Enrollee 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.");
	}
	
	$link=databaseconnect();
	
	session_start();
	if (DEBUGMU) shell_exec("echo Session variables as of ".date("H:i:s").">".SESSIONFILE);
	if (DEBUGMU) foreach($_SESSION as $_key=>$_value) shell_exec("echo $_key = $_value >>".SESSIONFILE);
	if (!array_key_exists("newby",$_SESSION)) $_SESSION["newby"]=1;
	
	$bugsy="";$errmsgs="";$msgs="";
	$redstar="<font color=\"red\"><strong>*</strong></font>";
	$script=$_SERVER["PHP_SELF"];
	$pagename=basename($script,".php");
	$newby=getnewby($pagename);
	buggywuggy("$pagename with newby=$newby accessed.",__LINE__,__FILE__);
	loggywoggy ("$script accessed from ".$_SERVER["REMOTE_ADDR"].".");
	
	if (array_key_exists("userIdentity",$_SESSION))
	{
		buggywuggy("We have a user");
		$oldby=$_SESSION["newby"];
		$openid=$_SESSION["userIdentity"];
		buggywuggy("We have a user named $openid");
		if ($oldby<$newby)
		{
			loggywoggy("Returning $openid to page $oldby.");
			buggywuggy("Returning $openid to page $oldby.");
			gobackto($oldby);
		}
		else if ($newby < 1)
		{
			buggywuggy("newby=$newby is less than one for $pagename.");
			$fred=43;
		}
		else if ($oldby > $newby)
		{
			buggywuggy("oldby=$oldby was bigger than newby=$newby, so we ask if we want to go back.");
			header("location:redo.php?newby=$newby");
			loggywoggy("$openid is going back to page $newby.");
			exit();
		}
		$enrollee=$_SESSION['enrollee'];
		$address=$_SESSION['address'];
		if (array_key_exists("subjectid",$_SESSION))
			$subjectid=$_SESSION['subjectid'];
		else
		{
			$subjectid=deslash($_SESSION['userIdentity']);
			$_SESSION["subjectid"]=$subjectid;
		}
		
		#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;
		buggywuggy("We are using $osbr--$browser on $opsys.");
	}
	else  ##userIdentity in $_SESSION
	{
		$fred=3;
		progress(__FILE__,__LINE__,"Unidentified user");
	}  ##end of if...else... on userIdentity in $_SESSION
	?>