#!/usr/local/bin/perl
##############################################################################
# CountDown                    Version 3.0                                   #
# Copyright 2000 Edward Preble scripts@datatrendsoftware.com                 #
# Created 11/30/98             Last Modified 01/28/00                        #
# Datatrend Software           http://www.datatrendsoftware.com/cgi.html     #
##############################################################################
# This script will do the following:                                         #
# 1. Is activated by a link of the following form,                           #
#    http://www.yoursite.com/yourdir/countdown.cgi?yourfile.anything         #
# 2. Updates a text log file with the counts of the downloads made so far,   #
#    ordered greatest to least.                                              #
# 3. Creates 2 output html files, 1 with all the download counts, and another#
#    with just the top ten downloads. These are great to let site visitors   #
#    see the most popular downloads available on your site.                  #
# 4. Optionally reads a data file to make the log files have a "real" name   #
#    instead of a filename in the list of downloads. For example, a file can #
#    be listed as "MS Word" instead of "word.exe". This is more useful in    #
#    tables that are displayed for web visitors.                             #
# 4. Can use custom headers and footers for the output pages. This idea      #
#    suggested by Lyon Lim.
# 5. Creates a javascript data file for javascript counters. This idea       #
#    suggested by Dan Williams.                                              #
# 6. Will auto-forward the web surfer to the download.                       #
# 7. The interface is seamless, there are no user prompts.                   #
##############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright 1998-2000 Edward Preble  All Rights Reserved.                    #
#                                                                            #
# This script is free.  You may use and modify this script as you please.    #
# Do not remove this header, as it is the only thing that gives me credit    #
# for my work in writing this code. If you wish to sell this code, you       #
# must obtain permission from the authors first.                             #
#                                                                            #
# Scripts provided by Datatrend Software are supplied "as-is". You agree     #
# to indemnify the author's from any liability that may arise from the use   #
# of this script.                                                            #
#                                                                            #
# Obtain permission before redistributing this software over the Internet or #
# in any other medium. In all cases copyright and header must remain intact. #
##############################################################################
#                                                                            #
# You must modify the the location of PERL in the first line above to match  #
# the location on your server.                                               #
# You must also modify the following variables to match your preferences.    #
# THE README.TXT FILE HAS DETAILED EXPLANATIONS OF THESE VARIABLES.          #

#Location and name of the CountDown Script on your server
$CountDownLocation = 'http://www.designinganalogchips.com/_count/countdown.pl';

# This is the directory location of the file(s) that will be downloaded
$DownloadFileDir = 'http://www.designinganalogchips.com/_count';

# This is the counter log filename
$Counter = 'countdown.log';

# Do you want to use Real Names, instead of filenames? (yes/no)
$UseRealNames = 'no';

# This is the location of your "real name" data file (if used)
$RealNameFile = 'realname.dat';

# This is the HTML output filename (lists all countdown activity)
$HTMLFile = 'countdownlog.htm';

# This is the HTML output filename for the Top Ten List only
$TopTenFile = 'countdowntopten.htm';

# These are the Javascript data file options, used to make live counters on
#your pages with javascript. (yes/no)
$CreateJavaScriptLog = 'no';

# Location and name of Javascript data file
$JavaScriptLog = 'countdown.js';

# Add Custom Headers to the HTML outputs? (yes/no)
$CustomTopTenHeader = 'no';
$CustomTopTenFooter = 'no';
$CustomHTMLPageHeader = 'yes';
$CustomHTMLPageFooter = 'yes';

# If you wanted headers and footers, specify the filenames here.
$TopTenHeaderFile = 'TopTenHeader.htm';
$TopTenFooterFile = 'TopTenFooter.htm';
$HTMLPageHeaderFile = 'HTMLHeader.htm';
$HTMLPageFooterFile = 'HTMLFooter.htm';

