<?php
##################
##  version 12  ##
##################

@extract($_GET);

//If the LFS player name has changed since registering LFS, edit the below file to 
//display the correct name and pull the correct stats.
include ("inc/userNameSwitch.php");
include ("inc/identKeys.php");
include ("inc/cp_unicode_tables.php");
include ("inc/points.php");

//Premium access for PubStats. Set to 1 for Premium, 0 (zero) for standard
$prem = 0;

//Reads the number of files in the images directory.
$files = (getDirFiles("images/")) ;              
   function getDirFiles($dirPath){
		if ($dirPath[strlen($dirPath)] != "/") 
			$dirPath .= "/";
		if ($handle = opendir($dirPath))  {
			while (false !== ($file = readdir($handle))) 
				if ($file != "." && $file != ".." && (!is_dir($dirPath . $file))) {   
					$filesArr[] = trim($file);
				};
			closedir($handle);
		}		  
		return $filesArr;     
	}
	
//If the template isn't explicitly set as a variable, set it to the default template.
if (!isset ($template) || empty($template)) {
	$template = 1;
}
//Calculates the number of unique templates in the images directory. 
if ($template == "R" | $template == "r") {
	$template = rand(1,(count($files)/2));
}

//Checks to see if the set template number exists. if not, use default template.
$offline = "images/lfs_check_offline".$template.".png";
$online = "images/lfs_check_online".$template.".png";

if (!file_exists($offline)) {
	$offline = "images/lfs_check_offline1.png";
	$online = "images/lfs_check_online1.png";
}

//UserNames with spaces was breaking the LFS query, so this fixes it.
$name = str_replace(" ", "%20",$name);

//Sets cache file name
$cachefile = 'cache/'.$name.'_cached.php';

//setup random cachetime, 2-6 minutes
$cachetime = rand(2,6) * 60;

$ver = '1.3';
$action = 'pst';
$host = 'http://www.lfsworld.net';
$path = '/pubstat/get_stat2.php';
$query = "?version=$ver&action=$action&racer=";
$idkey = "&idk=".$identKey;
$prem = "&ps=" . $prem;

// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
	$url = $cachefile;
	$stream = file_get_contents( $url );
	$stats = explode( "\n", $stream );
} else {
	if ($prem == 0) {
		$url = $host . $path . $query . $name . $idkey;
	} else {
		$url = $host . $path . $query . $name . $idkey . $prem;
	}
	$stream = file_get_contents( $url );
	$stats = explode( "\n", $stream );

	$calendar = date("M.d.Y ");
	$tzMod = 3;
	$hour = date("g") + $tzMod;
	$time = date(":i");
	$date = $calendar . $hour . $time;
	
//if refresh too soon is returned, read the cached file.
//if cached file doesn't exist, check LFS server for stats every 5 seconds
	if ($stats[0] == "can't reload this page that quickly after another"){
		if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
			$url = $cachefile;
			$stream = file_get_contents( $url );
			$stats = explode( "\n", $stream );
		} else {
			while ($stats[0] == "can't reload this page that quickly after another"){
				sleep(5);
					if ($prem == 0) {
						$url = $host . $path . $query . $name . $idkey;
					} else {
						$url = $host . $path . $query . $name . $idkey . $prem;
					}
				$stream = file_get_contents( $url );
				$stats = explode( "\n", $stream );
			}
// Cache the output to a file after 5 sec sleep.
			$fp = fopen($cachefile, 'w');
			fwrite($fp, $stream."\n<--cached-->\n".$date);
			fclose($fp);
		}
	} else {
// Cache the output to a file when reading live stats.
		$fp = fopen($cachefile, 'w');
		fwrite($fp, $stream."\n<--cached-->\n".$date);
		fclose($fp);
	}
}

//function for converting foreign texts for display on the graphic.		
function codepage_convert ($str) {
	global $cp_tables;

	$newstr = "";
	$current_cp = "L";
	$len = strlen ($str);
	for ($i=0; $i<$len; $i++) {
		if ($str{$i} == "^" && is_array ($cp_tables[$str{$i+1}])) {
			$i++;
			$current_cp = $str{$i};
		continue;
		}

	$decimal = ord ($str{$i});
		if ($decimal > 127) $newstr .= sprintf ("&#%05d;", $cp_tables[$current_cp][$decimal]);
		else $newstr .= $str{$i};
	}
		return $newstr;
}

//function that returns the current codepage of a given text.
function codepage_setting ($str) {
	global $cp_tables;
	$newstr = "";
	$current_cp = "L";
	$len = strlen ($str);
	for ($i=0; $i<$len; $i++) {
		if ($str{$i} == "^" && is_array ($cp_tables[$str{$i+1}])) {
			$i++;
			$current_cp = $str{$i};
		}
	}
	return $current_cp;
}
	
// Function to remove the colour code data from a string 
function remove_colour_codes($String){
	$ColCodes = array("^0","^1","^2","^3","^4","^5","^6","^7","^8","^9");
	$NewString = str_replace($ColCodes, "", $String);
	return $NewString;
}

