<?php



////////////////////////////////////////////////////////////////
// Download Counter ///////////////////////////////////////////
//
// Please visit http://stenehall.se/index.php?link=forum/index.php 
// and post your thoughts about the script. 
//
// Creative Commons License (creativecommons.org)
// http://creativecommons.org/licenses/by-nc-sa/2.0/
//
////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////

// How to use it:
//
// Place files for download in the same directory as $download,
// the same directory as this file.
// Run "www.yoursite.com/path/to/download/foleder/index.php?act=update".
// This will make the statistics for all files in the folder to update.
// If you want to see the statistics for downloads. 
// Run "www.yoursite.com/path/to/download/foleder/index.php?act=stats".

// You don't actualy need to run index.php?act=update.
// But it will help you with what links to use.
// And also remove statistics for deleted files.

// To add information about a file open data.txt from your server and add
// the text last on the line for the file.

// Like this:
//
// calendar.zip|281|2005-01-11 - 20.40|Small calendar with admin interface to add events.
//
// The text after the last "|" has been added
//
// Explanation:
// filename|downloads|last date for download|file explanation.


// In short:

// Update: download.php?act=update
// Stats:  download.php?act=stats
// Download: download.php?file=filname.ending

// Improvements by Andreas Koop on Aug-20-2005 
// - made this script "recursive capable" for the download directory
// - case insensitive with the extensions
// - pimped the layout, colors (are taken now from the blog configuration) and look!
// You're welcome to give any comments at http://www.multikoop.de/blog/index.php?entry=entry050822-025856

// Edit so it points to the download directory.
$download = "download/";


// If for some reason you want to change the name of the datafile.
$dataFile = "content/download.txt";

// Add the extensions you wish to be visible here.
$extension = array('.zip','.rar','.jpg','.doc','.pdf','.gz', '.txt', '.java', '.jar', '.jad', '.mpg', '.avi');

$sort = 'name';

// Standard SPHPBlog Setup
	// -------------------
	
	// Load/Include Functions
	require_once('scripts/sb_functions.php');
	require_once('scripts/deepdir/DeepDir.php');
	
	// Check Login (See scripts/sb_login.php for details)
	// ---------
	// logged_in( false, true ); // <-- Anyone can view this page.
	// logged_in( true, true ); // <-- Redirects to index.php if you are NOT logged in.
	global $logged_in;
	$logged_in = logged_in( false, true );
	
	// Read Configuration (See scripts/sb_config.php for details.)
	// --------------
	// Loads values into $blog_config global associative array.
	read_config();
	
	// Load/Define Language Strings
	// ----------------------
	// In most cases you won't be adding new strings
	// to the strings.php file unless you are developing
	// something for release.
//	require_once('languages/' . $blog_config[ 'blog_language' ] . '/strings.php');
	sb_language( 'index' );
	
// The $color1, $color2 can be changed to
// whatever you wish.
$color1 = "#efefef";
$color2 = $user_colors['entry_title_bg'];


// Fetches the input from user.
if(isset($_GET['act'])){
	$act = $_GET['act'];
} else {
	$act = "stats";
}

if(isset($_GET['file'])){
	$file = $_GET['file'];
	$act = "download";
} else {
	$file = "";
}
if(isset($_GET['sort'])){
	$sort = $_GET['sort'];
}



// Strips the filename.
$file = stripslashes(trim($file));
$file = nl2br($file);
$file = htmlentities($file);

$file = str_replace("../", "", $file);
$file = str_replace("./", "", $file);
$file = str_replace("..", "", $file);

if ($act == 'download'){
  $data = readData();

  $data = download($data);
  writeData($data);

  header("Location: " . dirname($_SERVER['HTTP_REFERER']) . '/' .  $download . $file);
}
	
//print_r($blog_config);
// Start HTML Page
// -------------
// You'll notice that some stuff is dynamically included
// in the HTML code. These include: charset, css style
// sheet from the theme, (an additional style that over
// write the default colors), and the page title.

html_header('',false);

// Page Content
// ----------
// Your actual page content will go INSIDE the
// page_content() function below. This function gets
// called from inside the theme_pagelayout() function
// at the bottom of this file...
		
function page_content() {
    global $act;
    global $file;

    if ($act == 'update'){
	$data = readData();
	$data = update($data);
	writeData($data);
	echo "<meta http-equiv=refresh content=\"0 URL=?act=stats\">"; 
	echo "Done updating!<BR />Redirect to stats.";
    }
    else{
	echo '<h2>Downloads</h2>';
	echo '<div align="center">';
	$data = readData();
	stats($data);
	echo '</div>';
    }
}



