<?php 

// Routine de download dérivée de l'excellent script de Simon Stenhouse (http://www.simonstenhouse.net)

session_start();
if (@$_SESSION["etat_log"] <> "connecte") header("Location: ../index.php");

include_once("../inc/config.inc.php");
include_once("../inc/fic_fici.inc.php");

// Chemin vers la page d'avertissement en cas de leech
$leech = REP.'/leech.php';

// Chemin vers la page d'avertissement en cas de hack
$hack = REP.'/hack.php';

// Chemin vers la page d'avertissement en cas de problème
$pbm = REP.'/pbm.php';

// Vitesse de téléchargement (en KB's par seconde)
$speed = 24;

// PURPOSE:        To return the size of a file in a user friendly format.
// PARAMS:        [string] $file - The name of a file
// RETURN:        [echo] - Size of file
function download_size($fichier)
{
	global $root, $url_tfc;
	$file = $root . $url_tfc . $fichier;
	
	if (file_exists($file))
	{
			$size = filesize($file);

			$kb = 1024;         // Kilobyte
			$mb = 1024 * $kb;   // Megabyte
			$gb = 1024 * $mb;   // Gigabyte
			$tb = 1024 * $gb;   // Terabyte

			if($size < $kb)
			{
					return number_format($size) . " B";
			}
			elseif ($size < $mb)
			{
					return number_format(round($size / $kb, 2)) . " KB";
			}
			elseif ($size < $gb)
			{
					return number_format(round($size / $mb, 2)) . " MB";
			}
			elseif ($size < $tb)
			{
					return number_format(round($size / $gb, 2)) . " GB";
			}
			else
			{
					return number_format(round($size / $tb, 2)) . " TB";
			}
	}
	else
	{
			return "0 B";
	}
}


// VARIABLES
$file = $_SERVER['QUERY_STRING'];
if (@$_SESSION["niv_log"] == 1)
	$file_real = $url_gfc."/clients/".strtolower(@$_SESSION["code_log"])."/".$file;
else
	$file_real = $url_gfc."/".$file;
$ip = $_SERVER['REMOTE_ADDR'];
$time = date("H:i:s");

