Location: PHPKode > projects > PHPSiteStats > phpsitestats/inc.func.php
<?php

if (phpversion() < '4.0.0') {
        echo "This software requires PHP version 4.0.0 or better.";
        die;
}

include_once("inc.conf.php");
$_SESSION['cfg_ignore'] = $cfg_ignore;
$_SESSION['cfg_dbname'] = $cfg_dbname;
$_SESSION['cfg_database'] = $cfg_database;
$_SESSION['cfg_minhit'] = $cfg_minhit;

if ($cfg_database=="on"){
        $link = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpass) or db_die("Could not connect to database",$cfg_dbname);
        $db = mysql_select_db($cfg_dbname,$link) or db_die("Could not select database");
}

if ($_GET['graphic'] && $_GET['what'] && $_GET['logfile']){
             graphic($_GET['graphic'],$_GET['logfile'],$_GET['what'],$_GET['month'],$_GET['extra']);
}

if ($_GET['picture'] && $_GET['img'] && $_GET['name']){
             picture($_GET['picture'],$_GET['img'],$_GET['name']);
}

function db_die ($message){
        conf_replace("inc.conf.php","cfg_database='on'","cfg_database='off'");
        echo "<img src=gfx/index.gif><h3>Error</h3>$message<br>The database has been disabled .<br><a href=setup.php>Setup your database</a><br>";
        mysql_query("CREATE DATABASE ".$_SESSION['cfg_dbname']) or die ("Could not create database ".$_SESSION['cfg_dbname']);
        die;
}

function db_table_make($tname){
        $query = "
         CREATE TABLE $tname (
           Id int(11) NOT NULL auto_increment,
           Date varchar(8) NOT NULL default '',
           Ip varchar(28) NOT NULL default '',
           Referrer varchar(200) NOT NULL default '',
           Agent varchar(100) NOT NULL default '',
           PRIMARY KEY  (`Id`)
         ) TYPE=MyISAM
         ";
        //check if not allready existant
        $tlist = mysql_list_tables($_SESSION['cfg_dbname']);
        while ($row = mysql_fetch_row($tlist)) {
                $tables[$row[0]] = exist ;
        }
        if ($tables[$tname] != "exist"){
              mysql_query($query) or die ("Failed to create table $tname <br>Debug info: $query". mysql_error());
        }
}

function db_table_echo ($tname){
        $query = "SELECT * FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read rows from $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ($row as $r){
                         echo "$r ";
                }
                echo "\n";
        }
        mysql_free_result($result);
}

function db_show_size($cfg_dbname,$tname){
        $query = "SHOW TABLE STATUS FROM $cfg_dbname LIKE '$tname'";
        $result = mysql_query($query) or die ("Failed to create get table size of $tname <br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_object($result)) {
                $size = $row->Data_length + $row->Index_length;
        }
        mysql_free_result($result);
        if ($size >= 1073741824){ $size = round($size / 1073741824 * 100) / 100 . ' Gb'; }
        elseif ($size >= 1048576){ $size = round($size / 1048576 * 100) / 100 . ' Mb'; }
        elseif ($size >= 1024){        $size = round($size / 1024 * 100) / 100 . ' Kb'; }
        elseif ($size > 0){ $size = $size . ' b'; }
        else{ $size = 'NA'; }
        echo $size;
}

function db_get_refs($tname){
        $query = "SELECT Referrer FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $ref ){
                                $refs[$ref] += 1;
                }
        }
        mysql_free_result($result);
        return $refs;
}

function db_get_spiders($tname){
        $sites = "Google|Yahoo|Inktomi|MSN|Alexa|Jeeves|Ingrid|AllTheWeb|Altavista|Teoma|Baidu|Boitho|Scooter|Asterias|MozDex|ZyBorg|WebCrawler|DeepIndex|Appie|Infoseek|Nutch|Szukacz|SlySearch|ASPseek|Almaden|Zeus|Xenu|WWWoffle|WiseWire|WebZIP|WebTrends|IlTrovatore|UltraKnowledge|Lycos|NetResearch|Skizzle|IconSurf|ObjectsSearch|Cobion|Wotbox|IUPUI|SoftByteLabs|SearchByUsa|Innerprise|Yotta|EmeraldShield|ThumbShots|NextGenSearch|OmniExplorer|CostaCider";
        $bots = "NPBot|Antibot|VoilaBot|Gigabot|Mirago|PSBot|Openbot|Uptimebot|SurveyBot|ExaBot|WISEbot|GeonaBot|NaverBot|GirafaBot|StokeyBot|PEERBot|HotBot|TurnitinBotSeekBot|JetBot|GaisBot|TestBot|InetBot|BruinBot|DiamondBot|ZipppBot|BecomeBot|SpurlBot|F-Bot|IRLbot|GMailBot|TutorGigBot|AlbertBot|MJ12Bot|InelaBot|ClushBot|McBot|CherchonsBot|QweeryBot|KazoomBot|AIPBot|NoxTrumbot|Unido-Bot|PolyBot";
        $other = "robo|spider|slurp|crawler|archiver|indexer|dloader|wget|curl";
        $query = "SELECT Agent FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
            foreach ( $row as $agent ){
                if (preg_match ("/$sites/i", $agent,$site)){
                        $spiders[ucwords($site[0])] += 1;
                }elseif (preg_match ("/bot/i", $agent)){
                        if (preg_match ("/$bots/i", $agent,$bot)){
                            $spiders[ucwords($bot[0])] += 1;
                        }else{
                            $spiders[_other] += 1;
                        }
                }elseif (preg_match ("/$other/i", $agent)){
                        $spiders[_other] += 1;
                }
            }
        }
        mysql_free_result($result);
        return $spiders;
}

