#!/usr/bin/perl

#-------------------------Welcome-----------------------------
#
# Click Tracker
# Ver. 1.0
# By Luke and Mark Pfeifer
# http://www.staff.net/cgi-scripts/		
# Released 11-16-98
# Updated 11-16-98
#
#
# Copyright Info: This application was written by Mark and Luke
# Pfeifer. Feel free to copy, cite, reference, sample, borrow 
# or plagiarize the contents.  However, if you don't mind,
# please let us know where it goes so that we can watch and take
# part in the development of it. Information wants to be free,
# support public domain freeware.  Donations are appreciated
# and will be spent on further upgrades and other public domain
# scripts.
#
# Finally, PLEASE SEND WORKING URL's to scripts@staff.net.
# We would like to keep a list of these scripts in use.
#-------------------------------------------------------------
#
#-----------------------Version History--------------------------
#
# Version 1.0 - 11-16-98     - Orginal Version Created
#
#-------------------------------------------------------------
#
#-----------------------ReadMe--------------------------------
#
# This script works with IIS (Internet Infromation Server)
# and PWS (Personal Web Server)!
#
# This script requires that PERL is loaded on your web server
# and that the web server is configured to run PERL scripts as
# CGI scripts.
#
# Configure the script in the User Configuration section below.
#
# Upload this file to your CGI directory on your web server in
# ASCII mode.  If you do not know if you have a CGI directory,
# ask your web server administrator.
#
# Chmod this file to 755, if you have Unix.
#
# On unix machines you must create an empty file with the name 
# of your log file and then chmod it to 777.  Most NT machines
# do this automatically for you.
#
# The script is called by adding an SSI line into the page you
# want to count.  The following is an example of doing this:
#   <!--#exec cgi="/cgi-bin/clicktracker/clicktracker.pl"--> hits since 1/1/1998
#
# To access the log file online go to the url
#   http://www.yourdomain.com/cgi-bin/clicktracker.pl?view=password
#
#   Notes on above example:
#
#	- You need to change the url of the script clicktracker.pl to
#	  where it is located on your server.
#
#	- Change "password" to the password you chose below for $view_log
#
#-------------------------------------------------------------
#
#--------------- Variable Defention --------------------------
#
# $filename - the name of the log file. 
#
# $main_dir - the location of the log file.  You must
#	have the full path.  If you are unsure what it is
#	contact your server admin.
#
# $autoadd - decides whether or not to automatically
#	add links that are not in the database.
#	1 = on      2 = off
#
# $view_log - The password you wish to use to view the
#	log file online so clicktracker.pl?view=whatever you 
#	chose for this string.  In this script it is set-up
#	to use test so you would use clicktracker.pl?view=test
#
# @ignore - List of IP Addresses to ignore and not count clicks
#	for.  Each IP Address is sperated by a comma and enclosed in
#	single qoutes.  You many leave this blank by putting a # sign
#	right before the @ sign in the line.
#-------------------------------------------------------------
#
#------- Start User Configuration ----------------------------
$filename = 'clicktracker.log';
$main_dir = '/web/cgi-bin/staff.net/cgi-scripts/click-tracker';
$autoadd=1;  
$view_log='test';
@ignore = ('209.207.58.3', '209.207.58.4', '209.207.58.5', '209.207.58.6');
#---End User Configuration -----------------------------------

#**************** DO NOT EDIT PAST THIS LINE *****************#
$scriptname = 'ClickTracker';
$version = '1.0';

&FormInput(*input);

################################
# Default Variables
################################
$addnew=0;

$lock = "$main_dir/clicktracker_lock.lock";
$logfile = "$main_dir/$filename";

####################
# Set Lock File
####################
if ($input{'view'} ne $view_log) 
  {
	&SetLock;
  }

####################
# Create the log file
# if it does not exist
####################
if (!(-e $logfile))
  {
	open(DATA, ">$logfile");
	close(DATA);
  }

####################
# Read in Data File
####################
if ( open(DATA,"$logfile") )
  {
	@lines = <DATA>;
	close(DATA);
  }
else
  {
	&PrintError("Error opening file $logfile", $!);
	&EndLock;
	exit;
  }


#####################
# View Log
#####################
if ($input{'view'} eq $view_log) 
  {
	$spacing = "&nbsp;&nbsp;&nbsp;&nbsp;";

	print "HTTP/1.0 200 OK\nContent-type: text/html\r\n" if $ENV{PERLXS} eq "PerlIS";
	print "Content-type: text/html\n\n";

	print "<html>\n";
	print "<title>$scriptname Log Viewer</title>\n";
	print "<body bgcolor=FFFFFF>\n";
	print "<center>\n";
	print "<h1>$scriptname Log Viewer - View all Pages</h1>\n";
	print "<table border=1>\n";
	print "<tr><td colspan=1 bgcolor=\"CCFFFF\">$spacing<strong><u>Page</strong></u>$spacing</td>\n";
	print "<td colspan=1 bgcolor=\"FF9999\">$spacing<strong><u>Hits</strong></u> $spacing</td></tr>\n";

	foreach $line (@lines)
  	  {
		($page1, $page2, $page_counter1) = split(/\|/,$line);
  		print "<tr><td bgcolor=\"CCFFFF\" align=left>$page2 $spacing</td>\n";
		print "<td bgcolor=\"FF9999\" align=right>$spacing $page_counter1</td></tr>\n";
  	  }

	print "</table>\n";
	print "<hr>\n";
	print "<br><em>$scriptname Ver. $version</em>\n";
	print "<br>Created By: <a href=\"http://www.staff.net/cgi-scripts/\">Click-Scripts</a> ";
	print "</center>\n";
	print "</body>\n";
	print "</html>\n";
  }  
