<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/Library/updates/20090312-stats-v4/resources/visit_log.class.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
class visit_log{
	var $visit_id=0;
	var $visitor_id='';
	var $start_date=array("year"=>0, "month"=>0, "day"=>0);
	var $start_time=array("hours"=>0, "minutes"=>0, "secondes"=>0);
	var $host=0;
	var $ip='';
	var $Browser='';
	var $os='';
	var $country_id='';
	var $provider='';
	var $user_id=0;
	var $language_id=0;
	var $nb_page_visited=0;
	var $duration=0;
	var $last_access_interval=0;
	var $is_bot;
	var $bot_name;
	static $limit_time=3600;
	static $kill_spam=true;
	static $spam_limit_page=10;
	static $spam_limit_time=4;

	/**
	*Charge les valeurs de la BD, si pas de valeur dans la DB pour ce visiteur
	*initialise avec les valeurs en paramètre
	*/
	function visit_log($visitor_id,$creation_date,$host,$ip,$userAgent,$remote_host,$user_id,$language,$url){//provider
		$db_conn = db_connect();
		if(!$visitor_id || $visitor_id==''){
			$this->createVisitor($userAgent,$remote_host,$creation_date,$ip);
		}else{
			$this->visitor_id=$visitor_id;
		}
		$this->language_id=$language;
		if($this->is_bot){
			$sql = "SELECT * FROM logs_visit WHERE VisitorID='".$this->visitor_id."' AND languageID='".encodeQuote($this->language_id)."' ORDER BY year DESC, month DESC, day DESC, startHours DESC, startMinutes DESC, startSeconds DESC LIMIT 1;";
		}else{
			$sql = "SELECT * FROM logs_visit WHERE VisitorID='".$this->visitor_id."' ORDER BY year DESC, month DESC, day DESC, startHours DESC, startMinutes DESC, startSeconds DESC LIMIT 1;";
		}
		debug_log($sql);
		$visit = $db_conn->getRow($sql);
		if($visit){
			$this->loadFromDb($visit,$creation_date,$host,$userAgent,$user_id,$ip,$remote_host,$url);
		}else{
			$this->init_value($creation_date,$host,$userAgent,$user_id,$ip,$remote_host,$url);
		}

		//---------------init values for all cases------------------
		$this->user_id=$user_id;
		if(!$this->user_id){
			$this->user_id=0;
		}
		$this->host=$this->getHostID($host,$url);

		$this->nb_page_visited++;
		if($this->ip != $ip){
			$this->ip = $ip;
			$ipsolved = ip2long($ip);
			$sql = "SELECT iso3 FROM ".$GLOBALS['generic_backoffice_db'].".ipv4 WHERE `from` < " . ($ipsolved+1) . " AND `to` > " . ($ipsolved-1) . " LIMIT 0,1;";
			$row = $db_conn->getRow($sql);
			$this->country_id = $row['iso3'];
		}
		
	}
	function loadFromDb($row,$creation_date,$host,$userAgent,$user_id,$ip,$remote_host,$url){
		$this->visit_id=$row['VisitID'];
		$this->visitor_id=$row['VisitorID'];
		$this->start_date['year']=$row['year'];
		$this->start_date['month']=$row['month'];
		$this->start_date['day']=$row['day'];
		$this->start_time['hours']=$row['startHours'];
		$this->start_time['minutes']=$row['startMinutes'];
		$this->start_time['secondes']=$row['startSeconds'];
		$this->duration=$row['duration'];
		$this->nb_page_visited=$row['NbPageVisited'];
		$this->host=$row['Host'];
		$this->ip=$row['IP'];
		$this->browser=$row['Browser'];
		$this->os=$row['OS'];
		$this->is_bot=$row['isBot'];
		$this->bot_name=$row['botName'];
		$this->country_id=$row['countryID'];
		$this->provider=$row['Provider'];
		$this->user_id=$row['UserID'];
		$this->language=$row['LanguageID'];

		//-----compute new duration--------
		$begin=mktime($this->start_time['hours'], $this->start_time['minutes'], $this->start_time['secondes'], $this->start_date['month'], $this->start_date['day'], $this->start_date['year']);
		$array_end=strptime($creation_date,"%Y-%m-%d %T");
		$end=mktime($array_end['tm_hour'], $array_end['tm_min'], $array_end['tm_sec'], $array_end['tm_mon']+1, $array_end['tm_mday'], $array_end['tm_year']+1900);
		//$end=time();//!!!!!!!!!!!!!!!!!!!!!!!!!!!!portage
		$old_duration=$this->duration;
		$this->duration=$end-$begin;
		$this->last_access_interval=$this->duration-$old_duration;//interval whit the precedent page viewed = total duration - the last total duration saved.
		if($this->last_access_interval > visit_log::$limit_time){
			$this->visit_id=0;
			$this->init_value($creation_date,$host,$userAgent,$user_id,$remote_host,$url);
		}
	}
	
