<?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/searchStatsV4.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/nqlOperation.class.php');
require_once(dirname(__FILE__)."/../common/descriptions.inc.php");
class searchStats extends RetrieveOperation{
	
	var $year;
	var $month;
	var $day;
	var $type;
	var $languageID;
	var $host;
	var $os;
	var $browser;
	var $browser_version;
	var $browser_major_version;
	var $browser_minor_version;
	var $country;
	var $page;
	var $byPage;
	
	function searchStats($param1,$param2=false){
		if(is_array($param1))
			$this->parseConfig($param1);
		else{
			parent::RetrieveOperation($param1,$param2);
		}
	}
	
	function setMonth($month){
		$this->month = $this->pad_month_or_day($month);
	}
	
	function setDay($day){
		$this->day = $this->pad_month_or_day($day);
	}
	
	function setYear($year){
		$this->year = $year;
	}
	
	function generateStats(){
		echo 'non implemented';
	}
	
	function getSelectStat(){
		$day = $this->day;
		$month = $this->month;
		$year = $this->year;
		$type = $this->type;
		$statConfig = $this->getStatTypeConfig($type);
		$origStatType = $type;
		$type = $statConfig['compute'];
		$languageID = $this->languageID;
		$os = $this->os;
		$browser = $this->browser;

		$db_conn = db_connect();
		$sql="SELECT * FROM logs_web_years WHERE year=$year;";
		$table = $db_conn->getRow($sql);
		if(!$table){
			return false;
		}

		$status = 0;
		if($year<date('Y')){
			$status = 1;
		}else if($year==date('Y') && $month!=0 && $month<date('m')){
			$status = 1;
		}else if($year==date('Y') && $month!=0 && $day!=0 && $month==date('m') && $day<date('d')){
			$status = 1;
		}
		//echo 'type='.$type."\n";

		$select_type_date_filter=" $status as Status, 'web' as Domain, '$type' as Type, $year as Year, $month as Month, $day as Day,";
		$select_type_date_filter.= " '$this->host' as Host, '$this->country' as CountryID, '$this->languageID' as LanguageID,";
		$select_type_date_filter.=$statConfig['is_browser_os_needed']?" '$this->os' as OS, '$this->browser' as Browser,":"";
		$select_filter_no_platform=" '$this->host' as Host, '$this->country' as CountryID, '$this->languageID' as LanguageID,";

		$where_filtre_sql="";
		if($this->languageID!='')
			$where_filtre_sql.= ' AND LanguageID="'.$this->languageID.'"';
		if($this->host!='')
			$where_filtre_sql.= ' AND host.DomainName="'.$this->host.'"';
		if($this->os!='' && $statConfig['is_browser_os_needed'])
			$where_filtre_sql.= ' AND OS="'.$this->os.'"';
		if($this->browser!='' && $statConfig['is_browser_os_needed'])
			$where_filtre_sql.= ' AND Browser="'.$this->browser.'"';
		if($this->country!='')
			$where_filtre_sql.= ' AND CountryID="'.$this->country.'"';

		$where_date_logs_web=($month!=0?" AND logs_web_$year.month=".$month:"").($day!=0?" AND logs_web_$year.day=".$day:"");
		$where_date_logs_visit=" AND year=$year".($month!=0?" AND month=".$month:"").($day!=0?" AND day=".$day:"");
		$join_visit_if_filter=$where_filtre_sql!=""?" JOIN logs_visit ON logs_web_".$year.".visitID=logs_visit.visitID":"";
		$join_host_if_filter=$this->host!=""?" JOIN host ON Host=host.ID":"";
		switch($type){
			case 'bots':
				$sql = "SELECT $select_type_date_filter botName as ID, sum(NbPageVisited) as Value,".
						" ROUND(100 * sum(NbPageVisited) / (SELECT sum(NbPageVisited) FROM logs_visit$join_host_if_filter".
											" WHERE isBot".$where_date_logs_visit.$where_filtre_sql."),2) as Pct".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE isBot ".$where_date_logs_visit.$where_filtre_sql." GROUP BY botName";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'uniquebots':
				$sql = "SELECT $select_type_date_filter count(distinct(botName)) as Value".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE isBot ".$where_date_logs_visit.$where_filtre_sql;
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'keywords':
				$sql = "SELECT $select_type_date_filter keyword as ID, count(keyword) as Value,".
						" ROUND(100 * count(keyword) / (SELECT count(keyword) FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
											" WHERE isSearch".$where_date_logs_web.$where_filtre_sql."),2) as Pct".
						" FROM logs_web_$year".$join_visit_if_filter.$join_host_if_filter.
						" WHERE isSearch ".$where_date_logs_web.$where_filtre_sql." GROUP BY keyword";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'indexed_pages':
				$sql = "SELECT $select_type_date_filter sum(NbPageVisited) as Value".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE isbot".$where_date_logs_visit.$where_filtre_sql;
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'external_referrers':
				$sql = "SELECT $select_type_date_filter CONCAT(CONCAT(DomainName, '/'),URI) as ID, count(*) as Value,".
								" ROUND(100 * count(*) / ( SELECT  count(*) FROM logs_web_$year".$join_visit_if_filter.$join_host_if_filter.
											" WHERE !isSearch AND referrerPage != 0".$where_date_logs_web.$where_filtre_sql."),2) as Pct ".
						" FROM logs_web_$year".$join_visit_if_filter.$join_host_if_filter.
						" JOIN referrer_page ON referrer_page.ID=referrerPage".
						" JOIN referrer ON referrer.ID=referrerHost".
						" WHERE !isSearch AND referrerPage !=0".$where_date_logs_web.$where_filtre_sql." GROUP BY referrerPage";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'unique_referrers':
				$sql = "SELECT $select_type_date_filter DomainName as ID, count(referrerHost) as Value,".
								" ROUND(100 * count(referrerHost) / ( SELECT  count(referrerHost) FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
											" WHERE !isSearch AND referrerHost != 0".$where_date_logs_web.$where_filtre_sql."),2) as Pct".
						" FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
						" JOIN referrer ON referrer.ID=referrerHost".
						" WHERE !isSearch AND referrerHost !=0".$where_date_logs_web.$where_filtre_sql." GROUP BY referrerHost";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'search_engines':
				$sql = "SELECT $select_type_date_filter DomainName as ID, count(referrerHost) as Value,".
								" ROUND(100 * count(referrerHost) / (SELECT count(*) FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
											" WHERE isSearch".$where_date_logs_web.$where_filtre_sql."),2) as Pct ".
						" FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
						" JOIN referrer ON referrer.ID=referrerHost".
						" WHERE isSearch".$where_date_logs_web.$where_filtre_sql." GROUP BY referrerHost";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'uniquevisitors':
				$sql = "SELECT $select_type_date_filter count(distinct(visitorID)) as Value".
						"  FROM logs_visit".$join_host_if_filter.
						" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql;
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'hourly_charges':
				$sql = "SELECT $select_type_date_filter hours as ID, count(*) as Value".
						" FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
						" WHERE 1".$where_date_logs_web.$where_filtre_sql." GROUP BY hours";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'hosts':
				$sql = "SELECT $select_type_date_filter DomainName as ID, sum(NbPageVisited) as Value,".
								" ROUND(100 * sum(NbPageVisited) / (SELECT sum(NbPageVisited) FROM logs_visit$join_host_if_filter".
											" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql."),2) as Pct".
						" FROM logs_visit JOIN host ON Host=host.ID".
						" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql." GROUP BY Host";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'tool_top':
				$sql = "SELECT $select_type_date_filter URI as ID, count(*) as Value,".
								" ROUND(100 * count(*) / (SELECT count(*) FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
											" WHERE isInnerURI ".$where_date_logs_web.$where_filtre_sql."),2) as Pct".
						" FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
						" JOIN referrer_page ON referrer_page.ID=URL".
						" WHERE isInnerURI ".$where_date_logs_web.$where_filtre_sql." GROUP BY URI";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'medias_top':
				$sql = "SELECT $select_type_date_filter elementID as ID, count(*) as Value,".
								" ROUND(100 * count(*) / (SELECT count(*) FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
											" WHERE elementID!=0".$where_date_logs_web.$where_filtre_sql."),2) as Pct".
						" FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
						" WHERE elementID!=0".$where_date_logs_web.$where_filtre_sql." GROUP BY elementID";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'mediatypes_top':
				$sql = "SELECT $select_type_date_filter MediaType as ID, count(*) as Value,".
								" ROUND(100 * count(*) / (SELECT count(*) FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
											" WHERE elementID!=0".$where_date_logs_web.$where_filtre_sql."),2) as Pct".
						" FROM logs_web_".$year.$join_visit_if_filter.$join_host_if_filter.
						" JOIN medias on elementID=medias.ID".
						" WHERE elementID!=0".$where_date_logs_web.$where_filtre_sql." GROUP BY MediaType";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'languages':
				$sql = "SELECT $select_type_date_filter LanguageID as ID, sum(NbPageVisited) as Value,".
								" ROUND(100 * sum(NbPageVisited) / (SELECT sum(NbPageVisited) FROM logs_visit$join_host_if_filter".
											" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql."),2) as Pct".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql." GROUP BY LanguageID";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'providers':
				$sql = "SELECT $select_type_date_filter Provider as ID, count(distinct(visitorID)) as Value,".
								" ROUND(100 * count(distinct(visitorID)) / (SELECT count(distinct(visitorID)) FROM logs_visit $join_host_if_filter".
											" WHERE !isBot AND Provider!=''".$where_date_logs_visit.$where_filtre_sql."),2) as Pct".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE !isBot AND Provider!='' ".$where_date_logs_visit.$where_filtre_sql." GROUP BY Provider";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'country':
				$sql = "SELECT $select_type_date_filter countryID as ID, count(*) as Value,".
								" ROUND(100 * count(*) / (SELECT count(*) FROM logs_visit $join_host_if_filter".
								" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql."),2) as Pct".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE !isBot AND year=$year".($month!=0?" AND month=".$month:"").($day!=0?" AND day=".$day:"").$where_filtre_sql." GROUP BY countryID";
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'visit_durations':
				$sql = "SELECT $select_type_date_filter sum(duration) as Value, avg(duration) as Avg".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql;
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			case 'visit_volumes':
				$sql = "SELECT $select_type_date_filter sum(NbPageVisited) as Value, avg(NbPageVisited) as Avg".
						" FROM logs_visit".$join_host_if_filter.
						" WHERE !isBot".$where_date_logs_visit.$where_filtre_sql;
				break;
				//---------------------------------------------------------------------------------------------------------------------
				//---------------------------------------------------------------------------------------------------------------------
			default:
				return false;
		}
		return $sql;
	}
	
	function isBot($userAgent){
		return eregi ( "(bot)|(google)|(slurp)|(spider)|(crawler)|(archive)|(linkwalker)|(findlinks)|(biglotron)|(worm)|(twiceler)", $userAgent);
	}
	function daysinmonth($month, $year){
	   if(checkdate($month, 31, $year)) return 31;
	   if(checkdate($month, 30, $year)) return 30;
	   if(checkdate($month, 29, $year)) return 29;
	   if(checkdate($month, 28, $year)) return 28;
	   return 0; // error
	}
	function pad_month_or_day($month){
		switch($month){
			case 1:return "01";break;
			case 2:return "02";break;
			case 3:return "03";break;
			case 4:return "04";break;
			case 5:return "05";break;
			case 6:return "06";break;
			case 7:return "07";break;
			case 8:return "08";break;
			case 9:return "09";break;
			default:return $month;
		}
	}
	function isSearchEngine($fromUrl){
		return eregi ( "(query=)|(search\?)|(&q=)|(\?q=)", $fromUrl);
	}

	function getStatTypeConfig($type){
		$compute = $type;
		$occurence = 'simple';
		$main_value = 'Value';
		$is_id_reference=false;
		$is_browser_os_needed=true;
		switch($type){
			case 'search_engines':
				$is_browser_os_needed=false;
			case 'external_referrers':
			case 'unique_referrers':
			case 'hosts':
			case 'medias_top':
			case 'tool_top':
			case 'mediatypes_top':
			case 'hourly_charges':
				$occurence = 'listing';
				break;
			case 'tld':
				$compute='country';
			case 'languages':
			case 'providers':
			case 'country':
			case 'keywords':
				$occurence = 'listing';
				break;
			case 'uniquevisitors_pageviews':
				$compute='visit_volumes';
				$main_value = 'Avg';
				break;
			case 'visit_durations':
				$main_value = 'Avg';
				break;
			case 'bots':
				$occurence = 'listing';
			case 'uniquebots':
			case 'indexed_pages':
				$is_browser_os_needed=false;
				break;
		}
		return array('compute'=>$compute,'occurence'=>$occurence,'main_value'=>$main_value,'is_id_reference'=>$is_id_reference, 'is_browser_os_needed'=>$is_browser_os_needed);
	}

	function getStatTypeList(){
		return array('uniquebots','keywords','indexed_pages','external_referrers','unique_referrers','search_engines','uniquevisitors','hourly_charges','hosts',
				'medias_top','mediatypes_top','languages','providers','tld','visit_durations','visit_volumes','uniquevisitors_pageviews');
	}


	function matchStatsFilter($row){
		//return true;
		if(!$row['UserAgent'] && ($this->os || $this->browser))
			return false;
		if($this->os || $this->browser){
			include_once(dirname(__FILE__)."/../common/phpSniff.class.php");
			$client =& new phpSniff($row['UserAgent']);

			//$user_agent=$client->property('ua');
			$browser=$client->property('long_name');
			$platform=$client->property('platform');
			$maj_version=$client->property('maj_ver');
			$min_version=$client->property('min_ver');
			if($this->browser && $browser!=$this->browser)
				return false;
			if($this->browser && $this->browser_major_version && $browser==$this->browser && $this->browser_major_version!=$maj_version)
				return false;
			if($this->browser && $this->browser_minor_version && $browser==$this->browser && $this->browser_minor_version!=$min_version)
				return false;
			if($this->os && $platform!=$this->os){
				return false;
			}
		}
		return true;
	}
	
	function getStatsFilterSQL(){
		$languageID = $this->languageID;
		$os = $this->os;
		$browser = $this->browser;
		$country = $this->country;
		$sql = '';
		$sql.= ' AND `LanguageID`="'.$languageID.'"';
		$sql.= ' AND `Host`="'.$this->host.'"';
		if($this->type!='uniquebots' && $this->type!='search_engines' && $this->type!='bots'){//?????????????????????????????????????????????????????
			//if browser or os is not in enum do not filter
			$db_conn = db_connect();//?????????????????????????????????????????????????????
			$enum_sql='SHOW COLUMNS FROM stats LIKE "OS"';
			$enum=$db_conn->getRow($enum_sql);//?????????????????????????????????????????????????????
			if(strpos($enum['Type'], $os)){
				$sql.= ' AND `OS`="'.$os.'"';//?????????????????????????????????????????????????????
			}else{
				$sql.= ' AND `OS`=""';//?????????????????????????????????????????????????????
			}
			$enum_sql='SHOW COLUMNS FROM stats LIKE "Browser"';//?????????????????????????????????????????????????????
			$enum=$db_conn->getRow($enum_sql);
			if(strpos($enum['Type'], $browser)){//?????????????????????????????????????????????????????
				$sql.= ' AND `Browser`="'.$browser.$this->browser_major_version.$this->browser_minor_version.'"';
			}else{//?????????????????????????????????????????????????????
				$sql.= ' AND `Browser`=""';
			}//?????????????????????????????????????????????????????
		}
		$sql.= ' AND `CountryID`="'.$country.'"';

		return $sql;
	}
	
	function prepareStatValue($value){
		return ceil($value*100)/100;
	}
	
	function parse(){
		$this->year = $this->firstNode->valueOf("YEAR[1]");
		$this->month = $this->pad_month_or_day($this->firstNode->valueOf("MONTH[1]"));
		$this->day = $this->pad_month_or_day($this->firstNode->valueOf("DAY[1]"));
		if(!$this->day){
			$this->day=0;
		}
		if(!$this->month){
			$this->month=0;
		}
		$this->type = $this->firstNode->valueOf("TYPE[1]");
		$this->languageID = $this->firstNode->valueOf("LANGUAGEID[1]");
		$this->host = $this->firstNode->valueOf("HOST[1]");
		$this->os = $this->firstNode->valueOf("OS[1]");
		if($this->os == 'windows')
			$this->os = 'win';
		$this->browser = $this->firstNode->valueOf("BROWSER[1]");
		$this->browser_version = $this->firstNode->valueOf("BROWSER[1]/@version");
		if($this->browser_version){
			$browser_parts = explode('.',$this->browser_version);
			$this->browser_major_version = $browser_parts[0];
			$this->browser_minor_version = $browser_parts[1];
		}
		$this->country = $this->firstNode->valueOf("COUNTRY[1]");
		$withNode = $this->firstNode->getElement('WITH');
		$paginateNode = $this->operationNode->getElement('PAGINATE');
		if($withNode){
			$profileNode = $withNode;
			$this->page = $profileNode->valueOf("@page");
			$this->byPage = $profileNode->valueOf("@perPage");
		}else if($paginateNode){
			$profileNode = $paginateNode;
			$this->page = $profileNode->valueOf("@page");
			$this->byPage = $profileNode->valueOf("@display");
		}

		if($this->type===false){
			$this->setError("No type of stats was found in your query.");
			return false;
		}
			
		if($this->year===false){
			$this->setError("No year was found in your query.");
			return false;
		}
		return true;	
	}
	
	function parseConfig($config){
		$this->year=$config['year'];
		$this->month=$config['month'];
		$this->day=$config['day'];
		$this->type=$config['type'];
		$this->languageID=$config['languageID'];
		$this->host=$config['host'];
		$this->os=$config['os'];
		$this->browser=$config['browser'];
		$this->browser_version=$config['browser_version'];
		$this->browser_major_version=$config['browser_major_version'];
		$this->browser_minor_version=$config['browser_minor_version'];
		$this->country=$config['country'];
		$this->page=$config['page'];
		$this->byPage=$config['byPage'];	
		if(!$this->day){
			$this->day=0;
		}
		if(!$this->month){
			$this->month=0;
		}
	}


	function operate(){
		debug_log('OPERATE STATS : '.$this->type);
		
		$year=$this->year;
		$month=$this->month;
		$day=$this->day;
		$type=$this->type;
		$page=$this->page;
		$byPage=$this->byPage;
		$languageID=$this->languageID;
		$host=$this->host;
		$os=$this->os;
		$browser=$this->browser;
		$browser_major_version=$this->browser_major_version;
		$browser_minor_version=$this->browser_minor_version;
		$country=$this->country;

		$db_conn = db_connect();

		$attributes = $this->getOperationAttributes();
		$query_result="<RESULTS".$attributes.">\n";
		$query_result.="<STATS>\n";
		$query_result.='<YEAR>'.$year.'</YEAR>';
		if($month!=0)
			$query_result.='<MONTH>'.$month.'</MONTH>';
		if($day!=0)
			$query_result.='<DAY>'.$day.'</DAY>';
		if($languageID)
			$query_result.='<LANGUAGEID>'.$languageID.'</LANGUAGEID>';
		if($os)
			$query_result.='<OS>'.$os.'</OS>';
		if($browser)
			$query_result.='<BROWSER>'.$browser.'</BROWSER>';
		if($country)
			$query_result.='<COUNTRY>'.$country.'</COUNTRY>';
		if($host)
			$query_result.='<HOST>'.$host.'</HOST>';
		$query_result.='<DOMAIN>web</DOMAIN>';
		$query_result.="<TYPE>".$type."</TYPE>\n";

		$config = array('year'=>$year,'month'=>$month,'day'=>$day,'type'=>$type,'page'=>$page,'byPage'=>$byPage,'languageID'=>$languageID,'host'=>$host,'os'=>$os,'browser'=>$browser,'browser_major_version'=>$browser_major_version,'browser_minor_version'=>$browser_minor_version,'country'=>$country);
		$IDs=array();
		if($statConfig['occurence']=='listing' && $day!=0){
			$summary_xml = $this->getStatsSummaryXML($IDs);
		}else{
			$summary_xml = $this->getStatsSummaryXML();
		}

		$statsConfig = $this->getStatTypeConfig($this->type);
		if($day!=0){
			$now_time = mktime(0,0,0,$month,$day,$year);
			
			$oneweekago=$now_time-7*24*3600;
			$twoweeksago=$now_time-14*24*3600;
			$config_oneweekago = $config;
			$config_oneweekago['year']=date('Y',$oneweekago);
			$config_oneweekago['month']=date('m',$oneweekago);
			$config_oneweekago['day']=date('d',$oneweekago);
			$stat_oneweekago = new SearchStats($config_oneweekago);
			if($statConfig['occurence']=='listing'){
				$summary_xml.= $stat_oneweekago->getStatsSummaryXML($IDs);
			}else{
				$summary_xml.= $stat_oneweekago->getStatsSummaryXML();
			}
			$config_twoweeksago = $config;
			$config_twoweeksago['year']=date('Y',$twoweeksago);
			$config_twoweeksago['month']=date('m',$twoweeksago);
			$config_twoweeksago['day']=date('d',$twoweeksago);
			$stat_twoweeksago = new SearchStats($config_twoweeksago);
			if($statConfig['occurence']=='listing'){
				$summary_xml.= $stat_twoweeksago->getStatsSummaryXML($IDs);
			}else{
				$summary_xml.= $stat_twoweeksago->getStatsSummaryXML();
			}
		}else if($month!=0 && $statsConfig['occurence']!='listing'){
			$nb_day = $this->daysinmonth($month,$year);
			for($i=1;$i<=$nb_day;$i++){
				$stat_perday = $this->duplicate();
				$stat_perday->setDay($i);
				$summary_xml.= $stat_perday->getStatsSummaryXML();
			}
		}else if($year && $statsConfig['occurence']!='listing'){
			for($i=1;$i<=12;$i++){
				$stat_permonth = $this->duplicate();
				$stat_permonth->setMonth($i);
				$res=$stat_permonth->getSelectStat();
				if($res===false){
					$this->setError('no data found');
					return false;
				}
				$summary_xml.= $stat_permonth->getStatsSummaryXML();
			}
		}
		$snap_xml = "<STATS_DATAS>\n";
		$snap_xml.=$summary_xml;
		$snap_xml.= "</STATS_DATAS>\n";
		$query_result.=$snap_xml;
		$query_result.="</STATS>\n";
		$query_result.="</RESULTS>\n";
		$this->xml = $query_result;
		return true;
	}
	
	function getStatsSummaryXML(&$IDs=false){
		$day = $this->day;
		$month = $this->month;
		$year = $this->year;

		$type = $this->type;
		$statConfig = $this->getStatTypeConfig($type);
		$origStatType = $type;
		$type = $statConfig['compute'];
		$languageID = $this->languageID;
		$host = $this->host;
		$os = $this->os;
		$browser = $this->browser;
		$country = $this->country;
		$page = $this->page;
		$byPage = $this->byPage;
		if($day){
			$complete_date=$year.'-'.$month.'-'.$day;
		}else if($month){
			$complete_date=$year.'-'.$month;
		}else{
			$complete_date=$year;
		}

		$sql=$this->getSelectStat();
		if($sql===false){
			$this->setError('no data found');
			return false;
		}
		$order_string =  ' ORDER BY `Year` ASC,`Month` ASC,`Day` ASC,';
		if($type=='hourly_charges'){
			$order_string .=  'ID ASC,';
		}
		$order_string .= '`Value` DESC';
		$db_conn = db_connect();
		if($page){
			if(!$byPage)
				$byPage = 10;
			if ($page==1){
				$limit_string=' LIMIT '.$byPage;
			}else{
				$startIndex =($page-1)*$byPage;
				$limit_string=' LIMIT '.$startIndex.','.$byPage;
			}
			$count_row = $db_conn->GetRow('SELECT COUNT(*) AS total FROM ('.$sql.') AS stats;');
			$count = $count_row['total'];
			if (is_numeric($page) && ($page*$byPage)>=$count )
				$isLastPage = "true";
			else
				$isLastPage = "false";
			$totalPages = ceil($count/$byPage);
			//$sql.=$limit_string;
		}
		
		$list_must_match = is_array($IDs) && !empty($IDs);
		if($list_must_match){
			$sql.=' AND ID IN("'.implode('","',$IDs).'")';
			//replacing the ordering, beacuse we do not want the items to be ordered by value, but in the same order as the initial day
			$order_string =  ' ORDER BY `Year` ASC,`Month` ASC,`Day` ASC';
			$order_string.=',FIELD(ID,"'.implode('","',$IDs).'")';
		}
		
		$stats_rs = $db_conn->Execute($sql.$order_string.$limit_string);
		debug_log($sql.$order_string.$limit_string);
		echo $db_conn->ErrorMsg();
		if($page){
			$attributes.=' page="'.$page.'" ';
			$attributes.=' isLastPage="'.$isLastPage.'" ';
			$attributes.=' totalPages="'.$totalPages.'" ';
			$attributes.=' totalCount="'.$count.'" ';
		}
		$summary_xml='<SUMMARY date="'.$complete_date.'"'.$attributes.">\n";
		if($list_must_match){ // its a top, we want to compare to another date and thus we must insert empy items (with value=0) if the entry has made zero hits
			$summary_rows_xml = array();
			while($row = $stats_rs->FetchRow()){
				$summary_rows_xml[$row['ID']]=$this->getStatsRowXML($row);
			}
			$empty_row = array();
			$empty_row['Value']=0;
			$empty_row['Pct']=0;
			$empty_row['Avg']=0;
			//$empty_row['isEmptyRow']=true;
			foreach($IDs as $origID => $statID){
				if(isset($summary_rows_xml[$origID])){
					$summary_xml.=$summary_rows_xml[$origID];
				}else{
					$empty_row['ID']=$origID;
					$summary_xml.=$this->getStatsRowXML($empty_row);
				}
			}
		}else{
			if($stats_rs->recordCount()>0){
				while($row = $stats_rs->FetchRow()){
					$summary_xml.=$this->getStatsRowXML($row);
					//save IDs for sorting later and value of refereces for name the empty rows
					if(is_array($IDs)){
						$IDs[$row['ID']]=$row['ID'];
					}
				}
			}else{
				$empty_row = array();
				$empty_row['Value']=0;
				$empty_row['Pct']=0;
				$empty_row['Avg']=0;
				$summary_xml.=$this->getStatsRowXML($empty_row);
			}
		}
		$summary_xml.="</SUMMARY>\n";
		return $summary_xml;
	}
	
	function getStatsRowXML($row){
		if($row===false){
			$row['Value']=0;
			$row['Pct']=0;
			$row['Avg']=0;
		}
		$key = $row['ID'];
		$hit = $row['Value'];
		$pct = $row['Pct'];
		$avg = $row['Avg'];
		$label_avg = 'AVG';
		$statConfig = $this->getStatTypeConfig($this->type);
		if($statConfig['main_value']=='Avg'){
			$avg = 0;
			$hit = $row['Avg'];
		}
		$type = $statConfig['compute'];

		if($type=='hourly_charges'){
			$key=sprintf("%02d", $row['ID']);
		}
		$detail_xml='<DATA'.(($key!='')?' ID="'.encode_to_xml($key).'"':'').'><VALUE>'.$this->prepareStatValue($hit).'</VALUE>'."<$label_avg>".$this->prepareStatValue($avg)."</$label_avg>".'<PCT>'.$this->prepareStatValue($pct).'</PCT>';
		if($this->type=='medias_top' && is_numeric($key)){
			$mediaModuleInfo = moduleInfo('media');
			$mediaInfo = getInfo($mediaModuleInfo,$key);
			if($mediaInfo){
				$element_infos[$key]['Denomination']= $mediaInfo['Denomination'];
				$desc_rs = getDescriptions($mediaModuleInfo->ID,$mediaInfo['ID'],'','label');
				while($desc = $desc_rs->FetchRow()){
					$element_infos[$key]['Descriptions'][$desc['LanguageID']]=$desc['Title'];
				}
			}else{
				$element_infos[$key]['Denomination']= $key;
			}
			$element_infos_xml[$key].='<DENOMINATION>'.encode_to_xml($element_infos[$key]['Denomination']).'</DENOMINATION>';
			if($element_infos[$key]['Descriptions']){
				foreach($element_infos[$key]['Descriptions'] as $lgID=>$desc_title)
					$element_infos_xml[$key].='<TITLE languageID="'.$lgID.'">'.$desc_title.'</TITLE>';
			}
			if(isset($element_infos[$key])){
				$detail_xml.=$element_infos_xml[$key];
			}
		}
		$detail_xml.="</DATA>\n";
		return $detail_xml;
	}
}
?>