#!/usr/bin/perl

################### Copyright ##################################################
# This script is copyright by CGI-Center.com 1999. All rights reserved and so  #
# on. You are not allowed to resell or destribute this script in any way blah  #
# blah blah blah blah.                                                         #
################################################################################
# For help, suggestions or correction regarding this script please visit our   #
# CGI forum at http://www.cgi-center.cx/forum/                                 #
################################################################################

################### Variables ##################################################
$password = "*****";
# Your admin password.                                                         #
                                                                               #
$image = "http://www.joiabr.com.br/figuras/blue.gif";
# The URL of your graph-image. You are welcome to use your own image for this. #
################################################################################
# Define what statistics you want on the admin area. If you do not define them #
# they will still be available by pressing a button on the admin area.         #
$last_refers = "yes";
                                                                               #
$top_refers = "yes";
                                                                               #
$last_visitors = "yes";
                                                                               #
$history = "yes";
                                                                               #
$top_pages = "yes";
                                                                               #
$search = "yes";
################################################################################
# How big will you allow your log file to grow? Defined in kb. There is no     #
# limit to how big it may be but less than 1000 kb is advicable.               #
$max_log = "500";
################################################################################

# No more editing is needed below this line
              #
              #
           #  #  #
            # # #
             ###
              #
###############################
&getinput;

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

$ip = $ENV{'REMOTE_ADDR'};

if ($INPUT{'password2'}) {&admin;}
elsif ($ENV{'QUERY_STRING'} eq "login") {&login;}
elsif ($INPUT{'login'}) {&admin;}
elsif ($INPUT{'history'}) {&history;}
elsif ($INPUT{'last_visitors'}) {&last_visitors;}
elsif ($INPUT{'last_refers'}) {&last_refers;}
elsif ($INPUT{'top_refers'}) {&top_refers;}
elsif ($INPUT{'search'}) {&search;}
elsif ($INPUT{'searchfor'}) {&searchfor;}
elsif ($INPUT{'searchfor2'}) {&searchfor;}
elsif ($INPUT{'top_pages'}) {&top_pages;}
elsif ($INPUT{'reset'}) {&reset;}
else {&count;}

sub login {
	print "<html><body><center><form action=mini_logger.pl method=post>Enter admin password below to login:<br>\n";
	print "<input type=text name=password2><input type=submit value=Login></form></body></html>";
}

sub count {
	&get_date;
	&check;

	unless (-e "data/date.txt") {
		open (DATE,">data/date.txt");
		print DATE "$today";
		close (DATE);
	}
	unless (-e "data/ips.txt") {
		open (IPS,">data/ips.txt");
		close (IPS);
	}

	open (DATE,"data/date.txt");
	$oldday = <DATE>;
	close (DATE);

	if (($oldday =~ /[0-9]/) && ($oldday < $today)) {
		open (DATE,">data/date.txt");
		print DATE "$today";
		close (DATE);

		open (COUNT,"data/count.txt");
		$count = <COUNT>;
		close (COUNT);
		chop ($count) if ($count =~ /\n$/);

		open (COUNT,">data/count.txt");
		close (COUNT);

		open (HISTORY,"data/history.txt");
		@history = <HISTORY>;
		close (HISTORY);

		open (HISTORY,">data/history.txt");
		print HISTORY "$yesterday|$count\n";
		foreach $line (@history) {
			print HISTORY "$line";
		}
		close (HISTORY);
	}
	unless ($oldday =~ /[0-9]/) {
		open (DATE,">data/date.txt");
		print DATE "$today";
		close (DATE);
	}
	open (COUNT,"data/count.txt");
	$count = <COUNT>;
	close (COUNT);

	chop ($count) if ($count =~ /\n$/);
	$count++;

	open (COUNT,">data/count.txt");
	print COUNT "$count";
	close (COUNT);

	open (INFO,"data/info.txt");
	@info = <INFO>;
	close (INFO);

	open (INFO,">data/info.txt");
	print INFO "$date|$clock|$ENV{'HTTP_REFERER'}|$ENV{'REMOTE_ADDR'}|$ENV{'REMOTE_HOST'}|$ENV{'HTTP_USER_AGENT'}|$ENV{'REQUEST_URI'}|\n";
	foreach $line (@info) {
		print INFO "$line";
	}
	close (INFO);
}

