#!/bin/perl #
##############################################################################
# Counter script
#    Compiled by Jerzy Sobczyk	J.Sobczyk@ia.pw.edu.pl
#    Created on: 1996.4.26	Last modified on: 1997.10.14
#    Script source:		http://www.ia.pw.edu.pl/js/counter/hits
# 
# Based on:
#    Counter Script		Version 1.1.1
#    Created by Matt Wright	mattw@misha.net
#    Created on: 10/27/95	Last Modified on: 1/11/96
#    Scripts Archive:		http://www.worldwidemart.com/scripts/
# and:
#    WWWCount Text Version (Requires Server Side Includes) Version 1.0
#    Created by Matt Wright	mattw@worldwidemart.com
#    Created on: 3/14/96	Last Modified on: 3/14/96
##############################################################################
# Define Variables
#system "echo aqq `date`>>/tmp/wrr";

# Data Dir is the directory on your server that you store files in.  

$data_dir = "/public/www/data";

# Count Dir is the directory on your server that you wish to store the 
# count files in.  Each page that has the counter on it will have it's own 
# file.  

$count_dir = "/public/www/counts";

# Default Font Dir is the directory on the server containing fonts
# for digits used to display counts and dates.

$def_font_dir = "/public/www/data/digits";

# Valid-Referer allows you to limit servers that can use your counter 
# program.  It is suggested that you put in your base domain (similar to 
# myself using worldwidemart.com) and the IP address of your server (mine 
# being 206.31.72.203)

@valid_referer = ('www.ia.pw.edu.pl','148.81.31.1');

##############################################################################
require 'cgi-lib.pl';

&ReadParse( *args );

#######################################################################
# Define Variables

	### FILE AND DIRECTORY LOCATIONS, REFERERS ###

$flyprog = "/usr/local/bin/fly -q";
$fly_temp = "/tmp/fly_temp.txt.$$";

$bad_referer_img = "http://www.ia.pw.edu.pl/img/bad_referer.gif";

	### IMAGE SETTINGS ###

if (exists $args{ 'transparent' }) {
   $tp = $args{ 'transparent' };
} else {
   $tp = "X";
}

if (exists $args{ 'inter' }) {
   $il = $args{ 'inter' };
} else {
   $il = "1";
}

if (exists $args{ 'farmewidth' }) {
   $farme_width = $args{ 'farmewidth' };
} else {
   $frame_width = "0";
}

if (exists $args{ 'frame_color' }) {
   $frame_color = $args{ 'frame_color' };
} else {
   $frame_color = "0,0,0";
}


# Done
#######################################################################
if (exists $args{ 'mode' }) {
   $mode = $args{ 'mode' };
} else {
   $mode = 'count';
}

if (exists $args{ 'text' }) {
   $text = $args{ 'text' };
} else {
   $text = '';
}

$font_dir = $args{ 'font' };
if ( "$font_dir" =~ /^-/ ) {
} elsif ( "$font_dir" ne "" && -d $font_dir ) {
   $digit_dir = $font_dir;
} elsif ( "$font_dir" ne "" && -d "$def_font_dir/$font_dir" ) {
   $digit_dir = "$def_font_dir/$font_dir";
} else {
   $digit_dir = "$def_font_dir/default";
}

$count_page = "$ENV{'HTTP_REFERER'}";
if ($count_page =~ /\/$/) {
   chop($count_page);
}
$count_page =~ s/\//_/g;

&check_referer;

if (-e "$count_dir/$count_page") {
   open(COUNT,"$count_dir/$count_page");
   $line = ;
   chop($line) if $line =~ /\n$/;
   close(COUNT);
   ($date,$count) = split(/\|\|/,$line);
   if (($date ne "") && ($date !~ /\./)) {
      ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($date);
      $mon++;
      $date = "19$year.$mon.$mday";
   }
}
else {
   &create;
#   &error('page_not_found');
}

if ($mode eq 'reset') {
   $count=0;
   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
   $mon++;
   $date = "19$year.$mon.$mday";
   open(COUNT,">$count_dir/$count_page") || &error('could_not_increment');
   print COUNT "$date\|\|$count";
   close(COUNT);
}

if ($mode eq 'count') {
   $count++;

   open(COUNT,">$count_dir/$count_page") || &error('could_not_increment');
   print COUNT "$date\|\|$count";
   close(COUNT);
}

