Просмотр файла includes/counter.php

Размер файла: 10.2Kb
<?php
error_reporting(0);
$site=explode('/',$_SERVER['QUERY_STRING']);
$ip=$site[2];
$pkey='/'.$site[1];
$site=$site[0];

$name=explode('.',$_SERVER['HTTP_X_FORWARDED_HOST']);
$domain=strtolower($name[1]);

$counterfile='/home/kmx/www/sites/'.$domain.'/'.$site.'/counter.dat';
if     ($site=='top')     $counterfile="/home/kmx/includes/sluzhebnye/top.counter";
elseif ($site=='wap')     $counterfile="/home/kmx/includes/sluzhebnye/wap.counter";
elseif ($site=='catalog') $counterfile="/home/kmx/includes/sluzhebnye/catalog.counter";
elseif ($site=='forum')   $counterfile="/home/kmx/includes/sluzhebnye/forum.counter";
elseif (!is_dir('/home/kmx/www/sites/'.$domain.'/'.$site))
	{
	header("Content-type: image/vnd.wap.wbmp");
	$im=ImageCreate(76,8);
	$white=ImageColorAllocate($im, 255,255,255);
	$black=ImageColorAllocate($im, 0,0,0);
	imageString($im, 1, 1, 0, 'Site not found!', $black);
	imagewbmp($im);
	imageDestroy($im);
	}

$page=file('/home/kmx/www/sites/'.$domain.'/'.$site.'/index.wml');
for ($i=0;$i<sizeof($page);$i++)
	{
	if (substr(trim($page[$i]),0,12)!='<!-- cnt -->') continue;
    $stra=explode('cnt.'.$domain.'.ru/'.$site,$page[$i]);
    $stra=explode('"',$stra[1]);
	$pkey_=$stra[0];
    break;
	}
unset($page);

$y2k = mktime(23,59,59,date('n'),date('j'),date('Y'));
setcookie($site, 1, $y2k);
$vizit=$HTTP_COOKIE_VARS[$site];

$hua="*".strtoupper($_SERVER['HTTP_USER_AGENT']);

$browser=$_SERVER['HTTP_USER_AGENT'];

$komp=false;

$komp=(trim($hua)=='*')
||strpos($hua,'MOZILLA')
||strpos($hua,'MSIE')
||strpos($hua,'WINDOWS')
||strpos($hua,'KLONDIKE')
#||strpos($hua,'OPERA')
||strpos($hua,'M3GATE')
||strpos($hua,'EMULATOR')
||strpos($hua,'TAGTAG')
||strpos($hua,'ALPHACELL')
||strpos($hua,'WAPSILON')
||strpos($hua,'EZOS')
||strpos($hua,'BILBO')
||strpos($hua,'WINWAP')
||strpos($hua,'MYSOCK')
||strpos($hua,'BERCUT')
||strpos($hua,'WAPPER')
||strpos($hua,'TTPCOM')
||strpos($hua,'UNKNOWN')
||strpos($hua,'PORTALMMM')
||strpos($hua,'EZZE')
||strpos($hua,'JAVA')
||strpos($hua,'JBROWSER')
||strpos($hua,'SEND')
||strpos($hua,'WINSIM')
||strpos($hua,'WAPALIZER')
||strpos($hua,'TELEPORT')
||strpos($hua,'TSM')
||strpos($hua,'TCL')
||strpos($hua,'OPWV')
||strpos($hua,'SKT');
if ($komp) $browser='-komp-';

if (!file_exists($counterfile))
	{
	# Создание файла данных счетчика
	$f=@fopen($counterfile,"w+");
	fseek($f,0,SEEK_SET); fwrite($f,str_repeat(' ',1500));
	fseek($f,0,SEEK_SET); fwrite($f,substr('ID='.$n.'      ',0,9)."\n");
	fseek($f,10,SEEK_SET); fwrite($f,substr(''.$counter[5].str_repeat(' ',55),0,60)."\n");
	fseek($f,71,SEEK_SET); fwrite($f,substr(''.$counter[6].str_repeat(' ',25),0,20)."\n");
	fseek($f,92,SEEK_SET); fwrite($f,substr(''.$counter[7].str_repeat(' ',75),0,60)."\n");
	fseek($f,153,SEEK_SET); fwrite($f,substr(''.trim($counter[8]).str_repeat(' ',75),0,23)."\n");
	fseek($f,177,SEEK_SET); fwrite($f,date('d.m.Y H:i:s (----------)')."\n");
	fseek($f,210,SEEK_SET); fwrite($f,str_repeat('=',29)."\n");
	fseek($f,240,SEEK_SET); fwrite($f,substr('ВСЕГО: '.$counter[0].str_repeat(' ',9),0,16)."\n");
	fseek($f,257,SEEK_SET); fwrite($f,str_repeat('-',29)."\n");
	fseek($f,287,SEEK_SET); fwrite($f,"            ПО ЧАСАМ  \n");
	fseek($f,310,SEEK_SET); fwrite($f,"HOUR    HIT   HOST TIMESTAMP \n");
	fseek($f,1060,SEEK_SET); fwrite($f,str_repeat('-',29)."\n");
	fseek($f,1090,SEEK_SET); fwrite($f,"            ПО ДНЯМ\n");
	fseek($f,1110,SEEK_SET); fwrite($f,"DAY     HIT   HOST TIMESTAMP \n");
	fclose($f);
	@chmod($counterfile,0777);
	}

