#!/usr/bin/perl
#########################################################################
#  Top Downloads v2.0                                                   #
#  Copyright (c)2000 Chi Kien Uong                                      #
#  URL: http://www.proxy2.de                                            #
#                                                                       #
# This Software is distributed under the GNU General Public             #
# License. For more details see license.txt                             #
#                                                                       #
# To count a download use:                                              #
# <a href="download.pl?file=file_id">file</a>                           #
#                                                                       #
# To show your top xx downloads:                                        #
# http://www.host.com/cgi-bin/download.pl?job=show&top=xx               #
#                                                                       #
# Administration:                                                       #
# http://www.host.com/cgi-bin/download.pl?admin=enter                   #
#                                                                       #
#########################################################################

# url to script
$cgiurl = "http://www.proxy2.de/cgi-bin/files/download.pl";

# url to the image files without trailing "/"
$base_gif = "http://www.proxy2.de/gif";

# administration password - should not contain '&','=' and "
$admin_pass = "pass123";

# file locking ($lock=0 for Win32!);
$lock = 1;

# check http referer 0=no 1=yes;
$check = 0;
@valid=('http://www.proxy2.de');

# log files
$basedat = "log.txt";
$daylog = "daylog.txt";
$stats = "download_stats.txt";

# base url to the downloads without trailing "/" (use for scanning)
$base_url = "http://www.proxy2.de/downloads";

# path to the downloads from the server root! (use for scanning)
$base_dir = "/home/www/you/public_html/downloads";

$back_img = "$base_gif/texture1.gif"; # url of background image
$bgcolor = "#FFFFFF";	# background color
$table_width = 560;	# width of hole table
$table_text = 250;	# width reserve for the file description
$table_bg = "#F7F7F7";	# table background color
$table_top = "#E1A8A8";	# top table background color
$font_size = "8pt";	# font size
$show_default = 15;	# 10=TOP_10  20=TOP_20,etc.
$bar_image_height =10;
$max_day = 28;
$max_bar_height = 180;

%scan = (

  zip => '*.zip',
  gz  => '*.gz',
  exe => '*.exe',
  mp3 => '*.mp3',
  pdf => '*.pdf',
  avi => '*.avi'

);

# End Setup
#################

&parse_form;

if ($FORM{'job'} eq "show")  {
	&show_table;
}
elsif ($FORM{'detail'} =~ /\S/) {
	&show_detail;
}	 
elsif ($FORM{'file'} =~ /\S/) {
	if ($check == 1) {
		foreach $referer (@valid) {
			if($ENV{'HTTP_REFERER'} =~ /$referer/) {
				$http_ref = "ok";
				last;
			}
		}
		if ($http_ref ne "ok") {
			&message('No valid referer');
		}
	}
	&count_download;
}
elsif ($FORM{'job'} eq "stats")  {
	&show_stats;
}
elsif ($FORM{'admin'} eq "enter") {
	&validation;
}
elsif ($FORM{'admin'} eq $admin_pass) {
	
	if ($FORM{'manage'}) {
		&manage("$FORM{'manage'}");
		&show_track;
	}
	elsif ($FORM{'action'} eq "Scan") {
		&scan_dir;
		&show_track;
	}
	elsif ($FORM{'action'} eq "Add entry") {
		&add_location;
		&show_track;
	}
	else {
		&message('No valid command');
	}
}
else {
	&message('No valid command');
}

# starting of subroutines

sub parse_form {

if ($ENV{'REQUEST_METHOD'} eq "GET") {
        $buffer = $ENV{'QUERY_STRING'};
}
else {
        read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}
@pairs = split(/&/, $buffer);

foreach $pair (@pairs) {
      ($name, $value) = split(/=/, $pair);
      $name =~ tr/+/ /;
      $name =~ s/%([a-f0-9]{2})/pack("C", hex($1))/egi;
      $value =~ tr/+/ /;
      $value =~ s/%([a-f0-9]{2})/pack("C", hex($1))/egi;
      $FORM{$name} = $value;
  }
}

