<?php

include("../functions.php");

$server = "http://media.tasbeha.org" ;

session_start();

// ********** CONFIG ***********
$limit = 20 ;


if (isset($_GET['gd']))
  $g = $_GET['gd'] ;
if (!isset($g)){
  echo "Please visit Tasbeha.org to download media" ;
  exit ;
} else {
  $fullPath = getcwd()."/".$g ;
}
$link = mysql_connect('localhost', 'kplaylist', "kplaylist") or 
		die('Could not connect to database. Please e-mail webmaster@tasbeha.org with this error.'); 

mysql_select_db('kplaylist', $link) or die ('Can\'t use db : ' . mysql_error());

//$username = loggedIn() ;

$p = $_GET['p'] ;
list($id,$md5) = explode(".",$p) ;
if (md5($id."|tasbeha555")==$md5){
  $bypass = 1 ;
}


$ip = GetIP() ;
$sql = "INSERT IGNORE INTO download_log (`file`, `last_ip`, `agent`, `lastupdated`) VALUES ('$g','$ip','$HTTP_USER_AGENT', NOW())" ;
mysql_query($sql) ;


if ($fd = @fopen ($fullPath, "rb")) {
	$fsize    = filesize($fullPath);
	$fname    = basename ($fullPath);

	$url = "$server/mp3/$g" ; 
	header("Location: $url") ;
	die();

	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
	header("Content-Type: audio/mpeg");
	header("Content-Disposition: attachment; filename=".$fname);
	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ".$fsize);

	fpassthru($fd);
} else {
	  echo "<h1>File Not Found</h1>We are sorry, this file was not found.<br>
		If this is a new a file, please try again in a few hours." ;
}	
/*
	} else {
		header("HTTP/1.0 403 Forbidden");
		printHeader("Download limit exceeded...") ;
		echo "Dear $username,<p>" ;
		echo "You have exceeded your download limit per day.<p>
				Download limits are enforced to sustain the speed of Tasbeha.org with the amount of resources we have.<p>
			  We urge you to consider <a href=\"http://www.copticchurch.net/donate/\"><b>making a donation</b></a> to this ministry to allow us to support more users and downloads." ;
	  exit;
	}
*/

function allowedtoDownload($username,$g){
	global $limit, $_GET, $HTTP_USER_AGENT;
	$retry_max = 2 ;
	$dl = 0 ;
	$bypass = $_GET['bypass'] ;

	$today = date("m")."-".date("d") ;

	$sql_s = "SELECT monthday, download_count, download_limit FROM member_downloads WHERE member_name='$username'" ;
	$res = mysql_query($sql_s) or die(mysql_error()) ;
	if (mysql_num_rows($res)>0){
		$row = mysql_fetch_array($res) ;
		extract($row) ;
		$dl = 0 ;
		if ($monthday==$today){	// Downloaded today already
			// Download Retry?
			$sqld= "SELECT * 
					FROM `download_log` WHERE `member_name`='$username' AND file='$g' AND
						DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= `lastupdated`" ;
			$res_dupe = mysql_query($sqld) or die(mysql_error()) ;
			if (mysql_num_rows($res_dupe)>0){ // Retry Download, let them in

				$d_row = mysql_fetch_array($res_dupe) ;
				$d_id = $d_row["id"] ;
				$retry_count = $d_row["retry_count"] ;
				$sql_retry = "UPDATE `download_log` SET retry_count=retry_count+1 WHERE id='$d_id'" ;
				mysql_query($sql_retry) or die(mysql_error());

				if ($retry_count<$retry_max){
					$dl = 1 ;
					$dl_count = $download_count ;
					$retry = 1;
				}

			} else if ($download_count < $download_limit){	// still below limit
				$dl = 1 ;
				$dl_count = $download_count+1 ;
			} else {
				$dl = 0 ;		// hit limit
				$dl_count = $download_count ;
			}
		} else {	// Didn't download today
			$dl = 1 ;
			$dl_count = 1 ;
			if ($download_limit < 25) { /* Not a hookup */
				// Set to new daily limit in config
				$download_limit = $limit ;
			}
		}
	} else {	// Not in table, never downloaded anything before
		$download_limit = $limit ;
		$sql = "INSERT INTO member_downloads (member_name, download_limit) VALUES ('$username',$download_limit)" ;
		mysql_query($sql) ;

		$dl = 1 ;
		$dl_count = 1 ;
	}

	if ($retry_count>=$retry_max){
		header("HTTP/1.0 403 Forbidden");
		printHeader("Number of retries exceeded...") ;
		echo "Dear $username,<p>" ;
		$max = $retry_max + 1 ;
		echo "You have attempted to download the same file over $max times in one day. This is not allowed as to keep our 
			resources available for all users. If you are using a download accelerator, please do not use it on our site." ;
		exit;
	}

	if ($dl==1 || $bypass!=0){ //$p: podcast download
		$ip = GetIP() ;		
		// Track # downloaded today
		$sql = "UPDATE member_downloads
			SET download_count=$dl_count, monthday='$today', 
				total_downloads=(total_downloads+1),
				`last_ip`='$ip', download_limit='$download_limit'
			WHERE member_name='$username'" ;
		mysql_query($sql) or die(mysql_error()."\n$sql") ;

		// Only log if not a retry. Retries are handled by retry flag
		if ($retry != 1){
		  // Add file to download history
		  $sql = "INSERT INTO download_log (member_name, `file`, `last_ip`, `agent`) VALUES ('$username','$g','$ip','$HTTP_USER_AGENT')" ;
		  mysql_query($sql) ;
		}

		return true ;
	} else {
		return false ;
	}

}




/*
function allowedtoDownload($username,$g){
	global $link ;

	$dl = 0 ;
    	$today = date("m")."-".date("d") ;
	mysql_select_db('kplaylist', $link) or die ('Can\'t use db : ' . mysql_error());

	$sqld= "SELECT * FROM `download_log` WHERE `member_name`='$username' AND file='$g' AND
        	       DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= `lastupdated`" ;
	$res_dupe = mysql_query($sqld) or die(mysql_error()) ;

	if(mysql_num_rows($res_dupe)==0){
		$dl = 1 ;
	} else {
		$sql_s = "SELECT monthday, download_count, download_limit FROM member_downloads WHERE member_name='$username'" ;
		$res = mysql_query($sql_s) or die(mysql_error()) ;
		if (mysql_num_rows($res)>0){
			$row = mysql_fetch_array($res) ;
			extract($row) ;
			if ($monthday==$today){ // Downloaded today already
				if ($download_count < $download_limit){ // still below limit
					$dl = 1 ;
				} else {
					$dl = 0 ;    // hit limit
				}
			} else {        // Didn't download today
				$dl = 1 ;
			}
		}
	}
	return $dl ;
}
*/


?>
