#!/usr/bin/perl
#################################
# psCounter.cgi            v1.8 #
# http://pscripts.psyon.org     #
# Copyright pScripts! 2001-2004 #
#################################

# Set this to the directory to store data.
# This directory must have write access.
# Use "." for cgi-bin directory
$DDIR = ".";

# Set this to the relative url where digit
# images will be stored.  This is only if
# a graphic display is used. 
$IPATH = "/imgs/digits";

# Image to use for show=image
# It must be in $IPATH
$IMAGE = "counter.gif";

###############################
# Script                      #
# Do not edit below this line #
###############################
@cookies = split(/;/, $ENV{'HTTP_COOKIE'});
foreach(@cookies) {
  ($name, $value) = split(/=/, $_);
  $name =~ s/\s+//g;
  $COOKIE{$name} = $value;
}

@pairs = split(/&/, $ENV{'QUERY_STRING'});
foreach $pair (@pairs)
{
    if($pair eq 'show') {
      $show = 1;
    } else {
      ($name, $value) = split(/=/, $pair);
      $value =~ tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
      $value =~ s/~!/ ~!/g;
      $FORM{$name} = $value;
    }
}

$cname = "pscounter-$ENV{'HTTP_HOST'}-$FORM{'id'}";

if(defined $COOKIE{$cname}) {
  $show = 1;
} else {
  $expr = &date(time + 86400);
  $domain = $ENV{'HTTP_HOST'};
  print "Set-Cookie: $cname=1; domain=$domain; expires=$expr\n";
}

print "Content-Type: application/x-javascript\n\n";
$file = "$DDIR/$FORM{'id'}.cnt";
if(! -e $file) {
  $count = 0;
} else {
  open(CNT, "$file") || die "count not read $file";
  $count = <CNT>;
  chomp($count);
  close(CNT);
}

if(!$show) {
  $count++;
  open(CNT, ">$file") || die "could not write to $file";
  print CNT $count;
  close(CNT);
}

print "<!-- //\n";

if($FORM{'display'} ne "hide") {
  if(defined($FORM{'zero'})) {
    $zeros = '0' x ($FORM{'zero'} - length($count));
    $count = $zeros . $count;
  }
  if($FORM{'display'} eq "graphic") {
    $count =~ s/([0-9])/<img src=\\"$IPATH\/$1.gif\\">/g;
  }
  if($FORM{'display'} eq "image") {
    $count = "<img src=\\\"$IPATH\/$IMAGE\\\">";
  }
  print "document.write(\'$count\');\n";  
} 

print <<EOF;
  /*
  <!--#echo banner=""-->
  */
// -->
EOF

exit;

sub date {
  local($time, $format) = @_;
  local($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = gmtime($time);
  
  $sec  = "0$sec" if ($sec < 10);
  $min  = "0$min" if ($min < 10);
  $hour = "0$hour" if ($hour < 10);
  $mon  = "0$mon" if ($mon < 10);
  $mday = "0$mday" if ($mday < 10);
  my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
                "Aug", "Sep", "Oct", "Nov", "Dec");
  my @days = ("Sunday", "Monday", "Tuesday", "Wednesday", " Thursday",
		"Friday", "Saturday");
  
  $month = $months[$mon];
  $day = $days[$wday];
  $year -= 100 if($year > 99);
  $year = "0$year" if ($year < 10);
  return "$day, $mday-$month-$year $hour\:$min\:$sec GMT";
}
