#!/usr/bin/perl

##########################################################################
# 755                                                                    #
#                                                                        #
#   <script language="JavaScript" type="text/javascript"                 #
#    src="http://www.krommer.com/counter/counter.pl"></script>           #
##########################################################################

# how many digits to show
$padding = 6;

# path to the log file
$log_dat = "hits.txt";

# url to the digits
$img = "http://www.krommer.com/counter/bilder/";

# url to the animated digits
$animated_img = "http://www.krommer.com/counter/bilder/";

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

# digit width and height
$width = 12;
$height = 15;

# optional configuration settings

$lock_ip =1; # IP locking (counter doesn't increments when page is reloaded) 1=yes 0=no
$ip_lock_timeout =30; # in minutes
$fpt_ip = "ip.txt"; # path to ip log file
# End Setup
##################

print "Content-Type: text/html\n\n";

sub checkIP {
  open (FILE,"$fpt_ip");
  @ip_array = <FILE>;
  close (FILE);
  open (TABLE,">$fpt_ip") || &error("Cannot create ip log file.\n");
  $this_time = time();
  foreach $visitor (@ip_array) {
    ($ip_addr,$time_stamp) = split(/\|/,$visitor);
    if ($this_time < $time_stamp+(60*$ip_lock_timeout)) {
      if ($ip_addr eq $ENV{'REMOTE_ADDR'}) {
        $found=1;
      } else {
        print TABLE "$ip_addr|$time_stamp";
      }
    }
  }
  print TABLE "$ENV{'REMOTE_ADDR'}|$this_time\n";
  close(TABLE);
  return ($found==1) ? 1 : 0;
}

sub error {
  print "$_[0]";
  exit (0);
}

$flag = ($lock_ip==1) ? &checkIP : 0;
if (!(-e "$log_dat")) {
  open (FILE,">$log_dat") || &error("Cannot create log file.\n");
  $count = 0;
  print FILE "$count";
  close (FILE);
} else {
  open (FILE,"+<$log_dat");
  $count = <FILE>;
  if ($lock_ip==0 || ($lock_ip==1 && $flag!=1)) {
    flock(FILE,2) if ($lock == 1);
    $count++;
    seek(FILE,0,0);
    print FILE "$count";
  }
  close (FILE);
}
$count = sprintf("%0"."$padding"."d", $count);
@digits = split(//, $count);
$count++;
@ani_digits = split(//, $count);
print "<!--\n";
print "document.write(\"<table cellpadding=0 cellspacing=0 border=0><tr align=center>\")\;\n";
$i = 0;
foreach $number (@digits) {
  if ($number == @ani_digits[$i]) {
    print "document.write(\"<td><img src=$img$number.gif width=$width height=$height></td>\")\;\n";
  } else {
    print "document.write(\"<td><img src=$animated_img@ani_digits[$i].gif width=$width height=$height></td>\")\;\n";
  }
  $i++;
}
print "document.write(\"</tr></table>\")\;\n";
print "// -->";
exit(0);

