<?php

 /*
  * php Battlefield 2 sig script
  * Copyright 2005, Nathan Lockett
  * 
  * 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, and provided that the above
  * copyright and permission notice is included with all distributed
  * copies of this or derived software.
  *
  * 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.
  *
  * A copy of the GNU General Public License is available from the GNU
  * website at the following URL: http://www.gnu.org/licenses/gpl.txt
  *
  * Modified by MrNiceGuy for compability with ABR www.bf2scripts.com
  *
  */

include("config.php");
require('win2uni.php');
header("Content-type: image/png; charset=windows-1251");

function xml2array($text) {
	$reg_exp = '/<(.*?)>(.*?)<\/\\1>/s';
	preg_match_all($reg_exp, $text, $match);
	foreach ($match[1] as $key=>$val) {
		if ( preg_match($reg_exp, $match[2][$key]) ) {
			$array[$val][] = xml2array($match[2][$key]);
		} else {
			$array[$val] = $match[2][$key];
		}
	}
	return $array;
} 

//handy dandy little function for making the string centered, and making it fit.
function imagestringcentered ($img,$font,$xoffset,$cy,$text,$color) {
 while (strlen($text) * imagefontwidth($font) > imagesx($img)-$xoffset) {
  if ($font > 1) { $font--; }
  else { break; }
 }  
 imagestring($img,$font,(imagesx($img)-$xoffset) / 2 - strlen($text) * imagefontwidth($font) / 2 + $xoffset,$cy,$text,$color);
}
//Make the text have a transparent background behind it
function imagestringtransparent ($img,$font,$x,$y,$text,$color,$opacity) {
	$width = strlen($text) * imagefontwidth($font);
	$height = imagefontheight($font);
	$boxcolor = imagecolorallocatealpha($img, 0, 0, 0, $opacity);
	imagefilledrectangle($img,$x, $y, $x + $width, $y + $height, $boxcolor);
	imagestring($img, $font, $x, $y, $text, $color);
	
}

function formatduration($time) {
return str_pad(intval(intval($time) / 3600),2,"0",STR_PAD_LEFT)." ч. " 
. str_pad(intval(($time / 60) % 60),2,"0",STR_PAD_LEFT)." мин.";
}

//Map converter
function mapconverter($mapnumber) {
$mapname[0] = "Kubra Dam";
$mapname[1] = "Mashtuur City";
$mapname[2] = "Operation Clean Sweep";
$mapname[3] = "Zatar Wetlands";
$mapname[4] = "Strike at Karkand";
$mapname[5] = "Sharqi Peninsula";
$mapname[6] = "Gulf of Oman";
$mapname[100] = "Daqing Oilfields";
$mapname[101] = "Dalian Plant";
$mapname[102] = "Dragon Valley";
$mapname[103] = "FuShe Pass";
$mapname[104] = "Dalian Plant";
$mapname[105] = "Songhua Stalemate";
$mapname[300] = "Devils Perch";
$mapname[301] = "Iron Gator";
$mapname[302] = "Night Flight";
$mapname[303] = "Warlord";
$mapname[304] = "Leviathan";
$mapname[305] = "Mass Destruction";
$mapname[306] = "Surge";
$mapname[307] = "Ghost Town";
$mapname[601] = "Wake Island";
return $mapname[$mapnumber];
}

//Kit converter
function kitconverter($kitnumber) {
$kitname[0] = win2uni('Противотанковые');
$kitname[1] = win2uni('Штурмовик');
$kitname[2] = win2uni('Инженер');
$kitname[3] = win2uni('Медик');
$kitname[4] = win2uni('Спецназ');
$kitname[5] = win2uni('Поддержка');
$kitname[6] = win2uni('Снайпер');
return $kitname[$kitnumber];
}

//Vehicle Converter
function vehicleconverter($vehiclenumber) {
$vehiclename[0] = win2uni('Танк');
$vehiclename[1] = win2uni('Самолет');
$vehiclename[2] = win2uni('ПВО');
$vehiclename[3] = win2uni('Вертолет');
$vehiclename[4] = win2uni('Джип');
$vehiclename[5] = win2uni('Артиллерия');
$vehiclename[6] = win2uni('ПТО');
return $vehiclename[$vehiclenumber];
}