function db_get_spider_months($tname,$spider){
        $query = "SELECT Date,Agent FROM `$tname` WHERE Agent LIKE '%$spider%'";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                            preg_match ("/^.*?\.(.*?)$/", $row[0] , $matches);
                            $date = $matches[1];
                            $dates[$date] += 1;
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_spider_days($tname,$fmonth,$fyear,$spider){
        $query = "SELECT Date,Agent FROM `$tname` WHERE Agent LIKE '%$spider%'";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)$/", $row[0] , $matches);
                        $day = $matches[1];
                        $month = $matches[2];
                        $year = $matches[3];
                        if ($month == $fmonth && $year == $fyear){
                                   $dates[$row[0]] += 1;
                        }
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_browsers($tname){
        $query = "SELECT Agent FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $agent ){
                if (!preg_match ("/bot|spider|slurp|crawler|googlebot|yahoo|inktomi|teoma|jeeves|robozilla|archiver/i", $agent)){
                        $browser = preg_replace("/;\s\.NET\sCLR\s(\d|\.)*|; DigExt/i", "", $agent);
                        $browsers[$browser] += 1;
                }
                }
        }
        mysql_free_result($result);
        return $browsers;
}

function db_get_queries ($tname,$site=NULL) {
         $slist = array(
                  "google"   =>      "q=",
                  "teoma"    =>      "q=",
                  "alexa"    =>      "q=",
                  "yahoo"    =>      "p=",
                  "altavista"=>      "q=",
                  "alltheweb"=>      "q=",
                  "msn"      =>      "MT=",
                  "baidu"    =>      "wd="
         );
        $query = "SELECT Referrer FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $ref ){
                    foreach ($slist as $k => $v){
                             if (preg_match ("/$v(\S*?)&/i", $ref,$match) && strstr($ref,$k)){
                                 $query = urldecode(str_replace("+"," ",$match[1]));
                                 if ($site){
                                      if ($site == $k) $querys[$query] += 1;
                                 }else{
                                       $querys[$k] += 1;
                                 }
                             }
                    }
                }
        }
        mysql_free_result($result);
        return $querys;
}

function db_get_oss($tname){
        $query = "SELECT Agent FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $agent ){
                if (preg_match ("/Windows|Winnt|Macos|Macintosh|Unix|Linux|Sunos|Aix|Iris|Netbsd|Freebsd|Openbsd|Beos|OS\/2/i", $agent , $os)){
                                $os = $os[0];
                                $oss[$os] += 1;
                }
                }
        }
        mysql_free_result($result);
        return $oss;
}

function db_get_alldays($tname){
        $query = "SELECT Date FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $day ){
                                $dates[$day] += 1;
                }
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_30days($tname){
        $query = "SELECT Date FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $day ){
                                $days[$day] += 1;
                }
        }
        mysql_free_result($result);
        $dates = array_slice ($days, -30);
        return $dates;
}

function db_get_visit_months($tname){
        $query = "SELECT Date FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $line ){
                            preg_match ("/^.*?\.(.*?)$/", $line , $matches);
                            $date = $matches[1];
                            $dates[$date] += 1;
                }
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_visit_days($tname,$fmonth,$fyear){
        $query = "SELECT Date FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $line ){
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)$/", $line , $matches);
                        $day = $matches[1];
                        $month = $matches[2];
                        $year = $matches[3];
                        if ($month == $fmonth && $year == $fyear){
                                $dates[$line] += 1;
                        }
                }
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_link_months($tname){
        $query = "SELECT Date,Referrer FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                            preg_match ("/^.*?\.(.*?)$/", $row[0] , $matches);
                            $date = $matches[1];
                            $temp[$date][$row[1]] = NULL;
        }
        foreach ($temp as $d => $s){
                $dates[$d] = count($s);
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_link_days($tname,$fmonth,$fyear){
        $query = "SELECT Date,Referrer FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)$/", $row[0] , $matches);
                        $day = $matches[1];
                        $month = $matches[2];
                        $year = $matches[3];
                        if ($month == $fmonth && $year == $fyear){
                                $temp[$row[0]][$row[1]] = NULL;
                        }
        }
        foreach ($temp as $d => $s){
                $dates[$d] = count($s);
        }
        mysql_free_result($result);
        return $dates;
}