sub count_download {
$down_date = &get_date($down_date);
open(DATA,"+<$basedat") || &message('Cannot open log file $basedat for writing!');
flock(DATA,2) if ($lock == 1);
my @lines = <DATA>;
shift(@lines);

$found=0;
foreach $line (@lines)  {
  	($file_id,$count,$location,$stamp,$descript) = split(/\|/,$line);
	if ($FORM{'file'} eq $file_id) {
                $count++;
                $line = ("$file_id|$count|$location|$stamp|$descript");
                $found=1;
                $redirect_to = $location;
                last;
  	}
}
if ($found == 1) {
	seek(DATA,0,0);
	print DATA ("$down_date\n");
	print DATA (@lines);
	close(DATA);
	if ($redirect_to =~ /^(f|ht)tp:\/\/[._a-z0-9-]+/i) {
		&count_daily;
		print "Location: $redirect_to\n\n";
	}
	else {
		&message('Invalid file URL!');
	}
}
else {
	close(DATA);
	&message('File not found in database!');
}
exit (0);
}

sub count_daily {

open(DATA,"$daylog");
my @line = <DATA>;
close(DATA);
chop($line[0]);
$count = $line[1];
$today = int(time()/86400);
if ($line[0] > 0 && $line[0] < $today) {
	
	if (($today-$line[0]) > 1) {
		$remain_days = ($today-$line[0]);
		for ($i=1; $i<$remain_days; $i++) {
			$stamp = ($today-$remain_days+$i)*86400;
			&get_date($stamp,1);
			$remain[$i-1] = "$date|0\n";
		}
		$append=1;
	}
	open(DATA,">$daylog");
	flock(DATA,2) if ($lock == 1);
	print DATA ("$today\n1");
	close(DATA);
	
	&get_date(($line[0]*86400),1);
	open(STAT,">>$stats");
	flock(STAT,2) if ($lock == 1);
	print STAT ("$date|$count\n");
	print STAT (@remain) if ($append==1);
	close(STAT);
}
else {
	$count++;
	open(DATA,">$daylog") || &message("Cannot create database file $daylog.");
	flock(DATA,2) if ($lock == 1);
	print DATA ("$today\n$count");
	close(DATA);
}

}

sub get_data {
unless (open(DATA,"$basedat")) {
	if (-e "$basedat") {
		&message('File exists, but cannot be opened.');
	} 
	else {	
		open(DATA,">$basedat") || &message("Cannot create database file $basedat.");
	}	
}
@sort_array = <DATA>;
chop (@sort_array);
close(DATA);
$last_download = shift(@sort_array);
$totalfiles = @sort_array;
}

