<?php
/***************************************************************************
 *                           downloadcounter.php
 *
 *                           --------------------
 *   begin                : wednesday, 12 sept, 2007
 *   owner                : Qumbetlian
 *   email                : qumbetlian@yahoo.com
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is a free script; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   Acest program este un script liber; il puteti redistribui si/sau modifica
 *   sub termenii Licentei Publice Generale asa cum este publicata de
 *   Fundatia Free Software; fie in versiunea a doua a licentei, sau 
 *   (la alegerea dvs.) oricarei versiuni ulterioare.
 *
 ***************************************************************************/

$fieldExist = 0;

// If storing file vas not set, then set storing file.
// Daca fisierul de stocare nu a fost precizat, atunci fixeaza fisierul de stocare.
if(!isset($downloadStoringFile))
	$downloadStoringFile = "downloadcount.txt"; // File of data storing. || Fisierul de stocare a datelor.

$url = $_GET['url'];

// See if URL is provided. || verificam daca URL-ul este furnizat.
if(isset($url)) {
	$sFfp = fopen($downloadStoringFile, 'r+');
	flock($sFfp, 3);
	// Read the file data storing line by line for finding the URL field.
	// Citim fisierul de stocare linie cu linie pentru gasirea cimpului cu URL-ul.
	while($buffer = fgets($sFfp)){
		if(!strcmp($buffer, $url."\n")){
			$sFtell = ftell($sFfp);
			$downloadcounter = fgets($sFfp);
			$downloadcounter = 1 + "$downloadcounter"; // Increasing value of counter.
			fseek($sFfp, $sFtell);
			fputs($sFfp, "$downloadcounter");
			$fieldExist = 1;
		}
	}
	// If the URL field vas not found, then write URL field to file.
	// Daca nu a fost gasit cimpul cu URL-ul, atunci scriem in fisier un cimp cu URL-ul. 
	if(!$fieldExist){
		fwrite($sFfp, $url."\n");
		fputs($sFfp, "1"."        \n");
	}
	fclose($sFfp);
	// Redirect browser to download file. || Redirectare browser pentru download-area fisierului.
	header("Location: " . $url);
}

// Function for showing downloads counter.|| Functie pentru afisarea contorului de downloaduri.
function showCount($urlName){
	$downloadcounter = 0;
	global $downloadStoringFile;
	$sFfp = fopen($downloadStoringFile, 'r');
	while($buffer = fgets($sFfp)){
		if(!strcmp($buffer, $urlName."\n")){
			$downloadcounter = fgets($sFfp);
			break;
		}
	}
	fclose($sFfp);
	return $downloadcounter;
}
?>