// On calcule le nom de votre site
$host = (substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.') ? substr($_SERVER['HTTP_HOST'], 4, strlen($_SERVER['HTTP_HOST'])) : $_SERVER['HTTP_HOST'];

// On calcule le nom du lien référant
preg_match("/^(http:\/\/)?([^\/]+)/i", $_SERVER['HTTP_REFERER'], $matches);
$referer = (substr($matches[2], 0, 4) == 'www.') ? substr($matches[2], 4, strlen($matches[2])) : $matches[2];


/*****************************************************************
**                                                             **
**                         S C R I P T                         **
**                                                             **
*****************************************************************/


// Vérification si le script de téléchargement a été appelé
if (basename($_SERVER['PHP_SELF']) == 'download.php')
{
	if ($_SERVER['QUERY_STRING'] != null)
	{
		// Analyse des tentatives de Hack
		// On vérifie que la requête n'essaye pas de passer sur un autre répertoire
		if (substr($file, 0, 1) == '.' || strpos($file, '..') > 0)
		{
			if ($referer == null)
			{
				$referer = "none";
			}
			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);
			$rech = "INSERT INTO " .TBFICLOG;
			$rech.= " (ficlog_date,ficlog_heure,ficlog_ip,ficlog_ref,ficlog_fic,ficlog_type)";
			$rech.= " VALUES";
			$rech.= " ('$datea','$time','$ip','$referer','$file','1')";
			$rs = mysql_query($rech) or die(mysql_error());
			mysql_close($conn);

			// On renvoie vers la page de Hack (si elle existe)
			if (file_exists($root . $hack))
			{
				header('Location: http://' . $host . '/' . $hack);
			}
			// Si elle n'existe pas, erreur 403 (Forbidden)
			else
			{
				header('Location: http://' . $host . '/403');
			}
			
			die();
		}

		// Analyse des tentatives de leech
		// Si le nom de domaine du site référent ne correspond pas au nom de domaine de votre site
		if ($referer != $host OR $referer==null)
		{
			if ($referer == null)
			{
				$referer = "none";
			}

			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);
			$rech = "INSERT INTO " .TBFICLOG;
			$rech.= " (ficlog_date,ficlog_heure,ficlog_ip,ficlog_ref,ficlog_fic,ficlog_type)";
			$rech.= " VALUES";
			$rech.= " ('$datea','$time','$ip','$referer','$file','2')";
			$rs = mysql_query($rech) or die(mysql_error());
			mysql_close($conn);

			// On renvoie vers la page de Leech (si elle existe)
			if (file_exists($root . $leech))
			{
				header('Location: http://' . $host . '/' . $leech);
			}
			// Si elle n'existe pas, erreur 403 (Forbidden)
			else
			{
				header('Location: http://' . $host . '/403');
			}

			die();
		}

		// Si le fichier demandé existe
		if (file_exists($file_real))
		{
			// On récupère l'extension du fichier demandé
			$extension = strtolower(substr(strrchr($file, "."), 1));

			// On détermine le type MIME
			switch($extension)
			{
				case "asf":     $type = "video/x-ms-asf";                break;
				case "avi":     $type = "video/x-msvideo";               break;
				case "bin":     $type = "application/octet-stream";      break;
				case "bmp":     $type = "image/bmp";                     break;
				case "cgi":     $type = "magnus-internal/cgi";           break;
				case "css":     $type = "text/css";                      break;
				case "dcr":     $type = "application/x-director";        break;
				case "dxr":     $type = "application/x-director";        break;
				case "dll":     $type = "application/octet-stream";      break;
				case "doc":     $type = "application/msword";            break;
				case "exe":     $type = "application/octet-stream";      break;
				case "gif":     $type = "image/gif";                     break;
				case "gtar":    $type = "application/x-gtar";            break;
				case "gz":      $type = "application/gzip";              break;
				case "htm":     $type = "text/html";                     break;
				case "html":    $type = "text/html";                     break;
				case "iso":     $type = "application/octet-stream";      break;
				case "jar":     $type = "application/java-archive";      break;
				case "java":    $type = "text/x-java-source";            break;
				case "jnlp":    $type = "application/x-java-jnlp-file";  break;
				case "js":      $type = "application/x-javascript";      break;
				case "jpg":     $type = "image/jpg";                     break;
				case "jpe":     $type = "image/jpg";                     break;
				case "jpeg":    $type = "image/jpg";                     break;
				case "lzh":     $type = "application/octet-stream";      break;
				case "mdb":     $type = "application/mdb";               break;
				case "mid":     $type = "audio/x-midi";                  break;
				case "midi":    $type = "audio/x-midi";                  break;
				case "mov":     $type = "video/quicktime";               break;
				case "mp2":     $type = "audio/x-mpeg";                  break;
				case "mp3":     $type = "audio/mpeg";                    break;
				case "mpg":     $type = "video/mpeg";                    break;
				case "mpe":     $type = "video/mpeg";                    break;
				case "mpeg":    $type = "video/mpeg";                    break;
				case "pdf":     $type = "application/pdf";               break;
				case "php":     $type = "application/x-httpd-php";       break;
				case "php3":    $type = "application/x-httpd-php3";      break;
				case "php4":    $type = "application/x-httpd-php";       break;
				case "png":     $type = "image/png";                     break;
				case "ppt":     $type = "application/mspowerpoint";      break;
				case "qt":      $type = "video/quicktime";               break;
				case "qti":     $type = "image/x-quicktime";             break;
				case "rar":     $type = "encoding/x-compress";           break;
				case "ra":      $type = "audio/x-pn-realaudio";          break;
				case "rm":      $type = "audio/x-pn-realaudio";          break;
				case "ram":     $type = "audio/x-pn-realaudio";          break;
				case "rtf":     $type = "application/rtf";               break;
				case "swa":     $type = "application/x-director";        break;
				case "swf":     $type = "application/x-shockwave-flash"; break;
				case "tar":     $type = "application/x-tar";             break;
				case "tgz":     $type = "application/gzip";              break;
				case "tif":     $type = "image/tiff";                    break;
				case "tiff":    $type = "image/tiff";                    break;
				case "torrent": $type = "application/x-bittorrent";      break;
				case "txt":     $type = "text/plain";                    break;
				case "wav":     $type = "audio/wav";                     break;
				case "wma":     $type = "audio/x-ms-wma";                break;
				case "wmv":     $type = "video/x-ms-wmv";                break;
				case "xls":     $type = "application/xls";               break;
				case "xml":     $type = "application/xml";               break;
				case "7z":      $type = "application/x-compress";        break;
				case "zip":     $type = "application/x-zip-compressed";  break;

				default:        $type = "application/force-download";    break;
			}

			// Correction bug IE [0]
			$header_file = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ? preg_replace('/\./', '%2e', $file, substr_count($file, '.') - 1) : $file;
			
			// Entêtes
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Cache-Control: public", false);
			header("Content-Description: File Transfer");
			header("Content-Type: " . $type);
			header("Accept-Ranges: bytes");
			header("Content-Disposition: attachment; filename=\"" . $header_file . "\";");
			header("Content-Transfer-Encoding: binary");
			header("Content-Length: " . filesize($file_real));

			// Envoi du fichier à télécharger
			@readfile($file_real);
			/*
			if ($stream = fopen($file_real, 'rb'))
			{
				while(!feof($stream) && connection_status() == 0)
				{
					print(fread($stream, $speed));
					flush();
					sleep(1);
				}

				fclose($stream);
			}
			*/

			// MAJ du log
			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);
			$rech = "INSERT INTO " .TBFICLOG;
			$rech.= " (ficlog_date,ficlog_heure,ficlog_ip,ficlog_ref,ficlog_fic,ficlog_type)";
			$rech.= " VALUES";
			$rech.= " ('$datea','$time','$ip','$referer','$file','0')";
			$rs = mysql_query($rech) or die(mysql_error());
			mysql_close($conn);

			// MAJ du nombre d'enregistrements
			maj_nbtel_enr_fic($file_real);
		}
		else
		{
			if ($referer == null)
			{
				$referer = "none";
			}

			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);
			$rech = "INSERT INTO " .TBFICLOG;
			$rech.= " (ficlog_date,ficlog_heure,ficlog_ip,ficlog_ref,ficlog_fic,ficlog_type)";
			$rech.= " VALUES";
			$rech.= " ('$datea','$time','$ip','$referer','$file','3')";
			$rs = mysql_query($rech) or die(mysql_error());
			mysql_close($conn);

			// On renvoie vers la page de problème (si elle existe)
			if (file_exists($root . $pbm))
			{
				header('Location: http://' . $host . '/' . $pbm);
			}
			// Si elle n'existe pas, erreur 403 (Forbidden)
			else
			{
				header('Location: http://' . $host . '/403');
			}
			

			die();
		}
	}
}
?>