sub show_table {
&get_data;
&header;
print "    <td align=\"right\">\n"; 
print "      <select name=\"files\" onChange=\"ViewDetail('self',this)\">\n";
print "        <option selected>show details</option>\n";
$total=0;
$this_time = time();
if ($FORM{'top'} eq "all") {
  $FORM{'top'} = $totalfiles
}
else {
  $FORM{'top'} = ($FORM{'top'} =~ /^(\d+)/) ? $1 : $show_default;
}
foreach $input (@sort_array) {
  ($filenum, $countnum, $location, $stamp, $description) = split(/\|/,$input);
  if ($FORM{'option'} eq "perDay") {  	
  	$dl_perday = ($this_time-$stamp>86400) ? sprintf("%.2f",($countnum*86400/($this_time-$stamp))) : 0;
  	$name_array{$filenum} = $dl_perday;
  	$total += $dl_perday;
  }
  else {
  	$name_array{$filenum} = $countnum;
  	$total += $countnum;
  }
  $descript_array{$filenum} = $description;
}
foreach $file (sort {$descript_array{$a} cmp $descript_array{$b}} (keys(%descript_array))) {
  print "        <option value=\"$file\">$descript_array{$file}</option>\n";
}
print "      </select>\n    </td>\n  </tr>\n</table>\n";
print "<table bgcolor=\"$table_bg\" border=0 cellpadding=2 cellspacing=1 width=$table_width align=center>\n"; 
print "  <tr>\n    <td colspan=2 bgcolor=\"$table_top\"><font color=\"#990000\"><b>Top $FORM{'top'} Downloads</b></font></td>\n  </tr>\n";
if ($total>0) {
 $show=0;
 $flag=0;
 foreach $file_id (sort {$name_array{$b} <=> $name_array{$a}} (keys(%name_array))) {
   if ($show < $FORM{'top'}) {
         $top_pos = $name_array{$file_id} if ($flag == 0);
         $percent = ($name_array{$file_id} *100/ $total);
 	 if ($percent <= 1) {$img = 'blue.gif';}
     	 elsif ($percent > 1 && $percent <= 2) {$img = 'green.gif';}
     	 elsif ($percent > 2 && $percent <= 5) {$img = 'aqua.gif';}
     	 elsif ($percent > 5 && $percent <= 8) {$img = 'pink.gif';}
     	 elsif ($percent > 8 && $percent <= 11) {$img = 'yellow.gif';}
     	 elsif ($percent > 11 && $percent <= 14) {$img = 'purple.gif';}
     	 elsif ($percent > 14 && $percent <= 17) {$img = 'brown.gif';}
     	 elsif ($percent > 17 && $percent <= 20) {$img = 'darkgreen.gif';}
     	 elsif ($percent > 20 && $percent <= 23) {$img = 'red.gif';}
     	 elsif ($percent > 23) {$img = 'gold.gif';}
     	 $img_width = int($name_array{$file_id} *($table_width-$table_text)/$top_pos);
     	 if ($descript_array{$file_id} ne "---") {
	 	print "    <tr>\n      <td>$descript_array{$file_id}</td>\n      <td nowrap><img src=\"$img\" width=$img_width height=$bar_image_height> $name_array{$file_id}</td>\n    </tr>\n";
         }
         else {
         	print "    <tr>\n      <td>$file_id</td>\n      <td><img src=\"$img\" width=$img_width height=$bar_image_height> $name_array{$file_id}</td>\n    </tr>\n";
         }
         $show++;
         $flag=1;
   }
   else {
      last;
   }
 }
}
$option = ($FORM{'option'} eq "perDay") ? 'Downloads per day' : 'Total Downloads';
print "    <tr>\n      <td>Statistic</td>\n      <td>Last Download: <font color=\"#660066\">$last_download</font>\n"; 
print "        $option: <font color=\"#FF0000\">$total</font></td>\n    </tr>\n  </table>\n";
&footer;
exit (0);
}

sub show_detail {
&get_data;
&header;
print "    <td align=\"right\">\n"; 
print "      <select name=\"files\" onChange=\"ViewDetail('self',this)\">\n";
print "        <option selected>show details</option>\n";
$total=0;
$this_time = time();
foreach $input (@sort_array) {
  ($filenum, $countnum, $location, $stamp, $description) = split(/\|/,$input);
  $total += $countnum;
  $descript_array{$filenum} = $description;
}
foreach $file (sort {$descript_array{$a} cmp $descript_array{$b}} (keys(%descript_array))) {
  print "        <option value=\"$file\">$descript_array{$file}</option>\n";
}
print "      </select>\n    </td>\n  </tr>\n</table>\n";
print "<table bgcolor=\"$table_bg\" border=0 cellpadding=2 cellspacing=1 width=$table_width align=center>\n"; 
print "  <tr>\n    <td colspan=2 bgcolor=\"$table_top\"><font color=\"#990000\"><b>Details for $FORM{'detail'}</b></font></td>\n  </tr>\n";
@details = ('Filename','Description','Added on','Total days','Downloads per day','Downloads total','Total percent');
foreach $detail (@sort_array) {
	if ($detail =~ /^$FORM{'detail'}/) {
		($file_id,$count,$location,$stamp,$descript) = split(/\|/,$detail);
		$file_date = &get_date($stamp,1);
		$total_days = int(($this_time-$stamp)/86400);
		$dl_perday = ($this_time-$stamp>86400) ? sprintf("%.2f",($count*86400/($this_time-$stamp))) : 0;
		$percent = sprintf("%.2f%",($count*100/$total));
		last;
	}
}
@vals = ($file_id,$descript,$file_date,$total_days,$dl_perday,$count,$percent);
$counter=0;
foreach $detail (@details) {
	print "  <tr>\n    <td width=35%>$detail</td>\n    <td>$vals[$counter]</td>\n  </tr>\n";
	$counter++;
}
print "</table>\n";
&footer;
exit (0);
}

