<?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/common/web_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/>.
*/
require_once(dirname(__FILE__)."/../common/nectil_object.class.php");
require_once(dirname(__FILE__)."/../common/date.class.php");

class web_log extends SusheeObject{
	var $creation_date;// = new Date();//=array("year"=>0, "month"=>0, "day"=>0,"hours"=>0, "minutes"=>0, "seconds"=>0);
	var $visit_id=0;
	var $url='';
	var $element_id=0;
	var $viewing_code='';
	var $language_id='';
	var $bot_name='';
	var $from_host='';
	var $from_uri='';
	var $from_host_id='';
	var $from_uri_id='';
	var $is_search=false;
	var $keyword='';
	var $referrerCode='';
	var $bannerCode='';
	function web_log($creation_date, $host, $url, $element_id, $viewing_code, $language_id, $from_url, $referrerCode, $bannerCode){
		$db_conn = db_connect();
                $this->creation_date=new Date($creation_date);
		/*$now=new Date($creation_date);
		$this->creation_date['year']=1900+$now['tm_year'];
		$this->creation_date['month']=$now['tm_mon']+1;
		$this->creation_date['day']=$now['tm_mday'];
		$this->creation_date['hours']=$now['tm_hour'];
		$this->creation_date['minutes']=$now['tm_min'];
		$this->creation_date['seconds']=$now['tm_sec'];*/

		$this->visit_id=$visit_id;
		//if($element_id && is_numeric($element_id)){
			$this->element_id=$element_id;
		//}else{
			//tools
			if(eregi('^/~',$url)){
				$url=eregi_replace('^/~[a-zA-Z0-9]*/','',$url);
			}else if(eregi('^/Residents/',$url)){
				$url=eregi_replace('^/Residents/'.$GLOBALS['resident_name'],'',$url);
			}
			if(substr($url,0,1)=='/'){
				$url=substr($url,1);
			}
			$sql = "SELECT ID FROM referrer_page WHERE URI=\"".encodeQuote($url)."\" ;";
			$this->logSQL($sql);
			$page = $db_conn->getRow($sql);
			if($page){
				$this->url=$page['ID'];
			}else{
				//insert page
				$sql = "SELECT * FROM referrer_page WHERE 1=-1;";
				$pseudo_rs = $db_conn->Execute($sql);
				$data = array();
				$data['URI']=$url;
				$data['isInnerURI']=1;
				$insert_sql = $db_conn->GetInsertSQL($pseudo_rs,$data);
				$this->logSQL($insert_sql);
				if($db_conn->Execute($insert_sql)!==false){
					$this->url=$db_conn->Insert_ID();
				}else{
					$this->url=0;
				}
			}
		//}
		$this->viewing_code=$viewing_code;
		$this->referrerCode=$referrerCode;
		$this->bannerCode=$bannerCode;
		$this->language_id=$language_id;
		
		$this->is_search=false;
		$url_parsed=parse_url($from_url);
		if($url_parsed['host'] && $url_parsed['host']!='' && $url_parsed['host']!==$host){
			if(strpos($url_parsed['host'], 'www.')===0){
				$this->from_host=substr($url_parsed['host'],4);
			}else{
				$this->from_host=$url_parsed['host'];
			}
			$this->from_uri=$url_parsed['path'].($url_parsed['query']?"?":"").$url_parsed['query'];

			$keyword=$this->getKeyWord($url_parsed['query']);
			if($keyword || $keyword!='')
				$this->is_search=true;
			$this->keyword=$keyword;
		}
		if($this->from_host && $this->from_host!=''){
			$sql = "SELECT ID FROM referrer WHERE DomainName=\"".encodeQuote($this->from_host)."\";";
			//debug_log($sql);
			$referrer = $db_conn->getRow($sql);
			echo $db_conn->ErrorMsg();
			if($referrer){
				$this->from_host_id=$referrer['ID'];
			}else{
				//insert referrer
				$sql = "SELECT * FROM referrer WHERE 1=-1;";
				$pseudo_rs = $db_conn->Execute($sql);
				$data = array();
				$data['DomainName']=$this->from_host;
				$insert_sql = $db_conn->GetInsertSQL($pseudo_rs,$data);
				if($db_conn->Execute($insert_sql)!==false){
					$this->from_host_id=$db_conn->Insert_ID();
				}else{
					$this->from_host_id=0;
					$this->from_host='';
				}
			}
		}
		if($this->from_host && $this->from_host!='' && $this->is_search===false){
			if(substr($this->from_uri,0,1)=='/'){
				$this->from_uri=substr($this->from_uri,1);
			}
			$sql = "SELECT ID FROM referrer_page WHERE referrer='".$this->from_host_id."' AND URI=\"".encodeQuote($this->from_uri)."\" ;";
			$page = $db_conn->getRow($sql);
			echo $db_conn->ErrorMsg();
			if($page){
				$this->from_uri_id=$page['ID'];
			}else{
				//insert page
				$sql = "SELECT * FROM referrer_page WHERE 1=-1;";
				$pseudo_rs = $db_conn->Execute($sql);
				$data = array();
				$data['referrer']=$this->from_host_id;
				$data['URI']=$this->from_uri;
				$insert_sql = $db_conn->GetInsertSQL($pseudo_rs,$data);
				if($db_conn->Execute($insert_sql)!==false){
					$this->from_uri_id=$db_conn->Insert_ID();
				}else{
					$this->from_uri_id=0;
				}
			}
		}
	}
	/**
	*return les mot clé de l'url passé en paramètre
	*/
	function getKeyWord($args){
		$URLparams = explode('&', $args);
		foreach($URLparams as $param){
			$parts = explode('=',$param);
			$paramName =  $parts[0];
			$paramValue =  $parts[1];
			if($parts && $paramValue!=''){
				// param of type keyword
				if($paramName=='q' || $paramName=='p' || $paramName=='MT'
						/*ajout->*/ || $paramName=='search' || $paramName=='searchText' || $paramName=='query'
						|| $paramName=='qt' || $paramName=='s' ||  $paramName=='kw' ||  $paramName=='qr'||  $paramName=='imgurl'){ 
					$keyword = strtolower(urldecode($paramValue));
					
				/*}else if((strpos($remote_host ,"lycos.com")!==false
						|| strpos($remote_host ,"lycos.fr")!==false
						|| strpos($remote_host ,"mamma.com")!==false
						|| strpos($remote_host ,"hotbot.com")!==false)
						&& $paramName=='query'){
					$keyword = strtolower(str_replace('+',' ',$paramValue));
					
				}else if((strpos($remote_host ,"looksmart.com")!==false)//post data?
						&& $paramName=='key'){
					$keyword = strtolower(str_replace('+',' ',$paramValue));
					
				}else if((strpos($remote_host ,"infoseek.com")!==false)//->go.com
						&& $paramName=='qt'){
					$keyword = strtolower(str_replace('+',' ',$paramValue));
				
				}else if((strpos($remote_host ,"tiscali.fr")!==false)//->serveur introuvable
						&& $paramName=='s'){
					$keyword = strtolower(str_replace('+',' ',$paramValue));
				
				}else if((strpos($remote_host ,"voila.fr")!==false)//?rdata
						&& $paramName=='kw'){
					$keyword = strtolower(str_replace('+',' ',$paramValue));
				
				}else if((strpos($remote_host ,"northernlight.com")!==false)//?
						&& $paramName=='qr'){
					$keyword = strtolower(str_replace('+',' ',$paramValue));*/
				}
				//==> http://forum.webrankinfo.com/recuperer-requete-qui-fait-venir-les-internautes-t11268.html
				//eureka.com->searchword
			}
		}
		return $keyword;
	}


