<?php
if (!defined('MODULE_FILE')) {
	Header("Location: ../../index.php");
	exit;
}
$module_name = basename(dirname(__FILE__));
$csmon['servers']='85.142.54.217:27015,css.theabyss.ru:27014'; //Сервера через запятую
$csmon['infopl']='1'; //Вывод инфы об игроках 0-выкл 1-вкл
$csmon['img']='1'; //Показывать изображение карты 0-выкл 1-вкл (карты звливаем в папку uploads/cs/maps/) формат карты должен быть jpg !!!
$csmon['highslide']='1'; //Использовать библиотеку highslide 0-нет 1-да
function arr_sort($a,$b) {list($key1,$val)=each($a);list($key2,$val)=each($b);if ($a == $b) return 0;return ($a[$key1] > $b[$key2]) ? -1 : 1;}
function main_cs () {
global $csmon, $pagetitle, $defis, $module_name, $ThemeSel;
$id = (isset($_GET['id'])) ? intval($_GET['id']) : 0;
$pagetitle="$defis Мониторинг Серверов CS 1.6";
$arrserv = (isset($_GET['serv'])) ? explode(",",text_filter($_GET['serv'])) : explode(",",$csmon['servers']);
$count = count($arrserv);
$bgr='1';

if ($id==0) head();
else {echo "<html><head><link rel=\"stylesheet\" href=\"templates/$ThemeSel/style.css\" type=\"text/css\">";}
echo "<link rel=\"stylesheet\" href=\"uploads/cs/style.css\" type=\"text/css\">";

echo "<script type=\"text/javascript\" src=\"uploads/cs/highslide/highslide-with-html.packed.js\"></script>";
echo "<script type=\"text/javascript\">hs.graphicsDir = 'uploads/cs/highslide/graphics/';hs.outlineType = 'rounded-white';hs.outlineWhileAnimating = true;</script>";
if ($id!=0) echo "</head>";

if ($id==0) {title("Мониторинг Серверов CS 1.6");OpenTable();}
for ($i = 0; $i <= $count-1; $i++) {
$data='';
$players='';
$info='';
$contentpl='';
$server = explode(":",$arrserv[$i]);
$adress=$server[0];
$port=$server[1];
$data=monitor_server($adress, $port, 'halflife', 'info');
$player=monitor_server($adress, $port, 'halflife', 'players');
$settings=monitor_server($adress, $port, 'halflife', 'settings');

if ($id==2) {
$ac=1;
$allpar="<tr><td><center><font class=\"content\"><b>Информация о параметрах</b></font></center></td><td></td></tr>";
foreach($settings as $key => $value)  {
if ($ac==1) $allpar .="<tr class=\"odd\"><td id=\"keythtd\">$key</td><td id=\"keythtd\">".text_filter($value)."</td></tr>";
elseif ($ac==2) $allpar .="<tr><td id=\"keythtd\">$key</td><td id=\"keythtd\">".text_filter($value)."</td></tr>";
$ac++;
if ($ac==3) $ac=1;
}
echo '<div id="boundary"><table id="keytable" align="center"><tbody id="keytbody">'.$allpar.'</tbody></table></div><div class="clear"></div>';
}

if ($data['server_os']=='w') $data['server_os']='Windows';
else if ($data['server_os']=='l') $data['server_os']='Linux';

if ($data['server_type']=='d') $data['server_type']='Dedicated';
else if ($data['server_type']=='l') $data['server_type']='Listen';
if ($data) {

    $hsl = ($csmon['highslide']==1 && intval($data['players'])>0) ? "<a href=\"index.php?name=$module_name&id=1&serv=".text_filter($data['ip']).":".text_filter($data['port'])."\" style=\"float:right;\" onclick=\"return hs.htmlExpand(this, { objectType: 'iframe' } )\">Подробнее об игроках...</a>" : "";

		$info .="<tr class=\"odd\"><td id=\"keythtd\">Сервер</td><td id=\"keythtd\">".text_filter($data['hostname'])."</td></tr>";
		$info .="<tr><td id=\"keythtd\">Игроки</td><td id=\"keythtd\">".intval($data['players'])." / ".intval($data['maxplayers'])."</td></tr>";
		$info .="<tr class=\"odd\"><td id=\"keythtd\">Карта</td><td id=\"keythtd\">".text_filter($data['mapname'])."</td></tr>";
		$info .="<tr><td id=\"keythtd\">Адрес</td><td id=\"keythtd\">".text_filter($data['ip']).":".text_filter($data['port'])."</td></tr>";
		$info .="<tr class=\"odd\"><td id=\"keythtd\">Режим</td><td id=\"keythtd\">".text_filter($data['gamemod'])."</td></tr>";
		$info .="<tr><td id=\"keythtd\">Network</td><td id=\"keythtd\">ver. ".text_filter($data['version'])."</td></tr>";
		$info .="<tr class=\"odd\"><td id=\"keythtd\">Тип серврера</td><td id=\"keythtd\">".text_filter($data['server_type'])."</td></tr>";
		$info .="<tr><td id=\"keythtd\">ОС</td><td id=\"keythtd\">".text_filter($data['server_os'])."</td></tr>";
		if ($csmon['highslide']=='1') $info .="<tr><td id=\"keythtd\"><a href=\"index.php?name=$module_name&id=2&serv=".text_filter($data['ip']).":".text_filter($data['port'])."\" style=\"float:right;\" onclick=\"return hs.htmlExpand(this, { objectType: 'iframe' } )\">Показать больше параметров...</a></td><td id=\"keythtd\">$hsl</td></tr>";
		}
		if ($player && $csmon['infopl']=='1') {
		usort($player,"arr_sort");
		$exmpl = array_keys($player);
		for ($b = 0; $b <= $data['players']; $b++) {
		if(in_array($b, $exmpl)) {
		$num=$b+1;
		if($bgr2=='1') {$bgcolor2='class="odd"';$bgr2='0';} 
    else {$bgcolor2='';$bgr2='1';}
    if ($player[$b]['id']=='0') $player[$b]['id']=$b;
		$players .="<tr $bgcolor2>";
		//$players .="<td id=\"keythtd\">".intval($player[$b]['id'])."</td>";
		$players .="<td id=\"keythtd\">$num</td>";
		$players .="<td id=\"keythtd\">".text_filter($player[$b]['name'])."</td>
		<td id=\"keythtd\">".intval($player[$b]['score'])."</td>
		<td id=\"keythtd\">".text_filter($player[$b]['time'])."</td>";
		}
		}
$contentpl .='<center><font class=\"content\"><b>Информация об игроках на сервере</b></font></center><div id="boundary_slide"><table id="keytable" align="center">';
$contentpl .='<thead id="keythead"><tr><th>#</th><th>Ник</th><th>Счет</th><th>Время</th></tr></thead>';
$contentpl .='<tbody id="keytbody">'.$players.'</tbody>';
$contentpl .='</table></div>';
		}
$info2 = '<center><b>Информация о сервере: <font color="#4A7003">'.text_filter($data['hostname']).'</font></b></center>';

if($csmon['img']=='1') {
if (!file_exists("uploads/cs/maps/".text_filter($data['mapname']).".jpg")) $map='uploads/cs/maps/no_map.jpg';
else $map="uploads/cs/maps/".text_filter($data['mapname']).".jpg";
$info2 .="<div class=\"center_image\">";
$info2 .= "<img src=\"$map\" alt=\"".text_filter($data['hostname'])."\" />";
$info2 .="<br /><small>".text_filter($data['mapname'])."</small>";
$info2 .="</div>";
}

if ($id==0) {
echo ''.$info2.'<div id="boundary"><table id="keytable" align="center">';
echo '<tbody id="keytbody">'.$info.'</tbody>';
echo '</table></div><div class="clear"></div>';
}
if (($id==1 && $csmon['highslide']==1) || $csmon['highslide']==0) echo "$contentpl";

		}
		
if ($id==0) {CloseTable();foot();}
else {echo "</body></html>";}
}

