<? 
//////////////////////////////////////////////////////////////////////////////
// GCounter info: CopyRight 12-01-2000 Scott Baker (bakers@web-ster.com)
// Gcounter is used to display the log information for the GCount program 
// if extended log information is used.  This has been tested using PHP 4
// and MySQL 3.23
//////////////////////////////////////////////////////////////////////////////
// format to put the dates in, if you would like to edit this see:
// http://www.php.net/manual/function.date.php for more information
$dateformat = "n-j-y (g:ia)";
//////////////////////////////////////////////////////////////////////////////
// Database variables, they should probably be the same as gcount.php
//////////////////////////////////////////////////////////////////////////////
require('mysql.php');
$dbtable = "counterlog";
//////////////////////////////////////////////////////////////////////////////
// Color variables and number of hues to created for the background
// If you want to use a single color for the background put the color you would
// like to use in first_color and set num_colors to 1
//////////////////////////////////////////////////////////////////////////////
$first_color = "#ffffff";
$last_color = "#00cc66";
$num_colors = 5;
// Max number of chars to display before it gets cut.  This fixes your tables
// looking funky because of long entries.
$displaylen = 40;
//////////////////////////////////////////////////////////////////////////////
// Number of records to show on one page
//////////////////////////////////////////////////////////////////////////////
$limit = 30;
//////////////////////////////////////////////////////////////////////////////
// Default name to use if none is specified
//////////////////////////////////////////////////////////////////////////////
$default_name = "default";
$show_report_link = 1;
//////////////////////////////////////////////////////////////////////////////
// Authentication. Set $authenticate to true if you want basic realm
// authentication enabled for this script. This would be used if you don't
// want just anybody looking at your statistics. (Which includes visitors'
// IP addresses!) Set $auth_passwd to the password desired.
//////////////////////////////////////////////////////////////////////////////
$authenticate = false;
$auth_user = "counter";
$auth_passwd = "count123";
////////////////////////////
// The text of the previous and next links
///////////////////////////
$newer_text = "Newer";
$older_text = "Older";
//////////////////////////////////////////////////////////////////////////////
// Warning: Actual code begins here, unless you know what you are getting into
// it's probably not a good idea to edit anything beneath here.
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Get the CGI variables
$name = $_GET['name'];
$log = $_GET['log'];
$offset = $_GET['offset'];
$show_report = $_GET['show_report'];

$GcountVisit = $_COOKIE['GcountVisit'];
///////////////////////////////////////////////////////////////////////////////

$style = "<style>
	body {font-family: verdana; font-size: 10pt; }
	td {font-family: verdana; font-size: 8pt; }
</style>";

if ($show_report) {
	show_report($show_report);
	exit;
}

if ($authenticate) {
	// If the user has chosen to do authentication,
	// include auth.inc
	include('auth.inc');
}

if ( !isset($name) ) { $name = $default_name; }

include ('dbfunction.inc');
$cn = ConnectDB($server,$username,$password,$database);

$sql = "SELECT CntCount FROM webcounter WHERE CntName = '$name'";
$result = mysql_query($sql);
$counter = mysql_fetch_array($result);
$counter = intval($counter['CntCount']);


$output .= "<title>Counter Information</title>\n";

$output .= "<font style=\"font-size: 18pt\">Web counter information for: <b>\n";
$output .= "$name</b> ($counter hits)</font>\n";
$output .= "<br>\n";
$output .= "<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">\n";

// Get the cntID from the main table, this is neccessary to look it up in the 
// main counterlog table.  If MySQL supported subselects we could do this in one
// query but it will take two without them.  Not a big deal.
$sql = "SELECT CntID FROM webcounter WHERE CntName = '$name'";
$result = mysql_query($sql);

// Take the recordset returned and pull out the cntID
$result = mysql_fetch_array($result);
$id = $result['CntID'];

// Get all the data needed to display the info on the page and put it in 
// $result for later use
$offset = intval($offset);
$sql = "SELECT UNIX_TIMESTAMP(logTimeStamp) AS TimeStamp,logOS,logOSVersion,logHost,logRefer,logBrowser,logBrowserVersion FROM $dbtable WHERE CntID = $id ORDER BY 1 DESC LIMIT $offset,$limit";
#print $sql . "<br>";

$result = mysql_query($sql);

// If we don't get any records back there aren't any stored for this user
if ( !$result ) {
	die("There are no records to be displayed for this counter.");
}

// Start $i at zero
$i = 0;
$step = 1;

// Get the background colors
$bgcolor = GetColors($num_colors,$first_color,$last_color);

if (!$bgcolor) {
	$bgcolor = "#000000";
}