function shortNumbers($str) {
	$len = strlen(round(str_replace(",", "", $str)));
	$mainNmbr = explode (",", $str);
	$subNmbr = "." . substr($mainNmbr[1], 0, 1);
	$str = $mainNmbr[0];
	if ($len > 3 & $len < 7){
		$str = $str . $subNmbr . "k";
	} else if ($len > 6 & $len < 10){
		$str = $str . $subNmbr . "m";
	} else if ($len >= 10 ){
		$str = $str . $subNmbr . "b";
	}
	
	return $str;
}

$tr_ptrn = array ("/\^d/", "/\^s/", "/\^c/", "/\^a/", "/\^q/", "/\^t/", "/\^l/", "/\^r/", "/\^v/", "/\^\^/", "/</");
$tr_ptrn_r = array ("&#92;", "&#47;", "&#58;", "*", "?", "\"", "<", ">", "|", "^", "&lt;"); 
		
// sets Units for Fuel and Distant to either metric or imperial	
if ($units == "metric") {
	$distDrvn = shortNumbers(number_format($stats[0] * .001, 0, ".", ",")) . " Km";	//Convert distance to km, add comna, no decimals
	$fuel = shortNumbers(number_format($stats[1] * .01, 0, ".", ",")) . " Ltr";		//Convert fuel to liters, add comma, no decimals
} else {
	$distDrvn = shortNumbers(number_format($stats[0] * .000621371, 0, ".", ",")). " Mi";	//Convert distance to miles, add comna, no decimals 
	$fuel = shortNumbers(number_format($stats[1] * .00264172, 0, ".", ",")) . " Gal";		//Convert fuel to gallons, add comma, no decimals
}
//Stats, add comma, no decimals
	$laps = shortNumbers(number_format($stats[2], 0, ".", ",")) . " laps";
	$wins = "1st: " . shortNumbers(number_format($stats[4], 0, ".", ","));
	$second = "2nd: " . shortNumbers(number_format($stats[5], 0, ".", ","));
	$podium = "Podium: " . shortNumbers(number_format($stats[4]+$stats[5]+$stats[6], 0, ".", ","));
	
	$carCodes = array("/UF1/", "/XFG/", "/XRG/", "/XRT/", "/RB4/", "/FXO/", "/LX4/", "/LX6/", "/RAC/", "/FZ5/", "/XFR/", "/UFR/", "/MRT/", "/FOX/", "/FO8/", "/BF1/", "/FXR/", "/XRR/", "/FZR/");
	$carNames = array("UF 1000", "XF GTi", "XR GT", "XR GT Turbo", "RB4 GT", "FXO Turbo", "LX4", "LX6", "RaceAbout", "FZ50", "XF GTR", "UF GTR", "MRT 5", "Formula XR", "Formula V8", "BMW F1", "FXO GTR", "XR GTR", "FZ50 GTR");
	
	$trackNumber = array("/^0../", "/^1../", "/^2../", "/^3../", "/^4../", "/^5../", "/^6../");
	$trackName = array("Blackwood", "South City", "Fern Bay", "Auto-X", "Kyoto Ring", "Westhill", "Aston");

	$car = preg_replace ($carCodes, $carNames, $stats[17]);
	$track = preg_replace ($trackNumber, $trackName, $stats[16]);
	
	$points = "Points: " . $points;
	
	$font = "fonts/verdana.ttf";
	$kana = $font;
	$header = header("content-type: image/jpeg");
	$fontSize = 7;
	
	$offlineTxt1 = "is not online";
	$offlineTxt2 = "last raced";
	
	$onlineTxt1 = "is online";
	
	if ($stats[13] == "1")
		$onlineTxt2 = "Spectating";
	else if ($stats[13] == "2")
		$onlineTxt2 = "In pits";
	else
		$onlineTxt2 = "Racing";
	
	if ($stats[16] == "<--cached-->") {
		$stats[19] = $stats[16];
		$stats[20] = $stats[17];
		$offlineTxt2 = "";
		$car = "";
		$track = "not yet set";
	}
	
	if (!empty ($stats[14])) {
		$server = remove_colour_codes($stats[14]);
		$cp = codepage_setting($server);
		if ($cp == "J"){
			//$kana = "fonts/msgothic.ttf";
			$kana = "fonts/ipagui.ttf";
			$fontSize = 8;				
		}
		$serverList = codepage_convert($server);
		$serverList = preg_replace ($tr_ptrn, $tr_ptrn_r, $serverList);
	}
	