////////////////////////////////////////////////////////////////
// Prints the download statistics /////////////////////////////
//
function stats($data) {
	global $color1, $color2, $download, $sort, $user_colors;

	////////////////////////////////////////////////////////
	// Prints the stats for every file. ///////////////////
	//
	
	echo '<table border="0" width="100%" cellpadding="2" cellspacing="0">'."\n";
	echo "<tr>\n";
	if ($sort == 'name'){ $link = '?sort=rname'; }
	else { $link = '?sort=name'; }
	echo "<td bgcolor='$color2'><a href='$link' style='color:#".$user_colors['entry_title_text']."'>Filename</a></td>\n";
	if ($sort == 'rdown'){ $link = '?sort=down'; }
	else { $link = '?sort=rdown'; }
	echo "<TD bgcolor='$color2'><a href='$link' style='color:#".$user_colors['entry_title_text']."'>Download</a></TD>\n";
	if ($sort == 'rsize'){ $link = '?sort=size'; }
	else { $link = '?sort=rsize'; }
	echo "<TD bgcolor='$color2'><a href='$link' style='color:#".$user_colors['entry_title_text']."'>Filesize</a></TD>\n";
	echo "<TD bgcolor='$color2'style='color:#".$user_colors['entry_title_text']."'>Description</TD>\n";
	echo "</TR>\n\n";


	// The loop.
	$c1 = $color1;
	$c2 = $user_colors['main_bg_color'];
	foreach ($data as $num => $key) {
		
		$file = $key[0];
		$icon = getFileIcon( $file);
		
		echo "<TR>\n<TD bgcolor='$c1' align='left'>";
		echo "<a href='?file=" . $file ."'><img src='interface/icons/$icon' border='0' alt='' /> "; 
		echo $file;
		echo "</A></TD>\n";
		
		echo"<TD align='center' bgcolor='$c1'>$key[1]</TD>\n";
		echo "<TD align='right' bgcolor='$c1' nowrap>";
		// echo @round(filesize($download.$file) / 1024, 2); 
		echo @round($key[3] / 1024, 2); 
		echo " Kb</TD>\n";
		echo "<TD bgcolor='$c1'>";
		echo $key[4];
		echo "</TD>";
		echo "</TR>\n\n";
		
		// Switches the colors.		
		$temp = $c1;
		$c1 = $c2;
		$c2 = $temp;
	}

	echo "</TABLE>";
	//
	////////////////////////////////////////////////////////


};
// End of stats function
////////////////////////////////////////////////////////////////	


////////////////////////////////////////////////////////////////
// Function for making sure the extention is ok. //////////////
//
function extOk($file) {
	global $extension;

	$ext = strtolower(strrchr($file,"."));
	if ($ext) {
	  foreach ($extension as $key) {
	    if($ext == $key) {
	      return true;
	    }
	  }
	}
	return false;
};
// End of extok function
////////////////////////////////////////////////////////////////		


////////////////////////////////////////////////////////////////
// Function for finding the right entry and updating. /////////
//
function download($data) {
	global $file, $download;


	// $file = $download . '/' .$file;
	$datafile = $download . '/' .$file;
	
	////////////////////////////////////////////////////////
	// Makes sure the file exists. ////////////////////////
	//
	
	if(empty($datafile) || $datafile == "." || !file_exists($datafile)) {
		echo "$datafile dosn't exits!";
		exit;
	}
	//
	////////////////////////////////////////////////////////
			
	////////////////////////////////////////////////////////
	// Find the right entry in the array. /////////////////
	//
			
	$exists = FALSE;
	$line = 0;
	//Find the file in the array.
	foreach ($data as $key) {
		if(array_search($file, $key) !== FALSE) {
			$exists = TRUE;
			break;
		}
		$line++;
	}
	//
	////////////////////////////////////////////////////////
	
	////////////////////////////////////////////////////////
	// If the entry did'nt exist create it. ///////////////
	//
	
	if (!$exists) {
		$data[] = array($file,1,date("Y-m-d - G.i"));
	} else {

	// Count up the download number and add new date. 
	
		$data[$line][1]++;
		$data[$line][2] = date("Y-m-d - G.i");	
	}
	
	//	
	////////////////////////////////////////////////////////

	return $data;

};
// End of download function
////////////////////////////////////////////////////////////////
	
////////////////////////////////////////////////////////////////	
// Function for writing to data-file./
//

	function writeData($data) {
		global $dataFile;

		// added by joerg (jorgen@gmx.net):
		// make a backup of the data file
		// restore old file if fwrite fails!

		copy($dataFile,$dataFile.'backup');

		$fp = fopen($dataFile,"w");
		if($fp) {
		foreach ($data as $key) {
		  if (!fwrite($fp, trim("$key[0]|$key[1]|$key[2]|$key[3]|$key[4]") . "\n")){
		    if (file_exists($dataFile.'backup')){  // if fwritee fails:
		      copy($dataFile.'backup',$dataFile);  // restore data file
		      break;                               // and stop!
		    }
		  }
		}
		}
		fclose($fp);
	};
	
