<?php

//Include the class file
require_once("SourceQuery.inc");

//Do some checking on some vars
if ( $conf['imageext'][0] != '.') {
	$conf['imageext'] = '.' . $conf['imageext'];
}
if ( $conf['mapext'][0] != '.') {
	$conf['mapext'] = '.' . $conf['mapext'];
}

if ( $conf['imagespath'][strlen($conf['imagespath'])-1] != '/') {
	$conf['imagespath'] .= '/';
}
if ( $conf['imagesurl'][strlen($conf['imagesurl'])-1] != '/') {
	$conf['imagesurl'] .= '/';
}
if ( $conf['mappath'][strlen($conf['mappath'])-1] != '/') {
	$conf['mappath'] .= '/';
}
if ( $conf['mapurl'][strlen($conf['mapurl'])-1] != '/') {
	$conf['mapurl'] .= '/';
}

function QueryServer($ipport)
{
	global $conf;

	list($ip,$port) = explode(":",$ipport);

	$starttime = getMicroTime();
	$query = new SourceQuery($ip,$port);
	$querytime = round(getMicroTime() - $starttime, 6);

	if ($query->success == TRUE)
	{
		//Setup vars to use in templates
		$serverIP = $query->serverIP;
		$serverPort = $query->serverPort;
		$serverPing = $query ->serverPing;
		$serverName = htmlspecialchars($query->hostName,ENT_QUOTES);
		$mapname = htmlspecialchars($query->map,ENT_QUOTES);
		$gamedir = htmlspecialchars($query->gameDir,ENT_QUOTES);
		$gamename = htmlspecialchars($query->gameType,ENT_QUOTES);
		$numPlayers = $query->numPlayers;
		$maxPlayers = $query->maxPlayers;
		$numBots = $query->numBots;
		$dedicated = $query->Dedicated == 1 ? "Yes" : "No";
		$serverOS = $query->OS == 'l' ? "Linux" : "Windows";
		$password = $query->password == 1 ? "Yes" : "No";
		$secure = $query->secure == 1 ? "Yes" : "No";
		$protocol = htmlspecialchars($query->netVersion,ENT_QUOTES);
		$gameVersion = htmlspecialchars($query->gameVersion,ENT_QUOTES);
		$appID = $query->appID;

		//Find AppID for HL1
		if (!$appID) {
			switch ($gamedir) {
				case "cstrike":	$appID = 10; break;
				case "tfc":		$appID = 20; break;
				case "dod":		$appID = 30; break;
				case "dmc":		$appID = 40; break;
				case "gearbox":	$appID = 50; break;
				case "ricochet":	$appID = 60; break;
				case "valve":		$appID = 70; break;
				case "czero":		$appID = 80; break;

				//Third party mods
				default:
				$appID = 70;
				$launchdir = " -game " . $gamedir;
				break;
			}
		}

		//Set Images Dir
		$imagesdir = $gamedir;
		if ($appID == 240 && strcmp($gamedir,"cstrike") == 0) {
			$imagesdir = "cstrikes";
		}

		//Extra Vars added for extra features

		//$applaunch - This can be used in an href link and will launch steam and connect to the server

		//Old Method
		//$applaunch = '\'steam:"-applaunch ' . $appID . $launchdir . ' +connect ' . $serverIP . ':' . $serverPort . '"\'';

		//New connect protocol
		$applaunch = 'steam://connect/' . $serverIP . ':' . $serverPort;

		//$imageurl
		if ($conf['imagespath'] && file_exists($conf['imagespath'] . $imagesdir . "/" . $mapname . $conf['imageext'])) {
			$imageurl = $conf['imagesurl'] . $imagesdir . "/" . $mapname . $conf['imageext'];
		}
		elseif ($conf['imagespath'] && file_exists($conf['imagespath'] . $mapname . $conf['imageext'])) {
			$imageurl = $conf['imagesurl'] . $mapname . $conf['imageext'];
		}
		elseif ($conf['imagespath'] && file_exists($conf['imagespath'] . "/" . $imagesdir . "/" . $conf['imagemiss'] . $conf['imageext'])) {
			$imageurl = $conf['imagesurl'] . $imagesdir . "/" . $conf['imagemiss'] . $conf['imageext'];
		}
		else {
			$imageurl = $conf['imagesurl'] . $conf['imagemiss'] . $conf['imageext'];
		}

		//$mapdlurl
		if ($conf['mappath'] && file_exists($conf['mappath'] . $mapname . $conf['mapext'])) {
			$mapdlurl = $conf['mapurl'] . $mapname . $conf['mapext'];
		}
		else {
			$mapdlurl = '';
		}

		//$dllink
		if ($imageurl && strcmp($conf['dllinktxt'],"image") == 0) {
			$linktxt = '<img src="' . $imageurl . '" border="0">';
		}
		elseif (strcmp($conf['dllinktxt'],"map") == 0 ) {
			$linktxt = $mapname;
		}
		else {
			if ($mapdlurl)	$linktxt = $conf['dllinktxt'];
			else			$linktxt = $conf['dlnolinktxt'];
		}

		if ($mapdlurl) {
			$dllink = '<a href="' . $mapdlurl . '">' . $linktxt . '</a>';
		}
		else {
			$dllink = $linktxt;
		}

		//$timeleft
		if ($query->numRules > 0) {
			$tlkey = array_search("amx_timeleft",$query->ruleName);
		}
		if ($tlkey != FALSE) {
			$timeleft = $query->ruleValue[$tlkey];
		}
		else {
			$timeleft = "Unknown";
		}

		//$noPlayers
		$noPlayers = $numPlayers == 0 ? "No Players in Server" : "&nbsp;";
	}
	else {
		$serverIP = $ip;
		$serverPort = $port;
		$serverName = "Unknown - Connection Error";
	}

	//Flush the template HTML into a variable
	ob_start();
	include($conf['template']);
	$pageHTML = ob_get_contents();
	ob_end_clean();

	if ($query->success == TRUE)
	{
		if (mb_strlen($query->RError) <= 0) {
			//Start Processing Rules
			$start = strpos($pageHTML, "<!--rules-->");
			$start = strpos($pageHTML, "\n", $start);
			$end = strpos($pageHTML, "<!--rules-end-->", $start);
			$rulesHTML = substr($pageHTML,$start,$end-$start);
			$end = strrpos($rulesHTML,"\n");
			$rulesHTML = substr($rulesHTML,0,$end);
			$end = $start + strlen($rulesHTML);

			$outputHTML = substr($pageHTML,0,$start);

			$filters = count($conf['rulefilter']);
			for ($x = 0; $x < $query->numRules; $x++) {
				for ($y = 0; $y < $filters; $y++) {
					if (!(strpos($query->ruleName[$x],$conf['rulefilter'][$y]) === FALSE)) {
						continue 2;
					}

				}
				$tmpHTML = str_replace('$ruleName', str_replace("$", "&#036;",htmlspecialchars($query->ruleName[$x],ENT_QUOTES)), $rulesHTML);
				$outputHTML .= str_replace('$ruleValue', str_replace("$", "&#036;",htmlspecialchars($query->ruleValue[$x],ENT_QUOTES)), $tmpHTML);
			}

			$outputHTML .= substr($pageHTML,$end);
			$pageHTML = $outputHTML;
			//End Processing Rules
		}
		if (mb_strlen($query->PError) <= 0) {
			//Start Processing Players
			$start = strpos($pageHTML, "<!--players-->");
			$start = strpos($pageHTML, "\n", $start);
			$end = strpos($pageHTML, "<!--players-end-->", $start);
			$playersHTML = substr($pageHTML,$start,$end-$start);
			$end = strrpos($playersHTML,"\n");
			$playersHTML = substr($playersHTML,0,$end);
			$end = $start + strlen($playersHTML);

			$outputHTML = substr($pageHTML,0,$start);

			if (strpos($playersHTML, "<!--players-next-->") === FALSE) {

				for ($x = 0; $x < $numPlayers; $x++) {
					$tmpHTML = str_replace('$playerName', str_replace("$", "&#036;",htmlspecialchars($query->playerName[$x],ENT_QUOTES)), $playersHTML);
					$tmpHTML = str_replace('$playerKills', $query->playerKills[$x], $tmpHTML);
					$outputHTML .= str_replace('$playerTime', $query->playerTime[$x], $tmpHTML);
				}
			}
			else {
				$pHTMLArr = explode("<!--players-next-->",$playersHTML);
				$numElemets = count($pHTMLArr);
				$x = 0;

				while (TRUE) {
					for ($y = 0; $y < $numElemets; $y++) {
						$tmpHTML = str_replace('$playerName', str_replace("$", "&#036;",htmlspecialchars($query->playerName[$x],ENT_QUOTES)), $pHTMLArr[$y]);
						$tmpHTML = str_replace('$playerKills', $query->playerKills[$x], $tmpHTML);
						$outputHTML .= rtrim(str_replace('$playerTime', $query->playerTime[$x], $tmpHTML));
						if (++$x >= $numPlayers) break 2;
					}
				}
			}

			$outputHTML .= substr($pageHTML,$end);
			$pageHTML = $outputHTML;
			//End Processing Players
		}
	}

	$outputHTML = "\n\n";
	if (mb_strlen($query->error) > 0) {
		$outputHTML = "<!-- " . $query->error . " -->\n";
	}
	if (mb_strlen($query->IError) > 0) {
		$outputHTML = "<!-- " . $query->IError . " -->\n";
	}
	if (mb_strlen($query->PError) > 0) {
		$outputHTML = "<!-- " . $query->PError . " -->\n";
	}
	if (mb_strlen($query->RError) > 0) {
		$outputHTML = "<!-- " . $query->RError . " -->\n";
	}
	$outputHTML .= $pageHTML;

	//Add slashes so eval doesn't break it
	$outputHTML = addslashes($outputHTML);

	//Parse the template to replace variables with their values
	eval("\$outputHTML=\"$outputHTML\";");

	//Calculate the full processing time
	$processtime = round(getMicroTime() - $starttime, 6);

	//Add the times to the bottom as a comment
	$outputHTML .= "\n<!-- Query Time: " . $querytime . " s - Processing Time: " . $processtime . " s -->\n\n";

	//Send parsed file to the browser
	echo $outputHTML;
}

?>