<?PHP
#wiie.inc.php-The things that IE on Windows will understand as a certificate request
switch ($part)
{
	case "display":
		$osbrdisplay="Internet Explorer on Windows";
		break;
	case "form":
		echo "<FORM METHOD=POST ACTION='".$_SERVER["PHP_SELF"]."' NAME='GenReqForm' onSubmit='GenReq()'>";
		echo "<INPUT type=hidden name='sessionid'>";
		echo "<INPUT type=hidden name='reqEntry'>";
		break;
	case "header":
?>
<OBJECT classid="clsid:127698E4-E730-4E5C-A2b1-21490A70C8A1"
codebase="xenroll.dll"
id=Enroll >
</OBJECT>
<OBJECT classid="clsid:98AFF3F0-5524-11D0-8812-00A0C903B83C"
codebase="certcli.dll"
id=Request >
</OBJECT>
<SCRIPT LANGUAGE="JavaScript">
<!---

// this is from JavaScript: The Definitive Guide, since
// Microsoft implementation of Math.random() is broken
//
function random() {
	random.seed = (random.seed*random.a + random.c) % random.m;
	return random.seed/random.m;
}
random.m = 714025; random.a = 4096; random.c = 150889;
random.seed = (new Date()).getTime()%random.m;

function GenReq ()
{
	var sessionid               = "a_unique_session_id";
	var reqHardware             = 0;
	var szName                  = "";
	var szPurpose               = "ClientAuth";
	var doOnline                = 1;
	var keySpec = 1;
	var comma = "";

	alert("We are in GenReq.");

	szName = "";

	if (document.GenReqForm.commonName.value == "")
		document.GenReqForm.commonName.value=document.GenReqForm.first.value+" "+document.GenReqForm.surname.value;

			szName = szName + comma+"CN=" + document.GenReqForm.commonName.value;
			comma=";";

	alert ("Your distinguished name is " + szName);



	if (document.GenReqForm.countryName.value != "")
	{
			szName = szName + comma+"C=" + document.GenReqForm.countryName.value;
			comma=";";

	alert ("Your distinguished name is " + szName);

	}

	if (document.GenReqForm.stateOrProvinceName.value != "")
	{
			szName = szName + comma+"S=" + document.GenReqForm.stateOrProvinceName.value;
			comma=";";
	}

	if (document.GenReqForm.localityName.value != "")
	{
			szName = szName + comma+"L=" + document.GenReqForm.localityName.value;
			comma=";";
	}

	if (document.GenReqForm.organizationName.value != "")
	{
			szName = szName + comma+ "O=" + document.GenReqForm.organizationName.value;
			comma=";";
	}

	if (document.GenReqForm.organizationalUnitName.value != "")
	{
			szName = szName + comma+"OU=" + document.GenReqForm.organizationalUnitName.value;
			comma=";";

	alert ("Your distinguished name is " + szName);

	}

	alert ("Your distinguished name is " + szName);

	/* make session id unique */
	sessionid = "xx" + Math.round(random() * 1000);

	alert ("Your session id is " + sessionid );

	sz10 = Enroll.createPKCS10( szName, "1.3.6.1.4.1.311.2.1.21");

	alert ("Your session ID is " + sessionid);

    /*
     *
     * The condition sz10 being empty occurs on any condition in which the
     * credential was not successfully generated. In particular, it occurs
     * when the operation was cancelled by the user, as well as additional
     * errors. A cancel is distinguished from other unsuccessful
     * generations by an empty sz10 and an error value of zero.
     *
     */

	if (sz10 != "")
	{
		document.GenReqForm.reqEntry.value = sz10;
		document.GenReqForm.sessionid.value = sessionid;
	}
	else
	{
		alert("Somehow, Internet Explorer was unable to generate a key pair and certificate request.  You might try again or change some name parts in the form but we can't really help you with an internal problem.");
		return false;
	}


}


--->
</SCRIPT>
</HEAD><BODY>
<?PHP
		break;
	case "makecert":
		$req = $_REQUEST["reqEntry"];
		if (strlen($req) == 0)
		{
			die("Your browser did not send a certificate request.");
		}
		# save the certificate request to a file
		$reqp=fopen($req_file,"w");
			fwrite($reqp,"-----BEGIN CERTIFICATE REQUEST-----\n");
			fwrite($reqp,$req);
			fwrite($reqp,"-----END CERTIFICATE REQUEST-----\n");
			fclose($reqp);

		$cmd = "$CA -batch -config $cnffile -extensions certificate_extensions "
			."$CACERT $CAKEY -in $req_file -out $result_file $DAYS 2>$ERRORFILE";
		$crcmd = "$CRL2PKCS7 -certfile $CAFILE -certfile $result_file "
			."-in $crlfile -out $pkcs7_file 2>>$ERRORFILE";

		system ($cmd,$rc);
		if ($rc != 0)
		{
			loggywoggy("Failure to make certificate with command\n$cmd.");
			die("Our certificate making process failed us.  We are sorry.  Try again?");
			die("Return code was $rc from our first command<BR>$cmd");
		}
		system ($crcmd,$rc);
		if ($rc == 0)
		{
			#Get the new certificate, strip its top and bottom lines, and remove new lines.
			#This is the way IE likes to see them.
			$certificate=file_get_contents($pkcs7_file);
			$cert=$certificate;
			$cert=substr($cert,22);
			$cert=substr($cert,0,-21);
			$cert=str_replace("\n","",$cert);
			$certificateid=$db->getOne("select nextval('certificate_certificateid_seq')");
			$query="insert into certificate (certificateid,signerid,serial_number,request,certificate,subjectid) values"
				." ($certificateid,".$signer["signerid"].",$count,'$req','$certificate',".$subject["subjectid"].")";
			if(pearcheck($db->query($query)))
			{
				$msgs.= "Unable to insert a certificate for transaction ".$transaction["transactionid"]. "using<BR>$query";
			}
			$page="done";
		}
		else
			die ("We could not complete the final step with<BR>$crcmd<BR>You will have to start over.");
		break;
	case "certheader":
?>
<!-- Use the Microsoft ActiveX control to install the certificate -->

<OBJECT  classid="clsid:127698E4-E730-4E5C-A2b1-21490A70C8A1"
    CODEBASE="xenroll.dll"
    id=IControl >
</OBJECT>

<SCRIPT LANGUAGE="JavaScript">
<!---
function InstallCertificate (subject, sessionid, cert)
{
	alert ("We are in the InstallCertificate function.");

	if( subject == "")
	{
		alert("We have lost your common name just as we were going to install the certificate.");
		return;
	}

	if( sessionid == "")
	{
		alert("We lost the session id just as we were going to install the certificate.");
		return;
	}

	if(cert == "")
	{
		alert("Somehow, we've lost your certificate between the server and here.");
		return;
	}

	alert("We are about to install the certificate.");
	result  = IControl.AcceptPKCS7(cert);
	alert(result);

	if(result == "")
	{
		var msg = "Attempt to install " + subject + " client certificate failed";
		alert(msg);
		return false;
	}
	else
	{
		var msg = subject + " client certificate installed";
		alert(msg);
	}
}
--->
</SCRIPT>
<?PHP
		echo "</HEAD>";
		echo "<BODY onLoad=\"InstallCertificate('".$_REQUEST["commonName"]."', '".$_REQUEST["sessionid"]."', '$cert');\">";
		break;
	default:
		break;
}
?>
