#!/usr/bin/perl5
# Graphical hit counter
# by Michele Beltrame
# -> Some parts of this source come from "Counter 1.1.1" by Matt Wright 
# -> (mattw@worldwidemart.com, http://www.worldwidemart.com/scripts/) 
# Version 1.1.0 : March 31st, 1997
# This software is under the GNU General Public License

@allow = ( 'www.marameo.net' );
$cdir = 'counts/';
$ddir = 'digits/';

($docu, $dig, $width, $height, $frame_w, $frame_c) = 
                                  split(/\|/, $ENV{'PATH_INFO'});

$docu =~ s/\//_/g;
$docu = $cdir.$docu;

if (!&checkrefl) {
    &rwcount;
    &dspcount;
}

exit(0);

# To ensure nobody else uses our CGI... ;-)

sub checkrefl {
    $ref=$ENV{'HTTP_REFERER'};
    if ($ref ne '') {
	$prohib=1;
	foreach $allw (@allow) {
	    if ($ref =~ /$allw/) { 
		$prohib=0;
		last;
	    }
	}
    } else { $prohib=0; }
    if ($prohib==1) { 
	print "Location: http://www.marameo.net/common/badref.gif\n\n";
        return 1;
    }
    return 0;
}

sub rwcount {
    if (-e $docu) {
	open (CFILE, $docu);
	$ct=<CFILE>;
	close (CFILE);
	$ct++;
    } else { $ct=1; }
    if (open (CFILE, ">$docu")) {
	flock (CFILE, 2); 
	print CFILE $ct;
	flock (CFILE, 8);
	close (CFILE);
    }
}

sub dspcount {
    $ncf = length($ct);
    $imgw = ($width*$ncf) + ($frame_w*2);
    $imgh = $height + ($frame_w*2);
    if (open (FLY, ">$docu.fly")) {
	flock (FLY, 2);
	print FLY "new\n";
	print FLY "size $imgw,$imgh\n";
	&makeframe;
	$j = 1;
	while ($j <= $ncf) {
	    $num = substr($ct,0,1);
	    substr($ct,0,1) = '';
	    print FLY "copy $insw,$insh,-1,-1,-1,-1,$ddir/$dig$num\.gif\n";
	    $insw = ($insw + $width);
	    $j++;
	}
	print FLY "interlace\n";
	flock (FLY, 8);
	close (FLY);
    }
    $output = `./fly -q -i$docu.fly`;
    print "Content-type: image/gif\n\n";
    print $output;
    unlink("$docu.fly");
}

sub makeframe {
    $insw = $insh = $frame_w;
    $ins_f = 0;
    while ($ins_f < $frame_w) {
	$currw = ($imgw - $ins_f);
	$currh = ($imgh - $ins_f);
	print FLY "line 0,$ins_f,$imgw,$ins_f,$frame_c\n";
	print FLY "line $ins_f,0,$ins_f,$imgh,$frame_c\n"; 
	print FLY "line $curr_w,0,$curr_w,$imgh,$frame_c\n";
	print FLY "line $curr_h,0,$curr_h,$imgw,$frame_c\n";
	$ins_f++;
    }
}
