#!/usr/local/bin/perl
#########################################################################
## Copyright Notice: This Script and all its contents are the copyrights#
## of Justin Garen.  Any attempt to steal code from this, or any other  # 
## script, may result in legal action.                                  #
## This script may be used freely as long as this copyright/header      #
## information remains intact.                                          #
## If you would like to modify this script, feel free. However,         #
## you cannot distribute this script without prior written consent from # 
## the owner, Justin Garen, who can be reached at: garen@isd.net        #
#########################################################################
### Define Vars ###
$basedir = "utenti.quipo.it/Analisi/counter";
$baseurl = "www.utenti.quipo.it/Analisi";
$gifurl  = "utenti.quipo.it/Analisi/counter";
$multi_submit = "no";
### Done with vars ###
### Do not do anything beyond this point ###

### Counter Actions ###
if($multi_submit =~ /no/) {
   if($ENV{'HTTP_COOKIE'} || !GoodIP()) {
      GetCount();
      PrintCount();
   }
   else {
      print "Set-Cookie: cookie-name = Unique; ";
      print "domain = .$baseurl; ";
      print "path = /; ";
      print "expires = Thursday, 11-Dec-2100 00:00:00 GMT\n";

      LogIP();
      GetCount();
      UpdateCount();
      PrintCount();
   }
}
else {
   GetCount();
   UpdateCount();
   PrintCount();
}
### Done ###

### Subroutines ###
sub GetCount {
   open(datafile,"$basedir/data.txt") || die$!;
   $data = <datafile>;
   close(datafile);
}

sub UpdateCount {
   open(datafile,">$basedir/data.txt") || die$!;
   flock("$basedir/data.txt",2);
   print datafile ++$data;
   flock("$basedir/data.txt",8);
   close(datafile);
}

sub PrintCount {
   print "Content-type:text/html\n\n";
   foreach $digit (split(//,$data)) {
      print "<img src=\"http://$gifurl/$digit.gif\">";
   }
}

sub LogIP {
   open(LOGFILE,"$basedir/log.txt") || die$!;
   @LOG = <LOGFILE>;
   close(LOGFILE);

   @LOG = splice(@LOG,0,99);
   unshift(@LOG,"$ENV{'REMOTE_ADDR'}\n");

   open(LOGFILE,">$basedir/log.txt");
   flock("$basedir/log.txt",2);
   foreach (@LOG) { print LOGFILE; }
   flock("$basedir/log.txt",8);
   close(LOGFILE);
}

sub GoodIP {
   open(LOGFILE,"$basedir/log.txt") || die$!;
   @LOG = <LOGFILE>;
   close(LOGFILE);

   foreach (@LOG) { return 0 && last if /$ENV{'REMOTE_ADDR'}/; }

   return 1;
}
### End of Subroutines ###