if ($mode eq 'modified') {
   $_ = "$ENV{'HTTP_REFERER'}";
   s/http:\/\/[^\/]*\///;
   s/Pl-[^\/]*\///;	# Remove polish character conversions

   s/~([^\/]*)/~\1/;
   if (/^\~/) {
      s/~//;
      s/\/.*//;
      ($a_name,$a_pass,$a_uid,$a_gid,$a_quot,$a_comm,$a_gcos,$a_dir,$a_sh)=getpwnam($_);
      $_="$a_dir/.homepage";
   }
   s/^([^\/])/\/public\/www\/data\/\1/;
   ($dev,$ino,$mod,$nlink,$uid,$gid,$rdev,$size,$atime,$date,$ctime,$blksiz,$blks) = stat( $_ );
   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($date);
   $mon++;
   $date = "19$year.$mon.$mday";

   &show_gif( $date );
} elsif ($mode eq 'date') {
#   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($date);
#   $mon++;
#   $date = "19$year.$mon.$mday";

   &show_gif( $date );
} elsif ($mode eq 'text') {
   &show_gif( $text );
} else {
   &show_gif( $count );
}

sub create {
   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
   $mon++;
   $date = "19$year.$mon.$mday";
   $count = "0";
   open(COUNT,">$count_dir/$count_page") || &error('count_not_created');
   print COUNT "$date\|\|$count";
   close(COUNT);
}

sub error {
   $error = shift(@_);

   if ($error eq 'page_not_found') {
      print "[WWWCount Fatal Error: This Page Not Found\; Auto-Create Option Disabled]";
   }
   elsif ($error eq 'bad_referer_or_uri') {
      print "[WWWCount Fatal Error: This Page Not In Valid Referer or URI]";
   }
   elsif ($error eq 'count_not_created') {
      print "[WWWCount Fatal Error: Could Not Write to File $count_dir/$count_page]";
   }
   elsif ($error eq 'could_not_increment') {
      print "[WWWCount Fatal Error: Could Not Increment Counter]";
   }
   exit;
}