while ( $data = mysql_fetch_array($result) ) {

	$os = $data['logOS'] . " " . $data['logOSVersion'];

	#This is a hack, fix it by making the DB better
	if ($os == "Linux Unknown") { $os = "Linux"; }
	
	#$osv = $data['logOSVersion'];

	$host = $data['logHost'];
	$refer = $data['logRefer'];
	$browser = $data['logBrowser'];
	$bversion = $data['logBrowserVersion'];
	$ts = date($dateformat,$data['TimeStamp']);
	
	// Chop the host if it's too long
	if (strlen($host) > $displaylen) { $host = substr($host,0,$displaylen) . "..." ; } 
	
	$output .= "<TR>\n";
	// print "$ts: $browser ($bversion) on $os referred by $refer<BR>\n";
	// print "\t<TD bgcolor=\"$bgcolor\">#$i</td>\n";
	$output .= "\t<TD bgcolor=\"$bgcolor[$i]\" width=140>$ts</td>\n";
	$output .= "\t<TD bgcolor=\"$bgcolor[$i]\" width=130>$browser $bversion</td>\n";
	$output .= "\t<TD bgcolor=\"$bgcolor[$i]\" width=90>$os</td>\n";
	$output .= "\t<TD bgcolor=\"$bgcolor[$i]\">$host</td>\n";
	
	// Chop the refering link if it's too long
	if (strlen($refer) > $displaylen) { $refertext = substr($refer,0,$displaylen) . "..." ; }
	else { $refertext = $refer; }
	
	if ($refer <> "none") {
		$output .= "\t<TD bgcolor=\"$bgcolor[$i]\"><a href=\"$refer\">$refertext</a></td>\n";
	}
	else {
		$output .= "\t<TD bgcolor=\"$bgcolor[$i]\"><b>$refertext</b></td>\n";
	}
	
	$output .= "<TR>\n";
    
	// Add or subtract on depending on what side we're on
    $i = $i + (1 * $step);
	
	// If we're over the top, then switch to negative and reset
    if ( $i > (count($bgcolor) - 1) ) {
        $i = count($bgcolor) - 2;
		$step = -$step;
    }
	// If we're less then zero reset to one, and switch directions
	elseif ( $i < 0 ) {
		$step = -$step;
		$i = 1;
	}
    
}

DisconnectDB($cn);

$previousnum = $offset + $limit;
$nextnum = $offset - $limit;

if ($nextnum < 0)
        {
        $nextnum = 0;
        $nextlink = $newer_text;
        }
else
        {
        $nextlink = "<a href=\"$PHP_SELF?name=$name&offset=$nextnum\">$newer_text</a>";
        }

if ($previousnum >= $counter)
        {
        $previousnum = $counter - $limit;
        $prevlink = $older_text;
        }
else
        {
        $prevlink = "<a href=\"$PHP_SELF?name=$name&offset=$previousnum\">$older_text</a>";
        }

$output .= "</table>\n\n";

$output .= $prevlink . " | " . $nextlink;
if ($show_report_link) { 
	$reportlink = $_SERVER['PHP_SELF'] . "?show_report=$name";
	$output .= " | <a href=\"$reportlink\">Report</a>"; 
}

if ($save) { $output .= "<P><font size=-2>$save</font>"; }

print "<body>\n$style$output<body>";

// This function takes a start and stop color and generates X colors in
// between them.  It's a really ugly function right now, I should clean 
// it up later.
function GetColors($number,$startc,$endc) {

    // Make sure the colors are in the aabbcc format, no leading #
    if (substr($startc,0,1) == "#" && strlen($startc) == 7) {
        $startc = substr($startc,1,6);
	}
	else {
		return false;
	}
    
    if (substr($endc,0,1) == "#" && strlen($endc) == 7) {
        $endc = substr($endc,1,6);
    }
	else {
		return false;
	}

	if ( (strlen($startc) != 6) || (strlen($endc) != 6) ) {
		return false;
	}
		
	// 1 or less selected probably only want one color
	if ($number <= 1) {
		return $startc;
	}
	
	// print "startc: $startc endc: $endc<BR>";
    
    $start_red = hexdec(substr($startc,0,2));
    $start_blue = hexdec(substr($startc,2,2));
    $start_green = hexdec(substr($startc,4,2));

    $end_red = hexdec(substr($endc,0,2));
    $end_blue = hexdec(substr($endc,2,2));
    $end_green = hexdec(substr($endc,4,2));
    
	// print "starts: $start_red $start_blue $start_green<BR>";
	// print "ends: $end_red $end_blue $end_green<BR>";
	
    $red_jump = (($end_red - $start_red) / ($number - 1));
    $blue_jump = (($end_blue - $start_blue) / ($number - 1));
    $green_jump = (($end_green - $start_green) / ($number - 1));
    
	// print "jumps: $red_jump $blue_jump $green_jump<P>";
	
    for ($i = 0;$i < $number;$i++) {
        $new_green = dechex($start_green + intval($i * $green_jump));
        $new_red = dechex($start_red + intval($i * $red_jump));
        $new_blue = dechex($start_blue + intval($i * $blue_jump));
        
		if (strlen($new_green) == 1) {
			$new_green = "0" . $new_green;
		}
		
		if (strlen($new_red) == 1) {
			$new_red = "0" . $new_red;
		}
		
		if (strlen($new_blue) == 1) {
			$new_blue = "0" . $new_blue;
		}
		
		// print("$new_red$new_blue$new_green<BR>");
		
        $colors[$i] = "#" . $new_red . $new_blue . $new_green;
    }
	
	return $colors;
}

