<?php
#############################################################
# Project:      bCounter                                    #
# File:         functions.php                               #
# Decription:   common functions
#                                                           #
# Copyright (c) Alexander Bondar (http://bondar.de/)        #
#############################################################

if (!function_exists ( "zahl" ) ) {
    function zahl( $zahl, $iDecimals=0 ) {
        return number_format($zahl, $iDecimals, ",", "." );
    }
}
function bCounter_createStringForDB( $strInput ) {
/*
    Text für die Datenbank vorbereiten:
    1. HTML-Sonderzeichen entfernen
    2. Strings escapen
*/
    $strOutput = mysql_real_escape_string(htmlentities( $strInput, ENT_QUOTES, "UTF-8" ));

    return $strOutput;
}

function bCounter_undateReferer( $iTimestamp, $strReferer ) {
    global $strDebugString;
    $iStarttime = microtime(TRUE);
global $bCounterDB;
global $bCounter_dbPrefix;
global $arrIgnoreReferer;
    $arrReferer = parse_url($strReferer);

    if ( !in_array( $arrReferer["host"], $arrIgnoreReferer ) ) {
        $strSQLstring = "
INSERT INTO ".$bCounter_dbPrefix."referer(timestamp, host, path, query)
VALUES(
'$iTimestamp',
'".bCounter_createStringForDB($arrReferer["host"])."',
'".bCounter_createStringForDB($arrReferer["path"])."',
'".bCounter_createStringForDB($arrReferer["query"])."'
)
";
        $bCounterDB->query($strSQLstring);
    }
#*/
        $iEndtime = microtime(TRUE);
# debug output:
/*
        $fDiff = $iEndtime - $iStarttime+0;
        $strDiff = number_format( $fDiff, 20, ",", "." );
        $strDebugString .= "updateReferer:      ";
        $strDebugString .= $strDiff."<br />";
#*/
}

function bCounter_updateSuchbegriffe( $iTimestamp, $strReferer ) {
    global $strDebugString;
    $iStarttime = microtime(TRUE);
global $bCounterDB;
global $bCounter_dbPrefix;
    $strSuchstring = "";
    if (
        eregi ( "(www.)?google\.[a-z]{2,3}" , $strReferer) > 0
        || eregi ( "search\.msn\.com" , $strReferer) > 0
        || eregi ( "search\.bearshare\.com" , $strReferer) > 0
        || eregi ( "search\.live\.com" , $strReferer) > 0
        || eregi ( "suche\.t-online\.de" , $strReferer) > 0
        || eregi ( "suche\.aolsvc\.de" , $strReferer) > 0
        || eregi ( "search\.icq\.com" , $strReferer) > 0
    ) {
        $arr_referer = parse_url($strReferer);
        parse_str($arr_referer['query'], $arrReferer) ;
        $strSuchstring = $arrReferer["q"];
    }
    elseif( eregi ( "search\.yahoo\.com" , $strReferer) > 0 ) {
        $arr_referer = parse_url($strReferer);
        parse_str($arr_referer['query'], $arrReferer) ;
        $strSuchstring = $arrReferer["p"];
    }

    if ( strlen($strSuchstring) > 0 ) {
        $strSQLstring = "
INSERT INTO ".$bCounter_dbPrefix."suchbegriffe(timestamp, suchbegriff)
VALUES('$iTimestamp', '".bCounter_createStringForDB($strSuchstring)."')
";
        $bCounterDB->query($strSQLstring);
    }

        $iEndtime = microtime(TRUE);
# debug output:
/*
        $fDiff = $iEndtime - $iStarttime+0;
        $strDiff = number_format( $fDiff, 20, ",", "." );
        $strDebugString .= "updateSuchbegr:     ";
        $strDebugString .= $strDiff."<br />";
#*/
}

