#!/usr/bin/perl -i

#V2.1

use CGI ':standard';

require "L10HC_Params.pl";
require "L10HC_LIB.pl";

@cookies = split(/;/,$ENV{'HTTP_COOKIE'});
$visitorLevel = 0;
$cookiesEnabled = 0;
$jSEnabled = 0;
$blockBrowser = 0;
$reload = 0;

foreach (@cookies) {
	($cKey,$cValue) = split(/=/,$_);
	if($cKey =~ m/L10HC_LV/) {
		@vDate = split(/\//,$cValue);
		if(&moreThan24Hrs($vDate[2],$vDate[0],$vDate[1],$vDate[3],$curYr,$curMo,$curDay,$curHr)) {
			$visitorLevel = 2;
		} else {
			$visitorLevel = 1;
		}
		$cookiesEnabled = 1;
	} elsif($cKey =~ m/L10HC_CC/) {
		$cookiesEnabled = 1;
		$jSEnabled = 1;
	} elsif($cKey =~ m/L10HC_BB/) {
		if($cValue eq "1") {
			$blockBrowser = 1;
		}
	}
}

if(($visitorLevel == 0) && (param('s') eq "swf")) {
	$visitorLevel = 1;
}

if(param('pg') ne "") {
	$url = param('pg');
} else {				 
	$url = $ENV{'HTTP_REFERER'};
}

if($url eq "") {
	$url = '[unknown]';
} else {
	$url =~ s/http:\/\///i;
	$url =~ s/https:\/\///i;
	$url =~ s/\&/\%26/g;
}

if(!$cookiesEnabled) {
	open (FILE, "L10HC_IP.log") || &gen_error("Cannot open L10HC_IP.log at \"Read Today's Stats Data\"");
	@IPs = <FILE>;
	close(FILE);
	$ipFound = 0;
	$testEntry = "";
	foreach (@IPs) {
		@ipInfo = split(/\t/,$_);
		if($ipInfo[0] eq $ENV{'REMOTE_ADDR'}) {
			$ipFound = 1;
			$testEntry = "R1-".$_;
			@cDate = split(/\//,$ipInfo[1]);
			if(($cDate[0] == $curDay) or ($cData[1] < $curHr)) {
				$visitorLevel = 1;
			}
			if($ipInfo[2] eq $url) {
				$reload = 1;				
			}
		}		
	}
	if(!$ipFound) {
		open (FILE, "L10HC_IP2.log") || &gen_error("Cannot open L10HC_IP2.log at \"Read Today's Stats Data\"");
		@IPs = <FILE>;
		close(FILE);
		foreach (@IPs) {
			@ipInfo = split(/\t/,$_);
			if($ipInfo[0] eq $ENV{'REMOTE_ADDR'}) {
				$ipFound = 1;
				$testEntry = "R2-".$_;
				@cDate = split(/\//,$ipInfo[1]);
				if(($cDate[0] == $curDay) or ($cData[1] < $curHr)) {
					$visitorLevel = 1;
				}
				if($ipInfo[2] eq $url) {
					$reload = 1;				
				}
			}		
		}
	}
	if(!$ipFound) {
		open(FILE, ">>L10HC_IP.log") || &gen_error("Cannot open L10HC_IP.log at \"Read Today's Stats Data\"");
		print FILE "".$ENV{'REMOTE_ADDR'}."\t$curDay/$curHr\t$url\n";
		close(FILE);
		$testEntry = "W-".$ENV{'REMOTE_ADDR'}."\t$curDay/$curHr\t$url";
		
	}
}

if(param('a') eq "r") {
	$reload = 1;
	exit 0;
}
	
# &log_error($ENV{'REMOTE_ADDR'}.",$visitorLevel,$reload,$blockBrowser,$url,".$ENV{'HTTP_COOKIE'}."\n");

# read today's stats data
unless(&lock_stats()) {
	&log_error("$curMo/$curDay/$curYr $curHr:$curMin:$curSec fileLockTO exceeded.");
	exit 0;
}
open (DSTAT_FH, "L10HC_Hits.dat") || &gen_error("Cannot open L10HC_Hits.dat at \"Read Today's Stats Data\"");
@dStat = <DSTAT_FH>;
close(DSTAT_FH);

if($dStat[0] ne "$dateStamp\n") {
	&log_event("Stats archived by time.");
	require "L10HC_LIB2.pl";
	&archiveStats();
}
 
if(param('action') eq "check") {
	&unlock_stats();
	print header;
	print "res=OK";	
	exit 0;
}

if($blockBrowser) {
	&unlock_stats();
	&returnHitImage();	
	exit 0;
}

if((param('a') eq "r") || ($reload)) {
	&unlock_stats();
	&returnHitImage();
	exit 0;
}

if(!$allowLocalFiles && $url =~ m/file:\/\//i) {
	&unlock_stats();
	&returnHitImage();
	exit 0;

}

@sStats = split(/\t/,$dStat[1]);
$VbyHr=$dStat[4];
$HbyHr=$dStat[5];
chop($VbyHr);
chop($HbyHr);

if($visitorLevel != 1) {
	$ref = param('ref');
	$ref =~ s/http:\/\///i;
	$ref =~ s/https:\/\///i;
	$ref =~ s/\&/\%26/g;
	open(FILE, ">>L10HC_Refs.dat")|| &gen_error("Cannot open L10HC_Refs.dat at \"Write Today's Stats Data\"");
	print FILE "$ref\t$url\n";
	close(FILE);
	if($ref =~ m/atmanager.com/) {
		&log_error("E".$ENV{'REMOTE_ADDR'}.",$visitorLevel,$reload,$blockBrowser,$url,$ref,".$ENV{'HTTP_COOKIE'}."\n");
	} else {
		&log_error($ENV{'REMOTE_ADDR'}.",$visitorLevel,$reload,$blockBrowser,$url,$ref,".$ENV{'HTTP_COOKIE'}."\n");
	}
	open(FILE, ">>L10HC_Extended.dat")|| &gen_error("Cannot open L10HC_Extended.dat at \"Write Today's Stats Data\"");
	if(param('sl') eq "undefined") {
		$lang = param('nl');
	} else {
		$lang = param('sl');
	}
	print FILE "".param('os')."\t".param('nn')."\t".param('nv')."\t$lang\t$cookiesEnabled\t$jSEnabled\t".param('cd')."\t".param('sx')."x".param('sy')."\t".param('tz')."\t".$ENV{'REMOTE_HOST'}."\n";
	close(FILE);
	$sStats[0] ++; # All Time Entry 
	$sStats[1] ++; # Year Entry
	$sStats[2] ++; # Month Entry
	$sStats[3] ++; # Week Entry
	$sStats[4] ++; # Day Entry

	@VbyHrArr = split(/\t/,$VbyHr);
	$VbyHrArr[$curHr] ++;
	$VbyHr = join("\t",@VbyHrArr);
}
$sStats[5] ++; # All Time Visit
$sStats[6] ++; # Year Visit
$sStats[7] ++; # Month Visit
$sStats[8] ++; # Week Visit
$sStats[9] ++; # Day Visit

@HbyHrArr = split(/\t/,$HbyHr);
$HbyHrArr[$curHr] ++;
$HbyHr = join("\t",@HbyHrArr);

# Write today's stats data

open(DSTAT_FH, ">L10HC_Hits.dat")|| &gen_error("Cannot open L10HC_Hits.dat at \"Write Today's Stats Data\"");
print DSTAT_FH "$dStat[0]";
print DSTAT_FH "$sStats[0]\t$sStats[1]\t$sStats[2]\t$sStats[3]\t$sStats[4]\t$sStats[5]\t$sStats[6]\t$sStats[7]\t$sStats[8]\t$sStats[9]\n";
print DSTAT_FH "$dStat[2]";
print DSTAT_FH "$dStat[3]";
print DSTAT_FH "$VbyHr\n";
print DSTAT_FH "$HbyHr\n";


$foundFlag = 0;
for($i=6; $i<=$#dStat; $i++) {
	print DSTAT_FH "$dStat[$i]";
	chop($dStat[$i]);
	if($url eq $dStat[$i]) {
		$i++;
		@pStats = split(/\t/,$dStat[$i]);
		if($visitorLevel != 1) {
			$pStats[0] ++; # All Time Entry
			$pStats[1] ++; # Year Entry
			$pStats[2] ++; # Month Entry
			$pStats[3] ++; # Week Entry
			$pStats[4] ++; # Day Entry
		}
		$pStats[5] ++; # All Time Visit
		$pStats[6] ++; # Year Visit
		$pStats[7] ++; # Month Visit
		$pStats[8] ++; # Week Visit
		$pStats[9] ++; # Day Visit
		print DSTAT_FH "$pStats[0]\t$pStats[1]\t$pStats[2]\t$pStats[3]\t$pStats[4]\t$pStats[5]\t$pStats[6]\t$pStats[7]\t$pStats[8]\t$pStats[9]\n";
		$foundFlag = 1;
	} else {
		$i++;
		print DSTAT_FH "$dStat[$i]";
	}

}
if(!$foundFlag) {
	if($visitorLevel != 1) {
		@pStats = (1,1,1,1,1,1,1,1,1,1);
	} else {
		@pStats = (0,0,0,0,0,1,1,1,1,1);
	}
	print DSTAT_FH "$url\n";	
	print DSTAT_FH "$pStats[0]\t$pStats[1]\t$pStats[2]\t$pStats[3]\t$pStats[4]\t$pStats[5]\t$pStats[6]\t$pStats[7]\t$pStats[8]\t$pStats[9]\n";
}

close(DSTAT_FH);
&unlock_stats();

&returnHitImage();

exit 0;

#####################################################
# Subroutine start
#####################################################

sub returnHitImage() {

	open (IMG, "L10HC_Image.gif") || &gen_error("Cannot open L10HC_Image.gif at \"Read Today's Stats Data\"");
	@imgd = <IMG>;
	# $cYr = $curYr+2; 
	# $dow = &DayOfWeek($cYr,$curMo,1);
	# @MON =qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
	# @WDAY = qw/Sun Mon Tue Wed Thu Fri Sat/;

	print "Content-type:  image/gif\n";
	print "Set-Cookie: L10HC_LV=$curMo\/$curDay\/$curYr\/$curHr\/$curMin\/$curSec;";		
	# print " expires=$WDAY[$dow], 01-$MON[$curMo-1]-$cYr 00:00:00 GMT; \n\n";
	print " expires=Fri, 31-Dec-10 00:00:01 GMT; \n\n";
	
	foreach (@imgd) {
		print $_;
	}
	close(IMG);
}