function db_get_site_months($tname,$site){
        if ($site == "_direct_link"){
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer=''";
        }elseif($site == "_google_link"){
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer LIKE '%google.%'";
        }elseif($site == "_spoofed_link"){
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer LIKE '%++++%'";
        }else{
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer LIKE '%$site%'";
        }
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                            preg_match ("/^.*?\.(.*?)$/", $row[0] , $matches);
                            $date = $matches[1];
                            $dates[$date] += 1;
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_site_days($tname,$fmonth,$fyear,$site){
        if ($site == "_direct_link"){
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer=''";
        }elseif($site == "_google_link"){
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer LIKE '%google.%'";
        }elseif($site == "_spoofed_link"){
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer LIKE '%++++%'";
        }else{
             $query = "SELECT Date,Referrer FROM `$tname` WHERE Referrer LIKE '%$site%'";
        }
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)$/", $row[0] , $matches);
                        $day = $matches[1];
                        $month = $matches[2];
                        $year = $matches[3];
                        if ($month == $fmonth && $year == $fyear){
                                   $dates[$row[0]] += 1;
                        }
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_sites($tname){
        $query = "SELECT Referrer FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $line ){
                      if (strstr($line,"google.")){
                          $date = "_google_link";
                      } elseif (preg_match ("/^http:\/\/(.*?)\//", $line , $matches)){
                          $date = $matches[1];
                      } elseif ($line == ""){
                          $date = "_direct_link";
                      } elseif (strstr($line,"++++")){
                          $date = "_spoofed_link";
                      }else{
                          $date = $line;
                      }
                      $date = str_replace("www.","",$date);
                      $date = str_replace("http://","",$date);
                      $dates[$date] += 1;
                }
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_ip_months($tname,$ip){
        $query = "SELECT Date,Ip FROM `$tname` WHERE Ip='$ip'";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                            preg_match ("/^.*?\.(.*?)$/", $row[0] , $matches);
                            $date = $matches[1];
                            $dates[$date] += 1;
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_ip_days($tname,$fmonth,$fyear,$ip){
        $query = "SELECT Date,Ip FROM `$tname` WHERE Ip='$ip'";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)$/", $row[0] , $matches);
                        $day = $matches[1];
                        $month = $matches[2];
                        $year = $matches[3];
                        if ($month == $fmonth && $year == $fyear){
                                   $dates[$row[0]] += 1;
                        }
        }
        mysql_free_result($result);
        return $dates;
}

function db_get_ips($tname){
        $query = "SELECT Ip FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        while ($row = mysql_fetch_row($result)) {
                foreach ( $row as $ip ){
                        $ips[$ip] += 1;
                }
        }
        mysql_free_result($result);
        return $ips;
}

function db_count_show($tname){
        $i = 0;
        $query = "SELECT * FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        $num = mysql_num_rows($result);
        $cntn = strlen($num);
        while($i < $cntn) {
                $tmpnum = substr($num, $i, 1);
                echo("<img src=\"phpsitestats/gfx/cnt_".$tmpnum.".gif\">");
                $i++;
        }
        unset ($i);
}

function db_visits_log($tname){
        if (strstr($_SESSION['cfg_ignore'],$_SERVER["REMOTE_ADDR"])){
        die;
        }else{
        $addr = $_SERVER["REMOTE_ADDR"];
        $cache = $tname."_cache";
        $date = date("d.m.y");
        $ref = mysql_escape_string($_SERVER["HTTP_REFERER"]);
        $agent = mysql_escape_string($_SERVER["HTTP_USER_AGENT"]);
        $query = "SELECT * FROM `$cache` WHERE `Date`='$date' AND `Ip`='$addr' AND `Referrer`='$ref' AND `Agent`='$agent'";
        $result = mysql_query($query) or die ("Failed to check cache for $tname<br>Debug info: $query". mysql_error());
        if (mysql_num_rows($result) == 0){
                $query = "INSERT INTO `$tname` (Id, Date, Ip, Referrer, Agent) VALUES ('', '$date', '$addr', '$ref', '$agent')";
                $result = mysql_query($query) or die ("Failed to log to $tname<br>Debug info: $query". mysql_error());
        }
        $query = "UPDATE `$cache` SET Date='$date', Ip='$addr', Referrer='$ref', Agent='$agent'";
        $result = mysql_query($query) or die ("Failed to cache to $cache<br>Debug info: $query". mysql_error());
        }
}

function db_visits_show ($tname){
        $visits = 0;
        $query = "SELECT * FROM `$tname`";
        $result = mysql_query($query) or die ("Failed to read $tname<br>Debug info: $query". mysql_error());
        $visits = mysql_num_rows($result);
        echo $visits;
}

function fl_chmod($fname){
   $perms = substr(base_convert(fileperms($fname), 10, 8), 3);
   if ($perms != "666"){
        $chmod = chmod ($fname, 0666);
                if (!$chmod){
                         echo "<b>Your server does not allow automatic file chmoding</b><br>";
                         echo "<b>You have to manually chmod 666 $fname/make it writable</b><br>";
                         die;
                }

   }
}

function fl_file_echo($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                print (fgets($fhandle, 4096));
        }
        fclose($fhandle);
}

