<?php
/**
* @version 0.0.1 - June 2010
* @package webalizer
* @copyright (C) Thierry CHEN - webologix.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* USAGE:
* Place that file into the webalizer ouput directory, containing all reports
* Hit the file to have a whole years visits graphic by months
*/

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            if (preg_match('/^usage_(?P<year>\d{4})(?P<month>\d{2}).html/', $file, $matches) ){
            	$stat =& $files[$file];

            	$stat->year = $matches['year'];
	            $stat->month 	= $matches['month'];
	            $stat->link 	= "<a href='$file'>".$matches['month']."</a>";

	            $content = nl_del( file_get_contents($file) );

            	$start = escape('Total Visites</FONT></TD><TD ALIGN=right COLSPAN=2><FONT SIZE="-1"><B>');
            	$end = escape('</B>');
            	if (preg_match("|$start(?P<nb_visites>\d*)$end|", $content, $matches) ){
	            	$stat->nb_visites = $matches['nb_visites'];
	            	if ( $stat->nb_visites > $max ) $max = $stat->nb_visites;
            	}
            }
        }
    }
    echo ("<html><head><title>All Statisics</title></head><BODY BGCOLOR='#E8E8E8' TEX'='#000000' LINK='#0000FF' VLINK='#FF0000'>
    		<table style='font-size:12px'><tr><th>Year</th><th>Month</th><th>visits (souce: webalizer)</th>");
    asort($files);
    foreach ($files as $key=>$stat){
    	echo '<tr>';
	    if ( $stat->month == '01' ) $year = $stat->year;
	    else $year='';
    	echo "<td>$year</td>";
    	echo "<td>$stat->link</td>";
        echo "<td width='800px'><div style='background:red; color:white; padding:2px; width:" . round($stat->nb_visites / $max * 100) . "%'>$stat->nb_visites</td>";
        echo '</tr>';
    }
    echo "</table></body></html>";
    closedir($handle);
}

function escape( $string ){
	$escaped='^.[]$()*+?|{}\!=:"';
	$chars = str_split($string);
	$return = '';
	foreach ( $chars as $char ){
		if ( strpos($escaped, $char) ) $return .= '\\' . $char;
		else $return .= $char;
	}
	return $return;
}

function nl_del( &$str ){
	$str1 = str_replace(CHR(10),"",$str);
	$str2 = str_replace(CHR(13),"",$str1);
	return $str2;
}