	/**init for a new insert*/
	function init_value($creation_date,$host,$userAgent,$user_id,$ip,$remote_host,$url){
		$now=strptime($creation_date,"%Y-%m-%d %T");
		$this->start_date['year']=1900+$now['tm_year'];
		$this->start_date['month']=$now['tm_mon']+1;
		$this->start_date['day']=$now['tm_mday'];
		$this->start_time['hours']=$now['tm_hour'];
		$this->start_time['minutes']=$now['tm_min'];
		$this->start_time['secondes']=$now['tm_sec'];
		$this->nb_page_visited=0;
		$this->duration=0;
		$this->provider=$this->getProvider($remote_host);

		include_once(dirname(__FILE__)."/../common/phpSniff.class.php");
		$client =& new phpSniff($userAgent);
		$os = $client->property('platform');
		if ($os != 'Unknown'){
			$this->os=$os;
		}else{
			$this->os='';
		}
		$browser = $client->property('long_name');
		if ($browser != 'Unknown'){
			$this->browser=$browser;
		}else{
			$this->browser='';
		}
		if($this->is_bot=($this->isCrawler($userAgent) || $this->isCrawler($remote_host))){
			$this->bot_name=$this->getBotName($userAgent,$remote_host);
		}else{
			$this->bot_name='';
		}
		$this->provider=$this->getProvider($remote_host);
	}

	function isNewVisit(){
		return $this->visit_id==0;
	}

	function isNewVisitor(){
		return $this->visitor_id==0;
	}

	function createVisitor($userAgent,$remote_host,$creation_date,$ip){
		if($this->is_bot=($this->isCrawler($userAgent) || $this->isCrawler($remote_host))){
			$this->bot_name=$this->getBotName($userAgent);
		}else{
			$this->bot_name='';
		}
		$date=substr($creation_date,0,strpos($creation_date,' '));
		if($this->is_bot){
			$this->visitor_id=md5($date.$this->bot_name);
		}else{
			$this->visitor_id=md5($date.$ip.$userAgent);
		}
		setCookie('visitorID',$this->visitor_id,time()+60*60*24*365);
	}

	function isSpamer(){
		return (!$this->is_bot && $this->nb_page_visited > visit_log::$spam_limit_page && ($this->duration/$this->nb_page_visited) < visit_log::$spam_limit_time);
	}
	
	function getProvider($remote_host){
		$doms = explode('.',$remote_host);
		$count_pts=0;
		if(!$remote_host || $remote_host==''){
			return '';
		}
		$provider=$doms[count($doms)-1];
		for($i=count($doms)-2;$i>=0;$i--){
			$provider=$doms[$i].".".$provider;
			if($count_pts>=2 || strlen($doms[$i])>3){
				break;
			}
			$count_pts++;
		}
		return $provider;
	}
	
