<?PHP
#The includer for the top level directory of the authentrus enrollment site
$allsites="/var/www/sites/allsites";
$common_folder=".";
require_once("$allsites/.htfunctions.inc.php");
###require_once("$common_folder/.htsite.inc.php");
$site_name="Tabelio Officer's Page";
$site_url=$_SERVER["SERVER_NAME"];
$logfile="/var/log/httpd/$site_url";
$logdirectory=".";
$logfilename="log";
define('SCRIPTFOLDER',".");
$certs_dir=HARDTOGET."webvivos";

##echo "<P>The host name of $HTTP_HOST gives us a live of $live.</P>";

require_once "DB.php";

if ($live == 1)
{
	$PKH_debug=DEBUG_FILE_WARN|DEBUG_FILE_ERROR|DEBUG_FILE_LOG;
}
else
{
	$PKH_debug=DEBUG_PAGE_PROGRESS|DEBUG_PAGE_WARN|DEBUG_FILE_WARN|DEBUG_FILE_PROGRESS
		|DEBUG_PAGE_ERROR|DEBUG_FILE_ERROR|DEBUG_PAGE_LOG|DEBUG_FILE_LOG;
}
$dsn["phptype"]="pgsql";
$dsn["username"]="authentrus";
$dsn["password"]="An apple a day uses Safari";
#$dsn["hostspec"]="localhost";
$dsn["database"]="authentrus";
$dsn["port"]="5432";

function addMessage($msg)
{
	return "<BR>$msg";
}
$msgs="";

function addError($msg)
{
	return "<BR>$msg";
}
$errors="";

function program_fault($message)
{
	echo "<BR><FONT color=red size=+3>$message</FONT>";
}

#For loggywoggy
if (!isset($logdirectory)) $logdirectory=".";
if (!isset($logfilename)) $logfilename="log";
if (!function_exists('byebye'))
{
function byebye($msg)
{
	global $logwogp;
	if (function_exists('error_get_last'))
	{
		if (($last=error_get_last()))
		{
			global $file;
			loggywoggy("The last error on $file was ".print_r($last,TRUE));
		}
	}
	if (isset($logwogp))
	{
		loggywoggy("Leaving $msg.\n\n");
		fclose($logwogp);
	}
}
}

if (!function_exists('loggywoggy'))
{
function loggywoggy($msg)
{
	global $logwogp,$surferid;
	if (!isset($logwogp))
	{
		global $logdirectory,$logfilename;
		$logwogp=fopen("$logdirectory/$logfilename","a");
		register_shutdown_function("byebye",$_SERVER["PHP_SELF"]);
	}
	fwrite($logwogp,date("d M Y-H:i:s-")."$surferid-".print_r($msg,TRUE)."\n");
	return;
}
}
if (!function_exists('buggywuggy'))
{
	function buggywuggy($msg)
	{
		loggywoggy($msg);
	}
}

function menues()
{
	$nlinks=5;
	$width=100/$nlinks;
	$urllet="<A href=$PHP_SELF?display=";
	$a="<TR>"
		."<TD width=$width% align=center>$urllet"."me>View/Edit my data</A></TD>"
		."<TD width=$width% align=center>$urllet"."enroll>Enroll someone</A></TD>"
		."<TD width=$width% align=center>$urllet"."correct>Correct a previous enrollee</A></TD>"
		."<TD width=$width% align=center>$urllet"."newsigner>Add a signing certificate</A></TD>"
		."</TR>";
	return $a;
}
function page_bottom()
{
	global $copyrighter;
	$a="</TD></TR>\n";
	$a.=menues();
	$a.="<TR><TD colspan=6 align=center>Copyright &copy; ".thisyear(2005)." by $copyrighter</TD></TR>";
	$a.="</TABLE>";
	echo $a;
}
function byebyebye()
{
	echo page_bottom();
}
function page_top($site_name="Osmio Address Book",$display="")
{
	$a="<HTML><HEAD><TITLE>$site_name</TITLE>";
	if ((strlen($display) > 0) && file_exists (SCRIPTFOLDER."/$display.js"))
		$a.="<SCRIPT language=javascript src='".SCRIPTFOLDER."/$display.js'></SCRIPT>";
	$a.="</HEAD><BODY>";
	$a.="<TABLE>";
	$a.=menues();
	$a.="<TR><TD colspan=6>\n";
	register_shutdown_function('byebyebye');
	return $a;
}
function formTag($tag)
{
	return "<TD align=right>$tag:</TD>";
}
########################END OF SITE-SPECIFIC INFORMATION

if (pearcheck($db =& DB::connect($dsn, $options)))
        die ("We are having trouble accessing our database.  Please come back a bit later.");
$db->setFetchMode(DB_FETCHMODE_ASSOC);

#Start off with a certificate check

if(isset($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on"))
{
	if (isset($_SERVER["SSL_CLIENT_CERT"])) 
	{
		$inserial=hexdec($_SERVER["SSL_CLIENT_M_SERIAL"]);
		$incert=$_SERVER["SSL_CLIENT_CERT"];
		$query="select * from officer where serial_number=$inserial";
		if (pearcheck($res=$db->query($query)))
		{
			loggywoggy ("Error looking up officer using<BR>$query");
			die("Sorry, we can't convince our database to look for you.");
		}
		$n=count($res);
		while ($surfer=$res->fetchRow())
		{
			if (($surfer["certificate"] == $incert)||(($surfer["certificate"]."\n") == $incert))
			{
				$surferid=$surfer["officerid"];
				$name=$surfer["common_name"];
				loggywoggy("Officer $surferid, ".make_name($surfer)." has just arrived from ".$_SERVER["REMOTE_ADDR"].".");
				break;
			}
			else
			{
				loggywoggy("Incoming certificate of length ".strlen($incert).",\n<BR>$incert\n<BR>does not match database certificate ".$surfer["certificateid"]." of length ".strlen($surfer["certificate"]).",\n<BR>".$surfer["certificate"]);
			}
		}
		if (!isset($surferid))
		{
			#####Look for previous attempts
			$query="select * from bad_officer where serial_number=$inserial";
			if (pearcheck($res=$db->query($query)))
			{
				#echo "The attempt to find the bad certificate failed.";
				buggywuggy("The attempt to find the bad certificate failed with<BR>$query");
			}
			else
			{
				while ($baddy=$res->fetchRow())
				{
					if ($baddy["certificate"] == $incert)
					{
						$attempts=$baddy["attempts"];
						echo "You have already tried "
							.(($attempts > 1)?
								($baddy["attempts"]." times since ".$baddy["first"].".")
								:("once before."))
							."  You still haven't been approved for admission.";
						$attempts++;
						$query="update bad_officer set attempts=$attempts,last=now() "
							."where bad_officerid=".$baddy["bad_officerid"];
						$db->query($query);
						die("Please talk to your sponsor.");
					}
				}
			}
			$query="insert into bad_officer(common_name,serial_number,certificate) "
				."values ('".$_SERVER["SSL_CLIENT_S_DN_CN"]."',$inserial,'$incert')";
			if(pearcheck($db->query($query)))
			{
				loggywoggy("Could not insert bad certificate with<BR>$query");
			}
			else
			{
				loggywoggy("Just inserted a bad certificate.");
			}
			die("<BR>We did not find your certificate in our records.");
		}
	}
	else
	{
		include ("$common_folder/nocert.php");
	}
}
else
{
	include ("$common_folder/nohttps.php");
}
?>