<?PHP
/*
	This is an attempt to create a generic provisional certificate generator.
		The database is defined by a file in HARDTOGET.DATABASE_LOGIN_FILE.
		The certificate directory which openssl uses in its ca application is defined in
*/
	if (!defined("ALLSITES")) define ("ALLSITES","/var/www/sites/allsites/dev");
	include (ALLSITES."/.htmachine.inc.php");     ##This defines HARDTOGET
	$domain=$_SERVER["SERVER_NAME"];
	if (substr($domain,0,4) == "www.")$domain=substr($domain,4);
	
	#These constants will change for different sites.
	define ("INTERNAL_NAME","Provisional registration for $domain");
	define("LOGDIR","/var/log/httpd/domains");
	define("LOGFILE",LOGDIR."/$domain.certlog");
	define("DATABASE_LOGIN_FILE","/ValID/valid.connect");	#database login is at HARDTOGET.DATABASE_LOGIN_FILE
	define("SYSTEM_EMAIL","sitemaster@$domain");
	define("EMAIL_EMAILER","certifier@$domain");			#sends mail for email verification
	define ("DEFAULT_BOUNDARY_CODE","Your new certificate is wonderful");
	define("OURLEGALNAME","Reliable ID");					#Howw we refer to ourselves
	define("OURDISPLAYNAME","Provisional Certificate");		#In <title> and maybe a few other places.
	define("OURCEONAME","Wes Kussmaul");					#Used in the NDA (not used for provisionals)
	#Title for and existence of each page.  This should match files in the command and display directories
	#	and in the /head direcotry if we ever start working on that.
	$toc=array(0=>"Start Page",
			   3=>"Enter email for validation",
			   4=>"Enter validation code",
			   6=>"Validate code",
			   8=>"generate key pair, request certificate", 
			   11=>"What next?",
			   15=>"No more");

	#the parameters for sending email to the enrollee and to the EO (used later for DBC)
	define ('DEBUGMU',TRUE);
	include_once(ALLSITES."/.htreportingerrors.inc.php");

	#connect to the database.
	include (HARDTOGET.DATABASE_LOGIN_FILE);
	if (pearcheck($db,"Bad database connection","Trying to connect to the database for ".INTERNAL_NAME))
	{
		die("We are very sorry but we can't find our database.  We have informed ourselves of the problem and hope to fix it.  Could you come back a bit later, please?");
		$bugsy.="Could not connect to the database.  Instead, we got<pre>".print_r($db,true)."</pre>";
	}
	
	#Start the session
	
	if (!session_start())
	{
		admin_notify("Sessions Disabled","We were unable to start a session for ");
		die("We have internal server problems which make going forward difficult.");
	}
	if (!array_key_exists("newby",$_SESSION)) $newby=0;
	
	loggywoggy("We are all initialized and are logging to ".LOGFILE.".",__LINE__,__FILE__);
	
	#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("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
	 */
/*		These are constants for something beyond the provisional certificate.
	#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.

	
	#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.
if (!function_exists("tapRequest"))
{
	function tapRequest($name)
	{
		if (array_key_exists($name,$_REQUEST)) return $_REQUEST[$name];
		else return NULL;
	}
}
	#Check the form of an email addresa
	if (!function_exists("_FORM_checkEmail"))
	{
		function _FORM_checkEmail($email)
		{
			$atpos=strpos($email,"@");
			$dotpos=strpos(substr($email,$atpos),".");
			buggywuggy("The email address, $email, breaks at $atpos and $dotpos.");
			if ($atpos<1 || $dotpos < 1)
				return false;
			else
				return true;
		}
	}
/*		functions for processing addresses which aren't needed for a provisional.

	##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;
	}
*/
	####################################################################################################
	
	##	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"].$_SERVER["SCRIPT_NAME"]);
		loggywoggy("Request from ".$_SERVER["REMOTE_ADDR"]." redirected to secure connection.");
		die("You should have come here with HTTPS, not HTTP.");
	}

?>