<?php
#
# HLstatsX - Real-time player and clan rankings and statistics for Half-Life 2
# http://www.hlstatsx.com/
# Copyright (C) 2005-2007 Tobias Oetzel (Tobi@hlstatsx.com)
#
# HlstatsX is an enhanced version of HLstats made by Simon Garner
# HLstats - Real-time player and clan rankings and statistics for Half-Life
# http://sourceforge.net/projects/hlstats/
# Copyright (C) 2001  Simon Garner
#             
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

  foreach ($_SERVER as $key => $entry) {
    if ($key !== "HTTTP_COOKIE") {
      $search_pattern  = array("/<script>/", "/<\/script>/", "/[^A-Za-z0-9.\-\/=:;_?#&~]/");
      $replace_pattern = array("", "", "");
      $entry = preg_replace($search_pattern, $replace_pattern, $entry);
      
      if ($key == "PHP_SELF") {
        if ((strrchr($entry, "/") !== "/hlstats.php") &&
			(strrchr($entry, "/") !== "/ingame.php") &&
			(strrchr($entry, "/") !== "/show_graph.php") &&
			(strrchr($entry, "/") !== "/sig.php") &&
			(strrchr($entry, "/") !== "/sig2.php") &&
			(strrchr($entry, "/") !== "/index.php") &&
			(strrchr($entry, "/") !== "/status.php") &&
			(strrchr($entry, "/") !== "/top10.php") &&
			(strrchr($entry, "/") !== "/config.php") &&
			(strrchr($entry, "/") !== "/") &&
			($entry !== "")) {
          header("Location: http://".$_SERVER['HTTP_HOST']."/hlstats.php");    
          exit;
        }    
      }
      $_SERVER[$key] = $entry;
	}
  }

  function valid_request($str, $numeric)  {
    $search_pattern  = array("/[^A-Za-z0-9\[\]*.,=()!\"$%&^`´':;ß²³#+~_\-|<>\/@{}äöüÄÖÜ ]/");
    $replace_pattern = array("");
    $str             = preg_replace($search_pattern, $replace_pattern, $str);
    if ($numeric == 0) 
      return htmlentities(strip_tags($str), ENT_QUOTES, "UTF-8");
    else {
      $temp = htmlentities(strip_tags($str), ENT_QUOTES, "UTF-8");
      if (is_numeric($str) === true) 
        return $temp;
      else
        return -1;  
    }    
  }  

 require("config.php");

 header("Content-Type: text/html; charset=utf-8");

	// Allows HLstats to work with register_globals Off
	if ( function_exists('ini_get') ) {
		$globals = ini_get('register_globals');
	} else {
		$globals = get_cfg_var('register_globals');
	}
	if ($globals != 1) {
		@extract($_SERVER, EXTR_SKIP);
		@extract($_COOKIE, EXTR_SKIP);
		@extract($_POST, EXTR_SKIP);
		@extract($_GET, EXTR_SKIP);
		@extract($_ENV, EXTR_SKIP);
	}

	// Check PHP configuration

	if (version_compare(phpversion(), "4.1.0", "<"))
	{
		error("HLstats requires PHP version 4.1.0 or newer (you are running PHP version " . phpversion() . ").");
	}

	if (!get_magic_quotes_gpc())
	{
		error("HLstats requires <b>magic_quotes_gpc</b> to be <i>enabled</i>. Check your php.ini or refer to the PHP manual for more information.");
	}

	if (get_magic_quotes_runtime())
	{
		error("HLstats requires <b>magic_quotes_runtime</b> to be <i>disabled</i>. Check your php.ini or refer to the PHP manual for more information.");
	}

	// this doesn't work with php 4.0.3+
	/*if (!ini_get("track_vars"))
	{
		error("HLstats requires <b>track_vars</b> to be <i>enabled</i>. Check your php.ini or refer to the PHP manual for more information.");
	}*/

	// do not report NOTICE warnings
    error_reporting(E_ALL ^ E_NOTICE);


  // Test if flags exists
  function flag_exists($flag, $default="0.gif")  {
    global $g_options;
    
    if ($flag == $default)
      return $flag;
      
    $url = $g_options["imgdir"] .  "/flags/". $flag;
    if ($g_options["imgpath"])
      $path = $g_options["imgpath"] . "/flags/".$flag;
    else {
      // figure out absolute path of image
      if (!ereg("^/", $g_options["imgdir"]))  {
         ereg("(.+)/[^/]+$", $_SERVER["SCRIPT_NAME"], $regs);
         $path = $regs[1] . "/" . $url;
      } else
        $path = $url;
      $path = $_SERVER["DOCUMENT_ROOT"] . $path;
    }
    
    if (file_exists($path))
      return $flag;  
    else
      return $default; 
  }  


	///
	/// Classes
	///

	// Load database classes
	require(INCLUDE_PATH . "/db.inc");


  // array getOptions (void)
  //
  // Retrieves HLstats option and style settings from the database.
  //

  function getOptions()
  {
    global $db;

    $result  = $db->query("SELECT keyname, value FROM hlstats_Options");
    $numrows = $db->num_rows($result);

    if ($numrows)
    {
        while ($rowdata = $db->fetch_row($result))
        {
            $options[$rowdata[0]] = $rowdata[1];
        }
        return $options;
    }
    else
    {
        error("Warning: Could not find any options in table " .
            "<b>hlstats_Options</b>, database <b>" . DB_NAME . "</b>. Check HLstats configuration.");
        return array();
    }
  }
    

	////
	//// Initialisation
	////

	define("VERSION", "1.20 RC2");

	$db_classname = "DB_" . DB_TYPE;
	$db = new $db_classname;

	$g_options = getOptions();

  if (!$g_options["scripturl"])
    $g_options["scripturl"] = $PHP_SELF;
    

  $g_options["scripturl"] = str_replace("/status.php", "", $g_options["scripturl"]);

	////
	//// Main
	////
    
    $game = "css";  
    if ((isset($_GET['game'])) && (is_string($_GET['game'])))
      $game = valid_request($_GET['game'], 0);
    $width = 185;  
    if ((isset($_GET['width'])) && (is_numeric($_GET['width'])))
      $width = valid_request($_GET['width'], 1);
    $server_id = 1;  
    if ((isset($_GET['server_id'])) && (is_numeric($_GET['server_id'])))
      $server_id = valid_request($_GET['server_id'], 1);
    $show_logo = 1;
    if ((isset($_GET['show_logo'])) && (is_string($_GET['show_logo'])))
      $show_logo = valid_request($_GET['show_logo'], 1);
    $show_password = "";  
    if ((isset($_GET['show_password'])) && (is_string($_GET['show_password'])))
      $show_password = valid_request($_GET['show_password'], 1);
    $map_image = 1;
    if ((isset($_GET['map_image'])) && (is_numeric($_GET['map_image'])))
      $map_image = valid_request($_GET['map_image'], 1);
    $show_summary = 1;
    if ((isset($_GET['show_summary'])) && (is_numeric($_GET['show_summary'])))
      $show_summary = valid_request($_GET['show_summary'], 1);
    $show_players = 1;
    if ((isset($_GET['show_players'])) && (is_numeric($_GET['show_players'])))
      $show_players = valid_request($_GET['show_players'], 1);
    $show_map_wins = 0;
    if ((isset($_GET['show_map_wins'])) && (is_numeric($_GET['show_map_wins'])))
      $show_map_wins = valid_request($_GET['show_map_wins'], 1);
    $top_players = 0;
    if ((isset($_GET['show_top'])) && (is_numeric($_GET['show_top'])))
      $top_players = valid_request($_GET['show_top'], 1);
    $background_color = "ABCCD6";  
    if (isset($_GET['bg_color']))
      $background_color = valid_request($_GET['bg_color'], 0);
    $body_color = "ECF8FF";  
    if ((isset($_GET['body_color'])) && (is_string($_GET['body_color'])))
      $body_color = valid_request($_GET['body_color'], 0);
    $color = "000000";  
    if ((isset($_GET['color'])) && (is_string($_GET['color'])))
      $color = valid_request($_GET['color'], 0);
    $small_fonts = 0;  
    if ((isset($_GET['small_fonts'])) && (is_numeric($_GET['small_fonts'])))
      $small_fonts = valid_request($_GET['small_fonts'], 1);
    $show_flags = 1;  
    if ((isset($_GET['show_flags'])) && (is_numeric($_GET['show_flags'])))
      $show_flags = valid_request($_GET['show_flags'], 1);
    $border_color = "ABCCD6";  
    if (isset($_GET['border_color']))
      $border_color = valid_request($_GET['border_color'], 0);
      
      
    // entries
    $result  = $db->query("SELECT * FROM hlstats_Servers WHERE serverId='$server_id'");
    $server_data = $db->fetch_array($result);
    
    if ($server_data['address'] != "")  {
        
        echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
        if ($small_fonts == 1) {
          echo '<html><head><title>HLstatsX</title>';
          echo '<style type="text/css">*{margin:0px; padding:0px;}</style>';
          echo '<link rel="stylesheet" type="text/css" href="hlstats.css">';
          echo '</head><body style="background:#'.$body_color.';color:#'.$color.';margin:0px;padding:0px;font-family: Verdana;font-size:9pt">';
        } else {
          echo '<html><head><title>HLstatsX</title>';
          echo '<style type="text/css">*{margin:0px; padding:0px;}</style>';
          echo '<link rel="stylesheet" type="text/css" href="hlstats.css">';
          echo '</head><body style="background:#'.$body_color.';color:#'.$color.';margin:0px;padding:0px;font-family: Verdana;font-size:10pt">';
        }  
        
        echo '<table border="0" cellpadding="0" cellspacing="0" style="border:1px solid #A8B090;background:#'.$background_color.';color:#'.$color.';width:'.$width.'px">';
        if ($show_logo > 0) {
          echo '<tr style="background-image:url('.$g_options['imgdir'].'/title-background.gif);"><td align="center" colspan="3">';
          echo '<a target="_blank" href="http://www.hlstatsx.com" style="display:block;"><img src="'.$g_options['imgdir'].'/title.gif" style="border:0px" alt="Realtime player statistics for Halflife2 Source Engine" title="Realtime player statistics for Halflife2 Source Engine" /></a>';
        } else {   
          echo '<tr style="background-image:url('.$g_options['imgdir'].'/title-background.gif);"><td align="center" colspan="3">';
          echo '<a target="_blank" href="http://www.hlstatsx.com" title="Realtime player statistics for Halflife2 Source Engine" style="color:white;text-decoration:none;"><strong>www.hlstatsx.com</strong></a>';
        }  
        echo '</td></tr>';

        echo '<tr><td align="center" colspan="2">';
        echo '<a target="_blank" href="'.$g_options['scripturl'].'" title="'.$g_options['sitename'].'" style="color:#'.$color.';text-decoration:none;"><small><strong>'.$server_data['name'].'</strong></small></a>';
        echo '</td></tr>';
        echo '<tr><td align="center" colspan="2">';
        echo '<a href="hlsw://'.$server_data['address'].':'.$server_data['port'].'" title="Watch with HLSW" style="color:#'.$color.';text-decoration:none;"><small><strong>'.$server_data['address'].':'.$server_data['port'].'</strong></small></a>';
        echo '</td></tr>';
        
        if ($show_password != "")  {
        echo '<tr><td align="center" colspan="2">';
        echo '<small><strong>Password:&nbsp;'.$show_password.'</strong></small>';
        echo '</td></tr>';
        }    
        
        if ($map_image == 1) {
          if (file_exists($g_options['imgpath'].'/maps/'.$game.'/'.$server_data['act_map'].'.jpg')) {  
            echo '<tr><td align="center" colspan="2">';
            echo '<a target="_blank" href="'.$g_options['siteurl'].'"><img src="'.$g_options['imgdir'].'/maps/'.$game.'/'.$server_data['act_map'].'.jpg" style="width:'.$width.'px;border:0px" alt="'.$g_options['sitename'].'" title="'.$g_options['sitename'].'" /></a>'; 
            echo '</td></tr>';
          } else {
            echo '<tr><td align="center" colspan="2">';
            echo '<a target="_blank" href="'.$g_options['siteurl'].'"><img src="'.$g_options['imgdir'].'/noimage.gif" style="width:'.$width.'px;border:0px" alt="'.$g_options['sitename'].'" title="'.$g_options['sitename'].'" /></a>'; 
            echo '</td></tr>';
          }   
        }
        
        if ($show_summary == 1)  {
          echo '<tr><td align="left">';
          echo '<small style="padding-left:3px">Players</small>'; 
          echo '</td><td align="right">';
          echo '<small style="padding-right:3px;font-weight:bold;">'.number_format($server_data['players']).'</small>'; 
          echo '</td></tr>';
    
          echo '<tr><td align="left">';
          echo '<small style="padding-left:3px">Kills</small>'; 
          echo '</td><td align="right">';
          echo '<small style="padding-right:3px;font-weight:bold;">'.number_format($server_data['kills']).'</small>'; 
          echo '</td></tr>';
    
          if ($server_data['headshots'] > 0)  {
            echo '<tr><td align="left">';
            echo '<small style="padding-left:3px">Headshots</small>'; 
            echo '</td><td align="right">';
            echo '<small style="padding-right:3px;font-weight:bold;">'.number_format($server_data['headshots']).'</small>'; 
            echo '</td></tr>';
          }  

        }    
        
        echo '<tr><td align="left">';
        echo '<small style="padding-left:3px">Map</small>'; 
        echo '</td><td align="right">';
        echo '<small style="padding-right:3px;font-weight:bold;">'.$server_data['act_map'].'</small>'; 
        echo '</td></tr>';
        $stamp = time()-$server_data['map_started'];
        $hours = sprintf("%02d", floor($stamp / 3600));
        $min   = sprintf("%02d", floor(($stamp % 3600) / 60));
        $sec   = sprintf("%02d", floor($stamp % 60)); 
        echo '<tr><td align="left">';
        echo '<small style="padding-left:3px">Map Time</small>'; 
        echo '</td><td align="right">';
        echo '<small style="padding-right:3px;font-weight:bold;">'.$hours.':'.$min.':'.$sec.'</small>'; 
        echo '</td></tr>';
        echo '<tr><td align="left">';
        echo '<small style="padding-left:3px">Players</small>'; 
        echo '</td><td align="right">';
        echo '<small style="padding-right:3px;font-weight:bold;">'.$server_data['act_players'].'/'.$server_data['max_players'].'</small>'; 
        echo '</td></tr>';
        
        if ($show_players > 0)  {
            $team_colors = array("CT"        => array("#D2E8F7", "#0080C0", "CT"),
                                 "TERRORIST" => array("#FFD5D5", "#FF2D2D", "TS"),
                                 "Allies"    => array("#C1FFC1", "#006600", "AL"),
                                 "Axis"      => array("#FFD5D5", "#FF2D2D", "AX")
                                );    

            echo '<tr><td colspan="2"><table border="0" cellpadding="0" cellspacing="0" style="padding:0px;margin:0px;width:100%">';
            $players = $db->query("SELECT * FROM hlstats_Livestats WHERE server_id=".$server_id." ORDER BY kills DESC");
            
            $teama_wins      = 0;
            $teama_kills     = 0;
            $teama_deaths    = 0;
            $teama_time      = 0;
            $teama_headshots = 0;
            $teama_pings     = 0;
            $teama_skill     = 0;
            $teama_shots     = 0;
            $teama_hits      = 0;
            
            $teamb_wins      = 0;
            $teamb_kills     = 0;
            $teamb_deaths    = 0;
            $teamb_time      = 0;
            $teamb_headshots = 0;
            $teamb_pings     = 0;
            $teamb_skill     = 0;
            $teamb_shots     = 0;
            $teamb_hits      = 0;

            $teama_players = array();
            $teamb_players = array();
            $co_players = array();
            while ($pl_rowdata = $db->fetch_array())
            {
                 if (($pl_rowdata['team'] == "CT") || ($pl_rowdata['team'] == "Allies")){
                   if ($pl_rowdata['connected'] > 0) {
                     $teama_players[]  = $pl_rowdata;
                     $teama_name       = $pl_rowdata['team'];       
                     $teama_kills     += $pl_rowdata['kills'];
                     $teama_deaths    += $pl_rowdata['deaths'];
                     $teama_headshots += $pl_rowdata['headshots'];
                     $teama_pings     += $pl_rowdata['ping'];
                     $teama_skill     += $pl_rowdata['skill'];
                     $teama_shots     += $pl_rowdata['shots']; 
                     $teama_hits      += $pl_rowdata['hits']; 
                     $teama_time      += time()-$pl_rowdata['connected'];
                   } else
                   $co_players[] = $pl_rowdata;  
                 } else if (($pl_rowdata['team'] == "TERRORIST") || ($pl_rowdata['team'] == "Axis")){
                   if ($pl_rowdata['connected'] > 0) {
                     $teamb_players[]  = $pl_rowdata;
                     $teamb_name       = $pl_rowdata['team'];       
                     $teamb_kills     += $pl_rowdata['kills'];
                     $teamb_deaths    += $pl_rowdata['deaths'];
                     $teamb_headshots += $pl_rowdata['headshots'];
                     $teamb_pings     += $pl_rowdata['ping'];
                     $teamb_skill     += $pl_rowdata['skill'];
                     $teamb_shots     += $pl_rowdata['shots']; 
                     $teamb_hits      += $pl_rowdata['hits']; 
                     $teamb_time      += time()-$pl_rowdata['connected'];
                   } else
                   $co_players[] = $pl_rowdata;  
                 } else
                   $co_players[] = $pl_rowdata;  
            }
        
            $color_team_a = "";
            if (isset($team_colors[$teama_name])) {
              $color_teama        = "background:".$team_colors[$teama_name][0].";color:".$team_colors[$teama_name][1];
              $color_teama_border = "background:".$team_colors[$teama_name][0].";color:".$team_colors[$teama_name][1].";border-top:1px ".$team_colors[$teama_name][1]." solid";
              $teama_display_name  = $team_colors[$teama_name][2];
            }     
        
            $color_team_b = "";
            if (isset($team_colors[$teamb_name])) {
              $color_teamb        = "background:".$team_colors[$teamb_name][0].";color:".$team_colors[$teamb_name][1];
              $color_teamb_border = "background:".$team_colors[$teamb_name][0].";color:".$team_colors[$teamb_name][1].";border-top:1px ".$team_colors[$teamb_name][1]." solid";
              $teamb_display_name  = $team_colors[$teamb_name][2];
            }
            
            $color_co = "background:#EFEFEF;color:#000";     

            $j=0;
            while (isset($teama_players[$j])) {        
              echo '<tr style="'.$color_teama.'"><td align="left" width="86%" style="padding-left:3px;">';
              $cut_pos = 15;
              if ($small_fonts == 1)
                $cut_pos += 10;
              $display_name = $teama_players[$j]['name'];
              if (strlen($teama_players[$j]['name'])> $cut_pos)
                $display_name = substr($teama_players[$j]['name'], 0, $cut_pos);
              echo '<a class="'.strtolower($teama_name).'_link" target="_blank" href="'.$g_options["scripturl"].'/hlstats.php?mode=playerinfo&amp;player='.$teama_players[$j]['player_id'].'">';
              if ($show_flags == 1)            
                echo '<img src="'.$g_options["imgdir"].'/flags/'.flag_exists(strtolower($teama_players[$j]['cli_flag']).".gif").'" style="border:0px;" alt="'.ucfirst(strtolower($teama_players[$j]['cli_country'])).'" title="'.ucfirst(strtolower($teama_players[$j]['cli_country'])).'">&nbsp;';   
              echo '<small title="'.htmlentities($teama_players[$j]['name'], ENT_COMPAT, "UTF-8").'" style="vertical-align:middle;">'.htmlentities($display_name, ENT_COMPAT, "UTF-8").'</small></a>';
              echo '</td><td align="right" width="7%" style="padding-right:3px">';
              echo '<small>'.$teama_players[$j]['kills'].'</small>';
              echo '</td><td align="right" width="7%">';
              echo '<small style="padding-right:3px">'.$teama_players[$j]['deaths'].'</small>';
              echo '</td></tr>'; 
              $j++;
            }  
            $j=0;
            while (isset($teamb_players[$j])) {        
              echo '<tr style="'.$color_teamb.'"><td align="left" width="86%" style="padding-left:3px;">';
              $cut_pos = 15;
              if ($small_fonts == 1)
                $cut_pos += 10;
              $display_name = $teamb_players[$j]['name'];
              if (strlen($teamb_players[$j]['name']) > $cut_pos)
                $display_name = substr($teamb_players[$j]['name'], 0, $cut_pos);
              echo '<a class="'.strtolower($teamb_name).'_link" target="_blank" href="'.$g_options["scripturl"].'/hlstats.php?mode=playerinfo&amp;player='.$teamb_players[$j]['player_id'].'">';
              if ($show_flags == 1)  {
                echo '<img src="'.$g_options["imgdir"].'/flags/'.flag_exists(strtolower($teamb_players[$j]['cli_flag']).".gif").'" style="border:0px;;" alt="'.ucfirst(strtolower($teamb_players[$j]['cli_country'])).'" title="'.ucfirst(strtolower($teamb_players[$j]['cli_country'])).'">&nbsp;';
              }     
              echo '<small title="'.htmlentities($teamb_players[$j]['name'], ENT_COMPAT, "UTF-8").'" style="vertical-align:middle;">'.htmlentities($display_name, ENT_COMPAT, "UTF-8").'</small></a>';
              echo '</td><td align="right" width="7%" style="padding-right:3px">';
              echo '<small>'.$teamb_players[$j]['kills'].'</small>';
              echo '</td><td align="right" width="7%">';
              echo '<small style="padding-right:3px">'.$teamb_players[$j]['deaths'].'</small>';
              echo '</td></tr>'; 
              $j++;
            }  
            $j=0;
            while (isset($co_players[$j])) {        
              echo '<tr style="'.$color_co.'">';
              echo '<td align="left" width="100%" style="padding-left:3px">';
              $cut_pos = 15;
              if ($small_fonts == 1)
                $cut_pos += 10;
              $display_name = $co_players[$j]['name'];
              if (strlen($co_players[$j]['name'])>$cut_pos)
                $display_name = substr($co_players[$j]['name'], 0, $cut_pos);
              echo '<a class="co_link" target="_blank" href="'.$g_options["scripturl"].'/hlstats.php?mode=playerinfo&amp;player='.$co_players[$j]['player_id'].'">';
              if ($show_flags == 1)            
                echo '<img src="'.$g_options["imgdir"].'/flags/'.flag_exists(strtolower($co_players[$j]['cli_flag']).".gif").'" style="border:0px;" alt="'.ucfirst(strtolower($co_players[$j]['cli_country'])).'" title="'.ucfirst(strtolower($co_players[$j]['cli_country'])).'">&nbsp;';   
              echo '<small title="'.htmlentities($co_players[$j]['name'], ENT_COMPAT, "UTF-8").'" style="vertical-align:middle;">'.htmlentities($display_name, ENT_COMPAT, "UTF-8").'</small></a>';
              echo '</td>';
              echo '<td align="right" width="7%" style="padding-right:3px">';
              echo '<small>'.$co_players[$j]['kills'].'</small>';
              echo '</td><td align="right" width="7%">';
              echo '<small style="padding-right:3px">'.$co_players[$j]['deaths'].'</small>';
              echo '</td>'; 
              echo '</tr>'; 
              $j++;
            }  
            if ((count($teama_players)==0) && (count($teamb_players)==0) && (count($co_players)==0)) {
              echo '<tr style="background:#EFEFEF;color:black"><td align="left" width="100%" colspan="3" style="padding-left:3px">';
              echo '<small>No Players</small>';
              echo '</td></tr>'; 
            }    
            echo '</table></td></tr>';

        }    
        
        if ((count($teama_players) > 0) || (count($teamb_players) > 0)) {
          if ($show_map_wins > 0)  {
            echo '<tr><td align="center" colspan="3">';
            echo '<small style="color:#0080C0;font-weight:bold;">'.$teama_display_name.'&nbsp;'.$server_data['map_ct_wins'].'&nbsp;</small><small style="color:black;">:&nbsp;</small><small style="color:#FF2D2D;font-weight:bold;">'.$server_data['map_ts_wins'].'&nbsp;'.$teamb_display_name.'</small>';
            echo '</td></tr>';
          }
        }  
        
        if ($top_players > 0)  {
          $query = "SELECT playerId, lastName, flag, country, skill, IFNULL(kills/deaths, '-') AS kpd, IFNULL(ROUND((hits / shots * 100), 1), 0.0) AS acc, ".
                   "IF(".MINACTIVITY." > (UNIX_TIMESTAMP() - last_event), ((100/".MINACTIVITY.") * (".MINACTIVITY." - (UNIX_TIMESTAMP() - last_event))), -1) as activity ".
                   "FROM hlstats_Players WHERE ".
                   "game='".$game."' AND hideranking=0 ".
                   "HAVING activity >= 0 ".
                   "ORDER BY skill DESC, kpd DESC LIMIT 0,".$top_players;
          $db->query($query);
          echo '<tr><td colspan="2"><br /><table border="0" cellpadding="0" cellspacing="0" style="width:100%">';
          echo '<tr><td align="center" colspan="2" style="border-bottom:1px solid black;padding-left:3px">';
          echo '<small><strong>TOP '.$top_players.' Players</strong></small>';
          echo '</td></tr>';
            
          while ($player = $db->fetch_array()) {
            echo '<tr><td align="left" width="85%" style="padding-left:3px">';
            $cut_pos = 15;
            if ($small_fonts == 1)
              $cut_pos += 10;
            $display_name = $player['lastName'];
            if (strlen($player['lastName']) > $cut_pos)
              $display_name = substr($player['lastName'], 0, $cut_pos);
            echo '<a target="_blank" style="color:#'.$color.';text-decoration:none;" href="'.$g_options["scripturl"].'/hlstats.php?mode=playerinfo&amp;player='.$player['playerId'].'">';
            if ($show_flags == 1) {
              if ($player['country'] == "")
                $player['country'] = "Unknown Country";               
              echo '<img src="'.$g_options["imgdir"].'/flags/'.flag_exists(strtolower($player['flag']).".gif").'" style="border:0px;" alt="'.ucfirst(strtolower($player['country'])).'" title="'.ucfirst(strtolower($player['country'])).'">&nbsp;';
            }     
            echo '<small title="'.htmlentities($player['lastName'], ENT_COMPAT, "UTF-8").'" style="vertical-align:middle;">'.htmlentities($display_name, ENT_COMPAT, "UTF-8").'</small></a>';
            echo '</td><td align="right" width="15%">';
            echo '<small>'.$player['skill'].'</small>';
            echo '</td></tr>'; 
          }
          echo '</table></td></tr>';
        }       
        
        echo '</table></body></html>';
    }    
    
    

?>

