<?php
if(!defined('DATALIFEENGINE')) {die("Hacking attempt!");}

$onl_options['separator']=", ";
$onl_useragent = $_SERVER['HTTP_USER_AGENT'];
$ip = $_SERVER['REMOTE_ADDR'];
$ip = str_replace(",", ".", $ip);
if (!$_TIME) $_TIME = time()+($config['date_adjust']*60);
$_TIME=intval($_TIME);
$online_time = $config['user_online']*60;
$datecut = $_TIME - $online_time;

function online_robots($useragent) {
	$r_or=false;

    $remap_agents = array(
        "#.*(yandex|yadirectbot).*#si" => "Yandex",
        "#.*(google|accoona|gsa-crawler).*#si" => "Google",
        "#.*rambler.*#si" => "Rambler",
        '#.*mail.ru.*#si' => "Mail.RU",
        "#.*aport.*#si" => "Aport",
        "#.*TurtleScanner.*#si" => "Turtle",
        "#.*msnbot.*#si" => "MSN",
        "#.*yahoo.*#si" => "Yahoo",
        "#.*scooter.*#si" => "Altavista",
        "#.*lycos.*#si" => "Lycos.com",
        "#.*libwww.*#si" => "Punto",
        "#.*(is_archiver|archive_org).*#si" => "Archive.org",
        "#.*(W3C_Validator|W3C_CSS_Validator).*#si" => "W3C"
    );
    $result = preg_replace(array_keys($remap_agents), $remap_agents, $useragent);
    $r_or = $result == $useragent ? $r_or : $result;
	
	return $r_or;
}

//Проверяем пользователи и обновляем онлайн статус
if(!$member_id['user_id']){
	$onl_botname = online_robots($onl_useragent);
}elseif( ($member_id['lastdate'] + $online_time) < $_TIME ){
	$db->query("UPDATE LOW_PRIORITY " . USERPREFIX . "_users SET lastdate='{$_TIME}', logged_ip='{$ip}' WHERE user_id='{$member_id['user_id']}'");
}

//if (isset($_COOKIE['lastusername'])) $lastusername = $_COOKIE['lastusername']; else $lastusername = "";
if (isset($_COOKIE['dle_onl_session'])) $onl_session = $_COOKIE['dle_onl_session']; else $onl_session = session_id();

# Удаляем лишних пользователей из списка в БД 
$db->query("DELETE FROM " . PREFIX . "_online WHERE lastdate < $datecut");

# Определяем количество пользователей по критерию и в зависимости от результата, выполняем запрос обноваления или создания записи о пользователе
$onl_query["search_us"]="SELECT COUNT(*) as count FROM " . PREFIX . "_online WHERE session='{$onl_session}'";
$onl_count_user = $db->super_query($onl_query["search_us"]);

if($onl_count_user['count']) {
	$onl_query["update_us"]="UPDATE " . PREFIX . "_online SET uid=".intval($member_id['user_id']).", lastdate={$_TIME}, useragent='{$onl_useragent}', ip='{$ip}' WHERE session='{$onl_session}'";
	$db->query($onl_query["update_us"]);
} else {
	$onl_query["create_us"]="INSERT INTO " . PREFIX . "_online (uid, session, lastdate, useragent, ip) VALUES(".intval($member_id['user_id']).", '{$onl_session}', {$_TIME}, '{$onl_useragent}', '{$ip}')";
	$db->query($onl_query["create_us"]);
	setcookie("dle_onl_session",session_id(), $_TIME+3600*24*365, "/", $domain);
}

# Выбираем пользователей из БД
$sql = "SELECT
			user.name AS user_name, user.user_group,
			online.uid, online.useragent, online.session, online.ip, online.lastdate
		FROM " . PREFIX . "_online AS online
		LEFT JOIN " . PREFIX . "_users AS user ON(user.user_id = online.uid)
		WHERE online.lastdate > $datecut
		ORDER BY name ASC";
$onl_userlist_q = $db->query($sql);

