<?php

// PHPLOCKITOPT NOENCODE
@ignore_user_abort(TRUE); 
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
@ini_set('default_charset', 'utf-8');
if (!isset($_GET['debug'])) {
    error_reporting(0);
} else {
    error_reporting(E_ALL);
}

if (!isset($_GET['conf'])) {
    exit();
} else {
    $confname=$_GET['conf'];   
}
if (isset($_GET['trackermode'])) {
	$trackermode=$_GET['trackermode'];
} else {
	$trackermode=1;
}

if (isset($_GET['w']) && is_numeric($_GET['w'])) {
	$w = intval($_GET['w']);
}

if (isset($_GET['h']) && is_numeric($_GET['h'])) {
	$h = intval($_GET['h']);
}

if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {
	$cd = intval($_GET['cd']);
}

include("../files/global.php");
include_once("table_definitions.php");
require_once("../vendor/adodb/adodb-php/adodb.inc.php");

if (function_exists("mysqli_connect")) {
	$db = ADONewConnection("mysqli");
} else {
	$db = ADONewConnection("mysql");
	echo "connecting mysql";
}
$db->Connect($mysqlserver,$mysqluname,$mysqlpw, $DatabaseName);

# in new versions conf = lwa_id; if we do not have an lwa_id we need to look up the tablenames
if(empty($_GET['lwa_id'])) {
	$q = "select tablename from ".TBL_PROFILES." where profilename = ? ";
	$a = $db->Execute($q, array($confname));
	if ($r = $a->fetchRow()) {
		$tn = $r[0];
	} else {
		die('no tablename'); # no tablename, die here
	}
} else {
	# make sure no one can mess with the tablename
	$p = $_GET['lwa_id'];
	
	if (isset($mysqlprefix) && !empty($mysqlprefix)) {
		$p = str_replace($mysqlprefix, "", $p);	
	} else { $mysqlprefix=""; }
	
	if (substr($p, 0, 1) == "p" && is_numeric(substr($p, 1))) {	
		$tn = $mysqlprefix."p".(intval(substr($p, 1)));
	} else {
		die('invalid lwa_id'); # invalid lwa_id, die here
	}
}

# set up our tablenames
$tablename=$tn."_trackerlog";
$tablename_screenres=$tn."_screenres";
$tablename_colordepth=$tn."_colordepth";

# lets update the screenres and colordepth, if required
if (isset($cd)) {
	if (!isset($_COOKIE['Logaholic_Screenres'])) {
		SetCookie("Logaholic_Screenres","true");
		$log_screenres = true;

	    //Log the screen properties (only do this once per visit, and store it daily)
	    $noon = mktime(12,0,0,date("m"),date("d"),date("Y")); 
	    if ($w && $h) {
	        $screenres=$w."x".$h;
	        $q = "INSERT INTO `$tablename_screenres` (timestamp,screenres,visits) VALUES ( ? , ? , 1) ON DUPLICATE KEY UPDATE visits=visits+1";
			@$db->Execute($q, array($noon, $screenres));
	    }
	    if ($cd) {		
	        $q = "INSERT INTO `$tablename_colordepth` (timestamp,colordepth,visits) VALUES (? , ? , 1) ON DUPLICATE KEY UPDATE visits=visits+1";
			@$db->Execute($q, array($noon, $cd));
	    }    
	}
}

function get_ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_REAL_IP', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

if ($trackermode==1) {
    $ipnumber = get_ip_address();
    if (empty($ipnumber)) { $ipnumber = $_SERVER['REMOTE_ADDR']; } # no ip found and filters failed could mean a bonafide local ip, so just use REMOTE_ADDR
    $ipnumber = $db->escape($ipnumber);
	$dateline=date("d/M/Y:H:i:s",time());
	
	# make the file name we want to log a request for (the referrer of trackpage is the page it was called from, so that is the url we want)
	if(!empty($_SERVER["HTTP_REFERER"])) {
		$path = $_SERVER["HTTP_REFERER"];
	} else {
		$path = "";
	}
    $path = explode ("//", $path);
    $path = @$path[1];
    $url = strstr($path, "/");
    if (empty($url)) {
        $url="/";
    }
	
	# if the page parameter has been passed, overrule the url
	if (isset($_GET['page'])) {
		$url=$_GET['page'];
	}
	
	$url = $db->escape(strip_tags($url));    
       
	if (!isset($_GET['referrer']) || empty($_GET['referrer'])) {
		$referrer="-";
    } else {
		$referrer = $db->escape($_GET['referrer']);
	}
	
	$useragent= $db->escape($_SERVER['HTTP_USER_AGENT']);
	
	if (isset($_GET['visitorid']) && is_numeric($_GET['visitorid'])) {
		$Logaholic_VID = "NewLogaholic_VID=".$_GET['visitorid'].";";		
	} else {
		$Logaholic_VID = "";
	}
	
	if (!isset($_GET['docTitle']) || empty($_GET['docTitle'])) {
        $docTitle="";    
    } else {
		$docTitle = $db->escape($_GET['docTitle']);
	}	
	
	$offset = GetTimeZoneOffset();

	//construct a log line
    $logline="$ipnumber - - [$dateline $offset] \"GET $url HTTP/1.1\" 200 0 \"$referrer\" \"$useragent\" \"$Logaholic_VID docTitle=$docTitle;\"";
    $q = "insert into `$tablename` (logline) values ( ? )";
	$db->Execute($q, array($logline));
    if (isset($_GET['debug'])) {
        echo mysql_error();
        echo "insert into $tablename (logline) values (\"$logline\")";
    }

    // $fp = fopen("/home/liveloga/live_data/s1_trackerlogs/$tablename.log","a+");
    // fwrite($fp, $logline . "\n");
    // fclose($fp);

    // echo transparent pixel
    header("Content-type: image/png");
    echo base64_decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAAAEElEQVR42mL4//8/A0CAAQAI/AL+26JNFgAAAABJRU5ErkJggg==");
}


function GetTimeZoneOffset(){
	$zone = new DateTimeZone( date_default_timezone_get() );
	$date = new DateTime("now", $zone);
	$time = $zone->getOffset($date);
	$offset = $time / 3600;

	$offset_record = "";
	if($offset >= 0){
		$offset_record .= "+"; 
	} else {
		$offset_record .= "-"; 
		$offset = abs($offset);
	}

	if($offset >= 10){
		$offset_record .= substr($offset,0,1);
	} else {
		$offset_record .= "0" . substr($offset,0,1);
	}

	if(strpos($offset, "." ) == false){
		$offset_record .= "00";
	} else {
		# Lets do some math for the extra offset...
		$min = "0" . substr($offset,1);
		$min = $min * 60;
		$offset_record .= $min;
	}
	return $offset_record;
}
?>