if ($stats[0] == "pst: no valid username") {
	$header;
	$im = imagecreatetruecolor(100,10);
	$white = imagecolorallocate($im, 255, 255, 255);
	$black = imagecolorallocate($im, 0, 0, 0);
	imagefilledrectangle($im, 0, 0, 399, 29, $white);
	$text = "invalid username";
	imagettftext($im, 8, 0, 1, 9, $black, $font, $text);
	imagegif($im);
	imagedestroy($im);
	unlink($cachefile);
	exit;
} elseif ($stats[0] == "Identification is required - http://www.lfsforum.net/showthread.php?t=14480") {
	$header;
	$im = imagecreatetruecolor(100,10);
	$white = imagecolorallocate($im, 255, 255, 255);
	$black = imagecolorallocate($im, 0, 0, 0);
	imagefilledrectangle($im, 0, 0, 399, 29, $white);
	$text = "id key required";
	imagettftext($im, 8, 0, 1, 9, $black, $font, $text);
	imagegif($im);
	imagedestroy($im);
	unlink($cachefile);
	exit;
} elseif ($stats[13] == "0") {
	$header;
	$im = imagecreatefrompng($offline);
	$white = imagecolorallocate($im, 255,255,255);
	$black = imagecolorallocate($im, 0,0,0);
	$grey = imagecolorallocate($im, 175,175,175);
  //imagettftext(image, font-size, tilt, x, y, color, font, text);
	imagettftext($im, 7, 0, 85, 64, $black, $font, "last server:");
	imagettftext($im, $fontSize, 0, 85, 74, $black, $kana, $serverList);
	imagettftext($im, 6, 0, 330, 65, $grey, $font, $stats[19]);
	imagettftext($im, 6, 0, 320, 75, $grey, $font, $stats[20]);
	imagettftext($im, 15, 0, 7, 24, $black, $font, $user);
	imagettftext($im, 15, 0, 6, 23, $white, $font, $user);
	imagettftext($im, 8, 0, 7, 41, $black, $font, $offlineTxt1);
	imagettftext($im, 8, 0, 7, 52, $black, $font, $offlineTxt2);
	imagettftext($im, 8, 0, 7, 63, $black, $font, $car);
	imagettftext($im, 8, 0, 7, 74, $black, $font, $track);
	imagettftext($im, 8, 0, 6, 40, $white, $font, $offlineTxt1);
	imagettftext($im, 8, 0, 6, 50, $white, $font, $offlineTxt2);
	imagettftext($im, 8, 0, 6, 61, $white, $font, $car);
	imagettftext($im, 8, 0, 6, 72, $white, $font, $track);
	imagettftext($im, 7, 0, 85, 36, $black, $font, $distDrvn);
	imagettftext($im, 7, 0, 85, 45, $black, $font, $fuel);
	imagettftext($im, 7, 0, 85, 55, $black, $font, $laps);
	imagettftext($im, 7, 0, 155, 36, $black, $font, $wins);
	imagettftext($im, 7, 0, 155, 45, $black, $font, $second);
	imagettftext($im, 7, 0, 155, 55, $black, $font, $podium);
	if ($points != "Points: 0"){
		imagettftext($im, 7, 0, 155, 65, $black, $font, $points);
	}
	imagejpeg($im,"",85);
	imagedestroy($im);			
} else {
	//If online, create online graphic
	$header;
	$im = imagecreatefrompng($online);
	$white = imagecolorallocate($im, 255,255,255);
	$grey = imagecolorallocate($im, 175,175,175);
	imagettftext($im, 7, 0, 85, 64, $black, $font, "on server:");
	imagettftext($im, $fontSize, 0, 85, 74, $black, $kana, $serverList);
	imagettftext($im, 6, 0, 330, 65, $grey, $font, $stats[19]);
	imagettftext($im, 6, 0, 320, 75, $grey, $font, $stats[20]);
	imagettftext($im, 15, 0, 7, 24, $black, $font, $user);
	imagettftext($im, 15, 0, 6, 23, $white, $font, $user);
	imagettftext($im, 8, 0, 7, 41, $black, $font, $onlineTxt1);
	imagettftext($im, 8, 0, 7, 52, $black, $font, $onlineTxt2);
	imagettftext($im, 8, 0, 7, 63, $black, $font, $car);
	imagettftext($im, 8, 0, 7, 74, $black, $font, $track);
	imagettftext($im, 8, 0, 6, 40, $white, $font, $onlineTxt1);
	imagettftext($im, 8, 0, 6, 50, $white, $font, $onlineTxt2);
	imagettftext($im, 8, 0, 6, 61, $white, $font, $car);
	imagettftext($im, 8, 0, 6, 72, $white, $font, $track);
	imagettftext($im, 7, 0, 85, 36, $black, $font, $distDrvn);
	imagettftext($im, 7, 0, 85, 45, $black, $font, $fuel);
	imagettftext($im, 7, 0, 85, 55, $black, $font, $laps);
	imagettftext($im, 7, 0, 155, 36, $black, $font, $wins);
	imagettftext($im, 7, 0, 155, 45, $black, $font, $second);
	imagettftext($im, 7, 0, 155, 55, $black, $font, $podium);
	if ($points != "Points: 0"){
		imagettftext($im, 7, 0, 155, 65, $black, $font, $points);
	}
	imagejpeg($im,"",90);
	imagedestroy($im);	
}
?>