<?php session_start(); ?>
<?php if (@$HTTP_SESSION_VARS["etat_log"] <> "connecte") header("Location: ../index.php") ?>
<?php
	include_once ("../inc/config.inc.php");
	include_once ("../inc/fic.inc.php");

  /*****************************************************************
   **                                                             **
   **             ___________________________________             **
   **            |                                   |            **
   **            |   [SimonStenhouse.NET] Download   |            **
   **            |___________________________________|            **
   **                                                             **
   **                                                             **
   **  ---------------------------------------------------------  **
   **                                                             **
   **  Author:  Simon Stenhouse                                   **
   **  Date:    26.11.2005                                        **
   **  Version: 1.1                                               **
   **  Website: http://www.simonstenhouse.net/                    **
   **  License: http://www.gnu.org/licenses/gpl.txt               **
   **                                                             **
   **  ---------------------------------------------------------  **
   **                                                             **
   **  Requirements:                                              **
   **                                                             **
   **   - PHP 4 >= 4.3.0 or PHP 5                                 **
   **                                                             **
   **  Features:                                                  **
   **                                                             **
   **   - Easy Installation                                       **
   **   - Supports unlimited file types                           **
   **   - Prevents the leeching of your files                     **
   **   - Hides the actual location of your files                 **
   **   - Logs all downloads as well as leech and hack attempts   **
   **   - Show the number of times a file has been downloaded     **
   **   - Show the size of a file in a user friendly way          **
   **   - Flat file system (no database needed)                   **
   **                                                             **
   **  ---------------------------------------------------------  **
   **                                                             **
   **  Installation:                                              **
   **                                                             **
   **   1 Open download.php and adjust the settings in the        **
   **     configuration area as needed.                           **
   **                                                             **
   **   2 Upload download.php to your sites root directory.       **
   **                                                             **
   **   3 Open leech.php, modify it to suit your site, and        **
   **     then upload it to the root of your site.                **
   **                                                             **
   **   4 Open hack.php, modify it to suit your site, and         **
   **     then upload it to the root of your site.                **
   **                                                             **
   **   5 Create a directory named 'data' off of the root         **
   **     and then CHMOD 777 that directory.                      **
   **                                                             **
   **   5 Create a directory named 'hidden' off of the root.      **
   **     NOTE: I advise you to choose a different name for       **
   **     this directory, which is where your downloadable        **
   **     files will hide, and adjust the relevant setting        **
   **     in the configuration area.                              **
   **                                                             **
   **  ---------------------------------------------------------  **
   **                                                             **
   **  Resulting Structure:                                       **
   **                                                             **
   **   /download.php                                             **
   **   /leech.php                                                **
   **   /hack.php                                                 **
   **   /data/                                                    **
   **   /hidden/                                                  **
   **                                                             **
   **  ---------------------------------------------------------  **
   **                                                             **
   **  Usage example:                                             **
   **                                                             **
   **   <a href="download.php?file.zip">Download</a>              **
   **   File Size: <?php echo download_size('file.zip'); ?>       **
   **   Download Count: <?php echo download_count('file.zip'); ?> **
   **                                                             **
   **   See the included 'example.php' file for a more detailed   **
   **   example.                                                  **
   **                                                             **
   **  ---------------------------------------------------------  **
   **                                                             **
   **  History:                                                   **
   **                                                             **
   **   1.1 - 24.12.2005                                          **
   **                                                             **
   **         Improved: download_count() and download_size()      **
   **                                                             **
   **          Changed these functions so they return their       **
   **          result instead of echo'ing them. Users can now     **
   **          do things like adding the download count of        **
   **          multiple files to get an overall total.            **
   **                                                             **
   **   1.0 - 26.11.2005                                          **
   **                                                             **
   **         Full Release with all features present.             **
   **                                                             **
   *****************************************************************/




  /*****************************************************************
   **                                                             **
   **                  C O N F I G U R A T I O N                  **
   **                                                             **
   *****************************************************************/


// PATHS
// -----------------------------------------------------------------

// Root path of your site
$root = $_SERVER['DOCUMENT_ROOT'] . '/';

// Path to downloadable files (will not be revealed to users so they will never know your files real address)
$hidden = $url_tfc;
// $hidden = 'maint/down/fictec/';

// Path to data files
// NOTE: This directory must have been CHMOD'd to 777
$data = $url_tfl;
// $data = 'maint/down/data/';

// Path to and name of your leech warning page
$leech = REP.'/down/leech.php';

// Path to and name of your hack warning page
$hack = REP.'/down/hack.php';




  /*****************************************************************
   **                                                             **
   **                      F U N C T I O N S                      **
   **                                                             **
   *****************************************************************/


// PURPOSE:        Check whether a file exists.  If it doesn't, the file is created.
// PARAMS:        [string] $file - The full path and name of a file
// RETURN:        [bool] - True if file exists | False if file doesn't exist but gets created
function download_check_file($file)
{
        if (!file_exists($file))
        {
                $handle = fopen($file, "w");
                fclose($handle);
                chmod($file, 0666);

                return false;
        }

        return true;
}