	function getHostID($host, $url){
		$db_conn = db_connect();
		$host_name=$host;
		if(eregi('^/~',$url)){
			$url=eregi_replace('^/~','',$url);
			$host_name=eregi_replace('/.*','',$url);
			$host_name='https://'.$host.'/~'.$host_name;
		}else if(eregi('^/Resident/',$url)){
			$url=eregi_replace('^/Resident/','',$url);
			$host_name=eregi_replace('/.*','',$url);
			$host_name=$host.'/Resident/'.$host_name;
		}
		$sql = "SELECT * FROM host WHERE DomainName='".encodeQuote($host_name)."';";
		//debug_log($sql);
		$domain = $db_conn->getRow($sql);
		if($domain){
			return $domain['ID'];
		}else{
			//insert host
			$sql = "SELECT * FROM host WHERE 1=-1;";
			$pseudo_rs = $db_conn->Execute($sql);
			$data = array();
			$data['DomainName']=$host_name;
			$insert_sql = $db_conn->GetInsertSQL($pseudo_rs,$data);
			//debug_log($insert_sql);
			if($db_conn->Execute($insert_sql)!==false){
				return $db_conn->Insert_ID();
			}
		}
		return 0;
	}

	function getBotName($userAgent,$remote_host){
		if($userAgent && $userAgent==''){
			return $this->getProvider($remote_host);
		}else{
			if(eregi('\\(compatible;.*\\)',$userAgent)){
				$botName = eregi_replace('.*\\(compatible;','',$userAgent);//remove all before '(compatible;'
				$botName = eregi_replace('(;.*)|(\\).*)','',$botName);//remove all after ')' or the next ';'
			}else{
				$botName = eregi_replace(' *\\(.*','',$userAgent);//remove all after '(' and if present the space before
			}
			return $botName;
		}
	}

	function isCrawler($agent){
		return eregi ( "(bot)|(google)|(slurp)|(spider)|(crawl)|(archive)|(linkwalker)|(findlinks)|(biglotron)|(worm)|(twiceler)|(monitor)|(scout)",$agent);
	}

	function insert(){
		$db_conn = db_connect();
		$sql = "SELECT * FROM logs_visit WHERE 1=-1;";
		$pseudo_rs = $db_conn->Execute($sql);
		$data = array();
		$data['VisitorID']=$this->visitor_id;
		$data['year']=$this->start_date['year'];
		$data['month']=$this->start_date['month'];
		$data['day']=$this->start_date['day'];
		$data['startHours']=$this->start_time['hours'];
		$data['startMinutes']=$this->start_time['minutes'];
		$data['startSeconds']=$this->start_time['secondes'];
		$data['NbPageVisited']=$this->nb_page_visited;
		$data['duration']=$this->duration;
		$data['Host']=$this->host;
		$data['IP']=$this->ip;
		$data['Browser']=$this->browser;
		$data['OS']=$this->os;
		$data['isBot']=$this->is_bot;
		$data['botName']=$this->bot_name;
		$data['CountryID']=$this->country_id;
		$data['Provider']=$this->provider;
		$data['UserID']=$this->user_id;
		$data['LanguageID']=$this->language_id;
		$insert_sql = $db_conn->GetInsertSQL($pseudo_rs,$data);
		debug_log($insert_sql);
		if($db_conn->Execute($insert_sql)!==false){
			$this->visit_id=$db_conn->Insert_ID();
		}else{
			$this->visit_id=0;
		}
	}

	function save(){
		if($this->isNewVisit()){
			$this->insert();
		}else{
			//update
			$db_conn = db_connect();
			$sql = "UPDATE logs_visit set userID=".$this->user_id.", IP='".$this->ip."', CountryID='".$this->country_id."', LanguageID='".encodeQuote($this->language_id)."',".
							" duration=".$this->duration.", NbPageVisited=".$this->nb_page_visited.", Host=".$this->host.
					" WHERE VisitID=".$this->visit_id.";";
			debug_log($sql);
			$db_conn->Execute($sql);
			echo $db_conn->ErrorMsg();//////////////////////////////////
		}
	}

}
?>
