<?php
//=========================================
//This code is copyright (c) ViciSoft SL, all rights reserved.
//The contents of this file are protected under law as the intellectual property
//of ViciSoft SL. Any use, reproduction, disclosure or copying
//of any kind without the express and written permission of ViciSoft SL is forbidden.
//Author: Vince Reid, vincereid@gmail.com
ob_end_clean();
ob_start();
include "db_conn_open.php";
include "includes.php";
include "inc/incfunctions.php";
include "inc/incemail.php";
@set_time_limit(1800);
global $digidownloadpattern,$digidownloadpath;
if(trim_(@$digidownloadpath)!=''){
	if(substr($digidownloadpath,-1)!='/'&&substr($digidownloadpath,-1)!='\\') $digidownloadpath.=DIRECTORY_SEPARATOR;
}else
	$digidownloadpath='';
function readfile_chunked($filename,$retbytes=true) {
	$chunksize = 5*(1024*1024); // how many bytes per chunk
	$buffer = '';
	$cnt =0;
	$handle = fopen($filename, 'rb');
	if ($handle === false) {
		return false;
	}
	while (!feof($handle)) {
		$buffer = fread($handle, $chunksize);
		echo $buffer;
		ob_flush();
		flush();
		if ($retbytes) {
			$cnt+=strlen($buffer);
		}
	}
	$status = fclose($handle);
	if($retbytes && $status) {
		return $cnt;
	}
	return $status;
}
$isdodgy=FALSE;
if(@$htmlemails==TRUE) $emlNl = "<br />"; else $emlNl="\n";
if(@$digidownloadsecret=="") $digidownloadsecret="this is some secwet text";
if(@$digidownloaddays=="") $digidownloaddays=3;
$ref = str_replace("'", "", getget("ref"));
if($ref=="") $ref="default";
$id = getget("id");
if(! is_numeric($id)) $id = 11111;
$pw = str_replace("'","",getget("rd"));
if($pw=="") $pw = "fg";
$sid = str_replace("'","",getget("sd"));
if($sid=="") $sid = 11111;
$cartprodid='';
$alreadygotadmin = getadminsettings();
$sSQL = "SELECT ordID,cartID,cartProdId,ordTotal,ordIP,ordEmail FROM cart INNER JOIN orders ON cart.cartOrderID=orders.ordID WHERE ordStatus>=3 AND ordAuthNumber<>'' AND cartCompleted=1 AND cartID='" . escape_string($id) . "' AND cartProdID='" . escape_string($ref) . "' AND cartSessionID='" . escape_string($sid) . "' AND cartDateAdded > '" . date("Y-m-d", (time()-(60*60*24*$digidownloaddays))) . "'";
$result = ect_query($sSQL) or ect_error();
if($rs = ect_fetch_assoc($result)){
	$theamnt = (float)$rs['ordTotal'];
	$ordid = $rs['ordID'];
	$cartid = $rs['cartID'];
	$cartprodid = $rs['cartProdId'];
	if(@$digitaldownloadlimit != '')
		if($theamnt > $digitaldownloadlimit) $isdodgy=TRUE;
	if(trim_(@$digidownloadpath)==''){
		$fingerprint = vrhmac($digidownloadsecret, $id . $cartprodid . $sid);
		if($fingerprint!=$pw) $isdodgy=TRUE;
	}
}else{
	$isdodgy=TRUE;
}
ect_free_result($result);
function dodgyfunction($thepath){
global $digidownloadwarn,$emailAddr,$ref,$id,$pw,$emlNl,$emailencoding,$htmlemails;
	$sSQL = "SELECT cartOrderID FROM cart WHERE cartID='" . escape_string($id) . "'";
	$result = ect_query($sSQL) or ect_error();
	if($rs = ect_fetch_assoc($result))
		$ordid = $rs['cartOrderID'];
	else
		$ordid = 'invalid';
	ect_free_result($result);
?><html>
<head>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
<title>Download Error</title>
</head>
<body>
<div class="downloaderror" style="font-family:sans-serif;margin:50px;padding:20px;text-align:center"><p>If you are trying to download 
  the products you have just purchased, then I am afraid you have received this 
  page in error.</p><p>Firstly please accept our sincerest apologies. Please email us at 
  <a href="mailto:<?php print $emailAddr?>"><?php print $emailAddr?></a> 
  with the details of your order, and we will send any products you purchased 
  by email.</p><?php
	if(@$digidownloadwarn==TRUE){
		$seBody = "Please note, the details below may not have been entered by the original purchaser." . $emlNl . $emlNl . "Prod Ref: " . $ref . $emlNl . 
			"Order Id: " . $ordid . $emlNl .
			"Cart Id: " . $id . $emlNl .
			"P-word: " . $pw . $emlNl . 
			"User Agent: " . @$_SERVER["HTTP_USER_AGENT"] . $emlNl . 
			"Query String: " . @$_SERVER["QUERY_STRING"] . $emlNl . 
			"IP: " . @$_SERVER["REMOTE_HOST"] . $emlNl;
		if($thepath != ''){
			$seBody .= "Failed to find: " . $thepath . $emlNl;
			$seBody .= "Path to this script : " . @$_SERVER["SCRIPT_FILENAME"] . $emlNl;
		}
		$headers = "MIME-Version: 1.0\n";
		$headers .= "From: " . $emailAddr . " <" . $emailAddr . ">\n";
		if(@$htmlemails==TRUE)
			$headers .= "Content-type: text/html; charset=".$emailencoding."\n";
		else
			$headers .= "Content-type: text/plain; charset=".$emailencoding."\n";
		mail($emailAddr, "Failed Download", $seBody, $headers);
	}
?>
<br><p>Please <a href="javascript:history.go(-1)">Click Here</a> to try the download again.</p></div>
</body>
</html>
<?php
}
if($isdodgy){
	dodgyfunction("");
}else{
	$sSQL = "SELECT pDownload FROM products WHERE pID='" . escape_string($ref) . "'";
	$result = ect_query($sSQL) or ect_error();
	if($rs = ect_fetch_assoc($result)) $thedownload=trim_($rs['pDownload']);
	ect_free_result($result);
	if(strtolower($thedownload)=="a") // auto download
		$strFileName = str_replace("%pid%", $ref, $digidownloadpattern);
	else
		$strFileName = $thedownload;
	$thedownloadarray=explode(',',$strFileName);
	$noregexpcol=FALSE;
	$sSQL="SELECT optRegExp FROM cartoptions INNER JOIN options ON cartoptions.coOptID=options.optID WHERE coCartID=" . $cartid . " ORDER BY coCartID";
	$result2 = ect_query($sSQL) or $noregexpcol=TRUE;
	if($noregexpcol != TRUE){
		while($rs2 = ect_fetch_assoc($result2)){
			$theexp = trim_($rs2["optRegExp"]);
			if(substr($theexp, 0, 1)=="!"){
				$theexp = substr($theexp, 1);
				for($dlindex=0; $dlindex<count($thedownloadarray);$dlindex++){
					if(substr($theexp, 0, 1)=="!"){
						$thedownloadarray[$dlindex]='';
					}else{
						$theexp = str_replace('%s', $thedownloadarray[$dlindex], $theexp);
						if(strpos($theexp, " ") !== FALSE){ // Search and replace
							$exparr = explode(' ', $theexp, 2);
							$thedownloadarray[$dlindex] = str_replace($exparr[0], $exparr[1], $thedownloadarray[$dlindex]);
						}else
							$thedownloadarray[$dlindex] = $theexp;
					}
				}
			}
		}
	}
	for($dlindex=0; $dlindex<count($thedownloadarray);$dlindex++){
		if($thedownloadarray[$dlindex]!=''){
			$downloadthisitem=TRUE;
			if($digidownloadpath!=''){
				$fingerprint = vrhmac($digidownloadsecret, $id . $cartprodid . $sid . $thedownloadarray[$dlindex]);
				$downloadthisitem=($fingerprint==$pw);
			}
			if($downloadthisitem){
				$strFileName = $digidownloadpath . $thedownloadarray[$dlindex];
				if($result2) ect_free_result($result2);
				$dlFileName = basename($strFileName);
				if(file_exists($strFileName)){
					// "application/octet-binary"
					ob_clean();
					header("Content-Type: application/save");
					header('Content-Disposition: attachment; filename="' . $dlFileName . '"');
					header("Content-Length: " . filesize($strFileName));
					if($fhan = readfile_chunked($strFileName)){
						// fpassthru($fhan);
					}
				}else{
					dodgyfunction($strFileName);
				}
				break;
			}
		}
	}
}
?>