elsif($ENV{'DOCUMENT_ROOT'} eq "" || $ENV{'DOCUMENT_URI'} eq "")
  {
	&PrintError("This script must be executed using SSI");
	&EndLock;
	exit;

  }

	
#####################
# Count Incrementing
#####################
else
  {


	foreach $ignore (@ignore)
	  {
		if($ENV{'HTTP_REFERER'} eq $ignore)
		  {
			$skip = "yes";
		  }
	  }

	if (!open(DATA,">$logfile"))
	  {
		&PrintError("Cannot open file $logfile for writing", $!);
		&EndLock;
		exit;
	  }

	  foreach $line (@lines)
	  {
	  	($page1, $page2, $page_counter1) = split(/\|/,$line);
	  	if ($ENV{'DOCUMENT_ROOT'} eq $page1 && $ENV{'DOCUMENT_URI'} eq $page2) 
		  {
			$page_counter1++ if $skip ne "yes";
		 	print DATA ("$page1|$page2|$page_counter1|\n");
		 	$addnew=1;
			$page_counterdp = $page_counter1;
	  	  }
	      else 
	  	  {
			print DATA $line;
	  	  }

	  }

	#####################
	# Auto Add entry
	#####################

	if ($addnew == 0 && $autoadd == 1)
	  {
		print DATA ("$ENV{'DOCUMENT_ROOT'}|$ENV{'DOCUMENT_URI'}|1|\n") if $skip ne "yes";
		$page_counterdp = 1;
	  }

	#####################
	# Close Log File
	#####################
	close(DATA);

	&EndLock;


	#######################
	# Print Count to Page
	#######################
	print "HTTP/1.0 200 OK\nContent-type: text/html\r\n" if $ENV{PERLXS} eq "PerlIS";
	print "Content-type: text/html\n\n";

	print $page_counterdp;
		
  } # Closes Else for View Log


exit;



#-------------------------------------------------------------
# function: FormInput
#-------------------------------------------------------------
sub FormInput
{
local (*qs) = @_ if @_;

if ($ENV{'REQUEST_METHOD'} eq "GET")
        {
        $qs = $ENV{'QUERY_STRING'};
        }
elsif ($ENV{'REQUEST_METHOD'} eq "POST")
        {
        read(STDIN,$qs,$ENV{'CONTENT_LENGTH'});
        }

@qs = split(/&/,$qs);

foreach $i (0 .. $#qs)
        {
        $qs[$i] =~ s/\+/ /g;
        $qs[$i] =~ s/%(..)/pack("c",hex($1))/ge;

        ($name,$value) = split(/=/,$qs[$i],2);

        if($qs{$name} ne "")
                {
                $qs{$name} = "$qs{$name}:$value";
                }
        else
                {
                $qs{$name} = $value;
                }
        }

return 1;
}

#-------------------------------------------------------------
# SetLock: Subroutine
#-------------------------------------------------------------
sub SetLock {

        $timecheck = 0;
	while(-e $lock)
	    {
            sleep(1);
	    $timecheck = $timecheck + 1;
	    if ($timecheck >= 15)
		{
		unlink("$lock");
		}
	    }
        open(LOCKFILE,">$lock");
        close(LOCKFILE);
        return;
}

#-------------------------------------------------------------
# EndLock: Subroutine
#-------------------------------------------------------------
sub EndLock {

	unlink("$lock");
        return;
}

#-------------------------------------------------------------
# PrintError: Subroutine
#-------------------------------------------------------------
sub PrintError {

	local ($err_msg1, $err_msg2) = @_ if @_;

	print "HTTP/1.0 200 OK\nContent-type: text/html\r\n" if $ENV{PERLXS} eq "PerlIS";
	print "Content-type: text/html\n\n";

	print "<html>\n";
	print "<title>$scriptname Error</title>\n";
	print "<body bgcolor=FFFFFF>\n";
	print "<center>\n";
	print "<h1>$scriptname Error - $err_msg1<br>\n";
	print "Error Message:  $err_msg2\n" if ($err_msg2 ne '');
	print "</h1><hr>\n";
	print "<br><em>$scriptname Ver. $version</em>\n";
	print "<br>Created By: <a href=\"http://www.staff.net/cgi-scripts/\">Click-Scripts</a> ";
	print "</center>\n";
	print "</body>\n";
	print "</html>\n";

}
