<?php

//function intToTime($sec, $padHours = true, $padMins = true, $padSecs = true) 
//{
	// start with a blank string
//	$hms = "";

	// do the hours first: there are 3600 seconds in an hour, so if we divide
	// the total number of seconds by 3600 and throw away the remainder, we're
	// left with the number of hours in those seconds
//	$hours = intval(intval($sec) / 3600); 

	// add hours to $hms (with a leading 0 if asked for)
//	$hms .= ($padHours) ? str_pad($hours, 2, "0", STR_PAD_LEFT). ":" : $hours. ":";

	// dividing the total seconds by 60 will give us the number of minutes
	// in total, but we're interested in *minutes past the hour* and to get
	// this, we have to divide by 60 again and then use the remainder
//	$minutes = intval(($sec / 60) % 60); 

	// add minutes to $hms (with a leading 0 if needed)
//	$hms .= ($padMins) ? str_pad($minutes, 2, "0", STR_PAD_LEFT). ":" : $minutes. ":";

	// seconds past the minute are found by dividing the total number of seconds
	// by 60 and using the remainder
//	$seconds = intval($sec % 60); 

	// add seconds to $hms (with a leading 0 if needed)
//	$hms .= ($padSecs) ? str_pad($seconds, 2, "0", STR_PAD_LEFT) : $seconds;

	// done!
//	return $hms;

//}

function intToTime($time)
{
	$hours = floor($time/3600);
	if ($hours < 0) $hours = '0';
	$mins = floor(($time-$hours*3600)/60);
	if ($mins < 0) $mins = '0';
	$secs  = floor($time-(($hours*3600)+($mins*60)));
	if ($secs < 10) $secs = '0'.$secs;
	if ($mins < 10) $mins = '0'.$mins;
	if ($hours < 10) $hours = '0'.$hours;
	return "$hours:$mins:$secs";
}

function intToHours($time)
{
	$hours = floor($time/3600);
	if ($hours < 0) $hours = '0';
	$mins = floor(($time-$hours*3600)/60);
	if ($mins < 0) $mins = '0';
	$secs  = floor($time-(($hours*3600)+($mins*60)));
	if ($secs < 10) $secs = '0'.$secs;
	if ($mins < 10) $mins = '0'.$mins;
	if ($hours < 10) $hours = '0'.$hours;
	global $lang;
    //echo $lang['Hours'];
	return $hours.' '.$lang['Hours'].'';
}


function intToMins($time)
{
	$secs = round($time%60, 0);
	return $mins = round($time/60, 0);
}