//Weapon Converter
function weaponconverter($weaponnumber) {
$weaponname[0] = win2uni('Штурм.винтовка');
$weaponname[1] = win2uni('Гранатомет');
$weaponname[2] = win2uni('Винтовка');
$weaponname[3] = win2uni('Ручной пулемет');
$weaponname[4] = win2uni('Снайп.винтовка');
$weaponname[5] = win2uni('Пистолет');
$weaponname[6] = win2uni('Ракеты');
$weaponname[7] = win2uni('Тяж. пулемет');
$weaponname[8] = win2uni('Дробовик');
$weaponname[9] = win2uni('Нож');
$weaponname[10] = win2uni('Дефибриллятор');
$weaponname[11] = win2uni('Взрывчатка');
$weaponname[12] = win2uni('Ручн.гранаты');
$weaponname[13] = win2uni('Лук');
return $weaponname[$weaponnumber];
}

$pid = $_GET["id"]; 
$mode = $_GET["image"];
$theme = $_GET["theme"];
if ($mode == "") {
	$mode = $defaultmode;
}
if ($pid == "") {
	/*$error = "No PID Specified";
	$mode = "error";
	include("themes/".$theme."/theme.php"); 
	exit;*/
	$pid = $defaultpid; //Player ID
}
if ($theme == "") { 
    $theme = "default";
} 
if ($AllowedPID[0] != "any") {
	if (!in_array($pid, $AllowedPID)) {
		$error = "PID $pid Not Authorized";
		$mode = "error";
		include("themes/".$theme."/theme.php"); 
		exit;
	}
}
$cachefilename = $statdir.$pid.".xml";
if ((!file_exists($cachefilename)) || ((time() - filemtime($cachefilename)) > $cachetime)) {

$filename = $asp . "/getplayerinfo.aspx?weapon=".$weaponnumbers."&kit=".$kitnumbers."&map=".$mapnumbers."&army=".$armynumbers."&vehicle=".$vehiclenumbers."&pid=".$pid."&info=".$infotoget.",rank"; // rank added to the end because the last stat always gets f'ed up for some reason so its a dummy stat"
ini_set("user_agent","GameSpyHTTP/1.0");
$fp = @fopen ($filename, "r");
		if (!$fp) {
		//Old Error Handler left incase someone wants it to do this instead of just reading the cache
		/*$error = "BF2 Stats Site Down.";
		$mode = error;
		include("themes/".$theme."/theme.php");
		exit;
		*/
		if (!file_exists($cachefilename)) {
		$error = "BF2Web Down and no cache file exists.";
		$mode = error;
		include("themes/".$theme."/theme.php");
		exit;
		}
		//read the cache for the stats
	$xmlfile = @fopen($cachefilename, "r");
	if (!$xmlfile) {
		$error = "Error Reading $cachefilename";
		$mode = "error";
		include("themes/".$theme."/theme.php"); 
		exit;
	}
	while(!feof($xmlfile)) {
		$xmldoc .= fread($xmlfile,4096);
	}
	fclose($xmlfile);
	$thestats = xml2array($xmldoc);		
	//end code for reading stat cache
	$namedstats = $thestats['stats'][0]['info'][0];
	$namedawards = $thestats['stats'][0]['awards'][0];
	$namedleader = $thestats['stats'][0]['leaderboard'][0];
	$namedunlocks = $thestats['stats'][0]['unlocks'][0];
		//end code for reading stat cache
		} else {
		$_xml ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n  <stats>\r\n    <info>\r\n";
		while (!feof ($fp)) { 
		    $content = fgets( $fp, 4096 );
		    //get names 
		    if (ereg("E\t107", $content) == true ) {
		    $error = "Ошибка. Неверный PID";
			$mode = "error";
			include("themes/".$theme."/theme.php"); 
			exit;
		    }
		    if (ereg("H\tpid", $content) == true ) {
		    $statnames = explode("\t",$content); //load up the names of the stats so that they can be used for the naming of the array
		   	}			
			//real stats 
			//start the first part of the xml file

		    if (ereg($pid, $content) == true ) {
				$stats = explode("\t",$content); //make the array with the stats
				//it goes to one less than the count becuase the last one is one i added since the last one always gets messed up for some reason
				//it also skips the first one because that is H (not a stat) from using explode it just picks this one up
				for($i = 1; $i<count($stats)-1; $i++ ) {
					$namedstats[$statnames[$i]] = "$stats[$i]"; //add the stat into a named array so its more easily configured.
					//begin xml generation code				
					$_xml .="\t  <".$statnames[$i].">" . $stats[$i] . "</".$statnames[$i].">\r\n";
				}
			}
		}
			fclose ($fp);
		$_xml .="    </info>\r\n    <awards>\r\n";
		}
		//award part
		$awardfilename = $asp . "/getawardsinfo.aspx?pid=".$pid;
		$afp = @fopen ($awardfilename, "r");
		if (!$afp) {
		} else {
		while (!feof ($afp)) { 
		    $content = fgets( $afp, 4096 );
		    if (ereg("D\t([0-9]{7})\t([0-9]*)", $content, $awards)) {
				//echo "1:".$awards[1]." 2:".$awards[2]."\n";
				if ($awards[1] != $pid)
				{
				$namedawards[$awards[1]] = $awards[2]; //add the stat into a named array so its more easily configured.
				//begin xml generation code
				$_xml .="\t  <".$awards[1].">" . $awards[2] . "</".$awards[1].">\r\n";
				}
			}
			}
		}
			fclose ($afp);
			
			
			
		$_xml .="    </awards>\r\n    <unlocks>\r\n"; 
		//Unlocks  part 
		$unlocksfilename = $asp . "/getunlocksinfo.aspx?pid=".$pid;
		$ufp = @fopen ($unlocksfilename, "r"); 
		if (!$ufp) { 
		} else { 
		while (!feof ($ufp)) { 
			$content = fgets( $ufp, 4096 ); 
			if (ereg("D\t([0-9]{2})\t([ns])", $content, $unlocks)) { 
				$namedunlocks[$unlocks[1]] = $unlocks[2]; //add the stat into a named array so its more easily configured. 
				//begin xml generation code 
				$_xml .="\t  <".$unlocks[1].">" . $unlocks[2] . "</".$unlocks[1].">\r\n"; 
			} 
		} 
		} 
	fclose ($ufp); 
			
			
		$_xml .="    </unlocks>\r\n    <leaderboard>\r\n";
		//end awards
		//leaderboard part
		$leaderfilename = $asp . "/getleaderboard.aspx?pid=".$pid."&type=score&id=overall";
		$lfp = @fopen ($leaderfilename, "r");
		if (!$lfp) {
		} else {
		while (!feof ($lfp)) { 
			$content = fgets( $lfp, 4096 );
		    if (ereg("H\tn\tpid", $content) == true ) {
				$leadernames = explode("\t",$content); //load up the names of the stats so that they can be used for the naming of the array
		   	}			
			//real stats 
			//start the first part of the xml file

		    if (ereg($pid, $content) == true ) {
				$leader = explode("\t",$content); //make the array with the stats
				//it also skips the first one because that is H (not a stat) from using explode it just picks this one up
				for($i = 1; $i<count($leader); $i++ ) {
					if ($i == (count($leader)-1)) {
					//this gets rid of the line break the last one has
					$leader[$i] = str_replace("\n", "", $leader[$i]);
					$leadernames[$i] = str_replace("\n", "", $leadernames[$i]);
					}
					$namedleader[$leadernames[$i]] = "$leader[$i]"; //add the stat into a named array so its more easily configured.
					//begin xml generation code				
					$_xml .="\t  <".$leadernames[$i].">" . $leader[$i] . "</".$leadernames[$i].">\r\n";
				}
			}
			}
		}
			fclose ($lfp);
		//end leaderboard
		

			$_xml .="    </leaderboard>\r\n  </stats>\r\n</xml>";
		$xmlcachefile = @fopen($cachefilename, "w");
		if (!$xmlcachefile) {
			$error = "Error Opening $cachefilename for writing";
			$mode = "error";
			include("themes/".$theme."/theme.php"); 
			exit;
		}

			if(fwrite($xmlcachefile, $_xml) === False) {
				$error = "Error Writing $cachefilename";
				$mode = "error";
				include("themes/".$theme."/theme.php"); 
				exit;
			}
			fclose($xmlcachefile);

		
} else {
		//read the cache for the stats
	$xmlfile = @fopen($cachefilename, "r");
	if (!$xmlfile) {
		$error = "Error Reading $cachefilename";
		$mode = "error";
		include("themes/".$theme."/theme.php"); 
		exit;
	}
	while(!feof($xmlfile)) {
		$xmldoc .= fread($xmlfile,4096);
	}
	fclose($xmlfile);
	$thestats = xml2array($xmldoc);		
		//end code for reading stat cache
	$namedstats = $thestats['stats'][0]['info'][0];
	$namedawards = $thestats['stats'][0]['awards'][0];
	$namedleader = $thestats['stats'][0]['leaderboard'][0];
	$namedunlocks = $thestats['stats'][0]['unlocks'][0];
	}