##########################################################
# No changes need to be made after these lines
##########################################################
$File = $ENV{'QUERY_STRING'};
# Strip off anything up to, and including, the last "/", if present
if ($File =~ /\//) { ($File) = $File =~ /^.*\/([^\/]+)$/g; }
$DownloadFile = "$DownloadFileDir/$File";

# Add hit to main counter
open (CNT,"+<$Counter") || &endIt;
flock (CNT,2); 
seek (CNT,0,0);
@infile = <CNT>;

# Use the Real Name data file if desired
# This file will allow real names to be listed, instead of file names
if ($UseRealNames eq 'yes')
	{open (REAL,"$RealNameFile") || &endIt;
	flock (REAL,2); 
	seek (REAL,0,0);
	@RealFile = <REAL>;
	close (REAL);
	$find = 0;
	while ($find <= $#RealFile)
		{($RealName,$filename,$eol) = split(/\|/,$RealFile[$find]);
		if ($filename eq $File)  #if this is the right file, change filename to RealName
			{$File = $RealName;
		}
	  $find++;
	}
}

# This will put the hits in order from max to min for each file added
$record = 0;		# Starting record in the log is always 0
$correctspot = 'N';	# Tells script if this record is the one that was hit

# Proceeds as long as the record number is less than the total 
# number of records in the file and the correct record hasn't been found yet.
while (($correctspot eq 'N') && ($record <= $#infile))  
	{($count,$filename,$eol) = split(/\|/,$infile[$record]);
	if ($filename eq $File)  #if this is the right record, hit it, trip correctspot
    	{$count++;
	    $infile[$record] = join ("\|",$count,$filename,"\n");
	    $correctspot = 'Y';
    }
  $record++;
}
if ($correctspot eq 'N')
	{$count = 1;
	$newrecord = join ("\|",$count,$File,"\n");
	push @infile, $newrecord;
}

@outfile = sort {($b =~ /(\d+)/)[0] <=> ($a =~ /(\d+)/)[0]} @infile;

seek (CNT,0,0);
print (CNT @outfile);
truncate (CNT,tell(CNT));
close (CNT);

if ($CreateJavaScriptLog eq 'yes')
	{open (Out,"+>$JavaScriptLog") || &endIt;
	flock (Out,2);
	foreach (@outfile) {
	($count,$filename,$eol) = split(/\|/,$_);
	print {Out} "$filename = $count\n";}
} 

if ($UseRealNames eq 'yes')
	{&RealOuts;}			#Output uses RealNames file
	else {&NormalOuts;}		#Output uses filenames passed from form

sub NormalOuts {
#Create HTML File which contains the whole list of downloads

open (Out,"+>$HTMLFile") || &endIt;
flock (Out,2);

# Create Header
if ($CustomHTMLPageHeader eq 'yes')
	{&HTMLCustomHeader;}			#Get custom header html
	else {&HTMLGenericHeader;}		#Create a generic header

# Create Normal Table (no real names)
print {Out} <<TextOut;
<table border="0" cellspacing="4">
  <tr>
    <td align="right"><strong>Downloads - </strong></td>
    <td><strong>File</strong></td>
  </tr>
TextOut
foreach (@outfile) {
($count,$filename,$eol) = split(/\|/,$_);
print {Out} <<TextOut;
  <tr>
    <td align="right">$count - </td>
    <td><a href="$CountDownLocation?$filename">$filename</a></td>
  </tr>
TextOut
}
print {Out} <<TextOut;
<tr><td align="right" colspan="2"><font face="Arial" size="1">&nbsp;</font>
<p>
<font face="Arial" size="1">This is a cumulative total of downloads since March 4, 2005.
</font></td></tr></table></p>
TextOut

# Create Footer
if ($CustomHTMLPageFooter eq 'yes')
	{&HTMLCustomFooter;}			#Get custom footer html
	else {&GenericFooter;}		#Create a generic footer
close (Out);

#Create HTML File - Top Ten List Only
open (Out,"+>$TopTenFile") || &endIt;
flock (Out,2);

# Create Header
if ($CustomTopTenHeader eq 'yes')
	{&TopTenCustomHeader;}			#Get custom header html
	else {&TopTenGenericHeader;}		#Create a generic header

# Create Top Ten HTML Table
print {Out} <<TextOut;
<table border="0" cellspacing="4">
  <tr>
    <td align="right"><strong>Top Ten Downloads - </strong></td>
    <td><strong>File</strong></td>
  </tr>
TextOut
if ($#outfile < 9) {
	for ($i = 0; $i <= $#outfile; $i++) {
	($count,$filename,$eol) = split(/\|/,$outfile[$i]);
print {Out} <<TextOut;
  <tr>
    <td align="right">$count - </td>
    <td><a href="$CountDownLocation?$filename">$filename</a></td>
  </tr>
TextOut
	}
} else {
for ($i = 0; $i <=9; $i++) {
($count,$filename,$eol) = split(/\|/,$outfile[$i]);
print {Out} <<TextOut;
  <tr>
    <td align="right">$count - </td>
    <td><a href="$CountDownLocation?$filename">$filename</a></td>
  </tr>
TextOut
	}
}
print {Out} <<TextOut;
<tr><td align="right" colspan="2"><font face="Arial" size="1">&nbsp;</font>
<p>
<font face="Arial" size="1">Log created with <a href="http://www.datatrendsoftware.com/countdown.html">CountDown</a> by <a href="http://www.datatrendsoftware.com/cgi.html">Datatrend Software</a>.
</font></td></tr></table></p>
TextOut

# Create Footer
if ($CustomTopTenFooter eq 'yes')
	{&TopTenCustomFooter;}			#Get custom footer html
	else {&GenericFooter;}		#Create a generic footer
close (Out);
}

sub HTMLGenericHeader {
print {Out} <<TextOut;
<html>
<head>
<title>CountDown Log File Contents</title>
</head>
<body>
TextOut
}
sub GenericFooter {
print {Out} <<TextOut;
</body>
</html>
TextOut
}
sub HTMLCustomHeader {
open (HEAD,"$HTMLPageHeaderFile") || &endIt;
flock (HEAD,2); 
seek (HEAD,0,0);
@Header = <HEAD>;
close (HEAD);
print {Out} "@Header";
}
sub HTMLCustomFooter {
open (FOOT,"$HTMLPageFooterFile") || &endIt;
flock (FOOT,2); 
seek (FOOT,0,0);
@Footer = <FOOT>;
close (FOOT);
print {Out} "@Footer";
}
sub TopTenGenericHeader {
print {Out} <<TextOut;
<html>
<head>
<title>CountDown Log File Contents</title>
</head>
<body>
TextOut
}
sub TopTenCustomHeader {
open (HEAD,"$TopTenHeaderFile") || &endIt;
flock (HEAD,2); 
seek (HEAD,0,0);
@Header = <HEAD>;
close (HEAD);
print {Out} "@Header";
}
sub TopTenCustomFooter {
open (FOOT,"$TopTenFooterFile") || &endIt;
flock (FOOT,2); 
seek (FOOT,0,0);
@Footer = <FOOT>;
close (FOOT);
print {Out} "@Footer";
}

sub RealOuts {
#Create HTML File - Whole List

open (REAL,"$RealNameFile") || &endIt;
	flock (REAL,2); 
	seek (REAL,0,0);
	@RealFile = <REAL>;
	close (REAL);

open (Out,"+>$HTMLFile") || &endIt;
flock (Out,2);

# Create Header
if ($CustomHTMLPageHeader eq 'yes')
	{&HTMLCustomHeader;}			#Get custom header html
	else {&HTMLGenericHeader;}		#Create a generic header

# Create Normal Table (no real names)
print {Out} <<TextOut;
<table border="0" cellspacing="4">
  <tr>
    <td align="right"><strong>Downloads - </strong></td>
    <td><strong>File</strong></td>
  </tr>
TextOut
foreach (@outfile)
		{($count,$filename,$eol) = split(/\|/,$_);
				$find = 0;
		while ($find <= $#RealFile)
			{($RealName,$LiteralName,$eol) = split(/\|/,$RealFile[$find]);
			if ($filename eq $RealName)  #if this is the right file, change filename to RealName
			    {$Output = $LiteralName;
		    }
			$find++;
		}
print {Out} <<TextOut;
  <tr>
    <td align="right">$count - </td>
    <td><a href="$CountDownLocation?$Output">$filename</a></td>
  </tr>
TextOut
}
print {Out} <<TextOut;
<tr><td align="right" colspan="2"><font face="Arial" size="1">&nbsp;</font>
<p>
<font face="Arial" size="1">Log created with <a href="http://www.datatrendsoftware.com/countdown.html">CountDown</a> by <a href="http://www.datatrendsoftware.com/cgi.html">Datatrend Software</a>.
</font></td></tr></table></p>
TextOut

# Create Footer
if ($CustomHTMLPageFooter eq 'yes')
	{&HTMLCustomFooter;}			#Get custom footer html
	else {&GenericFooter;}		#Create a generic footer

#Create HTML File - Top Ten List Only
open (Out,"+>$TopTenFile") || &endIt;
flock (Out,2);

# Create Header
if ($CustomTopTenHeader eq 'yes')
	{&TopTenCustomHeader;}			#Get custom header html
	else {&TopTenGenericHeader;}		#Create a generic header

# Create Top Ten HTML Table
print {Out} <<TextOut;
<table border="0" cellspacing="4">
  <tr>
    <td align="right"><strong>Top Ten Downloads - </strong></td>
    <td><strong>File</strong></td>
  </tr>
TextOut
if ($#outfile < 9) {
	for ($i = 0; $i <= $#outfile; $i++) {
	($count,$filename,$eol) = split(/\|/,$outfile[$i]);
			$find = 0;
		while ($find <= $#RealFile)
			{($RealName,$LiteralName,$eol) = split(/\|/,$RealFile[$find]);
			if ($filename eq $RealName)  #if this is the right file, change filename to RealName
			    {$Output = $LiteralName;
		    }
			$find++;
		}
print {Out} <<TextOut;
  <tr>
    <td align="right">$count - </td>
    <td><a href="$CountDownLocation?$Output">$filename</a></td>
  </tr>
TextOut
	}
} else {
for ($i = 0; $i <=9; $i++) {
($count,$filename,$eol) = split(/\|/,$outfile[$i]);
		$find = 0;
		while ($find <= $#RealFile)
			{($RealName,$LiteralName,$eol) = split(/\|/,$RealFile[$find]);
			if ($filename eq $RealName)  #if this is the right file, change filename to RealName
			    {$Output = $LiteralName;
		    }
			$find++;
		}
print {Out} <<TextOut;
  <tr>
    <td align="right">$count - </td>
    <td><a href="$CountDownLocation?$Output">$filename</a></td>
  </tr>
TextOut
	}
}
print {Out} <<TextOut;
<tr><td align="right" colspan="2"><font face="Arial" size="1">&nbsp;</font>
<p>
<font face="Arial" size="1">Log created with <a href="http://www.datatrendsoftware.com/countdown.html">CountDown</a> by <a href="http://www.datatrendsoftware.com/cgi.html">Datatrend Software</a>.
</font></td></tr></table></p>
TextOut

# Create Footer
if ($CustomTopTenFooter eq 'yes')
	{&TopTenCustomFooter;}			#Get custom footer html
	else {&GenericFooter;}		#Create a generic footer
}

sub HTMLGenericHeader {
print {Out} <<TextOut;
<html>
<head>
<title>CountDown Log File Contents</title>
</head>
<body>
TextOut
}
sub GenericFooter {
print {Out} <<TextOut;
</body>
</html>
TextOut
}
sub HTMLCustomHeader {
open (HEAD,"$HTMLPageHeaderFile") || &endIt;
flock (HEAD,2); 
seek (HEAD,0,0);
@Header = <HEAD>;
close (HEAD);
print {Out} "@Header";
}
sub HTMLCustomFooter {
open (FOOT,"$HTMLPageFooterFile") || &endIt;
flock (FOOT,2); 
seek (FOOT,0,0);
@Footer = <FOOT>;
close (FOOT);
print {Out} "@Footer";
}
sub TopTenGenericHeader {
print {Out} <<TextOut;
<html>
<head>
<title>CountDown Log File Contents</title>
</head>
<body>
TextOut
}
sub TopTenCustomHeader {
open (HEAD,"$TopTenHeaderFile") || &endIt;
flock (HEAD,2); 
seek (HEAD,0,0);
@Header = <HEAD>;
close (HEAD);
print {Out} "@Header";
}
sub TopTenCustomFooter {
open (FOOT,"$TopTenFooterFile") || &endIt;
flock (FOOT,2); 
seek (FOOT,0,0);
@Footer = <FOOT>;
close (FOOT);
print {Out} "@Footer";
}

	print "Content-type: text/html\n";
	print "Location: $DownloadFile\n\n";
#	print "Location: $File\n\n";

sub endIt # exit on error
{ exit;
} # end endIt