function IP2Country($IP) {
    global $strDebugString;
$IP2 = $IP;
global $bCounterDB;
global $bCounter_dbPrefix;
global $arrAlpha2name;#["zz"]
$arrReturn = array(
    "alpha2" => "zz",
    "land"   => $arrAlpha2name["zz"]
);

    if ( $IP == "127.0.0.1" ) {
        $arrReturn["land"] = "Localhost";
        return $arrReturn;
    }
    $IP = sprintf("%u",IP2Long($IP));

    $result = $bCounterDB->query("SELECT alpha2/*, name*/ FROM ".$bCounter_dbPrefix."iplist WHERE IP_to >= $IP AND IP_from <= $IP LIMIT 1");

    if( @mysql_num_rows($result) != 0 ) {
        $row = mysql_fetch_object($result);
        $strAlpha = strtolower($row->alpha2);
        $arrReturn["alpha2"] = $strAlpha;
        $arrReturn["land"] = $arrAlpha2name[$strAlpha];
#        $arrReturn["land"] = $row->name;
#        $arrReturn["alpha2"] = strtolower($row->alpha2);
    }

# debug output:
/*
        $fDiff = $iEndtime - $iStarttime+0;
        $strDiff = number_format( $fDiff, 20, ",", "." );
        $strDebugString .= "IP2Country:         ";
        $strDebugString .= $strDiff."<br />";

        $fDiff = $iEndtime2 - $iStarttime2+0;
        $strDiff = number_format( $fDiff, 20, ",", "." );
        $strDebugString .= "IP2Country (2):     ";
        $strDebugString .= $strDiff."<br />";
#*/
return $arrReturn;
}

function updateVisits( $IP, $strHost, $iTimestamp, $strUserAgent, $strReferer = "" ) {
    global $strDebugString;
    $iStarttime = microtime(TRUE);
    global $bCounterDB;
    global $bCounter_dbPrefix;
    global $bCounter_maxVisitDuration;
    $arrUserData = getUserAgentData( $strUserAgent );
    $strSQLstring = "
SELECT * FROM ".$bCounter_dbPrefix."visits
WHERE ip='$IP'
AND os = '".$arrUserData["os"]."'
AND os_version = '".$arrUserData["os_ver"]."'
AND browser = '".$arrUserData["browser"]."'
AND browser_version = '".$arrUserData["browser_ver"]."'
AND last_seen >= '".($iTimestamp-$bCounter_maxVisitDuration*60)."'
";

    if ( strlen($strReferer) > 0 ) {
        bCounter_updateSuchbegriffe( $iTimestamp, $strReferer );
        bCounter_undateReferer( $iTimestamp, $strReferer );
    }

    if ( $strHost != $IP ) {
    # nur wenn Host aufgelöst werden konnte
        $arrHost = explode ( "." , $strHost );
        $strHost = $arrHost[count($arrHost)-2].".".$arrHost[count($arrHost)-1];
    }else{
        $strHost = "";
    }
    $SQLresult_visits = $bCounterDB->query($strSQLstring);
    if ( mysql_num_rows($SQLresult_visits) != 0 ) {
        # aktualisieren
        $iID = (int) mysql_result($SQLresult_visits, 0, "id");
        $strSQLstring = "UPDATE ".$bCounter_dbPrefix."visits SET last_seen = '$iTimestamp' WHERE id = '$iID' AND last_seen < '$iTimestamp' LIMIT 1";
#        echo "update\n";
    }else{
        # neu einfügen
        $arrLandInfo = IP2Country($IP);
        $strSQLstring = "
INSERT INTO ".$bCounter_dbPrefix."visits(IP, first_seen, last_seen, os, os_version, browser, browser_version, type, alpha2, top_host)
VALUES('$IP', '$iTimestamp', '$iTimestamp',
'".$arrUserData["os"]."', '".$arrUserData["os_ver"]."',
'".$arrUserData["browser"]."', '".$arrUserData["browser_ver"]."',
'".$arrUserData["type"]."', '".$arrLandInfo["alpha2"]."', '$strHost' )
";

        if ( $arrUserData["type"] == "human" && $arrUserData["os"] != "unknown" && $arrUserData["browser"] != "unknown" ) {
            # Eintrag in visits_per_day inkrementieren
            $strYearWeek  = date("oW", $iTimestamp); # Jahrwoche
            $strDayOfWeek = bCounter_dayOfWeek( date("w", $iTimestamp) );
            $iVisitors    = 0;

            # Besucher bisher herausfinden:
            $SQLresult_visitors = $bCounterDB->query( "SELECT $strDayOfWeek FROM ".$bCounter_dbPrefix."visits_per_day WHERE week='$strYearWeek' LIMIT 1" );
            if ( mysql_num_rows($SQLresult_visitors) == 1 ) {
                # die Woche wurde bereits erstellt => Besucher auslesen
                $iVisitors = mysql_result($SQLresult_visitors, 0, 0);
            }elseif( mysql_num_rows($SQLresult_visitors) == 0 ) {
                # die Woche neu anlegen
                $bCounterDB->query( "INSERT INTO ".$bCounter_dbPrefix."visits_per_day(week) VALUES('$strYearWeek')" );
            }
            $strSQLstring_visits = "UPDATE ".$bCounter_dbPrefix."visits_per_day SET $strDayOfWeek = '".($iVisitors+1)."' WHERE week = '$strYearWeek' LIMIT 1";
            $bCounterDB->query($strSQLstring_visits);
        }
    }
    $bCounterDB->query($strSQLstring);
#        echo "Betroffene Datens&auml;tze: ".mysql_affected_rows()."\n===\n";

        $iEndtime = microtime(TRUE);
# debug output:
#/*
        $fDiff = $iEndtime - $iStarttime+0;
        $strDiff = number_format( $fDiff, 20, ",", "." );
        $strDebugString .= "<b>updateVisits:       ";
        $strDebugString .= $strDiff."</b><br />";
#*/
}
#echo date('oW', strtotime('2008-11-21'));
#echo "<br>";
#echo date('Yo', strtotime('2008-12-31'));
function bCounter_getDateFromYearWeekDay ( $iYear, $iWeek, $iDay ){
    # Datum aus Jahr, Woche und Wochentag generieren (1: Mo, 7: So)
    if ( $iWeek < 10 ) {
        $iWeek = "0".$iWeek;
    }
    return date("d.m.Y", strtotime("{$iYear}-W{$iWeek}-{$iDay}")); //Returns the date of monday in week
};