//rank converter
switch ($namedstats['rank']) {
    case 0: 
      //  $rank = "Private"; 
     	  $rank=win2uni('Рядовой: ');
        $ranknum = 150; 
        $prevnum = 0; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 1: 
      //  $rank = "Sergeant"; 
	$rank=win2uni('Ефрейтор: ');
        $ranknum = 500; 
        $prevnum = 150; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 2: 
//        $rank = "Lance Corporal"; 
     	  $rank=win2uni('Мл.Сержант: ');
        $ranknum = 800; 
        $prevnum = 500; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 3: 
//        $rank = "Corporal"; 
     	  $rank=win2uni('Сержант: ');
        $ranknum = 2500; 
        $prevnum = 800; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 4: 
//        $rank = "Sergeant"; 
     	  $rank=win2uni('Ст.Сержант: ');
        $ranknum = 5000; 
        $prevnum = 2500; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 5: 
//        $rank = "Staff Sergeant"; 
     	  $rank=win2uni('Старшина: ');
        $ranknum = 8000; 
        $prevnum = 5000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 6: 
//        $rank = "Gunnery Sergeant"; 
     	  $rank=win2uni('Прапорщик: ');
        $ranknum = 20000; 
        $prevnum = 8000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 7: 
//        $rank = "Master Sergeant"; 
     	  $rank=win2uni('Лейтенант: ');
        $ranknum = 50000; 
        $prevnum = 20000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 8: 
//        $rank = "First Sergeant"; 
     	  $rank=win2uni('Майор: ');
        $ranknum = 50000; 
        $prevnum = 20000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 9: 
//        $rank = "Master Gunnery Sergeant"; 
     	  $rank=win2uni('Подполковник: ');
        $ranknum = 250000; 
        $prevnum = 50000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 10: 
//        $rank = "Sergeant Major"; 
     	  $rank=win2uni('Полковник: ');
        $ranknum = 250000; 
        $prevnum = 50000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 11: 
//        $rank = "Sergeant Major of the Corps"; 
     	  $rank=win2uni('Генерал: ');
        $ranknum = 250000; 
        $prevnum = 0; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
         
} 
$format = '%m/%d %r';
$LastBattle = strftime ($format,$namedstats['lbtl']);
$playtime = str_pad(intval(intval($namedstats['time']) / 3600),2,"0",STR_PAD_LEFT)." hr. " 
. str_pad(intval(($namedstats['time'] / 60) % 60),2,"0",STR_PAD_LEFT)." min.";

//make any blank medals have a # of 0
if ($namedawards[2051907] == "") { $namedawards[2051907] = 0; }
if ($namedawards[2051919] == "") { $namedawards[2051919] = 0; }
if ($namedawards[2051902] == "") { $namedawards[2051902] = 0; }

include("themes/".$theme."/theme.php");
?>
