<?

require_once('altauth_lib.php');

function init()
{
	$tmpl_file = "altauth_htaccess";

	# already initialized
	if (! file_exists($tmpl_file)) return;

	$path = preg_replace('/\/[^\/]+$/', '', $_SERVER['PHP_SELF']);

	// if there is no .htaccess_old then we create it

	if( ! file_exists('.htaccess_old') )
	{
		# create an empty .htpasswd unless exists
		$fh = fopen('.htpasswd', "a+")
			or die("FAILURE: cannot open/create .htpasswd file");
		fclose($fh);

		$fh = fopen('.htaccess_old', "w+")
			or die("FAILURE: cannot create .htaccess_old file");

		fwrite($fh,
			"AuthUserFile $_SERVER[DOCUMENT_ROOT]$path/.htpasswd\n" .
			"AuthName 'Members Only'\nAuthType Basic\nrequire valid-user\n"
		);
	
		fclose($fh);
	}

	// initialize our own .htaccess file

	$fh = fopen('.htaccess', "w+")
		or die("FAILURE: cannot create/rewrite .htaccess file. Possible permissions problem");

	foreach ( file($tmpl_file) as $line )
	{
		$line = preg_replace('/\/test22/', $path, $line);
		fwrite($fh, $line);
	}

	fclose($fh);

	unlink($tmpl_file);

	// initialize admin user record

	$admin_username = 'admin';
	$admin_passwd = 'admin';

	save_user($admin_username, $admin_passwd);

?>
	<center><b style='color:blue'>Protection has beed initialized<br><br>
	Here is your URL and access codes to the admin area (keep them safe!):</b>
	<table>
		<tr><td><b>URL:</b>&nbsp;</td><td><a href=<?=$path?>/altauth_adminarea.php>http://<?=$_SERVER[HTTP_HOST]?><?=$path?>/altauth_adminarea.php</a></td></tr>
		<tr><td><b>Username:</b>&nbsp;</td><td><?=$admin_username?></td></tr>
		<tr><td><b>Password:</b>&nbsp;</td><td><?=$admin_passwd?></td></tr>
	</table>
	</center><br><br>
<?
}

function login()
{
	$username = strtolower($_REQUEST['username']);
	$password = $_REQUEST['password'];

	// read passwd file

	foreach ( file(locate_passwd_file()) as $line )
	{
		preg_match("(.*)\:(.*)", chop($line), $regs);

		if ( strcasecmp($username, $regs[1]) ) continue;

		$password1 = crypt($password, $regs[2]);
		$password2 = md5($password);
		$password3 = crypt_apr1_md5($password, $regs[2]);

		if ( $password1 != $regs[2] && $password2 != $regs[2] && $password3 != $regs[2] ) continue;

		// IP restrict
		if (iprestrict($username) && ! is_admin($username))
		{
			header('Location: ' . preg_replace('/\/[^\/]+$/', '', $_SERVER['PHP_SELF']) . '/altauth.php?no_access=1');
			return;
		}

		// set cookie & session file
		$longlife = isset($_REQUEST['longlife']) ? 1 : 0;
		$uid = ($longlife ? 'longlife_' : '') . md5(uniqid(rand(),1));
		if ($longlife)
		{
			setcookie("altauth_uid", $uid, time() + 3600*24*30*3);
		}
		else
		{
			setcookie("altauth_uid", $uid);
		}
		setcookie("altauth_user", $username);

		$fd = fopen("_altauth/$uid", "w")
			or die("failed to open session file");
		fwrite($fd, '');
		fclose($fd);

		header("Location: ". $_REQUEST['return_url']);
	}
}

function logout()
{
	$uid = $_COOKIE['altauth_uid'];
	if ($uid)
		unlink("_altauth/$uid");
	setcookie("altauth_uid", '');
	setcookie("altauth_user", '');

	$afterLogoutUrl = '';
	$afterLogoutFile = 'altauth_afterlogout.txt';

	if (file_exists($afterLogoutFile))
	{
		$afterLogoutUrl = preg_replace('/\\s+/', '', implode('', file($afterLogoutFile)));
	}
	else
	{
		$afterLogoutUrl = preg_replace('/\/[^\/]+$/', '', $_SERVER['PHP_SELF']);
	}

	header("Location: $afterLogoutUrl");
}

function iprestrict($username)
{
	$cfg_file = 'altauth_iprestrict.txt';

	if ( ! file_exists($cfg_file) ) return 0;

	$ip_count = join('', file($cfg_file)) + 0;

	if ( ! $ip_count ) return 0;

	$username = strtolower($username);

	$userdb = load_userdb();

	if ( ! isset($userdb[$username]) )
		$userdb[$username]['ip'] = array();

	if (in_array($_SERVER['REMOTE_ADDR'], $userdb[$username]['ip']))
		return 0;

	if ( $ip_count <= count($userdb[$username]['ip']))
		return 1;

	array_push($userdb[$username]['ip'], $_SERVER['REMOTE_ADDR']);

	if ( ! $userdb[$username]['ip'][0] )
		array_shift($userdb[$username]['ip']);

	save_userdb($userdb);
}

function cleanup_session_dir()
{
	$dh = opendir('_altauth');
	if ( ! $dh ) die("session directory corrupted");

	while ( $file = readdir($dh) ) :
		if ($file == '.' || $file == '..') continue;
		$st_file = stat("_altauth/$file");
		$longlife = preg_match('/^longlife_/', $file) ? 1 : 0;
		if ( time() - $st_file[9] > 3600 * 24 * (1 + 89 * $longlife) ) unlink("_altauth/$file");
	endwhile;

	closedir($dh);
}

//---------------------------------------- M A I N --------------------------------------


	if ( ! is_writeable('_altauth') )
		mkdir('_altauth');

	if ( isset($_REQUEST['do_login']) )
	{
		login();
		$Message = '<center><b style="color:red">* Authorization failed</b></center><br>';
		include('altauth_loginscreen.php');
	}
	else if ( isset($_REQUEST['do_logout']) )
	{
		logout();
	}
	else if ( isset($_REQUEST['no_access']) )
	{
		if ( file_exists('altauth_noaccess.php') )
			include('altauth_noaccess.php');
		else
			print '<center><b style="color:red">You have exceeded the allowed number of IP addresses you to login from</b></center><br>';
	}
	else if (! isset($_REQUEST['return_url']) || preg_match('/altauth.php$/', $_REQUEST['return_url']))
	{
		// initialize script if it's called directly
		init();
	}
	else
	{
		// display the login screen if called with a "return_url" parameter
		cleanup_session_dir();
		include('altauth_loginscreen.php');
	}

	print_copyright();

?>