sub get_date {
	@days   = ('Sunday','Monday','Tuesday','Wednesday',
	'Thursday','Friday','Saturday');
	@months = ('January','February','March','April','May','June','July',
	'August','September','October','November','December');

	($sec,$min,$hour,$mday,$mon,$year,$wday) = (localtime(time))[0,1,2,3,4,5,6];
	$time = sprintf("%02d:%02d:%02d",$hour,$min,$sec);
	$year += 1900;

	if ($min < 10) {
		$min = "0"."$min";
	}

	$today = ($year*365)+($mon*30)+$mday;
	$hour = ($hour - $minus)+$plus;
	if ($hour < "0") {
		$hour = $hour+24;
		$today--;
	}
	if ($hour > "23") {
		$hour = $hour-24;
		$today++;
	}
	$clock = "$hour:$min";
	$date = "@months[$mon] $mday";

	$mday--;
	if ($mday <= "0") {
		$test = ($mon/2);
		$mday = 30;
		if ($test =~ /\.|\,/) {
			$mday = 31;
		}
		$mon--;
	}
	if ($mon < "0") {
		$mon = 12;
	}
	$yesterday = "@months[$mon] $mday";
}

sub check {
	unless (-e "data/history.txt") {
		open (HISTORY,">data/history.txt");
		close (HISTORY);
	}
	unless (-e "data/count.txt") {
		open (COUNT,">data/count.txt");
		close (COUNT);
	}
	unless (-e "data/info.txt") {
		open (COUNT,">data/info.txt");
		close (COUNT);
	}
}

sub reset {
	open (HISTORY,">data/history.txt");
	close (HISTORY);

	open (COUNT,">data/count.txt");
	close (COUNT);

	open (COUNT,">data/info.txt");
	close (COUNT);

	open (COUNT,">data/ips.txt");
	close (COUNT);

	open (COUNT,">data/date.txt");
	close (COUNT);

	&admin;
}

