<?


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

		//var $TmpDir = './count/tmpdir';
		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 $ArrTypes = array(
										'keyword'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>false ),
										'referer'=>array( 'lastpage'=>true, 'allownull'=> true, 'newviewer'=>true ),
										'page'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>false, 'addfield'=>'pagetitle'  ),		'returner'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'country'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'province'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true, 'addfield'=>'country' ),
										'city'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true, 'addfield'=>'province' ),
										'area'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true, 'addfield'=>'city' ),
										);
		*/

		var $DayStartTime;
		var $DayStartTimeSave;
		function _Stat( )
		{	
			$time1 = microtime();
			global $TableList;			
			$this->website = $_GET[website];
			$this->TableList = $TableList;
			$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->GetUserIpAdd();
			$this->GetUserDir();
			$this->GetUserData();
			$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') 
													);


			$Res = @$this->_query( " select * from " . $this->TableList[day_data] . " where times = {$this->DayStartTime} and website = '$this->website'" );
			$DayData = mysql_fetch_array($Res);
			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,$PHPStatIsHiddenIco;
			
			$_GET[show] = @array_flip ( $_GET[show] );
			
			foreach( $this->ShowArr as $Key=>$Val )
			{
				if( isset( $_GET[show][$Key] ) )
				{
					$ShowStr .= '&nbsp;&nbsp;|&nbsp;&nbsp;' . $this->Charset( $Val[1] ) . ':' . $DayData["$Val[0]"] . '';
				}
				
			}
			
			$Title = $this->Charset( $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 $PHPStatIsHiddenIco == false)
			{	
				//去掉显示图标(logo)
				echo "document.getElementById(\"PCSCount\").innerHTML='<a href=".$this->ViewerInfo['counturl']."/index.php?website=".$this->website." target=\"_blank\" title=\"" . $Title . "\">".$ToShow."</a>';";
			}
			elseif( $PHPStatIsHiddenIco == false)
			{	
				//去掉显示图标(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 )
		{
			return $this->ViewerInfo[charset] == 'utf-8' ? utf82gb2312( $Str ) : $Str;		
		}

		function GetUserDir()
		{
			$this->UserDataDir = $this->TmpDir;
			if( ! is_dir( $this->UserDataDir ) )
			{
				if( ! mkdir( $this->UserDataDir ) )
				{
					$this->_Error( '创建用户目录出错 Error At ' . __line__ );
				}
			}
		}
		
		function GetUserIpAdd()
		{
			$Ip = $_SERVER['REMOTE_ADDR'];
			$Ip1 = getenv('HTTP_X_FORWARDED_FOR');
			if (($Ip1 != "") && ($Ip1 != "unknown")) 
				$this->ViewerInfo[REMOTE_ADDR] = $Ip1;
			else
				$this->ViewerInfo[REMOTE_ADDR] = $Ip;		
			//$this->ViewerInfo[REMOTE_ADDR] = "218.".rand(0,5).rand(0,5).".".rand(0,5).rand(0,5).".".rand(0,1).rand(0,5).rand(0,5);
		}

		function GetUserData()
		{
			$Sql = "SELECT  `id`  FROM " . $this->TableList[site] . "  where website = '$this->website'";
			$Res = @$this->_query( $Sql );
			$RetRows = mysql_num_rows($Res);

			if( $RetRows == 1 )
			{
				$this->UserData = $UserData[0];
			}
			elseif ( $RetRows == 0 )
			{
				echo "<SCRIPT LANGUAGE=\"JavaScript\">
				<!--
				alert('站点的统计代码未在服务器端注册');
				//-->
				</SCRIPT>";
				$this->_Error( '站点的统计代码未在服务器端注册--'.$this->website.', Error At ' . __line__ );
			}
			elseif ( $RetRows > 1 )
			{
				echo "<SCRIPT LANGUAGE=\"JavaScript\">
				<!--
				alert('站点的统计代码存在重复');
				//-->
				</SCRIPT>";
				$this->_Error( '站点的统计代码存在重复--'.$this->website.', Error At ' . __line__  );
			}

			$this->UserData = mysql_fetch_array($Res);
		}
		

		function CheckNewDay()
		{
			$this->UserTodayDir = $this->UserDataDir . '/' . $this->website .'_'.date("Ymd",$this->DayStartTime). ".phpstat" ;
			if( ! file_exists( $this->UserTodayDir ) )
			{
				$this->NewDay = true;
				$fp = fopen( $this->UserTodayDir ,"w+" );
				fclose( $fp );
				$this->ClearYesterday();
				$this->IniToday();
			}
		}

		function CheckNewViewer()
		{
			$Sql = "SELECT count(id) as count FROM " . $this->TableList[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 );
			}
					

			//转移当日访问明细到phpstat_ip_history
			//@$this->_query( "INSERT INTO ". $this->TableList[ip_history]." SELECT * FROM ".$this->TableList[ip]."") ;
			//删除IP当日临时表phpstat_ip_limit
			@$this->_query( "DELETE FROM " . $this->TableList[ip_limit] . " where website = '$this->website'" );
			//删除IP当日访问明细phpstat_ip
			//@$this->_query( "TRUNCATE " . $this->TableList[ip] . " " );
			
			//echo mysql_error();

			

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

			
		}

		function IniToday()
		{
			$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()
		{
			$this->ViewerInfo[TIME]				= &$this->Time;

			$this->ViewerInfo[page]				= $_GET[pageurl];
			if(eregi("script", $_GET[pageurl]) or eregi("iframe", $_GET[pageurl]))
			{exit;}			
			$this->ViewerInfo[charset]			= $_GET["charset"];
			$this->ViewerInfo[pagetitle]		= $this->Charset($_GET[pagetitle]);
			$this->ViewerInfo[REFERER]			= $_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]	= $_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['return']			= intval( $_GET['return1'] );
			$this->ViewerInfo['counturl']		= $_GET['counturl'];
			$this->ViewerInfo['image']			= $_GET[image];
			$this->ViewerInfo['text']			= $_GET[text];
			$this->ViewerInfo[type]				= intval( $_GET["type"] );
			

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

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

			//查找来源地区
			$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  INTO " . $this->TableList[ip_limit] . " ( 
								`ip`, `time`, `pageurl`, `pagetitle`, `pagefrom`, `language`, `color`, `screensize`, `http_user_agent`, `pagefromsite`, `keyword`, `country`, `address`, `province`, `city`,`alexatool`, `timezone`, `firsttime`, `lasttime`, `browser`, `bot`,`java`,`flash`,`system`, `todayfirst`, `returner` ,`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[HTTP_USER_AGENT]}', '{$this->ViewerInfo[referer]}', '{$this->ViewerInfo[keyword]}', '{$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]}',
								'{$this->ViewerInfo[bot]}',
								'{$this->ViewerInfo[java]}',
								'{$this->ViewerInfo[flash]}',
								'{$this->ViewerInfo[system]}', 
								'" . ( $this->NewViewer == true ? 1 : 0 ) . "', '".$this->ViewerInfo['return']."',
								'{$this->website}');";
			@$this->_query( $Sql );				
			}
			$Sql = "INSERT  INTO " . $this->TableList[ip] . " ( 
								`ip`, `time`, `pageurl`, `pagetitle`, `pagefrom`, `language`, `color`, `screensize`, `http_user_agent`, `pagefromsite`, `keyword`, `country`, `address`, `province`, `city`,`alexatool`, `timezone`, `firsttime`, `lasttime`, `browser`, `bot`,`java`,`flash`,`system`, `todayfirst`, `returner` ,`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[HTTP_USER_AGENT]}', '{$this->ViewerInfo[referer]}', '{$this->ViewerInfo[keyword]}', '{$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]}',
								'{$this->ViewerInfo[bot]}',
								'{$this->ViewerInfo[java]}',
								'{$this->ViewerInfo[flash]}',
								'{$this->ViewerInfo[system]}', 
								'" . ( $this->NewViewer == true ? 1 : 0 ) . "', '".$this->ViewerInfo['return']."',
								'{$this->website}');";
			@$this->_query( $Sql );
		
		}

		function _Error( $Msg )
		{
			$markdate = date("Y-m-d");
			$f = fopen( 'count/'.$markdate.'_common_error.log', 'a+' );
			fwrite( $f, date("Y-m-d H:i:s ") . '  ' .$Msg . "\n" );
			fclose( $f );	
			exit();
		}

		//查找关键字
		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] );
			}
			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 = utf82gb2312( urldecode( $Tmp[1] ) );
				}
			}
			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 = utf82gb2312( urldecode( $Tmp[1] ) );
				}
			}
			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, '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, '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 GetNapsBot()
		{
			$useragent = strtolower($this->ViewerInfo[HTTP_USER_AGENT]);
							
			if (strpos($useragent, 'googlebot') !== false){
					$bot = 'Googlebot';
			}
			
			else if (strpos($useragent, 'msnbot') !== false){
					$bot = 'MSNbot';
			}
			
			else if (strpos($useragent, 'slurp') !== false){
					$bot = 'Yahoobot';
			}
			
			else if (strpos($useragent, 'baiduspider') !== false){
					$bot = 'Baiduspider';
			}
			
			else if (strpos($useragent, 'sohu-search') !== false){
					$bot = 'Sohubot';
			}
			
			else if (strpos($useragent, 'lycos') !== false){
					$bot = 'Lycos';
			}
			
			else if (strpos($useragent, 'robozilla') !== false){
					$bot = 'Robozilla';
			}
			else
				$bot = '0';
			$this->ViewerInfo[bot] = $bot;
		}
		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->ip2num( $this->ViewerInfo[REMOTE_ADDR] );			
			if($this->NewViewer == true)
			{	
				$Res = @$this->_query( " select sql_cache * from " . $this->TableList[ip_data] . " where ipstart <= $IpNum and ipend >= $IpNum " );
			}
			else
			{
				$Res = @$this->_query( " select * from " . $this->TableList[ip_limit] . " where ip = '{$this->ViewerInfo[REMOTE_ADDR]}'" );
			}
			$IpInfo = mysql_fetch_array($Res);
			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(alexaid) 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 SaveArr()
		{			
			foreach( $this->ArrTypes as $Key=>$Val )
			{	
				if( ( $this->ViewerInfo[$Key] == '' && $Val[allownull] == false ) || ( $this->NewViewer == false && $Val[newviewer] == true ) )
				{
					continue;
				}
				
				$this->_SaveType( $Key);
			}
		}

		function _SaveType( $Type )
		{
			
			$Types = &$this->ArrTypes;
			$Field = $Types["$Type"][addfield];			
			if(isset($Field))
			{
				$FieldName = ", `$Field`";
				$FieldValue = $this->ViewerInfo["$Field"]." ";	
			}
			else
			{
				$FieldName = "";
				$FieldValue = "";	
			}
			if( ! isset( $Types[$Type] ) )
			{
				return false;
			}

			$Sql = " select count(*) as count, types, counts, {$Type}id from " . $this->TableList[$Type] . " where {$Type} = '" . $this->ViewerInfo["$Type"] . "' and types REGEXP '0|1' and website = '$this->website' group by types,{$Type}id,counts ";
			$Res = @$this->_query( $Sql );

			unset( $DelData );
			unset( $Data );
			
			while( $Tmp = mysql_fetch_array($Res) )
			{		
				if( isset( $Data["$Tmp[types]"] ) )
				{	
					$Tmp['isset'] = $Data["$Tmp[types]"];
					$DelData[] = $Tmp;
					continue;
				}
				$Data["$Tmp[types]"] = $Tmp;
			}
			
			//检查是否有需要添加的记录
			for( $i = 0; $i < 2; $i++ )
			{
				if( ! isset( $Data[$i] ) )
				{
					$Sql = "INSERT INTO " . $this->TableList[$Type] . " ( `website`,`{$Type}`, `times`,"  . ( $Types[$Type][lastpage] ?  "`lastpage`," : '' ) . " `counts`, `types` $FieldName) VALUES ( '$this->website','" . $this->ViewerInfo["$Type"] . "', '{$this->ViewerInfo[TIME]}', " . ( $Types[$Type][lastpage] ?  "'{$this->ViewerInfo[REFERER]}', " : '' ) . "'0', '$i' " . ( $FieldValue ?  ", '{$FieldValue}' " : '' ) . ");";
					@$this->_query( $Sql );					
				}
			}
			

			//检查是否有需要删除的记录
			if( count( $DelData ) > 0 )
			{	
				foreach( $DelData as $Val )
				{	//echo "\$Data[\$Tmp[types]]del";
					$Sql = " delete from " . $this->TableList[$Type] . " where {$Type}id = " . $Val["{$Type}id"] ." and website = '$this->website'";
					@$this->_query( $Sql );
					$Sql = " update " . $this->TableList[$Type] . " set counts = counts + $Val[counts] where {$Type}id = " . $Val['isset']["{$Type}id"]." and website = '$this->website'";
					@$this->_query( $Sql );
				}
			}

			$Sql = " update " . $this->TableList[$Type] . " set counts = counts + 1, "  . ( $Types[$Type][lastpage] ?  "lastpage='{$this->ViewerInfo[REFERER]}', " : '' ) . "times = '{$this->ViewerInfo[TIME]}' where {$Type} = '" . $this->ViewerInfo["$Type"] . "' and  types REGEXP '0|1' 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);
			}
			
		}
		function GetErrors($errors1,$errors2)
		{	
			$markdate = date("Y-m-d");
			$f = fopen( 'count/'.$markdate.'_mysql_error.log', 'a+' );
			fwrite( $f, date("Y-m-d H:i:s") . $errors1. '--' . $errors2 . "\n" );
			fclose( $f );
			return false;
		}
	}


?>