<?
/*
* ===========================================*
* 项目: Ourplus网站流量统计分析系统*
* 版本: Bate1*
* 开发: 看海*
* ===========================================*
* Copyright (c) 2004 - 2005*
* 主页: http://stat.ourplus.com*
* 信箱: fantasysisky@hotmail.com*
* 版权信息: 本软体为共享软体(shareware)提供个人网站免费使用，
                作者看海 (stat.ourplus.com) 保留全部权力，受相关法律和国际
				公约保护，请勿非法修改、转载、散播，或用于其他赢利行为，
				并请勿删除版权声明。*
* ===========================================*
*/
	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 $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 ),
										'color'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'screen'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'language'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'browser'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'system'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'area'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'timezone'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'page'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>false ),
										'return'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true )
										);
		

		var $DayStartTime;

		function _Stat( )
		{
			global $TableList;
			
			$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->GetUserDir();
			$this->GetUserData();
			$this->CheckNewDay();
			$this->GetViewerInfo();
			$this->CheckNewViewer();

			
			//处理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}" );
			$DayData = mysql_fetch_array( $Res, MYSQL_ASSOC );
			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}";
			$this->_query( $Sql );
			$this->OutLog( $DayData );
		}

		function OutLog( $DayData )
		{
			$_GET[show] = @array_flip ( $_GET[show] );

			foreach( $this->ShowArr as $Key=>$Val )
			{
				if( isset( $_GET[show][$Key] ) )
				{
					$ShowStr .= '[' . $this->Charset( $Val[1] ) . ':' . $DayData["$Val[0]"] . ']';
				}
				
			}

			$Title = $this->Charset( '网站流量统计分析系统' );
			if( $this->ViewerInfo[type] == 2 )
			{
				echo "document.getElementById(\"OurplusCount\").innerHTML='<a href=\"" . $this->ViewerInfo['counturl'] . "\" target=\"_blank\" title=\"Ourplus " . $Title . "\"><img src=\"" . $this->ViewerInfo['counturl'] . "/countlogo.gif\" style=\"border:0px;\"  align=\"absmiddle\"></a>';";
			}
			else
			{
				echo "document.write('<a href=\"" . $this->ViewerInfo['counturl'] . "\" target=\"_blank\" title=\"Ourplus " . $Title . "\"><img src=\"" . $this->ViewerInfo['counturl'] . "/countlogo.gif\" style=\"border:0px;\"  align=\"absmiddle\"></a>');";
				if( trim( $ShowStr ) != '' )
				{
					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 In GetUserDir At ' . __line__ );
				}
			}
		}

		function GetUserData()
		{
			$Sql = "SELECT  `id` , `manager` , `password` , `site` , `sitename` , `sitedes` , `sitetype` , `qq` , `email` , `msn` FROM " . $this->TableList[users] . " ";
			$Res = $this->_query( $Sql );
			$RetRows = mysql_num_rows( $Res );

			if( $RetRows == 1 )
			{
				$this->UserData = $UserData[0];
			}
			elseif ( $RetRows == 0 )
			{
				$this->_Error( 'Uninstall, Error At ' . __line__ );
			}
			elseif ( $RetRows > 1 )
			{
				$this->_Error( 'Database User Data Error' );
			}

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

		function CheckNewDay()
		{
			$this->UserTodayDir = $this->UserDataDir . '/' . $this->DayStartTime;
			if( ! is_dir( $this->UserTodayDir ) )
			{
				$this->NewDay = true;
				mkdir( $this->UserTodayDir );
				$this->ClearYesterday();
				$this->IniToday();
			}
		}

		function CheckNewViewer()
		{
			$Sql = "SELECT count(*) as count FROM " . $this->TableList[ip] . " where ip = '{$this->ViewerInfo[REMOTE_ADDR]}' and time > $this->DayStartTime ";
			$Res = $this->_query( $Sql );
			$Count = mysql_fetch_array( $Res, MYSQL_ASSOC );
			$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" );
			$YesterdayData = mysql_fetch_array( $Res, MYSQL_ASSOC );

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

			//Update Count Table
			$Sql = "update " . $this->TableList[users] . " 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]
			";
			$this->_query( $Sql );



			//Update Month Table
			$YesterdayMonthTime = mktime (0,0,0,$YesterdayMonth, 1, $YesterdayYear );
			$Res = $this->_query( " select count(*) as count from " . $this->TableList[month_data] . " where times = $YesterdayMonthTime" );
			$Row = mysql_fetch_array( $Res, MYSQL_ASSOC );
			
			if( $Row[count] == 0 )
			{	
				$Sql = " insert into " . $this->TableList[month_data] . " 
				( times, year, month, month_count, month_count_ip ) 
				values 
				( $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 ";
				$this->_query( $Sql );
			}

			//Update Year Table
			$YesterdayYearTime = mktime ( 0, 0, 0, 1, 1, $YesterdayYear );
			$Res = $this->_query( " select count(*) as count from " . $this->TableList[year_data] . " where times = $YesterdayYearTime" );
			$Row = mysql_fetch_array( $Res, MYSQL_ASSOC );
			
			if( $Row[count] == 0 )
			{	
				$Sql = " insert into " . $this->TableList[year_data] . " 
				( times, year, year_count, year_count_ip ) 
				values 
				( $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 ";

				$this->_query( $Sql );
			}


			//删除昨日详细访问统计
			$this->_query( "delete from " . $this->TableList[ip] . " where time < {$this->DayStartTime}" );
			//echo mysql_error();

			foreach( $this->ArrTypes as $Key=>$Val )
			{
				$Sql = "delete from " . $this->TableList[$Key] . " where types = 2 ";
				$this->_query( $Sql );
				$Sql = "update " . $this->TableList[$Key] . " set types = 2 where types = 1 ";
				$this->_query( $Sql );
			}


			//删除昨日产生的临时文件
			@rmdir( $this->UserDataDir . '/' . $YesterdayStartTime );
		}

		function IniToday()
		{
			$Sql = "INSERT INTO " . $this->TableList[day_data] . " (
													`times`, `year`, `month`, `day`, `week`
													) VALUES (
													'{$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];
			$this->ViewerInfo[REFERER] = $_GET[referer];
			$this->ViewerInfo[language] = strtolower( $_GET[language] );
			$this->ViewerInfo[color] = $_GET[color];
			$this->ViewerInfo[screen] = $_GET[screensize];
			$this->ViewerInfo[HTTP_USER_AGENT] = $_SERVER["HTTP_USER_AGENT"];
			$this->ViewerInfo[REMOTE_ADDR] = $_SERVER["REMOTE_ADDR"];
			$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[returncount]  = 0;

			$this->ViewerInfo[charset] = $_GET["charset"];
			$this->ViewerInfo[type] = intval( $_GET["type"] );


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

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

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

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

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

		function SaveViewerInfo()
		{
			$Sql = "INSERT INTO " . $this->TableList[ip] . " ( 
								`ip`, `time`, `pageurl`, `pagefrom`, `language`, `color`, `screensize`, `http_user_agent`, `pagefromsite`, `keyword`, `country`, `address`, `alexatool`, `timezone`, `firsttime`, `lasttime`, `browser`, `system`, `todayfirst`, `return` 
								) VALUES ( 
								'{$this->ViewerInfo[REMOTE_ADDR]}', '{$this->ViewerInfo[TIME]}', '{$this->ViewerInfo[page]}', '{$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[area]}', '{$this->ViewerInfo[address]}', '{$this->ViewerInfo[alexatool]}', '{$this->ViewerInfo[timezone]}', '{$this->ViewerInfo[firsttime]}', '{$this->ViewerInfo[lasttime]}', '{$this->ViewerInfo[browser]}', '{$this->ViewerInfo[system]}', '" . ( $this->NewViewer == true ? 1 : 0 ) . "', '".$this->ViewerInfo['return']."' );";
			//echo $Sql;
			//mysql_query( $Sql );
			$this->_query( $Sql );
		}

		function _Error( $Msg )
		{
			exit( $Msg );
		}

		//查找关键字
		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') )
			{
				preg_match( "|google.+q=([^\&]*)|is", $RefererUrl, $Tmp );
				$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 );
				$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 
			{
				$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->ip2num( $this->ViewerInfo[REMOTE_ADDR] );
			$Res = $this->_query( " select * from " . $this->TableList[ip_data] . " where ipstart <= $IpNum and ipend >= $IpNum" );
			$IpInfo = mysql_fetch_array( $Res, MYSQL_ASSOC );
			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} ";
			$Res = $this->_query( $Sql );
			
			//检查是否有需要添加的记录
			$Tmp = mysql_fetch_array( $Res, MYSQL_ASSOC );
			if( $Tmp[count] == 0 )
			{
					$Sql = "INSERT INTO " . $this->TableList[alexa] . " ( `times`, `lastpage`, `counts` ) VALUES ( '{$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} ";
			$this->_query( $Sql );
		}


		//保存各个属性信息
		function SaveArr()
		{
			//if( $this->ViewerInfo['return'] == 0 )
			//{
			//	unset( $this->ViewerInfo['return'] );
			//}
			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;

			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 != 2 group by types,{$Type}id,counts ";
			$Res = $this->_query( $Sql );

			unset( $DelData );
			unset( $Data );
			
			while( $Tmp = mysql_fetch_array( $Res, MYSQL_ASSOC ) )
			{
				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] . " ( `{$Type}`, `times`,"  . ( $Types[$Type][lastpage] ?  "`lastpage`," : '' ) . " `counts`, `types` ) VALUES ( '" . $this->ViewerInfo["$Type"] . "', '{$this->ViewerInfo[TIME]}', " . ( $Types[$Type][lastpage] ?  "'{$this->ViewerInfo[REFERER]}', " : '' ) . "'0', '$i' );";
					$this->_query( $Sql );
				}
			}
			
			//检查是否有需要删除的记录
			if( count( $DelData ) > 0 )
			{
				foreach( $DelData as $Val )
				{
					$Sql = " delete from " . $this->TableList[$Type] . " where {$Type}id = " . $Val["{$Type}id"];
					$this->_query( $Sql );
					$Sql = " update " . $this->TableList[$Type] . " set counts = counts + $Val[counts] where {$Type}id = " . $Val['isset']["{$Type}id"];
					$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 != 2";

			$this->_query( $Sql );

		}

		function _query( $Sql, $D = false )
		{
			$Res = mysql_query( $Sql );

			if( $D || $_GET[debug] == 'true'  )
			{
				echo $Sql . "<br>\n";
				echo mysql_error();
			}

			if( $Res )
			{
				return $Res;
			}
			else
			{
				$f = fopen( 'count/mysql_error.log', 'a+' );
				fwrite( $f, date("Y-m-d H:i:s") . mysql_error() . '--' . $Sql . "\n" );
				fclose( $f );
				return false;
			}
		}


	}




?>