#========= РАБОТА С ФАЙЛОМ СЧЕТЧИКА ============================================
if ($f=@fopen($counterfile,"r+"))
	{
	flock($f,2);
	fseek($f,0,SEEK_SET);

	// Время сейчас
	$hour=date('G');
	$day=date('w');
	$timestamp=time();

	// Время на счетчике
	fseek($f,198,SEEK_SET); $timestamp_=fread($f,10);
	$hour_=date('G',$timestamp_);
	$day_=date('w',$timestamp_);

	# Если большая пауза счета, то сбрасываем просроченые значения
	if ($timestamp-$timestamp_>3600)
	    {
	    for ($_hour=0;$_hour<24;$_hour++)
	        {
	        fseek($f,359+$_hour*30,SEEK_SET);
	        $_timestamp=fread($f,10);
	        fseek($f,340+$_hour*30,SEEK_SET);
	        if ($timestamp-$_timestamp>86400) fwrite($f,substr('0'.$_hour,-2)."        0      0 ----------\n");
	        }
	    for ($_day=0;$_day<7;$_day++)
	        {
	        fseek($f,1159+$_day*30,SEEK_SET);
	        $_timestamp=fread($f,10);
	        fseek($f,1140+$_day*30,SEEK_SET);
	        if ($timestamp-$_timestamp>604800) fwrite($f,$_day."         0      0 ----------\n");
	        }
	    }

    # Счетчик за час
    if ($hour_==$hour)
        {
        fseek($f,342+$hour*30,SEEK_SET);
        $hit_hour=trim(fread($f,9));
        $host_hour=trim(fread($f,7));
        }
    else
        {
        $hit_hour=0;
        $host_hour=0;
        }

    # Счетчик за день
    if ($day_==$day)
        {
        fseek($f,1142+$day*30,SEEK_SET);
        $hit_day=trim(fread($f,9));
        $host_day=trim(fread($f,7));
        }
    else
        {
        $hit_day=0;
        $host_day=0;
        }

    # Общее хитов
    fseek($f,247,SEEK_SET);
    $hit_all=trim(fread($f,9));

    if (($site=='top')||($site=='wap')||($site=='catalog')||($site=='forum')) $pkey=$pkey_;

    if ($pkey==$pkey_)
        {
        # Проверка уникальности
        $unical=true;
        $data_unical='';
        $userinfo=trim(substr(substr($_SERVER['REMOTE_ADDR'].str_repeat(' ',15),0,15).' '.$browser,0,68));
        fseek($f,1450,SEEK_SET);
        while (!feof($f))
            {
            $_timestamp=fread($f,10);
            $_userinfo=trim(fread($f,70));
            if ($timestamp-$_timestamp>3600) continue;
            $data_unical.=$_timestamp.' '.substr($_userinfo.str_repeat(' ',70),0,68)."\n";
            if ((substr($userinfo,0,15)==substr($_userinfo,0,15))&&(substr($_userinfo,15,6)=='-komp-')) $unical=false;
            if ($userinfo==$_userinfo) $unical=false;
            if ($vizit==1) $unical=false;
            }
        if ($unical) $data_unical.=$timestamp.' '.substr($userinfo.str_repeat(' ',70),0,68)."\n";
        fseek($f,1350,SEEK_SET); fwrite($f,str_repeat('-',39)."\n");
        fseek($f,1390,SEEK_SET); fwrite($f,"       УНИКАЛЬНЫЕ  \n");
        fseek($f,1410,SEEK_SET); fwrite($f,"TIMESTAMP  IP              USER_AGENT  \n");
        fseek($f,1450,SEEK_SET); fwrite($f,$data_unical);

	    # Увеличение хостов
	    if ($unical)
	        {
	        $host_day++;
	        $host_hour++;
	        }

	    # Увеличение хитов
	    $hit_all++;
	    $hit_day++;
	    $hit_hour++;

	    # Сохраняем
	    fseek($f,340+$hour*30,SEEK_SET); fwrite($f,substr('0'.$hour,-2).' '.substr('         '.$hit_hour,-8).' '.substr('          '.$host_hour,-6).' '.time()."\n");
	    fseek($f,1140+$day*30,SEEK_SET); fwrite($f,$day.' '.substr('          '.$hit_day,-9).' '.substr('          '.$host_day,-6).' '.time()."\n");
	    fseek($f,247,SEEK_SET); fwrite($f,substr($hit_all.str_repeat(' ',9),0,9)."\n");
	    fseek($f,177,SEEK_SET); fwrite($f,date('d.m.Y H:i:s (U)')."\n");

	    ftruncate($f,1450+strlen($data_unical));
	    }
	flock($f,3);
	fclose($f);
	}

