<?php

//////// C O N F I G ////////
$cfg_pass = "changeme";
$cfg_dir = "/etc/groove/";

error_reporting(E_ALL ^ E_NOTICE);
session_start();

if($_SESSION[file]) {
	
	// No whitespaces for filename in header...
	$file = explode("/", $_SESSION[file]);
	$file = strtr($file[count($file)-1], array(" " => "-"));
	
	// Tells the browser "Iam audio-content" & "Iam a download"
	header("Content-Type: audio/mpeg");
	header("Content-Disposition: attachment; filename=".$file);
	
	// Reads the file and sends it to browser
	readfile($_SESSION[file]);
	
	// DEBUG
//	echo $_SESSION[file];
//	echo "<br />";
//	print_r($file);
	
	// Remove temporary file
	unlink($_SESSION[file]);
	
	$_SESSION[file] = false;
	die();
}


?>
<html>
<body>

<?php

if($_POST) {
	
	// Someone tries to login...
	if($_POST[password] == $cfg_pass)
		$_SESSION[logged_in] = true;
	else
		echo "Sorry, but: nope..";
}

if(!$_SESSION[logged_in]) {
?>
	<form action="?" method="post">
		<input type="password" name="password" />
		<input type="submit" />
	</form>
	<?php
	die();
}

?>
You are logged in!<br />
<form action="?" method="get">
	Query: <input type="text" name="search" value="<?php echo $_GET[search]; ?>" />&nbsp;
<?php if($_GET[search]):
	?>
	Enter number:
	<input type="text" name="num" value="" />
	<?php
endif;

?>

<input type="submit" />
<br /><br />
<?php

if($_GET[search]):

$search = htmlspecialchars(strtr($_GET[search], array("'" => "", "\"" => "")));
$num = htmlspecialchars(strtr($_GET[num], array("'" => "", "\"" => "")));

?>
<pre>
<?php

if($_GET[num] != "") {
	passthru("cd $cfg_dir && java -jar SciLorsJGroovesharkDownloader.jar /c /d \"$search\" $num", $ret);
	$ite = new RecursiveDirectoryIterator($cfg_dir);

	foreach(new RecursiveIteratorIterator($ite) as $filename=>$cur) {
		$pathinfo = pathinfo($filename);
		if($pathinfo[extension] == "mp3") {
		   $_SESSION[file] = $filename;
		   die('<meta http-equiv="refresh" content="0; url=index.php">');
		}
	}
} else 
	passthru("cd $cfg_dir && java -jar SciLorsJGroovesharkDownloader.jar /c /l \"$search\"", $ret);
?>
</pre>
<?php


?>
</pre>
<?php
endif;
?>
</body>
</html>