<?php 

	if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
		header('WWW-Authenticate: Basic realm="My Realm"'); 
		header('HTTP/1.0 401 Unauthorized'); 
		include("login.html");
	} elseif ( isset($_SERVER['PHP_AUTH_USER']) &&  isset($_SERVER['PHP_AUTH_PW']) )
	{ 
		include("config.php"); 

### HACK BEGIN -- dont allow anything here until we get the database back up
			header('HTTP/1.0 401 Unauthorized'); 
			echo "Sorry, there is no username ".$username." with the specified password.<br>";
			echo "<a href=login.html>Try again</a>";
			exit; 
### HACK END
		require('sanitize.inc.php');
		$username = sanitize($_SERVER['PHP_AUTH_USER'],SQL);
		$password = sanitize($_SERVER['PHP_AUTH_PW'],SQL);


		// connect to the mysql server
		$link = mysql_connect($server, $db_user, $db_pass)
		or die ("Could not connect to mysql because ".mysql_error());

		// select the database
		mysql_select_db($database)
		or die ("Could not select database because ".mysql_error());

		$match = "select user_name from $table where user_name = '".$username."'
		and user_passwd = ENCRYPT('".$password."',user_salt);"; 

		$qry = mysql_query($match)
		or die ("Could not match data because ".mysql_error());
		$num_rows = mysql_num_rows($qry); 

		if ($num_rows <= 0) { 
			header('HTTP/1.0 401 Unauthorized'); 
			echo "Sorry, there is no username ".$username." with the specified password.<br>";
			echo "<a href=login.html>Try again</a>";
			exit; 
		} else {
			$url = "/mp3s/";
#			if (!headers_sent()) {
#				ob_end_clean();
#				header("Location: " . $url);
#			} 
			printf("<HTML>");
#			printf("<META http-equiv=\"Refresh\" content=\"0;url=%s\">", $url);
			printf("<BODY onload=\"try {self.location.href='%s' } catch(e) {}\">", $url, $url);
			echo "You are now logged in!<br>"; 
			printf("<a href=\"%s\">Redirect </a></BODY>",$url);
			printf("</HTML>"); 
		}
	} else { 
		header('HTTP/1.0 401 Unauthorized'); 
		echo "<p>You shall not pass!</p>"; 
	} 
?>
