<?


/*
 本软件版权归作者所有,在投入使用之前注意获取许可
 原作者: 看海
 修改者：程威（wiwiboy）
 郑州大学西亚斯国际学院网络信息技术专业
 电话：13553166317
 邮箱：wiwiboy@126.com
 QQ号：158839753
 网址：http://www.phpstat.net
*/	

	include_once "./websiteid.php";
	$website   = strtolower(strval($_GET[website]));
	$websiteid = intval($WebSiteId[$website]);
	if( file_exists( "./exclusion/website_".$websiteid.".php" ) )
	include_once "./exclusion/website_".$websiteid.".php";
	
	class _Stat
	{		
		var $TmpDir = TMPDIR;
		var $UserDataDir;
		var $UserData;
		var $UserTodayDir;
		var $Time;
		var $Year;
		var $Month;
		var $Day;
		var $Week;
		var $Hour;
		var $website;
		var $NewDay = false;
		var $NewViewer = true;
		var $ViewerInfo = array();

		var $DayStartTime;
		var $DayStartTimeSave;
		function _Stat( )
		{	
			
			if( file_exists( COUNT_DIRNAME."/count/get_".$_GET[website]."_record.phpstat" ) )
				sleep(30);
			$time1 = microtime();
			global $TableList,$exclusionip,$exclusioninter,$mainsitecode,$siteurl,$websiteid;
			$this->website        = strval($_GET[website]);
			$this->websiteid      = intval($websiteid);
			$this->TableList      = $TableList;
			$this->exclusionip    = $exclusionip;
			$this->exclusioninter = $exclusioninter;
			$this->siteurl		  = $siteurl;
			$this->mainsitecode   = DB_PREFIX.$mainsitecode;
			$this->Time			  = time();
			$this->Year			  = date( 'Y', $this->Time );
			$this->Month		  = date( 'm', $this->Time );
			$this->Day			  = date( 'j', $this->Time );
			$this->Week			  = date( 'w', $this->Time );
			$this->Hour			  = date('G', $this->Time );
			$this->DayStartTime	  = mktime(0, 0, 0, $this->Month, $this->Day, $this->Year);
			$this->DayStartTimeSave = $this->DayStartTime - 24*60*60*SAVE_OLD_DAYS;
			$this->GetUserData();
			$this->GetUserIpAdd();
			$this->GetUserDir();			
			$this->CheckNewViewer();
			$this->GetViewerInfo();
			$this->CheckNewDay();
			
			
			//处理alexa数据
			$this->AddAlexa();

			//$this->SaveArr();
			$this->SaveViewerInfo();
			$this->ShowArr = Array ( 	'DayCount'=>array('day_count','今日访问'), 
														'DayIpCount'=>array('day_count_ip','今日IP'), 
														'HourCount'=>array('hour'.$this->Hour,'本小时访问'), 
														'HourIpCount'=>array('hourip'.$this->Hour,'本小时IP'), 
														'AllCount'=>array('all_count','总访问量'), 
														'AllIpCount'=>array('all_count_ip','总IP访问量')  
													);


			$Res = @$this->_query( " select d.* ,s.all_count,s.all_count_ip from " . $this->TableList[day_data] . " d left join " . $this->TableList[site] . " s on d.website = s.website where d.times = {$this->DayStartTime} and d.website = '$this->website'" );
			$DayData = mysql_fetch_array($Res);
			$DayData[all_count]	   = $DayData[all_count] + $DayData[day_count];
			$DayData[all_count_ip] = $DayData[all_count_ip] + $DayData[day_count_ip];
			if( count( $DayData ) < 1 )
			{
				$this->IniToday();
			}

			$UpdateStr = "day_count = day_count + 1, hour{$this->Hour} = hour{$this->Hour} + 1";
			if( $this->NewViewer )
			{
				 $UpdateStr .= ", hourip{$this->Hour} = hourip{$this->Hour} + 1, day_count_ip = day_count_ip + 1 " ;
			}
			$Sql = " update " . $this->TableList[day_data] . " set $UpdateStr where times = {$this->DayStartTime} and website = '$this->website'";
			@$this->_query( $Sql );
			$this->OutLog( $DayData );
			$time2 = microtime();
			//echo '<B>'.sprintf("%01.5f",($time2-$time1)).'</B>';
		}

		function OutLog( $DayData )
		{
			global $PHPStatShowText,$PHPStatTitle,$PHPStatIsShowIco;
			
			$_GET[show] = @array_flip ( $_GET[show] );
			//print_r($_GET[show]);
			foreach( $this->ShowArr as $Key=>$Val )
			{	
				if( isset( $_GET[show][$Key] ) )
				{
					$ShowStr .= '&nbsp;|&nbsp;' . $this->Charset( $Val[1] ) . ':' . $DayData["$Val[0]"] . '';
				}	
				
			}
			if( isset( $_GET[show][GooglePR] ) )
			{
				$pagerank = (int)read_from_file( "pagerank/website_".$this->websiteid.".pr" );
				$ShowStr .= '&nbsp;|&nbsp;<IMG SRC='.$this->ViewerInfo['counturl'].'/seo/images/pagerank'.$pagerank.'.gif style=\"border:0px;\"  align=\"absmiddle\" title=\"PR值:'.$pagerank.'\">';
			}	

			$Title = $this->TitleCharset( $PHPStatTitle );
			if($this->ViewerInfo['image'] != "")
			{
				$ToShow = "<img src=\"" . $this->ViewerInfo['counturl'] . "/templates/".TPL_NAME."/imagefiles/icos/".$this->ViewerInfo['image']."\" style=\"border:0px;\"  align=\"absmiddle\">";
			}
			else if($this->ViewerInfo['text'] != "")
			{	
				if(@!in_array($this->ViewerInfo['text'],array('num1','num2')))
					$this->ViewerInfo['text'] = "num1";
				$ToShow = $PHPStatShowText[$this->ViewerInfo['text']] ;
			}
			else
			{
				$ToShow = "<img src=\"" . $this->ViewerInfo['counturl'] . "/templates/".TPL_NAME."/imagefiles/icos/countlogo1.gif\" style=\"border:0px;\"  align=\"absmiddle\">";
			}
			
			if( $this->ViewerInfo[type] == 2 and $PHPStatIsShowIco == 1)
			{	
				//去掉显示图标(logo)
				echo "document.getElementById(\"PCSCount\").innerHTML='<a href=".$this->ViewerInfo['counturl']."/index.php?website=".$this->website." target=\"_blank\" title=\"" . $Title . "\">".$ToShow."</a>';";
			}
			elseif( $PHPStatIsShowIco == 1)
			{	
				//去掉显示图标(logo)
				echo "document.write('<a href=".$this->ViewerInfo['counturl']."/index.php?website=".$this->website." target=\"_blank\" title=\"" . $Title . "\">".$ToShow."</a>');";
				if( trim( $ShowStr ) != '' )
				{
					//去掉显示图标(logo)
					echo "document.write('$ShowStr')";
				}
			}
		}

		function Charset( $Str )
		{	
			if(function_exists(iconv))
			{
				return @iconv($this->ViewerInfo[charset], DB_CHARSET, $Str);
			}
			else
			{
				return $Str;
			}
		}
		
		function TitleCharset( $Str )
		{	
			if(function_exists(iconv))
			{
				return @iconv(DB_CHARSET, $this->ViewerInfo[charset], $Str);
			}	
			else
			{
				return $Str;
			}
		}

		function KeyWordCharset( $Str )
		{	
			if( preg_match( "/%u.{4}|&#x.{4};|&#d+;/" ,$Str ) )
			{
				preg_match_all("/%u.{4}|&#x.{4};|&#d+;|.+/U",$Str,$r); 
				$ar = $r[0]; 
				foreach($ar as $k=>$v) 
					{ 
					 if(substr($v,0,2) == "%u") 
							  $ar[$k] = @iconv("UCS-2",DB_CHARSET,pack("H4",substr($v,-4))); 
					 elseif(substr($v,0,3) == "&#x") 
							  $ar[$k] = @iconv("UCS-2",DB_CHARSET,pack("H4",substr($v,3,-1))); 
					 elseif(substr($v,0,2) == "&#")  
							  $ar[$k] = @iconv("UCS-2",DB_CHARSET,pack("n",substr($v,2,-1))); 
					 } 
				return join("",$ar); 
           } 
		   else
		   {	
				if(function_exists(iconv))
				{
					return @iconv('utf-8', DB_CHARSET, $Str);
				}
				else
				{
					return utf82gb2312( $Str );
				}
		  }			
		}

		function GetUserDir()
		{
			$this->UserDataDir = $this->TmpDir;
			if( ! is_dir( $this->UserDataDir ) )
			{
				if( ! mkdir( $this->UserDataDir ) )
				{
					Error( '创建用户目录出错 <A HREF="http://www.phpstat.net/errorcode.php#001" target=_blank>001</A>');
				}
			}
		}
		
		function GetUserIpAdd()
		{
			$this->ViewerInfo[REMOTE_ADDR] = getIp();		
			//$this->ViewerInfo[REMOTE_ADDR] ="6".rand(0,0).".".rand(0,2).rand(0,3).".".rand(0,2).rand(0,3).".".rand(0,3).rand(0,1).rand(0,0);
			
			$this->ipnum = $this->ip2num( $this->ViewerInfo[REMOTE_ADDR] );
			for( $i=0;$i<count($this->exclusionip);$i++)
			{
				if( $this->ipnum >= $this->exclusionip[$i][startip] and $this->ipnum <= $this->exclusionip[$i][endip])
				{
					exit;
				}
			}			
			
			if( count($this->exclusioninter) > 0)
			{
				$isexit = true;
				for( $i=0;$i<count($this->exclusioninter);$i++)
				{	
					if( ereg( $this->exclusioninter[$i], $_GET[pageurl] )) 
					{
						$isexit = false;break;
					}
				}
			}
			if( $isexit )
			{
				exit;
			}
		}		
		

		function GetUserData()
		{			
			if ( !file_exists( "./exclusion/website_".$this->websiteid.".php" ) )
			{				
				Error( '缺少站点配置文件，一般重新编辑该站点 \''.$_GET[website].'\' 即可, Error code :<A HREF="http://www.phpstat.net/errorcode.php#002" target=_blank>002</A>' );
			}
		}
		

		function CheckNewDay()
		{
			$this->UserTodayDir = $this->UserDataDir . '/' . $this->website .'_'.date("Ymd",$this->DayStartTime). ".phpstat" ;
			if( ! file_exists( $this->UserTodayDir ) )
			{	
				$this->NewDay = true;	
				if( !is_writable( './'.$this->UserDataDir ) )
				{
					Error( '无法写入站点文件 '.$_GET[website].'.phpstat ,count/count目录不可写,属性设置为0777, Error code :<A HREF="http://www.phpstat.net/errorcode.php#005" target=_blank>005</A>' );
				}
				$fp = fopen( $this->UserTodayDir ,"w+" );
				fclose( $fp );
				$this->ClearYesterday();
				$Res = @$this->_query( "SELECT COUNT(datadayid) as counts FROM " . $this->TableList[day_data] . " WHERE times = '$this->DayStartTime' and website = '$this->website'" );		
				$ResNum = mysql_fetch_array( $Res );
				if( $ResNum[counts] < 1)				
				{
					$this->IniToday();
				}
			}
		}

		function CheckNewViewer()
		{	
			$Sql = "SELECT count(*) as count FROM " . $this->mainsitecode.'_ip_limit' . " where ip = '{$this->ViewerInfo[REMOTE_ADDR]}' and time > $this->DayStartTime and website = '$this->website'";
			$Res = @$this->_query( $Sql );
			$Count = mysql_fetch_array($Res);
			$Count = intval( $Count[count] );
			if( $Count > 0 )
			{
				$this->NewViewer = false;
			}
		}
  
		function ClearYesterday()
		{
			//echo '清除和整理指定天数的数据';
			$YesterdayStartTime = mktime (0, 0, 0, $this->Month, $this->Day-1, $this->Year);

			$YesterdayYear = date( 'Y', $YesterdayStartTime );
			$YesterdayMonth = date( 'm', $YesterdayStartTime );
			$YesterdayDay = date( 'j', $YesterdayStartTime );
			$YesterdayWeek = date( 'w', $YesterdayStartTime );
			$YesterdayHour = date('G', $YesterdayStartTime );

			$Res = @$this->_query( " select * from " . $this->TableList[day_data] . " where times = $YesterdayStartTime and website = '$this->website'" );
			$YesterdayData = mysql_fetch_array($Res);

			$YesterdayData[day_count] = intval( $YesterdayData[day_count] );
			$YesterdayData[day_count_ip] = intval( $YesterdayData[day_count_ip] );

			//Update Count Table
			$Sql = "update " . $this->TableList[site] . " set week{$YesterdayWeek} = week{$YesterdayWeek} + $YesterdayData[day_count], weekip{$YesterdayWeek} = weekip{$YesterdayWeek} + $YesterdayData[day_count_ip], 			day{$YesterdayDay} = day{$YesterdayDay} + $YesterdayData[day_count], dayip{$YesterdayDay} = dayip{$YesterdayDay} + $YesterdayData[day_count_ip], all_count = all_count  + $YesterdayData[day_count], all_count_ip = all_count_ip + $YesterdayData[day_count_ip] where website = '$this->website'";
			@$this->_query( $Sql );

			//Update Month Table
			$YesterdayMonthTime = mktime (0,0,0,$YesterdayMonth, 1, $YesterdayYear );
			$Res = @$this->_query( " select count(datamonthid) as count from " . $this->TableList[month_data] . " where times = $YesterdayMonthTime and website = '$this->website'" );
			$Row = mysql_fetch_array($Res);
			
			if( $Row[count] == 0 )
			{	
				$Sql = " insert into " . $this->TableList[month_data] . " 
				( website, times, year, month, month_count, month_count_ip ) 
				values 
				( '$this->website', $YesterdayMonthTime, $YesterdayYear, $YesterdayMonth, $YesterdayData[day_count], $YesterdayData[day_count_ip] )
				";
				@$this->_query( $Sql );
			}
			else
			{
				$Sql = " update " . $this->TableList[month_data] . " set month_count = month_count + $YesterdayData[day_count], month_count_ip = month_count_ip + $YesterdayData[day_count_ip] where times = $YesterdayMonthTime and website = '$this->website'";
				@$this->_query( $Sql );
			}

			//Update Year Table
			$YesterdayYearTime = mktime ( 0, 0, 0, 1, 1, $YesterdayYear );
			$Res = @$this->_query( " select count(datayearid) as count from " . $this->TableList[year_data] . " where times = $YesterdayYearTime and website = '$this->website'" );
			$Row = mysql_fetch_array($Res);
			
			if( $Row[count] == 0 )
			{	
				$Sql = " insert into " . $this->TableList[year_data] . " 
				(website, times, year, year_count, year_count_ip ) 
				values 
				( '$this->website', $YesterdayYearTime, $YesterdayYear, $YesterdayData[day_count], $YesterdayData[day_count_ip] )
				";
				@$this->_query( $Sql );
			}
			else
			{
				$Sql = " update " . $this->TableList[year_data] . " set year_count = year_count + $YesterdayData[day_count], year_count_ip = year_count_ip + $YesterdayData[day_count_ip] where times = $YesterdayYearTime and website = '$this->website'";

				@$this->_query( $Sql );
			}		
							
			//删除昨日产生的临时文件
			@unlink( $this->UserDataDir . '/' . $this->website .'_'.date("Ymd",$YesterdayStartTime) .".phpstat" );

			
		}

		function IniToday()
		{
			$Res = mysql_query( "SELECT COUNT(datadayid) as counts FROM " . $this->TableList[day_data] . " WHERE times = '$this->DayStartTime' and website = '$this->website'" );		
			$ResNum = mysql_fetch_array( $Res );
			if( $ResNum[counts] <= "0")
			{
				$Sql = "INSERT INTO " . $this->TableList[day_data] . " (
													`website`, `times`, `year`, `month`, `day`, `week`
													) VALUES ('{$this->website}',
													'{$this->DayStartTime}', '{$this->Year}', '{$this->Month}', '{$this->Day}', '{$this->Week}'
													);";
				@$this->_query( $Sql );
			}			
		}

		function GetFLTime( $Val )
		{
			$Val = explode( '-', $Val );
			return mktime ( $Val[3], $Val[4], $Val[5], $Val[1], $Val[2], $Val[0] );
		}

		function GetViewerInfo()
		{
			global $PHPStatIsCOUNTPAGETITLE;
			$this->ViewerInfo[TIME]				= &$this->Time;

			$this->ViewerInfo[page]				= addslashes( $_GET[pageurl] );
			if(eregi("script", $_GET[pageurl]) or eregi("iframe", $_GET[pageurl]))
			{exit;}			
			$this->ViewerInfo[charset]			= $_GET["charset"] == "" ? $_SERVER[HTTP_ACCEPT_CHARSET]:$_GET["charset"];
		
			if( $PHPStatIsCOUNTPAGETITLE )
				$this->ViewerInfo[pagetitle]	= addslashes( $this->Charset($_GET[pagetitle]) );
			else
				$this->ViewerInfo[pagetitle]	= '';
			$this->ViewerInfo[REFERER]			= addslashes( $_GET[referer] );
			//'http://www.google.com/google?q=stat_ip_data1&tn=myie2dg';
			$this->ViewerInfo[language]			= strtolower( $_GET[language] );
			$this->ViewerInfo[color]			= intval( $_GET[color] );
			$this->ViewerInfo[screen]			= $_GET[screensize];
			$this->ViewerInfo[java]				= intval( $_GET[java] );
			$this->ViewerInfo[flash]			= intval( $_GET[flash] );
			$this->ViewerInfo[HTTP_USER_AGENT]	= addslashes( $_SERVER["HTTP_USER_AGENT"] );			
			
			$this->ViewerInfo[timezone]			= $_GET["timezone"];
			$this->ViewerInfo[firsttime]		= $this->GetFLTime( $_GET["firsttime"] );
			$this->ViewerInfo[lasttime]			= $this->GetFLTime( $_GET["lasttime"] );
			$this->ViewerInfo[returnday]		=  floor(($this->ViewerInfo[lasttime]-$this->ViewerInfo[firsttime])/86400);
			
			$this->ViewerInfo['return']			= intval( $_GET['return1'] );
			if( $this->ViewerInfo[returnday] > 0 and $this->ViewerInfo['return'] == 0)
				$this->ViewerInfo['return'] = 1;
			$this->ViewerInfo['counturl']		= addslashes( $_GET['counturl'] );
			$this->ViewerInfo['image']			= addslashes( $_GET[image] );
			$this->ViewerInfo['text']			= addslashes( $_GET[text] );
			$this->ViewerInfo[type]				= intval( $_GET["type"] );
			

			//来自站点
			preg_match( "|(http://[^/]+?)/.*|isU", $this->ViewerInfo[REFERER], $Tmp );
			$this->ViewerInfo[referer]			= trim( $Tmp[1] );	

			//受访站点
			unset( $Tmp );			
			preg_match( "|(http://[^/]+?)/.*|isU", $this->ViewerInfo[page], $Tmp );
			if( trim( $Tmp[1] ) == $this->siteurl )
			{
				preg_match( "|http://[^/]+?(/.*)|is", $this->ViewerInfo[page], $Tmp1 );
				$this->ViewerInfo[page] = trim( $Tmp1[1] );
			}
			
			if( substr( $this->ViewerInfo[REFERER],0,7 ) == 'http://' )
				$this->ViewerInfo[REFERER] = substr( $this->ViewerInfo[REFERER],7 );

			if( substr( $this->ViewerInfo[referer],0,7 ) == 'http://' )
				$this->ViewerInfo[referer] = substr( $this->ViewerInfo[referer],7 );


			//查找关键字
			$this->GetKeyWord();
			

			//查找来源地区
			$IpInfo = $this->GetIpAdd( );
			//$this->ViewerInfo[area] = $IpInfo[country];
			$this->ViewerInfo['country']  = $IpInfo[country];
			$this->ViewerInfo['area']     = $IpInfo[address];
			$this->ViewerInfo['province'] = $IpInfo[province];
			$this->ViewerInfo['city']	  = $IpInfo[city];

			//查找是否有alexa工具条
			if( strpos( $this->ViewerInfo[HTTP_USER_AGENT], 'Alexa') )
			{
				$this->ViewerInfo[alexatool] = 1;
			}
			else
			{
				$this->ViewerInfo[alexatool] = 0;
			}

			//获取浏览器信息
			$this->GetBrowser();
			$this->GetSystem();
		}

		function SaveViewerInfo()
		{
			if($this->NewViewer == true)
			{	
			$Sql = "INSERT DELAYED INTO  " . $this->mainsitecode.'_ip_limit' . " ( 
								`ip`, `time`, `pageurl`, `pagetitle`, `pagefrom`, `language`, `color`, `screensize`, `pagefromsite`,  `country`, `address`, `province`, `city`,`alexatool`, `timezone`, `firsttime`, `lasttime`, `browser`, `bot`,`java`,`flash`,`system`, `returner`, `returnday`, `pagecount`, `timeslong`,`website`
								) VALUES ( 
								'{$this->ViewerInfo[REMOTE_ADDR]}', '{$this->ViewerInfo[TIME]}', 
								'{$this->ViewerInfo[page]}',
								'{$this->ViewerInfo[pagetitle]}',
								'{$this->ViewerInfo[REFERER]}', '{$this->ViewerInfo[language]}', 
								'{$this->ViewerInfo[color]}', 
								'{$this->ViewerInfo[screen]}', '{$this->ViewerInfo[referer]}', '{$this->ViewerInfo[country]}', 
								'{$this->ViewerInfo[area]}',
								'{$this->ViewerInfo[province]}',
								'{$this->ViewerInfo[city]}',
								'{$this->ViewerInfo[alexatool]}', '{$this->ViewerInfo[timezone]}', '{$this->ViewerInfo[firsttime]}', '{$this->ViewerInfo[lasttime]}', '{$this->ViewerInfo[browser]}',
								'0',
								'{$this->ViewerInfo[java]}',
								'{$this->ViewerInfo[flash]}',
								'{$this->ViewerInfo[system]}', '".$this->ViewerInfo['return']."',
								'{$this->ViewerInfo[returnday]}',
								'1',
								'1',
								'{$this->website}');";
			@$this->_query( $Sql );				
			}
			if($this->NewViewer == true) 
				$todayfirst = '1';
			else
				$todayfirst = '0';
			$Sql = "INSERT DELAYED INTO " . $this->mainsitecode.'_ip_hits' . " ( 
								`ip`, `time`, `pageurl`, `pagetitle`, `pagefrom`, `pagefromsite`, `keyword`, `todayfirst`, `website`
								) VALUES ( 
								'{$this->ViewerInfo[REMOTE_ADDR]}', '{$this->ViewerInfo[TIME]}', 
								'{$this->ViewerInfo[page]}',
								'{$this->ViewerInfo[pagetitle]}',
								'{$this->ViewerInfo[REFERER]}',  '{$this->ViewerInfo[referer]}',
								'{$this->ViewerInfo[keyword]}',
								$todayfirst,
								'{$this->website}');";
			@$this->_query( $Sql );
		
		}
		

		//查找关键字
		function GetKeyWord()
		{

			$DomainName = &$this->ViewerInfo[referer];
			$RefererUrl = &$this->ViewerInfo[REFERER];
			if( strstr( $DomainName, 'baidu.com') )
			{
				preg_match( "|baidu.+wo?r?d=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
				$this->ViewerInfo[referer] = 'www.baidu.com';
			}
			else if( strstr( $DomainName, 'google.com') or strstr( $DomainName, 'google.cn') )
			{
				preg_match( "|google.+q=([^\&]*)|is", $RefererUrl, $Tmp );
				if( strstr( $RefererUrl, 'gb2312' ) or strstr( $RefererUrl, 'GB2312' ) )
				{
					$KeyWord = urldecode( $Tmp[1] );
				}
				else 
				{
					$KeyWord = $this->KeyWordCharset( urldecode( $Tmp[1] ) );
				}
				$this->ViewerInfo[referer] = 'www.google.com';
			}
			else if( strstr( $DomainName, 'sohu.com') )
			{
				preg_match( "|sohu.+query=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, 'sina.com.cn') )
			{
				preg_match( "|sina.+searchkey=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, '163.com') )
			{
				preg_match( "|163.+q=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, 'yahoo.com') )
			{				
				preg_match( "|yahoo.+p=([^\&]*)|is", $RefererUrl, $Tmp );
				if( strstr( $RefererUrl, 'gb2312' ) or strstr( $RefererUrl, 'gbk' )  or strstr( $RefererUrl, 'zh-cn' ))
				{
					$KeyWord = urldecode( $Tmp[1] );
				}
				else 
				{
					$KeyWord = $this->KeyWordCharset( urldecode( $Tmp[1] ) );
				}
				$this->ViewerInfo[referer] = 'www.yahoo.com';
			}
			else if( strstr( $DomainName, 'lycos.com') )
			{
				preg_match( "|lycos.+query=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, '3721.com') )
			{
				preg_match( "|3721.+p=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, 'qq.com') )
			{
				preg_match( "|qq.+word=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, 'soso.com') )
			{
				preg_match( "|soso.+w=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, 'tom.com') )
			{
				preg_match( "|tom.+word=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, '21cn.com') )
			{
				preg_match( "|21cn.+word=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, 'sogou.com') )
			{
				preg_match( "|sogou.+query=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, '114.vnet.cn') )
			{
				preg_match( "|114.+kw=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			else if( strstr( $DomainName, 'live.com') )
			{
				preg_match( "|live.+q=([^\&]*)|is", $RefererUrl, $Tmp );
				if( strstr( $RefererUrl, 'gb2312' ) or strstr( $RefererUrl, 'gbk' )  or strstr( $RefererUrl, 'zh-cn' ))
				{
					$KeyWord = urldecode( $Tmp[1] );
				}
				else 
				{
					$KeyWord = $this->KeyWordCharset( urldecode( $Tmp[1] ) );
				}
				$this->ViewerInfo[referer] = 'www.live.com';
			}
			else if( strstr( $DomainName, 'msn.com') )
			{
				preg_match( "|msn.+q=([^\&]*)|is", $RefererUrl, $Tmp );
				if( strstr( $RefererUrl, 'gb2312' ) or strstr( $RefererUrl, 'gbk' )  or strstr( $RefererUrl, 'zh-cn' ))
				{
					$KeyWord = urldecode( $Tmp[1] );
				}
				else 
				{
					$KeyWord = $this->KeyWordCharset( urldecode( $Tmp[1] ) );
				}
				$this->ViewerInfo[referer] = 'www.msn.com.cn';
			}
			else if( strstr( $DomainName, 'aol.com') )
			{
				preg_match( "|aol.+query=([^\&]*)|is", $RefererUrl, $Tmp );
				$KeyWord = urldecode( $Tmp[1] );
			}
			$this->ViewerInfo[keyword] = $KeyWord;
		}

		//获取浏览器信息
		function GetBrowser()
		{
			if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(myie[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Netscape[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Opera[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(NetCaptor[^;^^()]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(TencentTraveler)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Firefox[0-9/\.^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(MSN[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Lynx[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Konqueror[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(WebTV[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(msie[^;^)^(]*)|i" ) );
			else if( $Browser = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Maxthon[^;^)^(]*)|i" ) );
			else 
			{
				$Browser = '其它';
			}
			//echo $Browser.'<br>';
			$this->ViewerInfo[browser] = trim( $Browser );
		}

		//获取操作系统版本
		function GetSystem()
		{
			if( $System = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Windows NT[\ 0-9\.]*)|i" ) );
			else if( $System = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Windows[\ 0-9\.]*)|i" ) );
			else if( $System = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Mac[^;^)]*)|i" ) );
			else if( $System = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(unix)|i" ) );
			else if( $System = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(Linux[\ 0-9\.]*)|i" ) );
			else if( $System = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(SunOS[\ 0-9\.]*)|i" ) );
			else if( $System = $this->matchbrowser( $this->ViewerInfo[HTTP_USER_AGENT], "|(BSD[\ 0-9\.]*)|i" ) );
			else 
			{
				$System = '其它';
			}
			$this->ViewerInfo[system] = trim( $System );
		}
		
		function matchbrowser( $Agent, $Patten )
		{
			if( preg_match( $Patten, $Agent, $Tmp ) )
			{
				return $Tmp[1];
			}
			else
			{
				return false;
			}
		}

		function ip2num( $Ip )
		{
			$IpData = explode( '.', $Ip );
			if( count( $IpData ) != 4 )
			{
				return 0;
			}
			$IpNum = 0;	
			foreach( $IpData as $Key => $Val )
			{
				$IpNum += intval( $Val ) * pow ( 256, 3-$Key );
			}
			return $IpNum;
		}

		//获取ip地址来源
		function GetIpAdd( )
		{
			$IpNum = $this->ViewerInfo[REMOTE_ADDR];	
			if($this->NewViewer == true)
			{	
				$IpInfo = convertip($IpNum,'../tools');
			}
			else
			{
				$Res = @$this->_query( " select * from " . $this->mainsitecode.'_ip_limit' . " where ip = '{$this->ViewerInfo[REMOTE_ADDR]}' and website = '$this->website' and time > $this->DayStartTime" );
				$IpInfo = mysql_fetch_array($Res);
				$timelong = (time() - $IpInfo[time]);
				if( $timelong < 0 ) $timelong = 1;
				@$this->_query( " Update " . $this->mainsitecode.'_ip_limit' . " set pagecount = pagecount + 1,timeslong = $timelong,lasttime = '".time()."' where ip = '{$this->ViewerInfo[REMOTE_ADDR]}' and website = '$this->website' and time > $this->DayStartTime" );
			}
			return $IpInfo;
		}

		//处理alexa工具条数据
		function AddAlexa()
		{
			if( $this->ViewerInfo[alexatool] != 1 || $this->NewViewer == false )
			{
				return false;
			}
			
			//$Time = mktime (0, 0, 0, $this->Month, $this->Day, $this->Year);

			$Sql = " select count(*) as count from " . $this->TableList[alexa] . " where times={$this->DayStartTime} and website = '$this->website'";
			$Res = @$this->_query( $Sql );
			
			//检查是否有需要添加的记录
			$Tmp = mysql_fetch_array($Res);
			if( $Tmp[count] == 0 )
			{
					$Sql = "INSERT INTO " . $this->TableList[alexa] . " ( `website`,`times`, `lastpage`, `counts` ) VALUES ('$this->website', '{$this->DayStartTime}', '{$this->ViewerInfo[REFERER]}', '0' );";
					@$this->_query( $Sql );
			}

			$Sql = " update " . $this->TableList[alexa] . " set counts = counts + 1, lastpage='{$this->ViewerInfo[REFERER]}', http_user_agent = '{$this->ViewerInfo[HTTP_USER_AGENT]}' where times={$this->DayStartTime}  and website = '$this->website'";
			@$this->_query( $Sql );
		}

		function _query( $Sql, $D = false )
		{	
			global $Conn;
			$times1 = microtime();
			$Res = mysql_query( $Sql );

			if( $D || $_GET[debug] == 'true'  )
			{
				echo $Sql . "<br>\n";
				echo mysql_error();				
			}
			$times2 = microtime();
			//echo '<B>'.sprintf("%01.5f",($times2-$times1)).'</B><BR>';
			if( $Res )
			{
				return $Res;
			}
			else
			{
				$this->GetErrors(mysql_error(),$Sql);
				exit;
			}
			
		}
		function GetErrors($errors1,$errors2)
		{	
			$file = file( $url.'errors/phpstat_mysql_error.log' );
			if( count( $file ) > 100)
				array_shift( $file );
			$file[] = date("Y-m-d H:i:s ") . '  ' . $errors1. '--' . $errors2 . "\n";
			$f = fopen( $url.'errors/phpstat_mysql_error.log', 'w' );
			fwrite( $f, implode( "", $file ) );
			fclose( $f );	
			exit();
		}
	}


?>