sub show_gif {
   local($value)=@_;
   local($val)=$value;
   # Determine Length of Counter Number
   $num = $length = length($value);

   # Set Individual Counter Numbers Into Associative Array
   while ($num > 0) {
      $CHAR{$num} = chop($value);
      $num--;
   }

   if ($font_dir !~ /^-/) {
      open(FIL, "$digit_dir/sizes");
      while () {
	 split;
	 @_[0] =~ s/\.gif//;
	 $widths{@_[0]} = @_[1];
	 $heights{@_[0]} = @_[2];
      }
      close(FIL);
   } else {
      if ($font_dir eq "-tiny") {
	 $widths{ "0"} = 5;
	 $heights{"0"} = 8;
      } elsif ($font_dir eq "-small") {
	 $widths{ "0"} = 6;
	 $heights{"0"} = 9;
      } elsif ($font_dir eq "-medium") {
	 $widths{ "0"} = 7;
	 $heights{"0"} = 11;
      } elsif ($font_dir eq "-large") {
	 $widths{ "0"} = 8;
	 $heights{"0"} = 16;
      } elsif ($font_dir eq "-giant") {
	 $widths{ "0"} = 9;
	 $heights{"0"} = 12;
      }
      foreach $i ("1", "2", "3", "4", "5",
		"6", "7", "8", "9", "dot", "colon") {
	 $widths{ $i} = $widths{ "0"};
	 $heights{$i} = $heights{"0"};
      }
   }

   # Determine the Height and Width of the Image
   $img_width = 0;
   $img_height = 0;

   $j = 1;
   while ($j <= $length) {
      if ($CHAR{$j} eq ".") {
	 $img_width = $img_width + $widths{"dot"};
	 $img_height = ($img_height > $heights{"dot"})
			     ? $img_height : $heights{"dot"};
      } elsif ($CHAR{$j} eq ":") {
	 $img_width = $img_width + $widths{"colon"};
	 $img_height = ($img_height > $heights{"colon"})
			     ? $img_height : $heights{"colon"};
      } elsif ($CHAR{$j} eq "a" && $CHAR{$j+1} eq "m" && -f "$digit_dir/am.gif") {
	 $img_width = $img_width + $widths{"am"};
	 $img_height = ($img_height > $heights{"am"})
			     ? $img_height : $heights{"am"};
      } elsif ($CHAR{$j} eq "p" && $CHAR{$j+1} eq "m" && -f "$digit_dir/pm.gif") {
	 $img_width = $img_width + $widths{"pm"};
	 $img_height = ($img_height > $heights{"pm"})
			     ? $img_height : $heights{"pm"};
      } else {
	 $img_width = $img_width + $widths{$CHAR{$j}};
	 $img_height = ($img_height > $heights{"$CHAR{$j}"})
			     ? $img_height : $heights{"$CHAR{$j}"};
      }
      $j++;
   }
   $img_width  = $img_width  + ($frame_width * 2);
   $img_height = $img_height + ($frame_width * 2);

   # Open the In-File for Commands
   open(FLY,">$fly_temp") || die "Can't Open In File For FLY Commands: $!\n";

   # Create New Counter Image
   print FLY "new\n";
   print FLY "size $img_width,$img_height\n";

   # If User Wants Frame, Print Commands to the In-File
   &make_frame;

   if ($font_dir =~ /^-/) {
      $font_dir =~ s/^-//;
      print FLY "fill 1,1,255,255,255\n";
      print FLY "string 0,0,0,$insert_width,$insert_height,$font_dir,$val\n";
   } else {
      # Copy Individual Counter Images Commands to In-File
      $j = 1;
      while ($j <= $length) {
	 if ($CHAR{$j} eq ".") {
	    print FLY "copy $insert_width,$insert_height,-1,-1,-1,-1,$digit_dir/dot\.gif\n";
	    $insert_width = ($insert_width + $widths{"dot"}); 
	 } elsif ($CHAR{$j} eq ":") {
	    print FLY "copy $insert_width,$insert_height,-1,-1,-1,-1,$digit_dir/colon\.gif\n";
	    $insert_width = ($insert_width + $widths{"colon"}); 
	 } elsif ($CHAR{$j} eq "a" && $CHAR{$j+1} eq "m" && -f "$digit_dir/am.gif") {
	    print FLY "copy $insert_width,$insert_height,-1,-1,-1,-1,$digit_dir/am\.gif\n";
	    $insert_width = ($insert_width + $widths{"am"}); 
	    $j++;
	 } elsif ($CHAR{$j} eq "p" && $CHAR{$j+1} eq "m" && -f "$digit_dir/pm.gif") {
	    print FLY "copy $insert_width,$insert_height,-1,-1,-1,-1,$digit_dir/pm\.gif\n";
	    $insert_width = ($insert_width + $widths{"pm"}); 
	    $j++;
	 } else {
	    print FLY "copy $insert_width,$insert_height,-1,-1,-1,-1,$digit_dir/$CHAR{$j}\.gif\n";
	    $insert_width = ($insert_width + $widths{$CHAR{$j}}); 
	 }
	 $j++;
      }
   }

   # If they want a color transparent, make it transparent
   if ($tp ne "X" && $tp =~ /.*,.*,.*/) {
      print FLY "transparent $tp\n";
   }

   # If they want the image interlaced, make it interlaced
   if ($il == 1) {
      print FLY "interlace\n";
   }

   # Close FLY
   close(FLY);

   $output = `$flyprog -i $fly_temp`;
   print "Content-type: image/gif\n\n";
   print "$output";

   # Remove Temp File
   unlink($fly_temp);
}

sub make_frame {
   $insert_width = $insert_height = $frame_width;

   $insert_frame = 0;

   while ($insert_frame < $frame_width) {
      $current_width = ($img_width - $insert_frame);
      $current_height = ($img_height - $insert_frame);
 
      print FLY "line 0,$insert_frame,$img_width,$insert_frame,$frame_color\n";
      print FLY "line $insert_frame,0,$insert_frame,$img_height,$frame_color\n";
      print FLY "line $current_width,0,$current_width,$img_height,$frame_color\n";
      print FLY "line $current_height,0,$current_height,$img_width,$frame_color\n";

      $insert_frame++;
   }
}

sub check_referer {
   if (@valid_referer && $ENV{'HTTP_REFERER'}) {
      foreach $referer (@valid_referer) {
         if ($ENV{'HTTP_REFERER'} =~ /$referer/) {
            $ref = 1;
            last;
         }
      }
   }
   else {
      $ref = 0;
   }

   if ($ref != 1) {
      print "Location: $bad_referer_img\n\n";

      if ($uselog == 1) {
         open(LOG,">>$error_log") || die "Can't Open User Error Log: $!\n";
         print LOG "$error: $ENV{'REMOTE_HOST'} [$date] $ENV{'HTTP_REFERER'} - $ENV{'HTTP_USER_AGENT'}\n";
         close(LOG);
      }

      exit;
   }
}

#