<?php
/*
=================================
Anti Leech File Gate
Version: (See "setting.php") 
Author:Wei Shi<swnet@263.net>
Created: (See "setting.php") 
Modified: (See "setting.php") 

Copyright (C) 2003 Wei Shi<swnet@263.net>

This program is free software; you can redistribute it and/or 
modify it under the terms of the ALFG License as included in the 
distribution in the file: License.txt 

This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 

If you did not receive a copy of ALFG license, or have any 
questions about ALFG licensing, please contact swnet@263.net. 

=================================
*/
set_magic_quotes_runtime(0);
$strProgidtext="Note: Download powered by Anti-Leech-File-Gate\n";
header($strProgidtext);//PgId

//check PCRE
if (!function_exists('preg_replace')) {
	fErrpage(903);//PCRE not found.
}
//
if(!file_exists(".htaccess")){
	fErrpage(901);// .htaccess not found.
}
//
if(file_exists("setting.php")){
	include("setting.php");// import setting.
}else{
	fErrpage(905);// maintenance out serving.
}
//
if($bDebug){
	error_reporting(2047);
}else{
	error_reporting(1);
}

//Chech if this php is modle version
$bApache_module=function_exists("getallheaders");

//compatible patch (legacy)
if($bApacheComp){
	if(@$HTTP_GET_VARS['z']==""){
		if(@$HTTP_GET_VARS['c']=="c") fErrpage(500); 
		if($bApache_module) header("HTTP/1.1 302 Found\n");// fix for php modle
		header("Status: 302\n");
		header("Location:http://".$HTTP_SERVER_VARS['HTTP_HOST'].$HTTP_SERVER_VARS['PHP_SELF']."?z=".rawurlencode($HTTP_SERVER_VARS["REQUEST_URI"])."&c=c");
		exit;
	}else{
		$strRequri=rawurldecode($HTTP_GET_VARS['z']);
	}
}else{
	$strRequri=$HTTP_SERVER_VARS["REQUEST_URI"];
}

//get real file info
$strRequri=preg_replace('/\?(.*)$/i','',$strRequri);

$strFilenamereal=preg_replace("/(\/.*\/)/","",$strRequri).$strScureword;
$strFilenamereal=str_replace(array('<', '>', '\\', '/', '='), '' ,$strFilenamereal); //security reason

$strThisfilename="/".preg_replace("/(\/.*\/)/","",$HTTP_SERVER_VARS['PHP_SELF'])."$/";
$strFilenamefake=preg_replace("/(\/.*\/)/","",$strRequri);

$strFilesubdirreal=str_replace(array(preg_replace($strThisfilename,"",$HTTP_SERVER_VARS['PHP_SELF']),$strFilenamefake),"",$strRequri);
$strFilesubdirreal=str_replace(array('..'), '' ,$strFilesubdirreal); //security reason

//referer check
$bMatched=false;$numFilesizecnt=0;
for($i=0;$i<count($strSdomain);$i++){
	if($strSdomain[$i]=="www"){
		$strSdomain[$i]="";
	}else{
		if($strSdomain[$i]!="") $strSdomain[$i]="(".$strSdomain[$i].".)";
	}
	
	$strLocaldomain="none232bcF3E";
	if($bFactorymode){
		if($strDomain[$i]=="localhost") $strDomain[$i]="none232bcF3E";
		$strLocaldomain="localhost";
	}
	
	$strDir[$i]=preg_replace("/\//","\/",$strDir[$i]);
	if(@preg_match("/^http:\/\/((www.)||".$strSdomain[$i].")((".$strDomain[$i].")||(".$strLocaldomain."))".$strDir[$i]."/i",$HTTP_SERVER_VARS['HTTP_REFERER']) && @$HTTP_SERVER_VARS['HTTP_REFERER']!="") $bMatched=true; //check referer integrity
}

//session check(Enhancement add-in)
if($bEnh && !$bInlineEnhOnly){
	session_start();
	if(isset($HTTP_SESSION_VARS['al_pticket']) && $HTTP_SESSION_VARS['al_pticket']=="A.L.F.G_Session_ID") $bMatched=true;//check session integrity
	session_write_close();
}
if(!$bMatched) fErrpage(404,"alfg_info_leech");

//log access count
fLog("access_count");

