<?PHP		#index.php of valID
if (!isset($_SERVER["HTTPS"]) || ($_SERVER["HTTPS"] != "on"))
{
	header("Location: https://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
	loggywoggy("Access from ".$_SERVER["REMOTE_ADDR"]." was insecure.");
	exit(1);
}
$stage=1;			#1-alpha, 2-beta, 3
$file="index.php";
include_once(".htfolder.inc.php");
define ('MIME_BOUNDARY',"Identity is the Foundation of Security");

#loggywoggy("We are in index.authentify.php with skipcall=$skipcall and testcall=$testcall.");


function user_agent()
{
	$agent=" ".$_SERVER["HTTP_USER_AGENT"];
	if (strpos($agent,"Konqueror") > 0) {$browser="Konqueror";$br="ko";}
	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
	{
		PKH_log("Could not figure out browser from $agent.");
		$browser="dn";
	}

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

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

function osbrchoice($default,$command,$tid)
{
	$a="\n";
	#$a.="<FORM action=".$_SERVER["PHP_SELF"]." method=post>";
	$a.="<TABLE>";
	$oss=split(",",OSNAMES);
	$brs=split(",",BROWSERS);
	$part="display";
	$noss=count($oss);$nbrs=count($brs);
	for ($i=0;$i<$noss;$i++)
	{
		$os=substr($oss[$i],0,2);
		$a.="\n<TR>";
		for ($j=0;$j<$nbrs;$j++)
		{
			$br=substr($brs[$j],0,2);
			$osbr=$os.$br;
			if (file_exists("osbr/".$osbr.".inc.php"))
			{
				#if($osbr == $default)
				include ("osbr/".$osbr.".inc.php");
				$a.="<TD><A href=".$_SERVER["PHP_SELF"]."?command=$command&tid=$tid&osbr=$osbr>$osbrdisplay</A></TD>";
			}
			else
			{
				$a.="<TD>";
				$a.=substr($brs[$j],3)." on ".substr($oss[$i],3);
				$a.="</TD>";
			}
		}
		$a.="</TR>";
	}
	return $a;
}
#echo phpinfo();
function form_table_row($tag,$type,$column,$value="",$comments="")
{
	$a="\n<TR><TD align=right>$tag:</TD><TD>";
	switch ($type)
	{
		case "int":
		case "float":
		case "char":
		case "varchar":
			$a.="<INPUT name='$column' value='";
			if (strlen($value) > 0)
				$a.=$value;
			else
				$a.=$_REQUEST[$column];
			$a.="'>";
			break;
		case "password":
			$a.="<INPUT type=password name='$column' value='";
			if (strlen($value) > 0)
				$a.=$value;
			else
				$a.=$_REQUEST[$column];
			$a.="'>";
			break;
		case "text":
			$a.="<TEXTAREA name='$column'>$value</TEXTAREA>";
			break;
		default:
			break;
	}
	$a.="</TD><TD>$comments</TD></TR>";
	return $a;
}
################################################################################
################################################################################

$msgs="";		#Messages (mostly for debugging to be spewed after the HEAD section)
if ($live == 2) $msgs.="<H2><FONT color=red>This is still in test mode.</FONT></H2>";
if (!isset($_REQUEST["command"])) $_REQUEST["command"]="NIL";
loggywoggy ("We are executing command ".$_REQUEST["command"]);

switch ($_REQUEST["command"])
{
	case "Please Certify Me":
		include_once(".htcnf.inc.php");	#defines a function which creates a configuration file.
		$transactionid=$_REQUEST["tid"];
		$transaction=DBrowByID($db,"transaction",$transactionid,"transactionid");
		$phone=DBrowById($db,"phone",$transaction["phoneid"],"phoneid");
		$subject=DBrowById($db,"subject",$transaction["subjectid"],"subjectid");
		$client=DBrowById($db,"client",$transaction["clientid"],"clientid");
		$osbr=$transaction["osbr"];
		$query="update transaction set status='rq' where transactionid=$transactionid";
		$db->query($query);

		loggywoggy("Preparing a certificate for client ".$transaction["clientid"]." in transaction ".$_REQUEST["tid"].".");

		#Prepare for certificate generation
		$signer=DBrowById($db,"signer",$client["signerid"],"signerid");
#resource openssl_csr_sign ( mixed $csr, mixed $cacert, mixed $priv_key, int $days [, array $configargs [, int $serial]] )
		$certs_dir = "$certsdir/".$signer["signerid"];		#Put all this stuff in an Apache directory
		$CA="$openssldir/openssl ca";
		$CRL2PKCS7 = "$openssldir/openssl crl2pkcs7";
		$DAYS = "-days ".$signer["days"];
		$CAFILE = "$certs_dir/root.pem";
		$KEYFILE= "$certs_dir/rootkey.pem";
		$query="select nextval('serial".$signer["signerid"]."_seq')";
		if (pearcheck($count=$db->getOne($query)))
		{
			PKH_error("Failed to get the certificate serial number with<BR>$query");
		}
		#$msgs.= "<BR>The serial number will be $count.";
		$hexcount=sprintf("%04X",$count);
		$ERRORFILE = "$certs_dir/errors";
		$srlfile="$certs_dir/$count.srl";
		$cnffile="$certs_dir/$count.cnf";
		$crlfile="$certs_dir/crl.pem";
		$req_file = "$certs_dir/$count.req"; # certificate request filename
		$result_file = "$certs_dir/$count.result"; # certificate filename
		$pkcs7_file = "$certs_dir/$count.pkcs";
		$dbfile="$certs_dir/$count.txt";
		if (!file_exists($certs_dir))		#If this is the first certificate on this signer, create a directory for it.
		{
			if (mkdir($certs_dir,0704))
			{
				file_put_contents($CAFILE,$signer["certificate"]);
				file_put_contents($KEYFILE,$signer["private_key"]);
				shell_exec("touch $certs_dir/database.txt");
				shell_exec("cp $certsdir/root.cnf $certs_dir/root.cnf");
				shell_exec("echo database = $certs_dir/database.txt >>$certs_dir/root.cnf");
				$crlcmd="$CA -gencrl -out $crlfile -config $certs_dir/root.cnf -key '".$signer["password"]."' -crldays 10000 -cert $CAFILE -keyfile $KEYFILE -md sha1 2> $ERRORFILE";
				$fred=shell_exec ($crlcmd);
				if(!file_exists($crlfile))
				{
					PKH_error("We were unable to create the revocation list at $crlfile<BR>$fred");
					echo "<BR>We encountered unexpected problems with our configuration.  Please contact us or "
						.$client["contact"]." who can contact us.";
					die("We are sorry that it didn't work out.");
				}
				#shell_exec("$openssldir/openssl ca -gencrl -config vivos.cnf -out $crlfile");
			}
			else
				die ("<P>We could not create directory $certs_dir.");
		}
		file_put_contents($srlfile,$hexcount);
		shell_exec("touch $dbfile");
		if (!cnf_make($cnffile,$count,$certs_dir))
		{
			loggywoggy("Could not open the configuration file.");
			die("We are sorry, we are having internal problems.  We cannot go on.");
		}

		$CRL = "$certs_dir/crl.pem";
		$CACERT = "-cert $CAFILE";
		$CAKEY = "-key ".$signer["password"];
		$part="makecert";
		include ("osbr/".$osbr.".inc.php");
		loggywoggy ("The certificate should be done.");
		break;
	case "Application Form":
		$transaction=DBrowByID($db,"transaction",$_REQUEST["tid"],"transactionid");
		$phone=DBrowById($db,"phone",$transaction["phoneid"],"phoneid");
		$subject=DBrowById($db,"subject",$transaction["subjectid"],"subjectid");
		$client=DBrowById($db,"client",$transaction["clientid"],"clientid");
		$osbr=$transaction["osbr"];
		if ($transaction["statuscode"] == "0")
		{
			if ($transaction["status"] == "ac")
				$page="certform";
			else if ($transaction["status"] == "cr")
			{
				$cert=DBrowById($db,"certificate",$transaction["certificateid"],"certificateid");
				die("You have already been given certificate ".$cert["certificate"]." and that's all you get.");
			}
			else
			{
				$msgs.="<BR>How did you get interrupted last time?  It would be better if you started over.";
				$page="default";
			}
		}
		else
		{
			$msgs.="<BR>You can't get a certificate because you never authenticated yourself by phone.";
			$page="";		#That will send it back to the default to start over.
		}
		break;
	case "callme":
		$query="update transaction set osbr='".$_REQUEST["osbr"]."' where transactionid=".$_REQUEST["tid"];
		$db->query($query);
		$msgs="<P>We have updated our records to reflect what you say are your browser and operating system.";
	case "Call Me Now":
		$transaction=DBrowByID($db,"transaction",$_REQUEST["tid"],"transactionid");
		$phone=DBrowById($db,"phone",$transaction["phoneid"],"phoneid");
		$subject=DBrowById($db,"subject",$transaction["subjectid"],"subjectid");
		$client=DBrowById($db,"client",$transaction["clientid"],"clientid");
		$osbr=$transaction["osbr"];
		$page="startcall";
		include ("authentificate.php");
		$query="update transaction set status='au' where transactionid=".$transaction["transactionid"];
		$db->query($query);
		$page="callwaiting";
		break;
	case "getit":
	case "Use this one":
		$phone=DBrowById($db,"phone",$_REQUEST["phoneid"],"phoneid");
		$subject=DBrowById($db,"subject",$phone["subjectid"],"subjectid");
		$client=DBrowById($db,"client",$subject["clientid"],"clientid");
		if (pearcheck($tid=$db->getOne("select nextval('transaction_transactionid_seq')")))
			echo "We did not get the next transactionid.";
		list($os,$br,$opsys,$browser)=user_agent();
		$osbr=$os.$br;
		$query="insert into transaction (transactionid,clientid,subjectid,phoneid,osbr) values ($tid,"
			.$client["clientid"].",".$subject["subjectid"].",".$phone["phoneid"].",'$osbr')";
		if (pearcheck($db->query($query)))
		{
			echo "The naughty query is<BR>$query<BR>";
		}
		$transaction=DBrowById($db,"transaction",$tid,"transactionid");
		PKH_log("Have just opened transaction $tid for ".$subject["first"]." ".$subject["surname"]." (id=".$subject["subjectid"].").");
		$page="getit";
		if (file_exists("osbr/".$osbr.".inc.php"))
		{
			$part="display";
			include ("osbr/".$osbr.".inc.php");
		}
		else
			$page="getosbr";
		if (($os=="ig") || ($br == "dn"))
			$page="getosbr";
		break;
	case "Please Find Me":
		$query="select * from subject where lowerfirst='".strtolower($_REQUEST["first"]).
			"' and lowersurname='".strtolower($_REQUEST["surname"]).
			"' and lowerpassphrase='".strtolower($_REQUEST["passphrase"])."'";
		$res=$db->query($query);
		$n=nrows($res);
		if ($n >1)
		{
			$page="pickme";
			#This should be a red flag for somebody.
			DBerror($db,"Found multiple subjects with same logins.",$query);
		}
		else if ($n==0)
			$page="nomatch";
		else
		{
			$subject=$res->fetchRow();
			if ( ($_REQUEST["first"] == $subject["first"]) && ($_REQUEST["surname"] == $subject["surname"]) &&($_REQUEST["passphrase"] == $subject["passphrase"]) )
			{
				$page="dome";
			}
			else
				$page="nomatch";
		}
	default:
		break;
}

echo "<HTML><HEAD>";
echo "<TITLE>ValID Certification Process</TITLE>";
if (!isset($page)) $page="NIL";
switch ($page)
{
	case "certform":
		$part="header";
		include ("osbr/".$osbr.".inc.php");
		break;
	case "done":
		$part="certheader";
		include ("osbr/".$osbr.".inc.php");
		break;
	default:
		echo "</HEAD>\n<BODY>";
		break;
}

echo $msgs;
loggywoggy("We are displaying page $page.");
switch ($page)
{
	case "done":
		echo "<H2>Certification Process for ".$subject["first"]." ".$subject["surname"]."</H2>";
		$certificateid=$db->getOne("select nextval('certificate_certificateid_seq')");
		$query="insert into certificate (certificateid,signerid,serial_number,request,certificate,private_key,subjectid) values "
			."($certificateid,".$signer["signerid"].",$count,'$req','$cert',NULL,".$subject["subjectid"].")";
		if (pearcheck($db->query($query)))
		{
			DBerror($db,"Could not insert certificate",$query);
		}
		$query="update transaction set certificateid=$certificateid,status='cr' where transactionid=" .$transaction["transactionid"];
		$db->query($query);
		$query="update subject set certificateid=$certificateid where subjectid=".$subject["subjectid"];
		$db->query($query);
		echo "<P>All Done";
		PKH_log("Have just granted certificate $certificateid for ".$subject["first"]." ".$subject["surname"]." (id=".$subject["subjectid"].").");
		echo "</P><P>We have just granted certificate $certificate from ".$signer["commonname"]." to ".$subject["first"]." ".$subject["surname"]." and it should be in your browser's certificate store right now.  ";
		echo "This marks the end of our work for you.  Now you may:<UL>";
		echo "<LI>Use the certificate as ".$client["contact"]." intended.</LI>";
		echo "<LI>Learn <A href=howto.php?osbr=$osbr>how to use it</A>.</LI>";
		echo "<LI><A href=findit.php?osbr=$osbr>Find and admire it</A> in your certificate store.</LI>";
		echo "<LI>Look into these <A href=others.php>other places</A> where client certificates are welcome.</LI>";
		echo "<LI>Go to sleep.</LI></UL>";
		break;
	case "certform";
		echo "<H2>Certification Process for ".$subject["first"]." ".$subject["surname"]."</H2>";
		echo "<H4>The Process</H4>";
		echo "<P>We have your essential information but you may add more in the form below before proceeding.";
		echo "  When you're ready please press the \"Please Certify Me\" button at the bottom of the form.";
		echo "</P>";
		$part="form";
		include ("osbr/".$osbr.".inc.php");
		echo "\n<INPUT type=hidden name=tid value=".$transaction["transactionid"].">";
		echo "\n<TABLE><TR><TH colspan=5>You may add more information to your certificate</TH></TR>";
	#	echo form_table_row("Honorific","varchar","honorific","","Title before your name like Dr., Sra., Col., Bayan, etc.");
		echo "\n<TR><TD align=right>Given Name:</TD><TD>".$subject["first"]."</TD></TR>";
		echo "<INPUT type=hidden name=first value='".$subject["first"]."'>";
		echo "\n<TR><TD align=right>Surname:</TD><TD>".$subject["surname"]."</TD></TR>";
		echo "<INPUT type=hidden name=surname value='".$subject["surname"]."'>";
	#	echo form_table_row("Generation","varchar","generation","","Jr., Sr., VII, etc.");
	#	echo form_table_row("Sobriquet","varchar","sobriquet","","Appendage after your name like Ph.D., USAF(ret), Bey");
		echo form_table_row("Common Name","varchar","commonName",$subject["first"]." ".$subject["surname"],"A name you go by.");
		echo "\n<TR><TD align=right>Organization</TD><TD>".$client["name"]."</TD></TR>";
		echo "<INPUT type=hidden name=organizationName value='".$client["name"]."'>";
		echo form_table_row("Division","varchar","organizationalUnitName","");
		echo "\n<TR><TD align=right>Country</TD><TD>";
			echo DBformSelect($db,"countryName","select * from country order by country", "inet_code","country",$phone["country"]);
			echo "</TD></TR>";
		echo form_table_row("State or Province","varchar","stateOrProvinceName");
		echo form_table_row("City","varchar","localityName");
		echo form_table_row("Email","varchar","emailAddress");
		echo "\n<TR><TD></TD><TD><INPUT TYPE='SUBMIT' name='command' value='Please Certify Me'></TD></TR>";
		echo "\n</TABLE>";
		echo "</FORM>";
		break;
	case "callwaiting":
		echo "<H2>Certification Process for ".$subject["first"]." ".$subject["surname"]."</H2>";
		echo "<P>We are now going to call you at ".$phone["number"].".  When you get the call, you will have to give us your confirmation number of<BR>"
			."<H3>".$transaction["confirmnumber"]."</H3>".".";
		echo "<P>In case the page doesn't change automatically for you after your phone call, press this button:<BR>";
			echo "<FORM action=".$_SERVER["PHP_SELF"]." method=post>";
			echo "<INPUT type=hidden name=tid value=".$transaction["transactionid"].">";
			echo "<INPUT type=submit name=command value='Application Form'>";
			echo "</FORM>";
		ob_flush();
		flush();
		include ("authentificate.php");
if ($skipcall == 1)
{
	$query="update transaction set statuscode=0,theirtime='long, long ago' where transactionid=".$transaction["transactionid"];
}
else
{
		$query="update transaction set statuscode=$statuscode,theirtime='".$newmsg->timestamp."' where transactionid=".$transaction["transactionid"];
}
		if (pearcheck($db->query($query)))
			loggywoggy("The offending query is:\n$query");
		if ($statuscode == 0)
		{
			echo "<P>Well done.  Now we can proceed to ask you what you want on your certificate.  Just click this handy button:<BR>";
			echo "<FORM action=".$_SERVER["PHP_SELF"]." method=post>";
			echo "<INPUT type=hidden name=tid value=".$transaction["transactionid"].">";
			echo "<INPUT type=submit name=command value='Application Form'>";
			echo "</FORM>";
		}
		else
		{
			echo "<P>Well, it looks like we can't honor your request because you failed to authentify yourself on the phone.";
		}
		break;
	case "getit":
	case "Use this one":
		echo "<H2>Certification Process for ".$subject["first"]." ".$subject["surname"]."</H2>";
		echo "<P>We have determined that you are using $osbrdisplay.  If this is untrue to reality, please choose a better description from this table.";
		echo osbrchoice($osbr,"callme",$tid);
		echo "</P>";
		echo "<H4>The Process</H4>";
		echo "<P>We are now ready to call you at ".$phone["number"].
			".  The next page will give you instructions and then call you.";
		echo "<FORM action=".$_SERVER["PHP_SELF"]." method=post>";
		echo "<INPUT type=hidden name=tid value=".$transaction["transactionid"].">";
		echo "<BR><INPUT type=submit name=command value='Call Me Now'>";
		echo "</FORM>";
		break;
	case "getosbr":
		$query="insert into newosbr(transactionid,osbr,useragent) values (".$transaction["transactionid"].",'$osbr','".$_SERVER["HTTP_USER_AGENT"]."')";
		$db->query($query);
		echo "<H2>Certification Process for ".$subject["first"]." ".$subject["surname"]."</H2>";
		echo "";
		if (($os=="ig") && ($br == "dn"))
		{
			echo "<P>We were unable to determine what you are using as an operating system and browser.";
		}
		else if ($os == "ig")
			echo "<P>We were unable to determine what you are using as an operating system.";
		else if ($br == "dn")
			echo "<P>We were unable to determine what you are using as a browser.";
		else
		{
			echo "It looks like you are using $browser on the $opsys operating system.  "
				."We don't have a script specifically for that combination but you might be able to choose a sufficiently similar one from "
				."the active links below.  I would go by browser first, then operating system.";
		}
		echo "<P>Please choose an appropriate combination of operating system and browser from the table below.";
		echo osbrchoice($osbr,"callme",$tid);
		break;
	case "dome":
		$subjectid=$subject["subjectid"];
		$client=DBrowById($db,"client",$subject["clientid"],"clientid");
		echo "<H2>".$subject["first"]." ".$subject["surname"]." of ".$client["name"]."</H2>";
		loggywoggy("Login by subject $subjectid.");
		$query="select * from phone where subjectid=".$subject["subjectid"];
		$res=$db->query($query);
		$n=nrows($res);
		if ($n==0)
		{
			echo "We don't have a phone number for you.  "
				."This makes it impossible to authenticate your identity.  "
				."Please contact the person in charge of this program for ".$client["name"].", ".$client["contact"].".";
			PKH_error("Subject $subjectid has no phone number.");
		}
		else if ($n==1)
		{
			$phone=$res->fetchRow();
			echo "Your phone number for verification is ".$phone["number"].".";
			echo "If this is right, please proceed to the <A href=".$_SERVER["PHP_SELF"]."?command=getit&phoneid=".$phone["phoneid"].">application page</A>.";
			echo "If it is wrong, there is not much we can do for you, go see the person in charge of the program, ".$client["contact"].".";
		}
		else
		{
			echo "You have more than one number available.  "
				."Please choose the one where you'll be to take the verification call.";
			echo "<FORM method=post action=".$_SERVER["PHP_SELF"].">";
			echo "<P>".DBformSelect($db,"phoneid","select * from phone where subjectid=".$subject["subjectid"]." order by phoneid", "phoneid","number",$_REQUEST["phoneid"])."</P>";
			echo "<INPUT type=hidden name=subjectid value=".$subject["subjectid"].">";
			echo "<INPUT type=hidden name=clientid value=".$client["clientid"].">";
			echo "<INPUT type=submit name=command value='Use this one'>";
			echo "</FORM>";
		}
		break;
	case "pickme":
		echo "<H2>We are in trouble</H2>";
		echo "<P>It seems that you have the same identifiers as other people.  Please go back to whoever set you up and ask for a different password.</P>";
		break;
	case "nomatch":
		echo "<H2>You do not exist</H2>";
		echo "<P>It seems that you are not to be found.  Could you try correcting the entries you gave us?</P>";
	default:
		echo "<H2>Welcome to ValID</H2>";
		echo "<P>This page is for people who have been asked to get one of our certificates.  ";
		echo "If this is not you, please <A href=http://www.authentrus.com>go elsewhere</A>.</P>";
		echo "<FORM method=post action=".$_SERVER["PHP_SELF"].">";
		echo "<TABLE><TR><TH colspan=5>My data</TH></TR>";
		echo form_table_row("Given Name","varchar","first","","Your first name, nickname, or whatever was given to us");
		echo form_table_row("Surname","varchar","surname","","Family name");
		echo form_table_row("Password","password","passphrase","","The password you were given.");
		echo "<TR><TD></TD><TD><INPUT type=submit name=command value='Please Find Me'></TD></TR>";
		echo "</TABLE>";
		echo "</FORM>";
		break;
}
echo "</BODY></HTML>";
?>