function show_report($name) {
	require("dbfunction.inc");
	global $server,$username,$password,$database,$style;
	$cn = ConnectDB($server,$username,$password,$database);

	$cntid = get_cntid($name);

	$sql = "SELECT CntCount FROM webcounter WHERE CntID = $cntid;";
	$total = mysql_one($sql);

	#######################################
	# Get the stats
	#######################################
	$browser = top_browser(9,$cntid);
	$os = top_os(9,$cntid);

	$output .= "<font style=\"font-size: 18pt\">Total hits for <b>$name</b>: $total</font><br><br>\n";

	$output .= "<b>Browsers:</b>";
	$output .= "<ul>\n";

	$total_count = total_count($browser);
	#$browser[] = array("<span style=\"color: red\">Other</span>",$total - $total_count);
	if ($total - $total_count) {
		$browser[] = array("Other",$total - $total_count);
	}

	$total_count = total_count($os);
	#$os[] = array("<span style=\"color: red\">Other</span>",$total - $total_count);
	if ($total - $total_count) {
		$os[] = array("Other",$total - $total_count);
	}

	##do the actual sorting work
	usort($browser, twod_sort);
	usort($os, twod_sort);

	if (!$browser) { die("No counter by the name of $name"); }

	foreach ($browser as $item) {
		#list($percent,$bar_graph,$name,$count) = $item;
		$name = $item[0];
		$count = $item[1];
		$percent = round(($item[1] / $total) * 100,1);

		$bar_graph = bar($count,$total);

		$output .= "\t<li><b>$name:</b> $count ($percent%)<br>\n$bar_graph<br>\n";

		$bar_graph = "";
	}

	$output .= "</ul>";

	$output .= "<b>Operating Systems:</b>";
	$output .= "<ul>\n";

	foreach ($os as $item) {
		#list($percent,$bar_graph,$name,$count) = $item;
		$name = $item[0];
		$count = $item[1];
		$percent = round(($item[1] / $total) * 100,1);

		$bar_graph = bar($count,$total);

		$output .= "\t<li><b>$name:</b> $count ($percent%)<br>\n$bar_graph<br>\n";

		$bar_graph = "";
	}
	
	$output .= "</ul>\n";

	$title = "<title>GCount Report for: $name</title>\n\n";
	
	$output = "$style\n\n<body>$title$output</body>";

	print $output;

	DisconnectDB;

	return 0;
}

function mysql_one($sql) {
	$rs = mysql_query($sql) or print mysql_error();

	$data = mysql_fetch_array($rs);
	
	$ret = $data[0];
	$ret || $ret = "0";

	return $ret;
}

function percent($item,$total) {
	if (!$total) { return 0; }
	$per = round($item/$total,3) * 100;

	$per .= "%";
	return $per;
}

function bar($item,$total) {
	if (!$total) { return 0; }

	#100% would be the width
	$width = 900;
	$height = 18;

	$per = round($item/$total,2) * 100;
	$bwidth = intval(($per * $width) / 100);

	#print "$item $total<br />";

	$bar .= "<img src=\"images/bar-left.png\" width=\"2\" height=\"$height\" alt=\"\" />";
	$bar .= "<img src=\"images/bar-middle.png\" width=\"$bwidth\" height=\"$height\" alt=\"\" />";
	$bar .= "<img src=\"images/bar-right.png\" height=\"$height\" width=\"2\" alt=\"\" />";

	return $bar;
}

function get_cntid($name) {
	$sql = "SELECT CntID FROM webcounter WHERE cntName = '$name'";

	return mysql_one($sql);
}

function top_os($count,$cntid) {
	$count || $count = 10;
	if (!$cntid) { return 0; }

	$sql = "SELECT concat(logOS,\" \",logOSVersion) as logOS, count(concat(logOS,\" \",logOSVersion)) as Counter FROM counterlog WHERE cntID = $cntid GROUP BY logOS ORDER BY Counter DESC LIMIT $count;";

	#print $sql;

	$rs = mysql_query($sql) or print mysql_error();

	while ($data = mysql_fetch_array($rs)) {
		$ret[] = array($data[0],$data[1]);
	}

	return $ret;
}

function top_browser($count,$cntid) {
	$count || $count = 10;
	if (!$cntid) { return 0; }

	$sql = "SELECT concat(logBrowser,\" \",logBrowserVersion) as Browser, count(concat(logBrowser,\" \",logBrowserVersion)) as logOS FROM counterlog WHERE cntID = $cntid GROUP BY Browser ORDER BY logOS DESC LIMIT $count;";

	#print $sql;

	$rs = mysql_query($sql) or print mysql_error();

	while ($data = mysql_fetch_array($rs)) {
		$ret[] = array($data[0],$data[1]);
	}

	return $ret;
}

function total_count($array) {
	foreach ($array as $item) {
		$count += $item[1];
	}

	return $count;
}

##create a function to compare
function twod_sort($a, $b) {
	#compare the second elements
   return $a[1] < $b[1];
}



?>
