<?php


//CONFIGURATION SECTION

$FILES_DIR = "/download/software/last/";
//URI to files
//Include beginning and trailing slash
//This is the web path to your files, not a server path
//Example:  www.yoursite.com/folder/files/ will be /folder/files/
//If you wish to serve offsite files, you can use http://www.site.com/downloads/

$MYSQL_USER = "soviaser_webuser";             //The username used to connect to MySQL
$MYSQL_PASS = "96(v#_v=Ec[l";         //The MySQL Password for the user
$MYSQL_HOST = "localhost";        //The host to connect to
$MYSQL_DB   = 'soviaser_downloadcounter';             //The database in which the dl_count table is in


##############################################################
# Thats IT!!  No more configuration required.
##############################################################

$ip=$_SERVER['REMOTE_ADDR'];

$referer=$_SERVER['HTTP_REFERER'];

$cnt_sql = @mysqli_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASS);

@mysqli_select_db($cnt_sql, $MYSQL_DB);

if(isset($_GET['file'])) {
	$file = urlencode($_GET['file']);

	if(empty($file)) {
		echo "No File Specified";
		exit;
	}
	if(strpos($file, "..") !== FALSE) {
		echo "HACK ATTEMPT!";
		exit;
	}
	if(strpos($file, "://") !== FALSE) {
		echo "Invalid File";
		exit;
	}

	$cookie = urlencode(str_replace(".", "_", $file));  //cookie fix

	$query = "SELECT * FROM detaliu WHERE file = '$file'";
	$result = mysqli_query($cnt_sql, $query );
	if(!$result) {
		echo mysqli_error($cnt_sql);
		exit;
	}

	$num_rows = mysqli_fetch_row($result)[0];



	if($num_rows == 0) {
		//first use of this file
		$query = "INSERT INTO detaliu VALUES(NULL, '$file', '$ip', CURRENT_TIMESTAMP(),'$referer')";
		$result = mysqli_query($cnt_sql, $query);
		setcookie("dl_" . $cookie, "set", time() + 60*60*24*365);
	} else {
		if(!isset($_COOKIE['dl_' . $cookie])) {
			$query = "INSERT INTO detaliu VALUES(NULL, '$file', '$ip', CURRENT_TIMESTAMP(),'$referer')";
			$result = mysqli_query($cnt_sql, $query);
			setcookie("dl_". $cookie, "set", time() + 60*60*24*365);
		}
	}



	header("Location: " . $FILES_DIR . $file);
}

function showCount($fileID)
{
	global $cnt_sql;
	$query = "SELECT count FROM detaliu WHERE file = '$fileID'";
	$result = mysqli_query($cnt_sql,$query);

	$num_rows = mysqli_fetch_row($result)[0];

	if($num_rows == 0) {
		return 0;
	} else {
		$count = mysqli_fetch_row($result)[0];
		return $count[0];
	}
}


?>