// End of writeData function
////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////
// Function for reading the data-file. ////////////////////////
//

	function readData() {
		global $dataFile;
		global $download;
		global $sort;

		$data = array();
		$fp = @fopen($dataFile,"r");
		if($fp) {
			while (!feof($fp)) {
			  $line = fgets($fp);
			  if(trim($line)) {
			    $data[] = split("\|", $line);
			    $i = count($data)-1;
			    if (isset($data[$i][3])){
			      $data[$i][3] = filesize($download.$data[$i][0]);
			    }
			  }
			}
			fclose($fp);
		}
		if ($sort == 'name'){
		  usort($data,'sort_name');
		}
		elseif ($sort == 'rname'){
		  usort($data,'reverse_sort_name');
		}
		elseif ($sort == 'down'){
		  usort($data,'sort_nrdownloads');
		}
		elseif ($sort == 'rdown'){
		  usort($data,'reverse_sort_nrdownloads');
		}
		elseif ($sort == 'size'){
		  usort($data,'sort_size');
		}
		elseif ($sort == 'rsize'){
		  usort($data,'reverse_sort_size');
		}
		return $data;
	};
	
// End of readData function
////////////////////////////////////////////////////////////////


function sort_name($a,$b){
  return strnatcasecmp($a[0],$b[0]);
}
function reverse_sort_name($a,$b){
  return strnatcasecmp($b[0],$a[0]);
}
function sort_nrdownloads($a,$b){
   if ($a[1] == $b[1]) {
       return 0;
   }
   return ($a[1] < $b[1]) ? -1 : 1;
}
function reverse_sort_nrdownloads($a,$b){
   if ($a[1] == $b[1]) {
       return 0;
   }
   return ($a[1] > $b[1]) ? -1 : 1;
}
function sort_size($a,$b){
   if ($a[3] == $b[3]) {
       return 0;
   }
   return ($a[3] < $b[3]) ? -1 : 1;
}
function reverse_sort_size($a,$b){
   if ($a[3] == $b[3]) {
       return 0;
   }
   return ($a[3] > $b[3]) ? -1 : 1;
}


////////////////////////////////////////////////////////////////
// Function for updating the data-file. ////////////////////////
//
	
function update($data) {
	global $dataFile;
	global $download;

	$temp = array();
	foreach ($data as $key) {
		
		$file = $key[0];
		if(file_exists($download.$file) && extOk($file)) {
			$temp[] = $key;
		}
	}
	
	$dir = new DeepDir();
  	$dir->setDir( $download );
  	$dir->load();
  	foreach( $dir->files as $n => $file ){
  		
  		$file = substr($file, strlen($download)+1);
  		
    	if ($file == "index.php" || $file == $dataFile || 
	      	is_dir($download.$file) || !extOk($file)) {
	    	continue;
	    }
	    
	    $found = false;
	    foreach ($data as $key) {
	   		if(array_search($file, $key) !== FALSE) {
				$found = true;
	      	}		
	    }
	    
	    if(!$found){
	      	$temp[] = array($file, 1, date("Y-m-d - G.i"), filesize($download.$file));
	    }
	  
  	}
  
	asort($temp);
	return $temp;
};


// End of update function
////////////////////////////////////////////////////////////////

function getFileIcon( $filename ) {
					
	$type = strtolower( strrchr( $filename, "." ) );

	if( $type == ".avi" || $type == ".mpg" || $type == ".mpeg" || $type == ".wmv" )
		return "movie.gif";
	else if( $type == ".doc" || $type == ".rtf" )
		return "word.gif";
	else if( $type == ".mp3" || $type == ".wav" || $type == ".wma" )
		return "mp3.gif";
	else if( $type == ".zip" )
		return "zip.gif";
	else if( $type == ".rar" || $type == ".tar" )
		return "rar.gif";
	else if( $type == ".pdf" )
		return "pdf.gif";
	else if( $type == ".jar" || $type == ".jad" )
		return "java.gif";
	else if( $type == ".png" || $type == ".gif" || $type == ".bmp")
		return "gif.gif";
	else if($type == ".jpg")
		return "jpg.gif";
	else if($type == ".txt")
		return "text.gif";
	else return "unknown.gif";
}


		
// Generate Page
// -----------
// The function below is what actually starts outputting all
// of the dynamic content. Including the <body> tags, the
// menus, the content, etc... This function calls the
// page_content() function above...
//
// Refer to themes/{theme_name}/themes.php for more details.
theme_pagelayout();

html_footer();

?>