function ValuetoID ($value)
{
global $player, $armies, $kits, $vehicles, $weapons, $TheaterData;

	switch($value) {
		case "timeENG": return $kits[0]['time2'];break;
		case "timeSNP": return $kits[0]['time6'];break;
		case "timeMED": return $kits[0]['time3'];break;
		case "timeSUP": return $kits[0]['time5'];break;
		case "timeSOP": return $kits[0]['time4'];break;
		case "timeASS": return $kits[0]['time1'];break;
		case "timeAT": return $kits[0]['time0'];break;
		case "timeENGS": return $kits[0]['time2'];break;
		case "timeSNPS": return $kits[0]['time6'];break;
		case "timeMEDS": return $kits[0]['time3'];break;
		case "timeSUPS": return $kits[0]['time5'];break;
		case "timeSOPS": return $kits[0]['time4'];break;
		case "timeASSS": return $kits[0]['time1'];break;
		case "timeATS": return $kits[0]['time0'];break;
		case "totalHP": return $player['heals'];break;
		case "totalSupP": return $player['ammos'];break;
		case "totalRP": return $player['repairs'];break;
		case "totalDRVSA": return $player['driverspecials'];break;
		case "totalCP": return $player['cmdscore'];break;
		case "totalTWP": return $player['teamscore'];break;
		case "totalDEF": return $player['defends'];break;
		case "time": return $player['time'];break;
		case "killstreak": return $player['killstreak'];break;
		case "deathstreak": return $player['deathstreak'];break;
		case "totalkills": return $player['kills'];break;
		case "timeCMD": return $player['cmdtime'];break;
		case "timeSqL": return $player['sqltime'];break;
		case "timeSqM": return $player['sqmtime'];break;
		case "bestscoreUS": return $armies[0]['best0'];break; #$armies[0]...
		case "bestscoreMEC": return $armies[0]['best1'];break;
		case "bestscorePLA": return $armies[0]['best2'];break;
		case "bestscoreSeals": return $armies[0]['best3'];break;
		case "bestscoreSAS": return $armies[0]['best4'];break;
		case "bestscoreSpets": return $armies[0]['best5'];break;
		case "bestscoreMECSF": return $armies[0]['best6'];break;
		case "bestscoreRebels": return $armies[0]['best7'];break;
		case "bestscoreInsurgents": return $armies[0]['best8'];break;
		case "bestscoreEU": return $armies[0]['best9'];break;
		case "winsUS": return $armies[0]['win0'];break;
		case "winsMEC": return $armies[0]['win1'];break;
		case "winsPLA": return $armies[0]['win2'];break;
		case "winsSeals": return $armies[0]['win3'];break;
		case "winsSAS": return $armies[0]['win4'];break;
		case "winsSpets": return $armies[0]['win5'];break;
		case "winsMECSF": return $armies[0]['win6'];break;
		case "winsRebels": return $armies[0]['win7'];break;
		case "winsInsurgents": return $armies[0]['win8'];break;
		case "winsEU": return $armies[0]['win9'];break;
		case "timeUS": return $armies[0]['time0'];break;
		case "timeMEC": return $armies[0]['time1'];break;
		case "timePLA": return $armies[0]['time2'];break;
		case "timeSeals": return $armies[0]['time3'];break;
		case "timeSAS": return $armies[0]['time4'];break;
		case "timeSpets": return $armies[0]['time5'];break;
		case "timeMECSF": return $armies[0]['time6'];break;
		case "timeRebels": return $armies[0]['time7'];break;
		case "timeInsurgents": return $armies[0]['time8'];break;
		case "timeEU": return $armies[0]['time9'];break; 			
		case "timeARMOR": return $vehicles[0]['time0'];break; 
		case "timeAIR": return $vehicles[0]['time1'];break;
		case "timeHELI": return $vehicles[0]['time3'];break;
		case "timeTRNS": return $vehicles[0]['time4'];break; 
		case "killsARMOR": return $vehicles[0]['kills0'];break;
		case "killsAIR": return $vehicles[0]['kills1'];break;
		case "killsHELI": return $vehicles[0]['kills3'];break;
		case "roadkillTRNS": return $vehicles[0]['rk4'];break;
		case "wins": return $player['wins'];break;
		case "killsKNF": return $weapons[9]['kills'];break;
		case "killsEXPL": return ($weapons[11]['kills']+$weapons[13]['kills']+$weapons[14]['kills']);break;
		case "killsPIST": return $weapons[5]['kills'];break;
		case "deployedTactical": return $weapons[15]['fired'];break;
		case "deployedGrapplinghook": return $weapons[16]['fired'];break;
		case "deployedZipline": return $weapons[17]['fired'];break;
		case "timeTUS": return $TheaterData[0]['time'];break;
		case "timeTSeals": return $TheaterData[3]['time'];break;
		case "timeTSAS": return $TheaterData[4]['time'];break;
		case "timeTSpets": return $TheaterData[5]['time'];break;
		case "timeTMECSF": return $TheaterData[6]['time'];break;
		case "timeTRebels": return $TheaterData[7]['time'];break;
		case "timeTInsurgents": return $TheaterData[8]['time'];break;
		case "timeTEU": return $TheaterData[9]['time'];break;
	}

}