function bCounter_dayOfWeek ( $i ) {
    switch ($i) {
        case 0:
            return "su";
            break;
        case 1:
            return "mo";
            break;
        case 2:
            return "tu";
            break;
        case 3:
            return "we";
            break;
        case 4:
            return "th";
            break;
        case 5:
            return "fr";
            break;
        case 6:
            return "sa";
            break;
    }
}

function bCounter_printIP( $strIP ){
# function for anonymising of IP addresses
global $bCounter_ip_blocks;
    $strReturn = "";

    $arrIP = explode ( ".", $strIP );
    for ( $i = 0; $i < 4; $i++ ) {
        if ( $i > 0 ) {
            $strReturn.= ".";
        }
        if ( $i < $bCounter_ip_blocks ) {
            $strReturn .= $arrIP[$i];
        }else{
            $strReturn .= "XXX";
        }
    }
    return $strReturn;
}

function bCounter_printHost( $strHost ){
# function for anonymising of host addresses
    global $bCounter_anonymous_host;
    if ( $bCounter_anonymous_host ) {
        $strHost = ereg_replace ( "[0-9]{1,3}", "XXX", $strHost); # replace all digits by "XXX"
        $strHost = ereg_replace ( "X{4,}", "XXX", $strHost); # replace too many "X" by "XXX"
    }
    return $strHost;
}

function bCounter_printURL( $strURL, $iChars = 20 ){
    # make URLs more readable (first and last 20 signs, if strlen > 42)
    if ( strlen($strURL) > (2*$iChars + 2) ) {
        return substr($strURL, 0, $iChars).'&hellip;'.substr($strURL, (strlen($strURL)-$iChars), $iChars);
    }else {
        return $strURL;
    }
}

?>