function monitor_server($ip, $port, $game, $request)    {
		$fp = @fsockopen("udp://$ip", $port, $errno, $errstr, 1);
		if (!$fp) return FALSE;
		stream_set_timeout($fp, 1, 0);
		stream_set_blocking($fp, true);  
	 if (($request == "settings" || $request == "players")) {
	    $challenge_code = "\xFF\xFF\xFF\xFFV\xFF\xFF\xFF\xFF";
	    fwrite($fp, $challenge_code);
	    $buffer = fread($fp, 4096);
	    if (!trim($buffer)) { fclose($fp); return FALSE; }
		$challenge_code = substr($buffer, 5, 4);
    	}
		if ($request == "info") $challenge = "\xFF\xFF\xFF\xFFTSource Engine Query\x00";
		if ($request == "players") $challenge = "\xFF\xFF\xFF\xFFU".$challenge_code;
		if ($request == "settings") $challenge = "\xFF\xFF\xFF\xFFV".$challenge_code;
		fwrite($fp, $challenge);
		$buffer = fread($fp, 4096);
		if (!$buffer) { fclose($fp); return FALSE; }     
		if ($request == "settings")	{
		$second_packet = fread($fp, 4096);
		if (strlen($second_packet) > 0)	{
		$reverse_check = dechex(ord($buffer[8]));      
		if ($reverse_check[0] == "1")	{
		$tmp = $buffer;                 
		$buffer = $second_packet;
		$second_packet = $tmp;
		}
		$buffer = substr($buffer, 13);         
		$second_packet = substr($second_packet, 9);   
		$buffer = trim($buffer.$second_packet);
		 }
		 else	$buffer = trim(substr($buffer, 4));
		 }
		 else	$buffer = trim(substr($buffer, 4)); 
		 fclose($fp);
		 if (!trim($buffer)) return FALSE;
		 
		 
		 if ($request == "info") {
		 unset($data);
		$tmp = explode("\x00", $buffer);
$place = strlen($tmp[0].$tmp[1].$tmp[2].$tmp[3].$tmp[4]) + 5;

$data['version'] = ord($buffer[$place + 2]); // Network Version

if ($data['version']=='47') {
$data['gamemod'] = $tmp[3];
$data['hostname'] = $tmp[1];
$data['mapname'] = $tmp[2];
} elseif ($data['version']=='0'){
$data['version'] = '48';
$data['gamemod'] = $tmp[2];
$data['hostname'] = trim(substr($tmp[0], 2));
$data['mapname'] = $tmp[1];
}

      
		$data['players'] = ord($buffer[$place]);
		$data['maxplayers'] = ord($buffer[$place + 1]);
		$data['password'] = ord($buffer[$place + 5]);
		//$data['cs_players']	= $cs_players;
		$data['ip'] = $ip;
		$data['port'] = $port; 
		$data['datatype'] = $buffer[0];               // m for steam info
		$data['description'] = $tmp[4];
		$data['server_type'] = $buffer[$place + 3];      // D edicated or L isten
		$data['server_os'] = $buffer[$place + 4];      // W indows or L inux
		$data['server_secure'] = ord($tmp[14]);            // VAC
		$exmpl = array_keys($tmp);
		if(in_array("15", $exmpl)) $data['server_bots'] = ord($tmp[15]);            // Number of Bots
		else $data['server_bots']=0;
		return $data;  
		}
		
		
		if ($request == "players") {
		$player_number = 0;
		$position = 2;
		do {
		$player_number++;
		$player0[$player_number]['name']='';                                  
		$player0[$player_number]['id'] = ord($buffer[$position]);
		$position ++;                                             
		while($buffer[$position] != "\x00" && $position < 4000) {
		$player0[$player_number]['name'] .= $buffer[$position];  
		$position ++;
		}
		$player[$player_number]['score'] = (ord($buffer[$position + 1]))
		+ (ord($buffer[$position + 2]) * 256)
		+ (ord($buffer[$position + 3]) * 65536)
		+ (ord($buffer[$position + 4]) * 16777216);
		if ($player[$player_number]['score'] > 2147483648) $player[$player_number]['score'] -= 4294967296;
		$player[$player_number]['name']=$player0[$player_number]['name'];
		$player[$player_number]['id']=$player0[$player_number]['id'];
		$time = substr($buffer, $position + 5, 4);               
		if (strlen($time) < 4) return FALSE;              
		   list(,$time) = unpack("f", $time);                
		    $time = mktime(0, 0, $time);                          
		    $player[$player_number]['time'] = date("H:i:s", $time);  
		    $position += 9;
		    }
		    while ($position < strlen($buffer));                   
		    return $player;
		    }

		    if ($request == "settings") {
			$tmp     = substr($buffer, 2); 
			$rawdata = explode("\x00", $tmp);
		  for($i=1; $i<count($rawdata); $i=$i+2) {
		  $rawdata[$i] = strtolower($rawdata[$i]);  
		  $setting[$rawdata[$i]] = $rawdata[$i+1];  
		  }
		    return $setting; 
		   }
 }

 switch($op) {
  default:
	main_cs();
	break;
	}
?>