function pbar($score,$need,$type,$joined,$lastonline)
{

    if ($score == 0) {$score = 1;}
    $output = "";
    if ($type == "time") {$output .= intToHours($need);}
//    if ($type == "time") {$output .= intToTime($need);}
    else $output .= $need;
    if ($score < $need and $type != "road" and $type != "time" and $type != "kill" and $type != "tota") $output .= " <strong class=\"notachieved\">&times;</strong>";
    elseif ($score >= $need and $type != "road") $output .= " <strong class=\"achieved\">&radic;</strong>";
    $pointD = ($need - $score);	//Point differential for next rank
    $rtime = $lastonline - $joined;
    $realtime = round($pointD * $rtime / $score / 86400);
    $pcntDiff2 = number_format( (($score / $need) * 100), 2);

    if ($score < $need and $type != "road" and $type != "best" and $type != "wins") {
        if ($type == "time") {$score = intToTime($score); $need = intToHours($need); $pointD = intToTime($pointD);}
		global $lang;
		$lang['complete1'] = sprintf($lang['complete'], $score, $need, $pointD, $realtime);
        $output .=  "<div class=\"progressbar\"><div class=\"progress\" style=\"width: ".$pcntDiff2."%\"><span> ".$pcntDiff2."%</span></div></div><br /><i class=\"stat-need\">".$lang['complete1']."</i>";
        }
    return $output;
}


/* CHACHING FUNCTIONS */

function isCached($id)
{
	$file = CACHE_PATH . $id .'.cache';
	if(getNextUpdate($file, RANKING_REFRESH_TIME) > 0)
	{
		return true;
	}
	else
	{
		deleteCache($id);
		return false;
	}
}

function getCache($id)
{
	$file = CACHE_PATH . $id .'.cache';
	if(file_exists($file))
	{
		return file_get_contents($file);
	}
	else
	{
		return false;
	}		
}

function writeCache($id, $content)
{
	//write the file
	file_put_contents( CACHE_PATH . $id .'.cache', $content );
}

function deleteCache($id)
{
	$file = CACHE_PATH . $id .'.cache';
	if (file_exists($file))
	{
		unlink($file);
	}
}

function cleanCache()
{
	$files = dirList( CACHE_PATH ) ;
	foreach ($files as $key => $value)
	{
		#echo "$value - last update:". intToTime(getLastUpdate($value)).' -- next update in '.intToTime(getNextUpdate($value)).'<br>';
		if (stripos($value,'current-ranking.cache') || stripos($value,'home.cache'))
		{
			// this is the ranking -> update this more often! 600 = every 10 minutes
			if (getNextUpdate($value, RANKING_REFRESH_TIME) < -1) // file is out of date -> delete (will be renewed when next user requests...)
				unlink($value); // file deleted!
		}
		else 
			if (getNextUpdate($value) < -1) // file is out of date -> delete (will be renewed when next user requests...)
				unlink($value); // file deleted!		
	}
}

function deleteCompleteCache()
{
	$files = dirList( CACHE_PATH ) ;
	foreach($files as $key => $value)
	{
		unlink($value); // file deleted!
	}
}

function getNextUpdate($filename, $limit=3600)
{
	if(file_exists($filename))
	{
		return (fileatime($filename)+$limit)-time();
	}
	else
	{
		return -1; // file not found 
	}		
}


function getLastUpdate($filename)
{
	if(file_exists($filename))
	{
		return time()-fileatime($filename);
	}
	else
	{
		return -1; // file not found
	}
}

function dirList($directory) 
{
    // create an array to hold directory list
    $results = array();
    // create a handler for the directory
    $handler = opendir($directory);
    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {
        // if $file isn't this directory or its parent, 
        // add it to the results array
        if ($file != '.' && $file != '..')
            $results[] = $directory.$file;
    }
    // tidy up: close the handler
    closedir($handler);
    // done!
    return $results;
}


function getRatio($val1, $val2)
{
	if($val2)
		return ($val1 / $val2);
	else
		return $val1;
}

function getPercent($val1, $val2)
{
	if($val1)
		return (100 * $val2 / $val1);
	else
		return 0;
}
?>