<?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");

function xml2array($text) {
	$reg_exp = '/<(.*?)>(.*?)<\/\\1>/s.png';
	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)." hr. " 
. str_pad(intval(($time / 60) % 60),2,"0",STR_PAD_LEFT)." min.";
}

//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] = "Анти-Танк"; // "Anti-Tank";
$kitname[1] = "Штурмовик"; // "Assault";
$kitname[2] = "Инженер"; // "Engineer";
$kitname[3] = "Медик"; // "Medic";
$kitname[4] = "Спецназ"; // "Spec-Ops";
$kitname[5] = "Поддержка"; // "Support";
$kitname[6] = "Снайпер"; // "Sniper";
return $kitname[$kitnumber];
}

//Vehicle Converter
function vehicleconverter($vehiclenumber) {
$vehiclename[0] = "Танки"; // "Tank";
$vehiclename[1] = "Самолеты"; // "Plane";
$vehiclename[2] = "ПВО"; // "Air Defense";
$vehiclename[3] = "Вертолеты"; // "Helicopter";
$vehiclename[4] = "Транспортники"; // "Transport";
$vehiclename[5] = "Артиллерия"; // "Artillery";
$vehiclename[6] = "ПТУР"; // "Ground Defense";
return $vehiclename[$vehiclenumber];
}

//Weapon Converter
function weaponconverter($weaponnumber) {
$weaponname[0] = "Штурм. винтовки"; // "Assault Rifles";
$weaponname[1] = "Подствольники"; // "Grenade Launchers";
$weaponname[2] = "Карабины"; // "Carbines";
$weaponname[3] = "Пулеметы"; // "Light Machine Guns";
$weaponname[4] = "Снайп. винтовки"; // "Sniper Rifles";
$weaponname[5] = "Пистолеты"; // "Pistols";
$weaponname[6] = "Ракеты"; // "Rockets";
$weaponname[7] = "Полуавтоматы"; // "Submachine Guns";
$weaponname[8] = "Дробовики"; // "Shotguns";
$weaponname[9] = "Ножик"; // "Knife";
$weaponname[10] = "Дефибриллятор"; // "Defibrillator";
$weaponname[11] = "Взрывчатка"; // "Explosives";
$weaponname[12] = "Гранаты"; // "Hand Grenade";
$weaponname[13] = "Арбалет"; // "Crossbow";
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\"?>\r\n  <stats>\r\n    <info>\r\n";
		while (!feof ($fp)) { 
		    $content = fgets( $fp, 4096 );
		    //get names 
		    if (ereg("E\t107", $content) == true ) {
		    $error = "Error Invalid 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"; 
        $ranknum = 150; 
        $prevnum = 0; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 1: 
        $rank = "Private First Class"; 
        $ranknum = 500; 
        $prevnum = 150; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 2: 
        $rank = "Lance Corporal"; 
        $ranknum = 800; 
        $prevnum = 500; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 3: 
        $rank = "Corporal"; 
        $ranknum = 2500; 
        $prevnum = 800; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 4: 
        $rank = "Sergeant"; 
        $ranknum = 5000; 
        $prevnum = 2500; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 5: 
        $rank = "Staff Sergeant"; 
        $ranknum = 8000; 
        $prevnum = 5000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 6: 
        $rank = "Gunnery Sergeant"; 
        $ranknum = 20000; 
        $prevnum = 8000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 7: 
        $rank = "Master Sergeant"; 
        $ranknum = 50000; 
        $prevnum = 20000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 8: 
        $rank = "First Sergeant"; 
        $ranknum = 50000; 
        $prevnum = 20000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 9: 
        $rank = "Master Gunnery Sergeant"; 
        $ranknum = 60000; 
        $prevnum = 50000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 10: 
        $rank = "Sergeant Major"; 
        $ranknum = 60000; 
        $prevnum = 50000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 11: 
        $rank = "Sergeant Major of the Corps"; 
        $ranknum = 60000; 
        $prevnum = 50000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 12: 
        $rank = "2nd Lieutenant"; 
        $ranknum = 75000; 
        $prevnum = 60000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 13: 
        $rank = "1st Lieutenant"; 
        $ranknum = 90000; 
        $prevnum = 75000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 14: 
        $rank = "Captain"; 
        $ranknum = 115000; 
        $prevnum = 90000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 15: 
        $rank = "Major"; 
        $ranknum = 125000; 
        $prevnum = 115000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 16: 
        $rank = "Lieutenant Colonel"; 
        $ranknum = 150000; 
        $prevnum = 125000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 17: 
        $rank = "Colonel"; 
        $ranknum = 180000; 
        $prevnum = 150000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 
    case 18: 
        $rank = "Brigadier General"; 
        $ranknum = 200000; 
        $prevnum = 180000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break;
    case 19: 
        $rank = "Major General"; 
        $ranknum = 200000; 
        $prevnum = 180000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break; 	
    case 20: 
        $rank = "Lieutenant General"; 
        $ranknum = 200000; 
        $prevnum = 200000; 
        $prgdone = $namedstats['scor']-$prevnum; 
        $prgtotal = $ranknum-$prevnum; 
        break;
    case 21: 
        $rank = "General"; 
        $ranknum = 200000; 
        $prevnum = 200000; 
        $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");
?>