# Обработка полученных данных из БД
$onl_guests=$onl_users=$onl_robots=$onl_lusers=$onl_lrobots=0;
while($onl_userlist = $db->get_array($onl_userlist_q)) {
	if($onl_userlist['uid']==false) {
		$current_robot = online_robots($onl_userlist['useragent']);
		if ($current_robot!="") {
			if ($onl_onlinebots[$current_robot]['lastdate']<$onl_userlist['lastdate']) {
				$onl_onlinebots[$current_robot]['name']=$current_robot;
				$onl_onlinebots[$current_robot]['lastdate']=$onl_userlist['lastdate'];
				$onl_onlinebots[$current_robot]['ip']=$onl_userlist['ip'];
			}
		} else $onl_guests++;
	} else {
		if ($onl_onlineusers[$onl_userlist['uid']]['lastdate']<$onl_userlist['lastdate']) {
			$onl_onlineusers[$onl_userlist['uid']]['name']=$onl_userlist['user_name'];
			$onl_onlineusers[$onl_userlist['uid']]['lastdate']=$onl_userlist['lastdate'];
			$onl_onlineusers[$onl_userlist['uid']]['group']=$onl_userlist['user_group'];
			$onl_onlineusers[$onl_userlist['uid']]['useragent']=$onl_userlist['useragent'];
			$onl_onlineusers[$onl_userlist['uid']]['ip']=$onl_userlist['ip'];
		}
	}
}

if (count($onl_onlineusers)) {
	foreach ($onl_onlineusers as $uid => $value) {
		    $onl_users++;
            $profile_url = $config['http_home_url']. "user/" . urlencode( $onl_onlineusers[$uid]['name'] ) . "/";

            if ($user_group[$onl_onlineusers[$uid]['group']]['colour']){
      			$group_span = $user_group[$onl_onlineusers[$uid]['group']]['colour'];
                $onl_ulink[] =  "\n<a href=\"$profile_url\"><span style=\"color:{$group_span}\">".$onl_onlineusers[$uid]['name']."</span></a>";
      		}else{
                $onl_ulink[] = "\n<a href=\"$profile_url\">".$onl_onlineusers[$uid]['name']."</a>";
      		}
	}
}

//unset ($onl_userlist_q, $onl_onlineusers);
$onl_userlist_q=$onl_onlineusers=array();

if (count($onl_onlinebots)) {
	foreach ($onl_onlinebots as $name => $value) {
		$onl_robots++;
		$onl_blink[] = '<span style="cursor:hand;">'.$name.'</span>';
	}
}

//unset($onl_onlinebots);
$onl_onlinebots=array();

$tpl->load_template('online.tpl');

# Составление списка пользователей
if (count($onl_ulink)==0) {
	$onl_userlist .= "Отсутствуют";
}
for($i=0;$i<count($onl_ulink);$i++) {
	$onl_userlist .= $onl_ulink[$i].$onl_options['separator'];
}
if(count($onl_ulink)) $onl_userlist=substr_replace($onl_userlist, '', strlen($onl_userlist)-strlen($onl_options['separator']), strlen($onl_options['separator']));
if (count($onl_blink)==0) {
	$onl_botlist = "Отсутствуют";
}
for($i=0;$i<count($onl_blink);$i++) {
	$onl_botlist .= $onl_blink[$i].$onl_options['separator'];
}
if(count($onl_blink)) $onl_botlist=substr_replace($onl_botlist, '', strlen($onl_botlist)-strlen($onl_options['separator']), strlen($onl_options['separator']));

$onl_ulink=$onl_lulink=$onl_blink=array();

if (!$is_logged) $userlist = "Список виден только зарегистрированным.";
else $userlist = $onl_userlist;

$tpl->set('{users}',$onl_users);
$tpl->set('{guest}',$onl_guests);
$tpl->set('{robots}',$onl_robots);
$tpl->set('{all}',($onl_users+$onl_guests+$onl_robots));
$tpl->set('{userlist}',$userlist);
$tpl->set('{botlist}',$onl_botlist);

//unset($onl_userlist, $onl_botlist);
$onl_userlist=$onl_botlist="";

$tpl->compile('online');
$tpl->clear();
?>