#================================ РАБОТА С БАЗОЙ ===============================

define("DBName","kmx");
define("HostName","localhost");
define("UserName","kmx");
define("Password","kmx-hosting");

# Сбрасываем значения счетчиков в каталоге и рейтинге
if (($hit_day<5)&&($hit_day>0))
	{
	$connectserv=@mysql_connect(HostName, UserName, Password);
	$selectDB=@mysql_select_db(DBName);
	$connect_bd=(($connectserv!=0)&&($selectDB!=0));

	if (!$connect_bd) die('Do not connect BD...');

	$q=@mysql(DBName,"SELECT `day` FROM `counter` WHERE `domain` = '".addslashes($domain)."' AND `login` = '".addslashes($site)."' LIMIT 0, 1");
	$data=@mysql_fetch_array($q);
	$s=@mysql_num_rows($q);
	if (($data['day'] != date('j'))&&($s>0))
		{
	                        				# Ставим текущую дату
		@mysql(DBName,"UPDATE `sites` SET 	`dd` = '".date('j')."' ,".
	                   						# обнуляем счетчик за текущий день недели
	                        				"`d".date('w')."` = '0' ,".
	                        				# обновляем общий счетчик
	                        				"`da` = `d0` + `d1` + `d2` + `d3` + `d4` + `d5` + `d6`".
	                        				# если не та дата...
	                        				"WHERE `dd` != '".date('j')."'");

		@mysql(DBName,"UPDATE `counter` SET `flag` = '0' ,
	                        `hit` = '0' ,
	                        `host` = '0' ,
	                        `day` = '".date('j')."'
	                        WHERE `day` != '".date('j')."'");
		file('http://kmx.ru/stat_magsu.php');
	    }
	if ($s<1) @mysql(DBName,"INSERT INTO `counter` ( `domain`, `login` , `day`, `hit` , `host` , `host24`) VALUES ( '".addslashes($domain)."', '".addslashes($site)."' , '".date('j')."' , '$hit_day' , '$host_day' , '$host24');");
	@mysql(DBName,"UPDATE `counter` SET `flag` = '1' WHERE `domain` = '".addslashes($domain)."' AND `login` = '".addslashes($site)."' LIMIT 1");
	}

$str=$host_day.'|'.$hit_day;

Header("Expires: Mon, 26 Jul 1988 05:00:00 GTM");
Header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
Header("Cache-Control: no-cache, must-relative");
Header("Pragma: no-cache");
header("Content-type: image/vnd.wap.wbmp");

$im=ImageCreate(strlen($str)*5+1,8);
$white=ImageColorAllocate($im, 255,255,255);
$black=ImageColorAllocate($im, 0,0,0);
imageString($im, 1, 1, 0, $str, $black);
imagewbmp($im);
imageDestroy($im);
print str_repeat("\x00",2000);

if ((!strpos($pkey,'.') && (substr($hit_day,-1)!='1') && (substr($hit_day,-1)!='6'))||(($site=='top')||($site=='wap')||($site=='catalog')||($site=='forum'))) exit;

$_key=rand(10000,99999).rand(10000,99999);
$npage='';
$page=file('/home/kmx/www/sites/'.$domain.'/'.$site.'/index.wml');
if (trim($page[1])=='') exit;
for ($i=0;$i<sizeof($page);$i++)
	{
	if (substr(trim($page[$i]),0,12)=='<!-- cnt -->') {$page[$i]='<!-- cnt --><br/><a href="http://top.'.$domain.'.ru"><img src="http://cnt.'.$domain.'.ru/'.$site.'/'.$_key.'" alt="TOP-KMX.Ru"/></a>';}
	$npage.=trim($page[$i])."\n";
	}
$fp = fopen ('/home/kmx/www/sites/'.$domain.'/'.$site.'/index.wml', 'w+');
fwrite ($fp, $npage);
fclose ($fp);
?>