//main procedure
if($bFilegate){// File Gate
	if(!file_exists("./".$strScuredir)) fErrpage(902);// secure-dir not found.
	if(!file_exists("./".$strScuredir.$strFilesubdirreal.$strFilenamereal)) fErrpage(404);
	if($bNotimelimit)set_time_limit(0);//set time limit
		
	if($bHttp206 && isset($HTTP_SERVER_VARS['HTTP_RANGE'])){
		if($bApache_module) header("HTTP/1.1 206 Partial content\n");// fix for php modle
		header("Status: 206\n");
	}else{
		if($bApache_module) header("HTTP/1.1 200 OK\n");// fix for php modle
		header("Status: 200\n");
	}
	
	$filemtime=filemtime($strScuredir.$strFilesubdirreal.$strFilenamereal);
	if(!$filemtime) fErrpage(500); //if can not get file modifiy date
	
	header("Cache-control: private\n"); // fix for IE http/1.1
	header("Pragma: no-cache\n");// fix for http/1.0
	header("Last-Modified:  ".date("D, d M Y H:i:s \G\M\T",$filemtime)."\n");
	
	$p=explode('.', $strFilenamefake); 
    $pc=count($p); 
	$strFilextfake=$p[$pc-1];

	if($pc>1 && isset($mimetype[$strFilextfake])){// inline
		
		if($bEnh && $bInlineEnhOnly){// enhancer add-in only apply to inline doc
			session_start();
			if(!isset($HTTP_SESSION_VARS['al_pticket']) || $HTTP_SESSION_VARS['al_pticket']!="A.L.F.G_Session_ID") fErrpage(404,"alfg_info_leech");;//check session integrity
			session_write_close();
		}
		
		header("Content-Type: ".$mimetype[$strFilextfake]."\n"); 
		if(!isset($HTTP_SERVER_VARS['HTTP_RANGE'])) header("Content-Disposition: inline; filename=\"".$strFilenamefake."\"\n");
		
	}else{// download attachment
		
		$attachment=(!strstr($HTTP_SERVER_VARS["HTTP_USER_AGENT"],"Mozilla/4") || strstr($HTTP_SERVER_VARS["HTTP_USER_AGENT"],"MSIE"))?' attachment;':'';
		if(!isset($HTTP_SERVER_VARS['HTTP_RANGE'])) header("Content-Disposition: ".$attachment." filename=\"".$strFilenamefake."\"\n");
		
		header("Content-Type: application/octet-stream\n");
		header("Content-Transfer-Encoding: binary\n"); 
		header ("Connection: close\n");
	}
	
	$filesize=filesize($strScuredir.$strFilesubdirreal.$strFilenamereal);
	$filesizeorg=$filesize;

	$fh=fopen("./".$strScuredir.$strFilesubdirreal.$strFilenamereal, "rb");
	 
	if($bHttp206 && isset($HTTP_SERVER_VARS['HTTP_RANGE'])){
		$iCutto=preg_replace(array("/(\040*|)bytes(\040*|)=(\040*|)/","/(\040*|)\-.*$/"),array("",""),$HTTP_SERVER_VARS['HTTP_RANGE']);
		if($filesize<$iCutto) fErrpage(411); 
		$filesize-=$iCutto;
		header("Accept-Ranges: bytes");
		header("Content-Range: bytes ".$filesize."-".($filesizeorg-1)."/".$filesizeorg);
		fseek($fh,$iCutto);
	}
	
	header("Content-Length:".$filesize."\n");
	
	if($bSmallmem){
		register_shutdown_function('fShutdown');
		while(!feof($fh)) {
			echo fread($fh, 4096);
			$numFilesizecnt+=4096;
		}
		fclose($fh);
	}else{
		fpassthru($fh);// possible memory hog!
		$numFilesizecnt=$filesize;
		register_shutdown_function('fShutdown');
	}
	
}else{// Redirector
	if($bApache_module) header("HTTP/1.1 302\n");// fix for php modle
	header("Status: 302\n"); 
	header("Location:".$strDowndir.$strScuredir.$strFilesubdirreal.$strFilenamereal);
	header($strProgidtext);//PgId
	$numFilesizecnt=filesize($strScuredir.$strFilesubdirreal.$strFilenamereal);
	fShutdown();
}
//-------------------------------------
function fErrpage($err,$reason="",$text=""){	
global $bApache_module,$HTTP_SERVER_VARS,$bUseLeechRedirecter,$bLeechRedirecter,$strLeechFile;
if($reason=="")$reason="Script Test";
if($text=="")$text="<H1>fErrpage:".$err."</H1>";

switch($err){
case 404:
	if($reason=="alfg_info_leech") fLog("leech_report");//log leecher
	//Custom error page
	if($bUseLeechRedirecter && $strLeechFile!=""){
		if($bLeechRedirecter){ //t-Redirecter
			if($bApache_module) header("HTTP/1.1 302\n");
			header("Status: 302\n"); 
			header("Location:".$strLeechFile."\n");
		}else{ //f-Filegate
			if(!file_exists($strLeechFile)) fErrpage(904);
			$strFilenamefake=preg_replace("/(\/.*\/)/","",$HTTP_SERVER_VARS["REQUEST_URI"]);
			
			if($bApache_module) header("HTTP/1.1 200 OK\n");
			header("Status: 200\n");
			header("Cache-control: private\n");
			header("Pragma: no-cache\n");
			header("Content-Type: application/octet-stream\n");
			header("Content-Transfer-Encoding: binary\n"); 
			header("Connection: close\n");
			header("Content-Length:".filesize($strLeechFile)."\n");
			
			$fh=fopen($strLeechFile,"rb");
			while(!feof($fh)) {
				echo fread($fh, 4096);
			}
			fclose($fh);
		}
		exit;
	}else{
		//Default 404 page
		if($bApache_module) header("HTTP/1.1 404 Not Found\n");
		header("Status: 404");
		$reason="404 Not Found";
		$text="<H1>404 Not Found</H1>";
	}
	break;
case 411:	
	if($bApache_module) header("HTTP/1.1 411 Length Required\n");
	header("Status: 411");
	$reason="411 Length Required";
	$text="<H1>411 Length Required</H1>";
	break;
case 500:
	if($bApache_module) header("HTTP/1.1 500 Server Error\n");
	header("Status: 500");
	$reason="500 Server Error";
	$text="<H1>500 Server Error</H1>";
	break;
case 501:
	if($bApache_module) header("HTTP/1.1 501 Not Implemented\n");
	header("Status: 501");
	$reason="501 Not Implemented";
	$text="<H1>501 Not Implemented</H1>";
	break;
case 901:// in fact 901 error won't happen.
	header("Status: 200");
	$reason="901 Configure Error";
	$text="<H1>901 File .htaccess Not Found! Please Use download/admin.php Configure First.</H1>";
	break;
case 902:
	header("Status: 200");
	$reason="902 Configure Error";
	$text="<H1>902 Secure-Directory Not Found! Please Check The Setting.</H1>";
	break;
case 903:
	header("Status: 200");
	$reason="903 System Configure Error";
	$text="<H1>903 PCRE Not Available! Please Check PHP Configure Or Update.</H1>";
	break;
case 904:
	header("Status: 200");
	$reason="904 Configure Error";
	$text="<H1>904 Custom Error Page Not Found! Please Check The Setting.</H1>";
	break;
case 905:
	header("Status: 200");
	$reason="905 Maintenance";
	$text="<H1>905 Server is under maintenance, please back later.</H1>";
	break;
default:
	header("Status: 200");
}
echo "<TITLE>".$reason."</TITLE>".$text;
exit;
}
//------------------------------------------
function fLog($type){
global $strSdomain,$strDomain,$strDir,$bFilegate,$strScuredir,$strFilesubdirreal,$strFilenamereal,$HTTP_SERVER_VARS,$bLogaccesscnt,$bLogleech,$bLogtrafficnt,$bLogleechcnt,$numFilesizecnt,$strThisfilename;
$temp="";$arrFilecont="";
if(!$bLogaccesscnt || !$bLogleech || !$bLogleechcnt || !$bLogtrafficnt) return false;

switch($type){

case "access_count": // access_count.log
	
	$fp=fopen("access_count.log","ab+");
	
	flock($fp,2);
	fseek($fp,0);
	while (!feof($fp)){
		$temp.=fread($fp, 4096);
	}
	@$arrFilecont=unserialize($temp);
	
	if(strlen($temp)==0 || !is_array($arrFilecont)){
		$arrFilecont=array(array("<*SITE URL*>","<*DOWNLOAD COUNT*>"));
	}
	
	for($i=0;$i<count($strDomain);$i++){
		$strSite=str_replace(array("(",")"),array("",""),$strSdomain[$i]).$strDomain[$i].$strDir[$i];
		if(@$arrFilecont[$i][0]==$strSite){
			if(preg_match("/^http:\/\/((www.)||".$strSdomain[$i].")((".$strDomain[$i].")||(localhost))".$strDir[$i]."/i",$HTTP_SERVER_VARS['HTTP_REFERER']))
			$arrFilecont[$i][1]++;
		}else{
			$arrFilecont[$i][0]=$strSite;
			$arrFilecont[$i][1]=1;
		}
	}
	$temp=serialize($arrFilecont);
	
	ftruncate($fp,0);
	fseek($fp,0);
	fwrite($fp,$temp,strlen($temp));
	
	flock($fp,3);
	fclose($fp);

break;
case "leech_report": // leech_report.log || leech_count.log
		
	$fp=fopen("leech_report.log","ab");// long report.
	flock($fp,2);
	$strReport=">".date("D, d M Y H:i:s",time())." - - ".$HTTP_SERVER_VARS["REMOTE_ADDR"]."[".str_replace("\n","",$HTTP_SERVER_VARS["HTTP_USER_AGENT"])."] Try To Download \"".str_replace("\n","",$HTTP_SERVER_VARS["REQUEST_URI"])."\" From NON-Authorized Site \"".str_replace("\n","",(isset($HTTP_SERVER_VARS['HTTP_REFERER']))?$HTTP_SERVER_VARS['HTTP_REFERER']:"(laking info)")."\"  Failed.\r\n";
	fwrite($fp,$strReport,strlen($strReport));
	
	flock($fp,3);
	fclose($fp);
	
	if(!$bLogleechcnt) break;//end long report
	
	$strReqfile=$strScuredir.$strFilesubdirreal.$strFilenamereal;
	$numReqfilesize=0;
	if(file_exists($strReqfile)) $numReqfilesize=filesize($strReqfile);
	
	$fp=fopen("leech_count.log","ab+");// short count.
	flock($fp,2);
	fseek($fp,0);
	while (!feof($fp)){
		$temp.=fread($fp, 4096);
	}
	
	@$arrFilecont=unserialize($temp);
	if(strlen($temp)==0 || !is_array($arrFilecont)){
		$arrFilecont=array(array("<*LEECHER'S SITE URL*>","<*NUMBER OF LEECH SPOTED*>","<*BANDWIDTH SAVED*>"));
	}

	$strSite=str_replace("\n","",(isset($HTTP_SERVER_VARS['HTTP_REFERER']) || @$HTTP_SERVER_VARS['HTTP_REFERER']!="")?$HTTP_SERVER_VARS['HTTP_REFERER']:"Others");
	$bFoundsite=false;
	for($i=0;$i<count($arrFilecont);$i++){
		if(@$arrFilecont[$i][0]==$strSite){
			$arrFilecont[$i][1]++;
			$arrFilecont[$i][2]+=$numReqfilesize;
			$bFoundsite=true;
		}
	}
	if(!$bFoundsite){
		$tPos=count($arrFilecont);
		$arrFilecont[$tPos][0]=$strSite;
		$arrFilecont[$tPos][1]=1;
		$arrFilecont[$tPos][2]=$numReqfilesize;
	}

	$temp=seront[$i][0]==$strSite){
			$arrFilecont[$i][1]++;
			$arrFilecont[$i][2]+=$numReqfilesize;
			$bFoundsite=true;
		}
	}
	if(!$b	
break;
case "traffic_count": // traffic_count.
	if(!$bFilegate && isset($HTTP_SERVER_VARS['HTTP_RANGE'])) break;
	
	$fp=fopen(preg_replace($strThisfilename,"",$HTTP_SERVER_VARS['PATH_TRANSLATED'])."/traffic_count.log","ab+");
	flock($fp,2);
	fseek($fp,0);
	while (!feof($fp)){
		$temp.=freadsite=true;
		}
	}
	if(!$b	
break;
case "traffic_count": // traffic_count.
	if(!$bFilegate && isset($HTTP_SERVER_VARS['HTTP_RANGE'])) break;
	
	$fBYTES*place($strThisfilename,"",$HTTP_SERVER_VARS['PATH_TRANSLATED'])."/traffic_count.log","ab+");
	flock($fp,2);
	fseek($fp,0);
	while (!feof($fp)){
		
		if(@$arrFilecont[$i][0		}
	}
	if(!$b	
break;
case "traffic_count": // traffic_count.
	if(!$bFilegate && isset($HTTP_SERVER_VARS['HTTP_RANGE'])) break;
	
	$fBYTES*place($strThisfilename,"",$HTTP_SERVER_V=$numFilesizecnt;
		}else{
			$arrFilecont[$i][0]=$strSite;
			$arrFilecont[$i][1]=$numFilesizecnt;
		}
	}
	
	;
			$arrFilecont[$i][1]=$numFilesizecnt;
		}
	}
	
	;
			$arrFilecont[$i][1]=$numFilesizecnt;
		}
	}
	
	;
			$arrFilecont[$i][1]=
break;
}
return true;
}
//-------------------------------------------
function fShutdown(){
fLog("traffic_count");
}
//-------------------------------------------
//The END
?>