sub header {
$this_day = &get_date($this_day);
print "Content-type: text/html\n\n";
print <<Header ;
<html>
<head>
<title>Top Downloads</title>
<style type=text/css>
td { font-family: Arial, Helvetica, sans-serif; font-size: $font_size}
a:hover { color: #ff0000; text-decoration: underline }
select {  font-family: Arial, Helvetica, sans-serif; font-size: $font_size}
input {  font-size: $font_size}
tt {  font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13pt; font-weight: bold}
a {  text-decoration: none}
</style>
<base href="$base_gif/">
<script language="Javascript">
<!--
function ViewDetail(target,selObj) {
  eval(target+".location='$cgiurl?detail="+selObj.options[selObj.selectedIndex].value+"'");
}
// -->
</script>
</head>
<body bgcolor="$bgcolor" background="$back_img" text="#000000" link="#006600" vlink="#006600" alink="#006600">
<br>
<form method="post" action="$cgiurl">
<table width="$table_width" border="0" cellspacing="0" cellpadding="2" height="55" align="center">
  <tr> 
    <td> <tt>Top Downloads 2.0</tt></td>
    <td align="right"> <img src="point.gif" width="9" height="9"><a href="$cgiurl?admin=enter">Administration</a> 
      | <img src="point.gif" width="9" height="9"><a href="$cgiurl?job=stats">Downloads by 
      Day</a> | <img src="point.gif" width="9" height="9"><a href="http://www.proxy2.de" target="_blank">Check 
      for Updates</a></td>
  </tr>
  <tr>
    <td><img src="point2.gif" width="9" height="9"><b>Date: $this_day</b></td>
Header

}

sub footer {
print <<Footer ;
 <table border=0 width="$table_width" align="center" cellspacing="1" cellpadding="3">
  <tr> 
    <td valign="top"> Top Downloads 2.0<br>http://www.proxy2.de</td>
    <td align="right"> 
       <select name="option">
         <option value="total" selected>downloads total</option>
         <option value="perDay">downloads per day</option>
       </select>
       <select name="top">
         <option value="10" selected>Top 10</option>
         <option value="15">Top 15</option>
         <option value="20">Top 20</option>
         <option value="30">Top 30</option>
         <option value="all">all</option>
       </select>
       <input type="submit" value="Submit">
       <input type="hidden" name="job" value="show">
    </td>
  </tr>
</table>
</form>
</body>
</html>
Footer

}

sub show_stats {
my(@days,@today,$total,$total_days,$remain_days,$position,$browse_back,$browse_next);

open(DATA,"$stats") || &message("Cannot open log file $stats.");
@days = <DATA>;
close(DATA);
chop (@days);

open(DATA,"$daylog") || &message("Cannot open log file $daylog.");
@today = <DATA>;
close(DATA);
&message("Invalid log file $daylog.") unless ($today[1] > 0);
chop $today[0];
&header;
$total_days = @days;
if ($total_days < $max_day) {
  $max_day = $total_days;
  $remain_days = 0;
  $position = 0;
}
else {
  if ($FORM{'remain'} =~ /^\d+/) {
    if ($FORM{'remain'} > $max_day) {
      $position = $total_days - $FORM{'remain'};
      $remain_days = ($FORM{'remain'} - $max_day);
    }
    else {
      $position = $total_days - $max_day;
      $remain_days = 0;
    }
  }
  elsif ($FORM{'skip'} =~ /^\d+/) {
    if ($FORM{'skip'} > $max_day) {
      $position = $FORM{'skip'} - $max_day;
      $remain_days = $total_days - $FORM{'skip'};
    }
    else {
      $position = 0;
      $remain_days = $total_days - $max_day;
    }
  }
  else {
    $position = 0;
    $remain_days = $total_days - $max_day;
  }
}
$browse_back = ($remain_days == 0) ? "&nbsp;" : "<img src=\"back.gif\" width=9 height=14>&nbsp;<a href=\"$cgiurl?job=stats&remain=$remain_days\"><font color=\"#000099\">back</font></a>";
$browse_next = ($position == 0) ? "&nbsp;" : "&nbsp;&nbsp;<a href=\"$cgiurl?job=stats&skip=$position\"><font color=\"#000099\">next</font></a>&nbsp;<img src=\"next.gif\" width=9 height=14>";

print <<Table ;
     <td align="right">$browse_back $browse_next</td>
  </tr>
</table>
<table width="$table_width" border="0" cellspacing="1" cellpadding="2" align="center" bgcolor="#F7F7F7">
  <tr bgcolor="#E1A8A8"> 
    <td><font color="#990000"><b>Downloads by Day</b></font></td>
  </tr>
  <tr>
    <td><br><br><br>
      <table bgcolor="#F7F7F7" border=0 cellpadding=0 cellspacing=1>
        <tr valign="bottom">
Table

for ($i=0; $i<$max_day; $i++) {
  ($day, $downloads) = split(/\|/,$days[$total_days-$position-1-$i]);
  $top_day = $downloads if ($downloads > $top_day);
  $thisday[$i] = $downloads;
  $dates[$i] = $day;
  $total += $downloads;
}
$top_day = $today[1] if ($today[1] > $top_day);
for ($i=0; $i<$max_day; $i++) {
  $img_height = int($max_bar_height*$thisday[$max_day-1-$i]/$top_day);
  print "          <td>$thisday[$max_day-1-$i]<br><img src=\"bar.gif\" width=15 height=$img_height alt=\"$dates[$max_day-1-$i]\"></td>\n";
}
if ($position == 0) {
  $img_height = int($max_bar_height*$today[1]/$top_day);
  $total += $today[1];
  print "          <td>$today[1]<br><img src=\"bar2.gif\" width=15 height=$img_height alt=\"today\"></td>\n";
}
print "        </tr>\n       </table>\n      </td>\n    </tr>\n    <tr>\n"; 
print "      <td>Statistic: <font color=\"#660066\">$dates[$max_day-1]</font> to<font color=\"#660066\">\n"; 
print "        $dates[0]</font> Total Downloads: <font color=\"#FF0000\">$total</font>\n      </td>\n    </tr>\n</table>\n";
&footer;
exit(0);	
}

sub get_date {
my @months = ('January','February','March','April','May','June','July','August','September','October','November','December');
my @wdays = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
my $time_stamp = ($_[1] == 1) ? $_[0] : time();
my ($min,$hour,$mday,$mon,$year,$wday) = (localtime($time_stamp))[1,2,3,4,5,6];
$min = "0$min" if ($min < 10);
$hour = "0$hour" if ($hour < 10);
$mday = "0$mday" if ($mday < 10);
$year += 1900;
$date=("$wdays[$wday], $mday $months[$mon] $year");
return ("$wdays[$wday], $mday $months[$mon] $year $hour:$min");
}

sub show_track {
open(DATA,"$basedat");
@lines = <DATA>;
close(DATA);
shift (@lines);
chop (@lines);
$totalfiles = @lines = sort(@lines);

print "Content-type: text/html\n\n";
print <<TopHTML ;
<html>
<head>
<meta http-equiv="Expires" content="Tue, 01 Jan 1980 1:00:00 GMT">
<meta http-equiv="Pragma" content="no-cache">
<title>Top Downloads</title>
<style type="text/css">
<!--
td {  font-family: Arial, Helvetica, sans-serif; font-size: $font_size}
a {  text-decoration: none; color: #000000}
a:hover { color: #000099; text-decoration: underline }
.input {  font-size: $font_size}
tt {  font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13pt; font-weight: bold}
//-->
</style>
<script language="Javascript">
<!--
function check_char(strg) {
 var found = 0;
 for (char_pos=0; char_pos<strg.length; char_pos++) {
    if (strg.charAt(char_pos) == "|" || strg.charAt(char_pos) == "&" || strg.charAt(char_pos) == "=" || strg.charAt(char_pos) == '"' || strg.charAt(char_pos) == "'") {
       found = 1;
       break;
    }
 }
 return (found == 1) ? false : true;
}
function substitute_char(new_strg) {
 for (char_pos=0; char_pos<new_strg.length; char_pos++) {
    if (new_strg.charAt(char_pos) == " ") {
       new_strg=new_strg.substring(0,new_strg.indexOf(" "))+"%20"+new_strg.substring((new_strg.indexOf(" ")+1),new_strg.length);
    }
    else if (new_strg.charAt(char_pos) == "~") {
       new_strg=new_strg.substring(0,new_strg.indexOf("~"))+"%7E"+new_strg.substring((new_strg.indexOf("~")+1),new_strg.length);
    } 
 }
 return new_strg;
}
function set_value(entry, old_value) {
 var new_value = window.prompt("Change value for entry '"+entry+"' to:",old_value)
 var found = 0;
 if (new_value != "" && new_value != null) {
    for (char_pos=0; char_pos<new_value.length; char_pos++) {
       if (!(new_value.charAt(char_pos) >= '0' && new_value.charAt(char_pos) <= '9')) {
          found = 1;
       }
    }
    if (found == 1) {
       alert ("You entered an invalid value for "+entry+"!");
    }
    else if (new_value == old_value) {
       alert ("No changes were made!");
    }
    else { 
       window.location.href = "$cgiurl?admin=$admin_pass&manage=set_value&id="+entry+"&value="+new_value
    }
 }
}
function ChangeEntry(entry, old_name, feature) {
 var new_name = window.prompt("Enter a new "+feature+" for "+entry+":",old_name)
 var found = 1;
 if (new_name != "" && new_name != null) {
    if (check_char(new_name)) {
         new_name = substitute_char(new_name);
         found = 0;
    }
    if (found == 1) {
       alert ("Error! "+feature+" for "+entry+" contains unacceptable characters!");
    }
    else if (new_name == old_name) {
       alert ("No changes were made!");
    }
    else if (feature == "description") {
       window.location.href = "$cgiurl?admin=$admin_pass&manage=ren_entry&id="+entry+"&new_des="+new_name
    }
    else if (feature == "FileID") {
       window.location.href = "$cgiurl?admin=$admin_pass&manage=ren_id&id="+entry+"&new_id="+new_name
    }
    else if (feature == "URL") {
       window.location.href = "$cgiurl?admin=$admin_pass&manage=set_loc&id="+entry+"&new_loc="+new_name
    }
 }
}
function del_entry(entry) {
 if (window.confirm("Do you really want to delete this entry: "+entry)) {
    window.location.href = "$cgiurl?admin=$admin_pass&manage=del_entry&id="+entry
 }
}
function check_form() {
 var found = 1;
 des_field=document.form.description.value;
 id_field=document.form.new_id.value;
 if (des_field == "" || id_field == "") {
    alert ("Please fill out all blanks!");
    return false;
 }
 if (check_char(des_field) && check_char(id_field)) {
    found = 0;
 }
 if (found == 1) {
    alert ("Error! Unacceptable characters found!");
    return false;
 }
 if (document.form.new_loc.value.indexOf("tp://")==-1 || document.form.new_loc.value.indexOf(".")==-1) {
    alert("Please enter a valid location!");
    document.form.new_loc.focus();
    return false;
 }
}
// -->
</script>
</head>
<body bgcolor="$bgcolor" background="$back_img">
 <table width="$table_width" border="0" align="center">
  <tr>
    <td height="40"><tt>Administration Centre</tt></td>
    <td height="40" align="right" valign="bottom"><img src="$base_gif/point.gif" width="9" height="9"><a href="$cgiurl?job=show&amp;top=$show_default">Back to Top Downloads</a></td>
  </tr>
 </table>
 <table bgcolor="$table_bg" border=1 cellspacing=0 cellpadding=3 width="$table_width" align="center">
    <tr bgcolor="$table_top"> 
      <td><b>Description</b></td>
      <td><b>Filename</b></td>
      <td><b>Downloads</b></td>
      <td><b>Location</b></td>
      <td><b>Entry</b></td>
    </tr>
TopHTML
$total=0;
foreach $entry (@lines) {
  ($file_id,$count,$location,$stamp,$descript) = split(/\|/,$entry);
  print "    <tr>\n      <td><a href=\"javascript:ChangeEntry('$file_id','$descript','description')\">$descript</a></td>\n      <td><a href=\"javascript:ChangeEntry('$file_id','$file_id','FileID')\">$file_id</a></td>\n";
  print "      <td><a href=\"javascript:set_value('$file_id','$count')\">$count</a></td>\n      <td><a href=\"javascript:ChangeEntry('$file_id','$location','URL')\">set location</a></td>\n"; 
  print "      <td><a href=\"javascript:del_entry('$file_id')\">delete</a></td>\n    </tr>\n";
  $total+=$count;
}
print qq~
    <tr> 
      <td><b><font color="#336600">&gt;&gt;Total Files:</font></b> <font color="#FF0000">$totalfiles</font></td>
      <td colspan="4"><b><font color="#336600">&gt;&gt;Total Downloads:</font></b> <font color="#FF0000">$total</font></td>
    </tr>
  </table>
  <form method="post" action="$cgiurl" name="form">
    <table width="$table_width" border="0" align="center">
      <tr> 
        <td colspan="2"><input type="submit" name="action" value="Scan" class="input">
          <select name="type" class="input">
            <option value="all" selected>all files</option>
~;
foreach $type (keys %scan) {
  print "            <option value=\"$type\">$scan{$type}</option>\n";
}
print qq~          </select> Scan base directory for new files 
          <hr size="1"></td>
      </tr>
      <tr>
        <td>External Location: </td>
        <td><input type="text" name="new_loc" value="http://" size="32">
          <input type="hidden" name="admin" value="$admin_pass">
      </tr>
      <tr> 
        <td>Filename ID: </td>
        <td><input type="text" name="new_id" size="32"></td>
      </tr>
      <tr> 
        <td>Description: </td>
        <td><input type="text" name="description" size="32">
          <input type="submit" name="action" value="Add entry" onclick="return check_form()" class="input"></td>
      </tr>
      <tr> 
        <td colspan="2"><br>This script can be found at
         <img src="$base_gif/point2.gif" width="9" height="9"><a href="http://www.proxy2.de" target="_blank"><font color="#990000"><u>http://www.proxy2.de</u></font></a> 
         | <img src="$base_gif/point2.gif" width="9" height="9"><a href="$cgiurl?job=show&amp;top=$show_default">Back to Top Downloads</a></td>
      </tr>
    </table>
  </form>
</body>
</html>
~;
exit (0);
}

sub manage {
my ($last_date,$found,@lines);

open(DATA,"$basedat");
@lines = <DATA>;
close(DATA);
$last_date = shift(@lines);
$found=0;
foreach $main_line (@lines) {
      ($file_id,$count,$location,$stamp,$descript) = split(/\|/,$main_line);
      if ($FORM{'id'} eq $file_id) {
         if ($_[0] eq "del_entry") {
         	$main_line = "";
         	$found=1;
         	last;
         }
         elsif ($_[0] eq "ren_entry") {
         	$FORM{'new_des'} =~ s/ +/ /g;
         	$main_line = ("$file_id|$count|$location|$stamp|$FORM{'new_des'}\n");
         	$found=1;
         	last;
      	 }
      	 elsif ($_[0] eq "ren_id") {
      	 	$FORM{'new_id'} =~ s/\s*//g;
         	$main_line = ("$FORM{'new_id'}|$count|$location|$stamp|$descript");
         	$found=1;
         	last;
      	 }
      	 elsif ($_[0] eq "set_value") {
      	 	$main_line = ("$file_id|$FORM{'value'}|$location|$stamp|$descript");
         	$found=1;
         	last;
      	 }
      	 elsif ($_[0] eq "set_loc") {
         	$FORM{'new_loc'} =~ s/\s*//g;
         	$main_line = ("$file_id|$count|$FORM{'new_loc'}|$stamp|$descript");
         	$found=1;
         	last;
      	 }
      }
}
if ($found == 1) {
	open (DATA,">$basedat") || die $!;
	flock(DATA,2) if ($lock == 1);
	print DATA ("$last_date");
	print DATA (@lines);
	close (DATA);
}
}

sub scan_dir {
my ($new_date,$last_date,$found,$scantype,@lines,@filename,@new_array);
opendir(HOMEDIR, "$base_dir");
@filename = readdir(HOMEDIR);
closedir(HOMEDIR);

open(DATA,"$basedat");
@lines = <DATA>;
close(DATA);
$last_date = shift(@lines);

$scantype = ($FORM{'type'} eq "all") ? '.' : '.'.$FORM{'type'};
foreach $new_line (@filename) {
	next if ($new_line eq '.' || $new_line eq '..');
	next if ($new_line !~ /.*($scantype)$/ );
	foreach $test_line (@lines)  {
  		($file_id,$stub) = split(/\|/,$test_line,2);
		if ($new_line eq $file_id) {
			$found =1;
			last;
		}
		$found=0;				
	}
	$stamp = time();
	push (@new_array, "$new_line|0|$base_url/$new_line|$stamp|---\n") if ($found == 0);
}
if (@new_array>0) {
	open(FILE,">>$basedat");
	flock(FILE,2) if ($lock == 1);
	unless ($last_date =~ /\w+/) {
		$new_date = &get_date($new_date);
		print FILE ("$new_date\n");
	}
	print FILE (@new_array);
	close(FILE);
}
}

sub add_location {
my ($new_date,$last_date,$found,@lines);
$FORM{'new_id'} =~ s/\|//g;
$FORM{'new_id'} =~ s/=//g;
$FORM{'new_id'} =~ s/&//g;
$FORM{'new_id'} =~ s/\'//g;
$FORM{'new_id'} =~ s/\"//g;
$FORM{'new_id'} =~ s/\s*//g;
$FORM{'new_loc'} =~ s/\s*//g;
if ($FORM{'new_loc'} =~ /^(f|ht)tp:\/\/[._a-z0-9-]+/i && $FORM{'new_id'} ne '') {
	open(DATA,"$basedat");
	@lines = <DATA>;
	close(DATA);
	$last_date = shift(@lines);
	$found=0;
	foreach $main_line (@lines) {
		($file_id,$stub) = split(/\|/,$main_line,2);
		if ($FORM{'new_id'} eq $file_id) {
			$found =1;
			last;
		}
	}
	if ($found == 0) {
		$FORM{'description'} =~ s/\|//g;
		$FORM{'description'} =~ s/=//g;
		$FORM{'description'} =~ s/&//g;
		$FORM{'description'} =~ s/\'//g;
		$FORM{'description'} =~ s/\"//g;
		$FORM{'description'} =~ s/ +/ /g;
		$FORM{'description'} ="---" unless ($FORM{'description'});
		open(FILE,">>$basedat");
		flock(FILE,2) if ($lock == 1);
		unless ($last_date =~ /\w+/) {
			$new_date = &get_date($new_date);
			print FILE ("$new_date\n");
		}
		$stamp = time();
		print FILE ("$FORM{'new_id'}|0|$FORM{'new_loc'}|$stamp|$FORM{'description'}\n");
		close(FILE);
	}
}
else {
	&message('Invalid URL or file ID');
}
}

sub validation {
	
	if ($FORM{'password'} eq $admin_pass) {
		&show_track;		
	}
	elsif ($FORM{'password'} eq "") {
		&enterpass('Please enter a valid password!');
	} 
	else {
		&enterpass('<font color="#FF0000">You entered an invalid password. Please try again.</font>');
	}
}

sub enterpass {
print "Content-type: text/html\n\n";
print <<ENTERHTML ;
<html>
<head>
<title>Top Downloads</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
td {  font-family: Arial, Helvetica, sans-serif; font-size: $font_size}
tt {  font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13pt; font-weight: bold}
-->
</style>
</head>
<body bgcolor="$bgcolor" background="$back_img">
<form method="post" action="$cgiurl">
 <table width="$table_width" border="0" align="center">
  <tr>
    <td height="40"><tt>Administration Centre</tt></td>
  </tr>
 </table>
 <table width="$table_width" border="0" cellspacing="0" cellpadding="3" align="center">
   <tr bgcolor="$table_top">
     <td><b>Administration</b></td>
   </tr>
   <tr bgcolor="$table_bg"> 
     <td> 
       <input type="password" name="password">
       <input type="submit" value="Submit">
       <input type="hidden" name="admin" value="enter">
     </td>
   </tr>
   <tr bgcolor="$table_bg"> 
     <td>$_[0]</td>
   </tr>
   <tr> 
     <td><br>
       This script can be found at <a href="http://www.proxy2.de" target="_blank">http://www.proxy2.de</a> 
       | <a href="$cgiurl?job=show&amp;top=$show_default">Back to Top Downloads</a></td>
   </tr>
 </table>
</form>
</body>
</html>
ENTERHTML
exit (0);
}

sub message {
print "Content-type: text/html\n\n";
print <<ERROR ;
<html>
<head>
<meta http-equiv="Expires" content="Tue, 01 Jan 1980 1:00:00 GMT">
<meta http-equiv="Pragma" content="no-cache">
<title>Error</title>
</head>
<body bgcolor="#FFFFFF">
<font face="Verdana, Arial" size="3" color="#000099"><b>Top Downloads 2.0</b></font> 
<hr size="1" width="300" align="left">
<font face="Verdana, Arial" size="2">$_[0]</font>
</body>
</html>
ERROR
exit (0);
}