sub admin {
	if ($INPUT{'password2'}) {
		$INPUT{'password'} = $INPUT{'password2'};
	}
	&check_password;
	&get_date;

	open (COUNT,"data/count.txt");
	$count = <COUNT>;
	close (COUNT);

	open (HISTORY,"data/history.txt");
	@history = <HISTORY>;
	close (HISTORY);

	foreach $line (@history) {
		@stats = split/\|/,$line;
		if (@stats[0] eq $yesterday) {
			$yesterdayhits = @stats[1];
		}
	}
	unless ($yesterdayhits) {
		$yesterdayhits = "&nbsp;";
	}

	print "<html><head><title>Mini logger admin area</title>\n";
	print "<style type=\"text/css\">\n";
	print "<!--\n";
	print "body       { font-size: 8pt; font-family: \"Arial\"}\n";
	print "font       { font-size: 8pt; font-family: \"Arial\"}\n";
	print "td        { font-size: 10pt; font-family: \"Arial\"}\n";
	print "h3       { font-size: 14pt; font-family: \"Arial\"}\n";
	print "-->\n";
	print "</style>	\n";
	print "</head>	\n";     
	print "<body link=black vlink=black text=black>\n";
	print "<form action=mini_logger.pl method=post>\n";

	print "<center><table border=1 cellspacing=0 cellpadding=3><tr><td>Visitors today</td><td><b>$count</b></td></tr>\n";
	print "<tr><td>Yesterday</td><td>$yesterdayhits</td></tr>\n\n";
	print "<tr><td colspan=2 align=center valign=middle><input type=submit name=login value=\"Reload\"> <input type=submit name=reset value=\"Reset all\"></td></tr></table></center><br><br>\n\n";

	print "<center><input type=submit name=last_visitors value=\"Last 50 visitors\"><input type=submit name=last_refers value=\"Last 50 refers\"><input type=submit name=top_refers value=\"Top refers\">";
	print "<input type=submit name=history value=\"History to date\"><input type=submit name=top_pages value=\"Top pages\"><input type=submit name=search value=\"Search for visitor\"><br><br>\n";
	print "<input type=hidden name=password value=$INPUT{'password'}>\n";

	if ($history eq "yes") {
		&history;
	}
	if ($last_refers eq "yes") {
		&last_refers;
	}
	if ($top_refers eq "yes") {
		&top_refers;
	}
	if ($last_visitors eq "yes") {
		&last_visitors;
	}
	if ($top_pages eq "yes") {
		&top_pages;
	}
	if ($search eq "yes") {
		&search;
	}

	open (FILE, "data/info.txt");
	@info = <FILE>;
	($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat(FILE);
	close (FILE);

	$size = $size/1000;
	print "<hr>Your log file is currently $size kb.<br>\n";
	if ($size > $max_log) {
		print "Redusing log file...<br>";
	}
	if ($size > $max_log) {
		foreach $line (@info) {
			$lines++;
		}
		$percent = $max_log/$size;
		$lines = $lines*$percent;
		$new_max = ($lines/10)*9.99;

		open (INFO,">data/info.txt");
		foreach $line (@info) {
			unless ($count > $new_max) {
				print INFO "$line";
			}
			$count++;
		}
		close (INFO);
		open (INFO,"data/info.txt");
		($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat(INFO);
		close (INFO);
		
		$size = $size/1000;

		print "The log file is now $size kb.\n";
	}
}

	###########
	# Actions #
	###########
	     #
	     #
	  #  #  #
	   # # #
	    ###
	     #

sub last_refers {
	&check_password;
	&get_date;
	open (COUNT,"data/count.txt");
	$count = <COUNT>;
	close (COUNT);

	open (INFO,"data/info.txt");
	@info = <INFO>;
	close (INFO);

	open (HISTORY,"data/history.txt");
	@history = <HISTORY>;
	close (HISTORY);

	$num = 0;
	print "<center><h3>Last 50 referres</h3></center>\n";
	print "<table border=1 cellspacing=0>\n";
	foreach $line (@info) {
		unless ($num > 50) {
			@stuff = split/\|/,$line;
			print "<tr><td valign=top><font size=2>@stuff[1]</td>\n";
			if (@stuff[2]) {
				print "<td><font size=2><a href=@stuff[2]>@stuff[2]</td></tr>\n";
			}
			else {
				print "<td>No refer</td></tr>\n";
			}
		}
		$num++;
	}
	print "</table><br><br>\n\n";
}

sub top_pages {
	$numbertolist = "49";
	if ($INPUT{top_pages}) {
		print "<html><body link=black vlink=black>";
		&check_password;
		$numbertolist = "39";
	}
	@info = "";
	@refers = "";
	@found = "";
	@list = "";
	@number = "";
	@sorted = "";
	@stuff = "";
	$match = "";
	$all = "";
	$max = "";
	$a = "";
	$b = "";

	open (INFO,"data/info.txt");
	@info = <INFO>;
	close (INFO);

	foreach $line (@info) {
		@stuff = split/\|/,$line;
		$test = substr(@stuff[6],0,1);
		if ($test eq "/") {
			@refers[$b] = @stuff[6];
			$b++;
		}
		$all++;
	}

	@found[0] = "1";
	foreach $refer (@refers) {
		foreach $refer2 (@found) {
			if ($refer eq $refer2) {
				$match = 1;
			}
		}
		unless ($match) {
			@found[$a] = $refer;
			$a++;
		}
		$match = "";
	}

	$a = 0;
	foreach $refer (@found) {
		foreach $refer2 (@refers) {
			if ($refer eq $refer2) {
				@number[$a]++;
			}
		}
		$a++;
	}

	$a = 0;
	foreach $refer (@found) {
		@list[$a] = @number[$a] . " " . $refer;
		$a++;
	}

	@sorted = sort { $b <=> $a }@list;

	print "<center><h3>Top pages</h3></center>\n";
	print "<table border=1 cellspacing=0 cellpadding=2><tr><td><b>Hits</b></td><td><b>Percent</b></td><td><b>Page</b></td></tr>\n";
	foreach $line (@sorted) {
		unless ($max > $numbertolist) {
			($number, $refer) = split/ /,$line;
			$percent = ($number/$all)*100;
			$percent =~ s/(\d+\.\d).*/$1/;
			print "<tr><td align=center><font size=2>$number</td><td><font size=2>$percent\%</td><td><font size=2><a href=\"$refer\">$refer</a></td></tr>\n";
		}
		$max++;
	}
	print "</table><br><br>";
}

sub top_refers {
	&check_password;
	if ($INPUT{top_refers}) {
		print "<html><body link=black vlink=black>";
	}
	open (INFO,"data/info.txt");
	@info = <INFO>;
	close (INFO);

	foreach $line (@info) {
		@stuff = split/\|/,$line;
		if (@stuff[2] =~ /http:\/\//) {
			@refers[$b] = @stuff[2];
			$b++;
		}
		$all++;
	}

	@found[0] = "1";
	foreach $refer (@refers) {
		foreach $refer2 (@found) {
			if ($refer eq $refer2) {
				$match = 1;
			}
		}
		unless ($match) {
			@found[$a] = $refer;
			$a++;
		}
		$match = "";
	}

	$a = 0;
	foreach $refer (@found) {
		foreach $refer2 (@refers) {
			if ($refer eq $refer2) {
				@number[$a]++;
			}
		}
		$a++;
	}

	$a = 0;
	foreach $refer (@found) {
		@list[$a] = @number[$a] . " " . $refer;
		$a++;
	}

	@sorted = sort { $b <=> $a }@list;

	print "<center><h3>Top referres</h3></center>\n";
	print "<table border=1 cellspacing=0 cellpadding=2><tr><td><b>Hits</b></td><td><b>Percent</b></td><td><b>URL</b></td></tr>\n";
	foreach $line (@sorted) {
		unless ($max > 49) {
			($number, $refer) = split/ /,$line;
			$percent = ($number/$all)*100;
			$percent =~ s/(\d+\.\d).*/$1/;
			print "<tr><td align=center><font size=2>$number</td><td><font size=2>$percent\%</td><td><font size=2><a href=\"$refer\">$refer</a></td></tr>\n";
		}
		$max++;
	}
	print "</table><br><br>";
}

sub history {
	&check_password;
	&get_date;
	open (COUNT,"data/count.txt");
	$count = <COUNT>;
	close (COUNT);

	open (HISTORY,"data/history.txt");
	@history = <HISTORY>;
	close (HISTORY);

	print "<center><h3>History</h3></center>\n";
	print "<table border=1 cellspacing=0>\n";
	foreach $line (@history) {
		@stuff = split/\|/,$line;
		if ($highest < @stuff[1]) {
			$highest = @stuff[1];
		}
	}
	if ($highest < $count) {
		$highest = $count;
	}

	unless ($highest eq "") {
		$max = 400/$highest;
	}
	$num = 0;

	$width = $max*$count;
	$width =~ s/(\d+)\.\d.*/$1/;
	print "<tr><td valign=top>$date</td>\n";
	print "<td>$count</td>\n";
	print "<td><img src=$image width=$width height=12></td></tr>\n";

	foreach $line (@history) {
		unless ($num > 49) {
			@stuff = split/\|/,$line;
			$width = $max*@stuff[1];
			$width =~ s/(\d+)\.\d.*/$1/;
			print "<tr><td valign=top>@stuff[0]</td>\n";
			print "<td>@stuff[1]</td>\n";
			print "<td><img src=$image width=$width height=12></td></tr>\n";
		}
		$num++;
	}
	print "</table><br><br>";
}

sub last_visitors {
	&check_password;
	open (INFO,"data/info.txt");
	@info = <INFO>;
	close (INFO);

	$num = "0";
	print "<center><h3>Last 50 visitors</h3></center>\n";
	print "<table border=1 cellspacing=0><tr><td><b>Time</b></td><td><b>IP address</b></td><td><b>Host address</b></td><td><b>User agent</b></td></tr>\n";
	foreach $line (@info) {
		unless ($num > 49) {
			@stuff = split/\|/,$line;
			&findagent;
			print "<tr><td valign=top><font size=2>@stuff[0] - @stuff[1]</font></td>\n";
			print "<td><font size=2>@stuff[3]</font></td>\n";
			print "<td><font size=2>@stuff[4]</font></td>\n";
			print "<td><font size=2>@stuff[5]</font></td></tr>\n";
		}
		$num++;
	}
	print "</table><br><br>\n\n";
}

sub search {
	&check_password;
	print "<center><h3>Search</h3></center>\n";
	print "<form action=mini_logger.pl method=post><input type=hidden name=password value=$INPUT{'password'}>\n";
	print "Search for <select name=what>\n";
	print "<option value=date>Date</option>\n";
	print "<option value=clock>Clock</option>\n";
	print "<option value=refer>Refer URL</option>\n";
	print "<option value=ip>IP address</option>\n";
	print "<option value=host>Host address</option>\n";
	print "<option value=agent>User agent</option>\n";
	print "</select><br>\n\n";

	print "Show <select name=show>\n";
	print "<option value=half>visitors who contains this info</option>\n";
	print "<option value=match>visitors with EXACTLY this info</option>\n";
	print "</select><br>\n\n";

	print "<input type=text name=searchfor><input type=submit name=searchfor2 value=Search>\n";
}

sub searchfor {
	&check_password;
	print "<html><body link=black vlink=black>";

	open (INFO,"data/info.txt");
	@info = <INFO>;
	close (INFO);

	if ($INPUT{'what'} eq "date") {$what = "0";}
	elsif ($INPUT{'what'} eq "clock") {$what = "1";}
	elsif ($INPUT{'what'} eq "refer") {$what = "2";}
	elsif ($INPUT{'what'} eq "ip") {$what = "3";}
	elsif ($INPUT{'what'} eq "host") {$what = "4";}
	elsif ($INPUT{'what'} eq "agent") {$what = "5";}

	print "<h2>Search result</h2>\n";

	if ($INPUT{'show'} eq "match") {
		foreach $hit (@info) {
			@stuff = split/\|/,$hit;
			unless (@stuff[2]) {
				@stuff[2] = "No refer";
			}
			&findagent;
			if (@stuff[$what] eq $INPUT{'searchfor'}) {
				$url = @stuff[2];
				@stuff[$what] =~ s/$INPUT{'searchfor'}/\<b\>$INPUT{'searchfor'}\<\/b\>/gi;
				@result[$a] = "<tr><td><font size=1>@stuff[0]</td><td><font size=1>@stuff[1]</td><td width=300><font size=1><a href=\"$url\">@stuff[2]</a></td><td><font size=1>@stuff[3]</td><td><font size=1>@stuff[4]</td><td><font size=1>@stuff[5]</td></tr>\n";
				$found++;
				$a++;
			}
			$all++;
		}
	}
	elsif ($INPUT{'show'} eq "half") {
		foreach $hit (@info) {
			@stuff = split/\|/,$hit;
			unless (@stuff[2]) {
				@stuff[2] = "No refer";
			}
			&findagent;
			if (@stuff[$what] =~ /$INPUT{'searchfor'}/gi) {
				$url = @stuff[2];
				@stuff[$what] =~ s/$INPUT{'searchfor'}/\<b\>$INPUT{'searchfor'}\<\/b\>/gi;
				@result[$a] = "<tr><td><font size=1>@stuff[0]</td><td><font size=1>@stuff[1]</td><td width=300><font size=1><a href=\"$url\">@stuff[2]</a></td><td><font size=1>@stuff[3]</td><td><font size=1>@stuff[4]</td><td><font size=1>@stuff[5]</td></tr>\n";
				$found++;
				$a++;
			}
			$all++;
		}
	}
	if ($found) {
		$percent = ($found/$all)*100;
		$percent =~ s/(\d+\.\d).*/$1/;
		print "$found matches were found out of $all visitors. That is $percent\%.<table border=1 cellpadding=2 cellspacing=0>\n";
		foreach $result (@result) {
			unless ($zzz > 49) {
				print "$result";
			}
			$zzz++;
		}
		print "</table>\n";
	}
	unless ($found) {
		print "Sorry, no matches found.\n";
	}
}

sub check_password {
	unless ($INPUT{'password'} eq "$password") {
		print "<h2>Error</h2>The password you entered was incorrect.\n";
		exit;
	}
}
	
sub getinput {
	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	@pairs = split(/&/, $buffer);
	foreach $pair (@pairs) {
		($name, $value) = split(/=/, $pair);
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$INPUT{$name} = $value;
	}

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

$teste ="Mozilla/4.7 [en] (Win95";

sub findagent {
	if (@stuff[5] =~ /netscape/gi) {
#	if (@stuff[5] =~ /$teste/gi) {
		@stuff[5] = "Netscape";
	}
	elsif (@stuff[5] =~ /compatible/gi) {
		@temp = split/\;/,@stuff[5];
		if (@temp[2] =~ /win/gi) {
			@tempp = split/\)/,@temp[2];
			@stuff[5] = "@temp[1], "."@tempp[0]";
		}
		elsif (@temp[3] =~ /win/gi) {
			@tempp = split/\)/,@temp[3];
			@stuff[5] = "@temp[1], "."@tempp[0]";
		}
		elsif (@temp[4] =~ /win/gi) {
			@tempp = split/\)/,@temp[4];
			@stuff[5] = "@temp[1], "."@tempp[0]";
		}
		elsif (@temp[5] =~ /win/gi) {
			@tempp = split/\)/,@temp[5];
			@stuff[5] = "@temp[1], "."@tempp[0]";
		}
		elsif (@stuff[5] =~ /Mac_PowerPC/gi) {
			@stuff[5] = "@temp[1], "."Mac_PowerPC";
		}
		elsif (@stuff[5] =~ /Mac_PowerPPC/gi) {
			@stuff[5] = "@temp[1], "."Mac_PowerPPC";
		}
		elsif (@stuff[5] =~ /Mac_PPC/gi) {
			@stuff[5] = "@temp[1], "."Mac_PPC";
		}
		elsif (@stuff[5] =~ /RISC OS/gi) {
			@stuff[5] = "@temp[1], "."RISC OS";
		}
		elsif (@stuff[5] =~ /WebTV/gi) {
			@stuff[5] = "@temp[1], "."WebTV";
		}
		elsif (@stuff[5] =~ /FDSE/gi) {
			@stuff[5] = "Unknown";
		}
		else {
			@stuff[0] = "Unknown";
		}
		chop (@stuff[5]) if (@stuff[5] =~ /\)/);;
	}
	elsif (@stuff[5] =~ /Win95/gi) {
		@stuff[5] = "Windows 95";
	}
	elsif (@stuff[5] =~ /Win98/gi) {
		@stuff[5] = "Windows 98";
	}
	elsif (@stuff[5] =~ /Win16/gi) {
		@stuff[5] = "Windows 16";
	}
	elsif (@stuff[5] =~ /WinNT/gi) {
		@stuff[5] = "Windows NT";
	}
	elsif (@stuff[5] =~ /Linux/gi) {
		@stuff[5] = "Linux";
	}
	elsif (@stuff[5] =~ /Macintosh/gi) {
		@stuff[5] = "Macintosh";
	}
	elsif (@stuff[5] =~ /AOLpress/gi) {
		@stuff[5] = "AOLpress";
	}
	elsif (@stuff[5] =~ /FreeBSD/gi) {
		@stuff[5] = "FreeBSD";
	}
	elsif (@stuff[5] =~ /SunOS/gi) {
		@stuff[5] = "SunOS";
	}
	else {
		@stuff[5] = "Unknown";
	}
}