<?
	/*
		Script that handle the download of a file -- Modelib website
		Romain Gaucher

		use: dl.php?file=URI
		use: dl.php
			> download page
			> links etc.
			> auto-package building ?
	*/
	if (!empty($_GET['file']))
	{

		// for to download the selected file
		$file = $_GET['file'];

		// test if the file exists
		if (!@file_exists($file))
		{
			echo "<html>\n<body>\n<h1>501</h1>\nError, the file cannot be downloaded <br />\n</body>\n</html>";
			return;
		}
		else
		{
			$file_extension = strtolower(substr(strrchr($file,"."),1));

			switch($file_extension)
			{
			  case "pdf": $ctype="application/pdf"; break;
			  case "exe": $ctype="application/octet-stream"; break;
			  case "zip": $ctype="application/zip"; break;
			  case "doc": $ctype="application/msword"; break;
			  case "xls": $ctype="application/vnd.ms-excel"; break;
			  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
			  case "gif": $ctype="image/gif"; break;
			  case "png": $ctype="image/png"; break;
			  case "jpeg":
			  case "jpg": $ctype="image/jpg"; break;
			  default: 
			  	$ctype="application/force-download";
			}


			$fp = @fopen("stats.dat","r");
			// read datas
			$value_str = fgets($fp);
			fclose($fp);
			$value = intval($value_str); $value++;
			$fp = @fopen("stats.dat","w");
			// read datas
			fputs($fp,$value);
			fclose($fp);

			header("Pragma: public"); // required
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Cache-Control: private",false); // required for certain browsers
			header("Content-Type: $ctype");
			header("Content-Disposition: attachment; filename=".basename($file).";" );
			header("Content-Transfer-Encoding: binary");
			header("Content-Length: ".filesize($file));
			readfile("$file");
			exit();
		}
	}
?>
