<?php


function no_admins () {
	global $db;

	/* see if there are any administrators set-up */
	$sql = "select vfs_user from vfs_users where administrator='1'";
	$result = $db->execute($sql);
	if($result->numTuples > 0) return 0;
	else return 1;
}


function authenticate_user() {
	global $PHP_AUTH_USER;

	/* authenticate the user */
	if(! $PHP_AUTH_USER) {
		// force user to authenticate
		authenticate_message ();
	}
	else {	
		// Check username and password against the database
		check_credentials();
	}
}




function authenticate_message () {

	Header("WWW-Authenticate: Basic realm=\"VFS\"");
	Header("HTTP/1.0 401 Unauthorized");
	print "You must authenticate to view this site\n";
	exit;	

}




function check_credentials() {
	global $db, $PHP_AUTH_USER, $PHP_AUTH_PW, $is_administrator;

	$sql = "select password, administrator from vfs_users where vfs_user='$PHP_AUTH_USER'";
	$result = $db->execute($sql);
	if($result->numTuples > 0) {
		$db_user_password = $result->getVal(0,0);
		$administrator = $result->getVal(0,1);
		if(function_exists("md5")) {
		    $password = md5($PHP_AUTH_PW);
		}
		else {
		    $password = $PHP_AUTH_PW;
		}
		if($result->getVal(0,0) != $password) {
			authenticate_message ();
		}
		else if($administrator == 't') $is_administrator = 1;
	}
	else authenticate_message ();
}




function first_time_setup() {
	global $db;

?>
<html>
<body bgcolor="#ffffff">
<div align="center"><h1>VFS - Virtual File System</h1></div>
<br>
<form action="add_admin.php3" method="POST">
<blockquote>
Welcome to the Virtual File System. To start using this system
you must enter a username and password for the system administrator
<br>
<br>
<table cellpadding="8">
<tr><td align="right">Username:</td><td><input type="text" name="username"><br><br></td></tr>
<tr><td align="right">Password:</td><td><input type="password" name="password1"></td></tr>
<tr><td align="right">Password Confirmation:</td><td><input type="password" name="password2"><br></td></tr>
</table>
<br>
<input type="hidden" name="sys_setup" value="true">
<input type="submit" name="submit" value="Submit">
</blockquote>
</form>
<br>
</body>
</html>
<?php
	exit;
}


$is_administrator = 0;
/* run these functions on loading this include file */
if(no_admins()) {
	/* the system hasn't been set-up yet */
	if(! $sys_setup) {
		first_time_setup();
	}
}
else {
	/* we have users no the system - try to authenticate */
authenticate_user();
}

?>