function fl_show_size($fname){
        $size = filesize($fname) or die ("could not open $fname");
        if ($size >= 1073741824){ $size = round($size / 1073741824 * 100) / 100 . ' Gb'; }
        elseif ($size >= 1048576){ $size = round($size / 1048576 * 100) / 100 . ' Mb'; }
        elseif ($size >= 1024){        $size = round($size / 1024 * 100) / 100 . ' Kb'; }
        elseif ($size > 0){ $size = $size . ' b'; }
        else{ $size = 'NA'; }
        echo $size;
}

function fl_get_refs($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^.*?\s<\s(.*?)\s-\s.*?$/", $line , $matches);
                $ref = $matches[1];
                $refs[$ref] += 1;
        }
        fclose($fhandle);
        return $refs;
}

function fl_get_spiders($fname){
        $sites = "Google|Yahoo|Inktomi|MSN|Alexa|Jeeves|Ingrid|AllTheWeb|Altavista|Teoma|Baidu|Boitho|Scooter|Asterias|MozDex|ZyBorg|WebCrawler|DeepIndex|Appie|Infoseek|Nutch|Szukacz|SlySearch|ASPseek|Almaden|Zeus|Xenu|WWWoffle|WiseWire|WebZIP|WebTrends|IlTrovatore|UltraKnowledge|Lycos|NetResearch|Skizzle|IconSurf|ObjectsSearch|Cobion|Wotbox|IUPUI|SoftByteLabs|SearchByUsa|Innerprise|Yotta|EmeraldShield|ThumbShots|NextGenSearch|OmniExplorer|CostaCider";
        $bots = "NPBot|Antibot|VoilaBot|Gigabot|Mirago|PSBot|Openbot|Uptimebot|SurveyBot|ExaBot|WISEbot|GeonaBot|NaverBot|GirafaBot|StokeyBot|PEERBot|HotBot|TurnitinBotSeekBot|JetBot|GaisBot|TestBot|InetBot|BruinBot|DiamondBot|ZipppBot|BecomeBot|SpurlBot|F-Bot|IRLbot|GMailBot|TutorGigBot|AlbertBot|MJ12Bot|InelaBot|ClushBot|McBot|CherchonsBot|QweeryBot|KazoomBot|AIPBot|NoxTrumbot|Unido-Bot|PolyBot";
        $other = "robo|spider|slurp|crawler|archiver|indexer|dloader|wget|curl";
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^.*? < .*? - (.*?)$/", $line , $matches);
                if (preg_match ("/$sites/i", $matches[1],$site)){
                        $spiders[ucwords($site[0])] += 1;
                }elseif (preg_match ("/bot/i", $matches[1])){
                        if (preg_match ("/$bots/i", $matches[1],$bot)){
                            $spiders[ucwords($bot[0])] += 1;
                        }else{
                            $spiders[_other] += 1;
                        }
                }elseif (preg_match ("/$other/i", $matches[1])){
                        $spiders[_other] += 1;
                }
        }
        fclose($fhandle);
        return $spiders;
}

function fl_get_spider_months($fname,$spider){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $ref = fgets($fhandle, 4096);
                preg_match ("/^.*?\.(.*?) : .* <  - .*".$spider."/i", $ref , $matches);
                if ($matches[1]){
                        $date = $matches[1];
                        $dates[$date] += 1;
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_spider_days($fname,$fmonth,$fyear,$spider){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $ref = fgets($fhandle, 4096);
                preg_match ("/^.*?\.(.*?) : .* <  - .*".$spider."/i", $ref , $matches);
                if ($matches[1]){
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)\s:.*?/", $ref , $match);
                        $day = $match[1];
                        $month = $match[2];
                        $year = $match[3];
                        $date = $day.".".$month.".".$year;
                        if ($month == $fmonth && $year == $fyear){
                                   $dates[$date] += 1;
                        }
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_browsers($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^.*? < .*? - (.*?)$/", $line , $matches);
                if (!preg_match ("/bot|spider|slurp|crawler|googlebot|yahoo|inktomi|teoma|jeeves|robozilla|archiver/i", $matches[1])){
                        $browser = preg_replace("/;\s\.NET\sCLR\s(\d|\.)*|; DigExt/i", "", $matches[1]);

                        $browsers[$browser] += 1;
                }
        }
        fclose($fhandle);
        return $browsers;
}

function fl_get_queries ($fname,$site=NULL) {
         $slist = array(
                  "google"   =>      "q=",
                  "teoma"    =>      "q=",
                  "alexa"    =>      "q=",
                  "yahoo"    =>      "p=",
                  "altavista"=>      "q=",
                  "alltheweb"=>      "q=",
                  "msn"      =>      "MT=",
                  "baidu"    =>      "wd="
         );
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^.*?\s<\s(.*?)\s-\s.*?$/", $line , $matches);
                $ref = $matches[1];
                    foreach ($slist as $k => $v){
                             if (preg_match ("/$v(\S*?)&/i", $ref,$match) && strstr($ref,$k)){
                                 $query = urldecode(str_replace("+"," ",$match[1]));
                                 if ($site){
                                      if ($site == $k) $querys[$query] += 1;
                                 }else{
                                       $querys[$k] += 1;
                                 }
                             }
                    }
        }
        fclose($fhandle);
        return $querys;
}

function fl_get_oss($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^.*? < .*? - (.*?)$/", $line , $matches);
                if (preg_match ("/Windows|Winnt|Macos|Macintosh|Unix|Linux|Sunos|Aix|Iris|Netbsd|Freebsd|Openbsd|Beos|OS\/2/i", $matches[1] , $os)){
                                $os = $os[0];
                                $oss[$os] += 1;
                }
        }
        fclose($fhandle);
        return $oss;
}