// PURPOSE:        To return the number of times a file was downloaded.
// PARAMS:        [string] $file - The name of a file
// RETURN:        [echo] Number of times the file was downloaded
function download_count($file) // Laissé pour les fichiers chargé en direct (FTP, SSH, ou autre)
{
        global $root, $hidden, $file_download;
        $count = 0;

        if (file_exists($root . $hidden . $file))
        {
                if (file_exists($file_download))
                {
                        // Read data from download file into an array
                        $download = explode("\n", file_get_contents($file_download));

                        // Loop through the downloadarray
                        foreach ($download as $line)
                        {
                                // Split and store array values
                                list($stored_file, $stored_ip, $stored_time, $stored_day, $stored_month, $stored_year) = explode("|", $line);

                                // Count how many times the file was downloaded
                                if ($file == $stored_file)
                                {
                                        $count++;
                                }
                        }
                }
        }

        return $count;
}


// 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, $hidden;
        $file = $root . $hidden . $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";
        }
}


// Modified by Galawa
// PURPOSE:        To see if there has been some leeches
// PARAMS:        [string] $file - The name of the DAT leeches file
// RETURN:        [echo] boolean (file size > 0)
function download_exist_leech()
{
        global $file_leech;
        $exists = FALSE;

		if (file_exists($file_leech))
		{
			if (filesize($file_leech) > 0)
			{
				$exists = TRUE;
			}
		}

        return $exists;
}


// Modified by Galawa
// PURPOSE:        To see if there has been some hacks
// PARAMS:        [string] $file - The name of the DAT hacks file
// RETURN:        [echo] boolean (file size > 0)
function download_exist_hack()
{
        global $file_hack;
        $exists = FALSE;

		if (file_exists($file_hack))
		{
			if (filesize($file_hack) > 0)
				$exists = TRUE;
		}

        return $exists;
}


  /*****************************************************************
   **                                                             **
   **           I N I T I A L I S E   V A R I A B L E S           **
   **                                                             **
   *****************************************************************/

// DATA FILES
$file_download = $root . $data . 'download.dat';
$file_leech    = $root . $data . 'leech.dat';
$file_hack     = $root . $data . 'hack.dat';

// VARIABLES
$file          = $_SERVER['QUERY_STRING'];
if (@$HTTP_SESSION_VARS["niv_log"] == 1)
	$file_real = $url_gfc."/clients/".strtolower(@$HTTP_SESSION_VARS["code_log"])."/".$file;
else
	$file_real     = $url_gfc."/".$file;
$ip            = $_SERVER['REMOTE_ADDR'];

$time          = time();
$day           = date("j");
$month         = date("n");
$year          = date("Y");

// Determine domain name of your site
$host          = (substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.') ? substr($_SERVER['HTTP_HOST'], 4, strlen($_SERVER['HTTP_HOST'])) : $_SERVER['HTTP_HOST'];

// Determine domain name of referer site
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                         **
   **                                                             **
   *****************************************************************/


// Check to see if the download script was called
if (basename($_SERVER['PHP_SELF']) == 'download.php')
{
        if ($_SERVER['QUERY_STRING'] != null)
        {
                // Create log files if they don't exist
                download_check_file($file_download);
                download_check_file($file_leech);
                download_check_file($file_hack);

                // HACK ATTEMPT CHECK
                // Make sure the request isn't escaping to another directory
                if (substr($file, 0, 1) == '.')
                {
                        if ($referer == null)
                        {
                                $referer = "none";
                        }
                        $handle_hack = fopen($file_hack, "a");
                        flock($handle_hack, LOCK_EX);
                        fwrite($handle_hack, "$file|$ip|$time|$day|$month|$year|$referer\n");
                        fclose($handle_hack);

                        // Hack attempt made so redirect to hack warning page (if found)
                        if (file_exists($root . $hack))
                        {
                                header('Location: http://' . $host . '/' . $hack);
                        }
                        // Otherwise cause a 403 error (Forbidden)
                        else
                        {
                                header('Location: http://' . $host . '/403');
                        }

                        die();
                }

                // LEECH ATTEMPT CHECK
                // If the domain name of the referer does not match the
                // the domain name of your site, then someone has tried
                // to leech one of your files!
                if ($referer != $host)
                {
                        if ($referer == null)
                        {
                                $referer = "none";
                        }
                        $handle_leech = fopen($file_leech, "a");
                        flock($handle_leech, LOCK_EX);
                        fwrite($handle_leech, "$file|$ip|$time|$day|$month|$year|$referer\n");
                        fclose($handle_leech);

                        // Leech attempt made so redirect to leech warning page (if found)
                        if (file_exists($root . $leech))
                        {
                                header('Location: http://' . $host . '/' . $leech);
                        }
                        // Otherwise cause a 403 error (Forbidden)
                        else
                        {
                                header('Location: http://' . $host . '/403');
                        }

                        die();
                }

                // If requested file exists
                if (file_exists($file_real))
                {
                        // Get extension of requested file
                        $extension = strtolower(substr(strrchr($file, "."), 1));

                        // Determine correct MIME type
                        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;
                        }

                        // Log the download

						maj_nbtel_enr_fic($file_real);
						
						
                        $handle_download = fopen($file_download, "a");
                        flock($handle_download, LOCK_EX);
                        fwrite($handle_download, "$file|$ip|$time|$day|$month|$year\n");
                        fclose($handle_download);

                        // Send file for download
                        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=" . $file . ";");
                        header("Content-Transfer-Encoding: binary");
                        header("Content-Length: " . filesize($file_real));
                        @readfile($file_real);
                }
                else
                {
                        // Requested file does not exist so cause a 404 error (File not found)
                        header('Location: http://' . $host . '/404');

                        die();
                }
        }
}
?>