	function save(){
		$db_conn = db_connect();
		$sql = "SELECT * FROM logs_web_".$this->creation_date->getYear()." WHERE 1=-1;";
		$pseudo_rs = $db_conn->Execute($sql);
		if(!$pseudo_rs){ // new year !!!
			$sql_newyear="
			INSERT INTO logs_web_years (year) VALUES (".date('Y').");";
			$db_conn->Execute($sql_newyear);

			$sql_newyear="
			CREATE TABLE IF NOT EXISTS logs_web_".date('Y')." (
				month tinyint(1) NOT NULL DEFAULT '0',
				day tinyint(1) NOT NULL DEFAULT '0',
				hours tinyint(1) NOT NULL DEFAULT '0',
				minutes tinyint(1) NOT NULL DEFAULT '0',
				seconds tinyint(1) NOT NULL DEFAULT '0',
				VisitID bigint(20) NOT NULL DEFAULT '0',
				URL bigint(20) NOT NULL DEFAULT '0' REFERENCES referer_page(ID),
				elementID bigint(20) NOT NULL DEFAULT '0',
				ViewingCode varchar(250) NOT NULL DEFAULT '',
				LanguageID varchar(10) NOT NULL DEFAULT '',
				referrerHost bigint(20) NOT NULL DEFAULT '0' REFERENCES referer(ID),
				referrerPage bigint(20) NOT NULL DEFAULT '0' REFERENCES referer_page(ID),
				isSearch tinyint(1) NOT NULL DEFAULT '0',
				keyword text NOT NULL DEFAULT '',
				referrerCode varchar(255) NOT NULL DEFAULT '',
				bannerCode varchar(255) NOT NULL DEFAULT '',
				KEY(month, day),
				KEY(VisitID)
			) TYPE=MyISAM;";
			$db_conn->Execute($sql_newyear);
			$pseudo_rs = $db_conn->Execute($sql);
		}
		$data = array();
		$data['month']=$this->creation_date->getMonth();
		$data['day']=$this->creation_date->getDay();
		$data['hours']=$this->creation_date->getHour();
		$data['minutes']=$this->creation_date->getMinute();
		$data['seconds']=$this->creation_date->getSecond();
		$data['VisitID']=$this->visit_id;
		$data['URL']=$this->url;
		$data['elementID']=$this->element_id;
		$data['ViewingCode']=$this->viewing_code;
		$data['LanguageID']=$this->language_id;
		$data['botName']=$this->bot_name;
		$data['referrerHost']=$this->from_host_id;
		$data['referrerPage']=$this->from_uri_id;
		$data['isSearch']=$this->is_search;
		$data['keyword']=$this->keyword;
		$data['referrerCode']=$this->referrerCode;
		$data['bannerCode']=$this->bannerCode;

		$insert_sql = $db_conn->GetInsertSQL($pseudo_rs,$data);
		$this->logSQL($insert_sql);
		$db_conn->Execute($insert_sql);
	}
}
?>