function fl_get_alldays($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^(.*?)\s:\s.*?$/", $line , $matches);
                $day = $matches[1];
                if ($day != ""){
                        $dates[$day] += 1;
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_30days($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^(.*?)\s:\s.*?$/", $line , $matches);
                $day = $matches[1];
                if ($day != ""){
                        $days[$day] += 1;
                }
        }
        fclose($fhandle);
        $dates = array_slice ($days, -30);
        return $dates;
}

function fl_get_visit_months($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^.*?\.(.*?)\s:\s.*?$/", $line , $matches);
                $date = $matches[1];
                if ($date != ""){
                        $dates[$date] += 1;
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_visit_days($fname,$fmonth,$fyear){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^(.*?)\s:\s.*?$/", $line , $matches);
                $date = $matches[1];
                if ($date != ""){
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)$/", $date , $matches);
                        $day = $matches[1];
                        $month = $matches[2];
                        $year = $matches[3];
                        if ($month == $fmonth && $year == $fyear){
                                $dates[$date] += 1;
                        }
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_link_months($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                if (preg_match ("/^.*?\.(.*?)\s:.*?\s<\s(.*?)\s-\s.*?$/", $line , $matches)){
                       $date = $matches[1];
                       $ref = $matches[2];
                       $temp[$date][$ref] = NULL;
                }
        }
        foreach ($temp as $d => $s){
                $dates[$d] = count($s);
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_link_days($fname,$fmonth,$fyear){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                if (preg_match ("/^.*?\.(.*?)\s:.*?\s<\s(.*?)\s-\s.*?$/", $line , $matches)){
                       $date = $matches[1];
                       $ref = $matches[2];
                       preg_match ("/^(.*?)\.(.*?)\.(.*?)\s:.*?/", $line , $match);
                       $day = $match[1];
                       $month = $match[2];
                       $year = $match[3];
                       $date = $day.".".$month.".".$year;
                       if ($month == $fmonth && $year == $fyear){
                                     $temp[$date][$ref] = NULL;
                       }
                }
        }
        foreach ($temp as $d => $s){
                $dates[$d] = count($s);
        }
        fclose($fhandle);
        return $dates;
}


function fl_get_site_months($fname,$site){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $ref = fgets($fhandle, 4096);
                if ($site == "_direct_link"){
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<  -\s.*?$/", $ref , $matches);
                }elseif($site == "_google_link"){
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<\s.*?google\..*?\s-\s.*?$/", $ref , $matches);
                }elseif($site == "_spoofed_link"){
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<\s.*?\+\+\+\+.*?\s-\s.*?$/", $ref , $matches);
                }else{
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<\s.*?".$site.".*?\s-\s.*?$/", $ref , $matches);
                }
                if ($matches[1]){
                        $date = $matches[1];
                        $dates[$date] += 1;
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_site_days($fname,$fmonth,$fyear,$site){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $ref = fgets($fhandle, 4096);
                if ($site == "_direct_link"){
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<  -\s.*?$/", $ref , $matches);
                }elseif($site == "_google_link"){
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<\s.*?google\..*?\s-\s.*?$/", $ref , $matches);
                }elseif($site == "_spoofed_link"){
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<\s.*?\+\+\+\+.*?\s-\s.*?$/", $ref , $matches);
                }else{
                        preg_match ("/^.*?\.(.*?)\s:.*?\s<\s.*?".$site.".*?\s-\s.*?$/", $ref , $matches);
                }
                if ($matches[1]){
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)\s:.*?/", $ref , $match);
                        $day = $match[1];
                        $month = $match[2];
                        $year = $match[3];
                        $date = $day.".".$month.".".$year;
                        if ($month == $fmonth && $year == $fyear){
                                   $dates[$date] += 1;
                        }
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_sites($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $ref = fgets($fhandle, 4096);
                preg_match ("/^.*?\s<\s(.*?)\s-\s.*?$/", $ref , $matches);
                $line = $matches[1];
                      if (strstr($line,"google.")){
                          $date = "_google_link";
                      } elseif (preg_match ("/^http:\/\/(.*?)\//", $line , $matches)){
                          $date = $matches[1];
                      } elseif ($line == ""){
                          $date = "_direct_link";
                      } elseif (strstr($line,"++++")){
                          $date = "_spoofed_link";
                      }else{
                          $date = $line;
                      }
                      $date = str_replace("www.","",$date);
                      $date = str_replace("http://","",$date);
                      $dates[$date] += 1;
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_ip_months($fname,$ip){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $ref = fgets($fhandle, 4096);
                preg_match ("/^.*?\.(.*?)\s:\s".$ip."\s<\s.*?$/", $ref , $matches);
                if ($matches[1]){
                        $date = $matches[1];
                        $dates[$date] += 1;
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_ip_days($fname,$fmonth,$fyear,$ip){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $ref = fgets($fhandle, 4096);
                preg_match ("/^.*?\.(.*?)\s:\s".$ip."\s<\s.*?$/", $ref , $matches);
                if ($matches[1]){
                        preg_match ("/^(.*?)\.(.*?)\.(.*?)\s:.*?/", $ref , $match);
                        $day = $match[1];
                        $month = $match[2];
                        $year = $match[3];
                        $date = $day.".".$month.".".$year;
                        if ($month == $fmonth && $year == $fyear){
                                   $dates[$date] += 1;
                        }
                }
        }
        fclose($fhandle);
        return $dates;
}

function fl_get_ips($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^.*? : (.*?) < .*?$/", $line , $matches);
                $ip = $matches[1];
                $ips[$ip] += 1;
        }
        fclose($fhandle);
        return $ips;
}

function fl_count_log($fname){
        $file = file($fname);
        $num = ($file[0] + 1);
        $fh = fopen($fname, "w") or die ("could not open $fname");
        fwrite($fh, "$num\n");
        fclose($fh);
}

function fl_count_show($fname){
        $i = 0;
        $file = file($fname);
        $num = ($file[0] + 1);
        $cntn = strlen($num);
        while($i < $cntn) {
                $tmpnum = substr($num, $i, 1);
                echo("<img src=\"phpsitestats/gfx/cnt_".$tmpnum.".gif\">");
                $i++;
        }
        unset ($i);
}

function fl_visits_log($fname){
        if (strstr($_SESSION['cfg_ignore'],$_SERVER["REMOTE_ADDR"])){
        die;
        }else{
        $addr = $_SERVER["REMOTE_ADDR"];
        $date = date("d.m.y");
        $ref = $_SERVER["HTTP_REFERER"];
        $agent = $_SERVER["HTTP_USER_AGENT"];
        $entry = "$date : $addr < $ref - $agent\n";
        preg_match ("/([\w|-]*\.\S*)/", $fname , $path);
        $cache = do_tempchk()."/".$path[1]."_cache";
        touch($cache);
        //write log
        if (file_get_contents($cache) != $entry){
              $fh = fopen($fname, "a") or die ("could not open $fname");
              fwrite($fh, $entry);
              fclose($fh);
        }
        //write cache
        $fh = fopen($cache, "w") or die ("could not cache $fname");
        fwrite($fh, $entry);
        fclose($fh);
        }
}

function fl_visits_show($fname){
        $fhandle = fopen($fname, "r") or die ("could not open $fname");
        while (!feof($fhandle)) {
                $line = fgets($fhandle, 4096);
                preg_match ("/^(.*?)\s:\s.*?$/", $line , $matches);
                $day = $matches[1];
                if ($day != ""){
                        $visits += 1;
                }
        }
        fclose($fhandle);
        echo "$visits";
}

function conf_replace($file,$find,$replace) {
    $fh = fopen($file, "r") or die ("could not open $file");
    if (!$fh) {
        echo "Could not open $file";
    } else {
        $content = "";
        while (!feof($fh)) {
        $line = fgets($fh, 4096);
        $content .= ereg_replace($find ,$replace, $line);
        }
        fclose($fh);
        $fh = fopen($file, "w");
        fwrite($fh, $content);
        fclose($fh);
    }
}

function conf_insert($file,$string) {
    $fh = fopen($file, "r") or die ("could not open $file");
    if (!$fh) {
        echo "Could not open $file";
    } else {
        $content = "";
        while (!feof($fh)) {
        $line = fgets($fh, 4096);
           if (!preg_match("/\?>/", $line)){
                $content .= $line;
           }
        }
        fclose($fh);
        $content .= "$string\r\n";
        $content .= "?>\r\n";
        $fh = fopen($file, "w");
        fwrite($fh, $content);
        fclose($fh);
    }
}

function conf_remove($file,$string) {
    $fh = fopen($file, "r") or die ("could not open $file");
    if (!$fh) {
        echo "Could not open $file";
    } else {
        $content = "";
        while (!feof($fh)) {
        $line = fgets($fh, 4096);
           if (!preg_match("/$cfg_flogs\['$string'\]/", $line)){
                $content .= $line;
           }
        }
        fclose($fh);
        $fh = fopen($file, "w");
        fwrite($fh, $content);
        fclose($fh);
    }
}

function graphic($graphic,$fname,$what,$month,$extra){
if ($graphic == "percentage"){
        $height = "300";
        $width = "700";
        $diameter = "200";
        $title = "Percentage chart of $what";
        //get number
        if ($what == "fl_sites"){      $dates = fl_get_sites($fname); }
        if ($what == "fl_ref"){      $dates = fl_get_refs($fname); }
        if ($what == "fl_browser"){  $dates = fl_get_browsers($fname); }
        if ($what == "fl_spider"){   $dates = fl_get_spiders($fname); }
        if ($what == "fl_os"){       $dates = fl_get_oss($fname); }
        if ($what == "fl_ip"){       $dates = fl_get_ips($fname); }
        if ($what == "fl_query"){       $dates = fl_get_queries($fname); }
        if ($what == "fl_querys"){       $dates = fl_get_queries($fname,$month); }
        if ($what == "db_sites"){    $dates = db_get_sites($fname); }
        if ($what == "db_ref"){      $dates = db_get_refs($fname); }
        if ($what == "db_browser"){  $dates = db_get_browsers($fname); }
        if ($what == "db_spider"){   $dates = db_get_spiders($fname); }
        if ($what == "db_os"){       $dates = db_get_oss($fname); }
        if ($what == "db_ip"){       $dates = db_get_ips($fname); }
        if ($what == "db_query"){       $dates = db_get_queries($fname); }
        if ($what == "db_querys"){       $dates = db_get_queries($fname,$month); }

        $tables = split (",",$tables);
        $value = "";
        foreach ($dates as $name => $number) {
                $n = preg_replace("/\r|\n/i", "", $name);
                $n = preg_replace("/\s{1,}/i", " ", $name);
                $n = substr($n,0,60);
                $items[$n] += $number;
        }
        asort($items);
        $items = array_reverse($items);
        $items = array_slice($items, 0, 13);
        foreach ($items as $Name => $Val){
                 $itemName[] = $Name;
                 $itemVal[] = $Val;
        }
        include("inc.chart.php");
}
if ($graphic == "progress"){
        $height = "300";
        $width = "700";
        $gtitle = "Graphic for $what";
        $ytitle = "count";
        $xtitle = "date";
        //get month
        list($fmonth,$fyear)= split ("\.", $month, 2);
        //get number
        if ($what == "fl_alldays"){  $dates = fl_get_alldays($fname); }
        if ($what == "fl_30days"){   $dates = fl_get_30days($fname); }
        if ($what == "fl_visit_days"){     $dates = fl_get_visit_days($fname,$fmonth,$fyear); }
        if ($what == "fl_visit_months"){   $dates = fl_get_visit_months($fname); }
        if ($what == "fl_link_days"){     $dates = fl_get_link_days($fname,$fmonth,$fyear); }
        if ($what == "fl_link_months"){   $dates = fl_get_link_months($fname); }
        if ($what == "fl_site_days"){     $dates = fl_get_site_days($fname,$fmonth,$fyear,$extra); }
        if ($what == "fl_site_months"){   $dates = fl_get_site_months($fname,$extra); }
        if ($what == "fl_ip_days"){     $dates = fl_get_ip_days($fname,$fmonth,$fyear,$extra); }
        if ($what == "fl_ip_months"){   $dates = fl_get_ip_months($fname,$extra); }
        if ($what == "fl_spider_days"){     $dates = fl_get_spider_days($fname,$fmonth,$fyear,$extra); }
        if ($what == "fl_spider_months"){   $dates = fl_get_spider_months($fname,$extra); }
        if ($what == "db_alldays"){  $dates = db_get_alldays($fname); }
        if ($what == "db_30days"){   $dates = db_get_30days($fname); }
        if ($what == "db_visit_days"){     $dates = db_get_visit_days($fname,$fmonth,$fyear); }
        if ($what == "db_visit_months"){   $dates = db_get_visit_months($fname); }
        if ($what == "db_link_days"){     $dates = db_get_link_days($fname,$fmonth,$fyear); }
        if ($what == "db_link_months"){   $dates = db_get_link_months($fname); }
        if ($what == "db_site_days"){     $dates = db_get_site_days($fname,$fmonth,$fyear,$extra); }
        if ($what == "db_site_months"){   $dates = db_get_site_months($fname,$extra); }
        if ($what == "db_ip_days"){     $dates = db_get_ip_days($fname,$fmonth,$fyear,$extra); }
        if ($what == "db_ip_months"){   $dates = db_get_ip_months($fname,$extra); }
        if ($what == "db_spider_days"){     $dates = db_get_spider_days($fname,$fmonth,$fyear,$extra); }
        if ($what == "db_spider_months"){   $dates = db_get_spider_months($fname,$extra); }

        foreach ($dates as $date => $regs) {
                        $day_dates[] = $date;
                        $day_regs[] = $regs;
        }
        //get the highest number
              $i = 0;
              while(list($day, $regs) = each($day_regs)) {
                      if ($regs > $i ) {
                              $i = $regs;
                      }
              }
              reset($day_regs);
              $l5 = $i;
              $l4 = round (3/4 * $i);
              $l3 = round (2/4 * $i);
              $l2 = round (1/4 * $i);
              $l1 = round ($l2 / 2);
        //make dataXlabels
              $dataXlabels[] = $l1;
              if ($l2 != $l1) {$dataXlabels[] = $l2;}
              if ($l3 != $l1 && $l3 != $l2 && $l3 != $l4 && $l3 != $l5) {$dataXlabels[] = $l3;}
              if ($l4 != $l5) {$dataXlabels[] = $l4;}
              $dataXlabels[] = $l5;
        //make dataYlabels
              while(list($day, $dates) = each($day_dates)) {
                   $dataYlabels[] = $dates;
              }
        //make dataValues
              while(list($day, $regs) = each($day_regs)) {
                     $dataValues[] = $regs;
              }
        include("inc.graph.php");
}
}

function picture($picture,$img,$name){
        if ($picture == "fl"){ fl_visits_log($name); }
        if ($picture == "db"){ db_visits_log($name); }
        //show picture
        Header("Content-type: image/gif");
        $fhandle = fopen($img, "r") or die ("could not open $img");
        $contents = fread ($fhandle, filesize ($img));
        echo ($contents);
        fclose($fhandle);
}

function do_backup ($dbtable,$fname){
        //get database data
        $query = "SELECT * FROM $dbtable";
        $result = mysql_query($query) or die ("Failed to get $dbtable data<br>Debug info: $query". mysql_error());
        //process data
        $v=1;
        while ($line = mysql_fetch_assoc($result)){
           if ($line){
                foreach($line as $col_value) {
                $values[$v] .= "'".$col_value."',";
                }
                $v++;
           }
        }
        //write backup file
        $fhw = fopen("$fname", "w");
        if ($values){
          fwrite ($fhw,"TRUNCATE $dbtable;\r\n");
          foreach ($values as $values_n=> $values_v){
                $values_v = substr($values_v, 0, -1);
                $values_v = "INSERT INTO $dbtable VALUES ($values_v);";
                fwrite ($fhw,"$values_v\r\n");
          }
        }
        unset ($values);
}


function do_chmod($fname){
   $perms = substr(base_convert(fileperms($fname), 10, 8), 3);
   if ($perms != "666"){
        $chmod = chmod ("$fname", 0666);
                if (!$chmod){
                         echo "<b>Your server does not allow automatic file chmoding</b><br>";
                         echo "<b>You have to manually chmod 666 $fname/make it writable</b><br>";
                         die;
                }

   }
}

function do_tempchk(){
        if (!$tpath){
                $tpath = ini_get('upload_tmp_dir');
        }
        if (!$tpath){
                $tpath = ini_get('session.save_path');
        }
        if (!$tpath){
                echo "<center>Please set <b>upload_tmp_dir</b> or <b>session.save_path</b> in php.ini";
                die;
        }
        return $tpath;
}

function do_gzip_PFC($Val){
        //Print Four Chars
        for ($i = 0; $i < 4; $i ++){
                $return .= chr($Val % 256);
                $Val = floor($Val / 256);
        }
        return $return;
}

function do_gzip($infile,$outfile){
         //check first
         $phpver = phpversion();
         if($phpver >= "4.3"){
            if(extension_loaded("zlib")){
               $can_gzip = TRUE;
            }else{echo "Error : zlib extension not loaded";die;}
         }else{echo "Error : php version too old";die;}
         //then do it
        if($can_gzip){
          $Size = filesize($infile);
          $infile = file_get_contents($infile);
          $Crc = crc32($infile);
          $contents = gzcompress($infile);
          $content = "\x1f\x8b\x08\x00\x00\x00\x00\x00".substr($contents, 0, strlen($contents) - 4).do_gzip_PFC($Crc).do_gzip_PFC($Size);
        $fh = fopen($outfile, "w");
        fwrite ($fh,$content);
        }
}

function get_fname($fname){
          preg_match ("/^.*[\/|\\\](.*?)$/", $fname , $matches);
          $return = $matches[1];
          return $return;
}

function show_avg($data,$what,$when,$how = "in"){
        foreach ( $data as $k => $a){
             $months += 1;
             $visits += $a;
        }
        $percent = round($visits / $months);
        $end = substr($when,0,-1);
        echo "$visits $what $how $months $when <b>($percent/$end avg)</b>";
}

function get_files ($dir) {
   $list = array();
   $dh  = @opendir($dir);
   if ($dh!=FALSE) {
       while (false !== ($filename = readdir($dh))) {
          if (!is_dir($dir."/".$filename) && $filename != "." && $filename != ".."){
             $list[] = $filename;
          }
       }
   }
   return $list;
}

function get_tables (){
    if ($_SESSION['cfg_database']=="on"){
        $tlist = mysql_list_tables($_SESSION['cfg_dbname']);
        while ($row = mysql_fetch_row($tlist)) {
               $all[] =  $row[0];
        }
        if (is_array($all)){
        foreach ($all as $t){
                 if (in_array($t."_cache",$all)){
                       $tables[] = $t;
                 }
        }
        }
    }
    return $tables;
}

function get_path ($file) {
   $path = str_replace($file,"",$_SERVER['SCRIPT_FILENAME']);
   return $path;
}

function do_dbopt (){
         $tables = get_tables();
         if (is_array($tables)){
               foreach($tables as $name) {
                       $result = mysql_query("ALTER TABLE `$name` ORDER BY `Id`") or die ("Failed to optimize". mysql_error());
                       echo "Optimised table $name .<br>\n";
               }
         }
}


?>
Return current item: PHPSiteStats