<?php
/*======================================================================*\
|| #################################################################### ||
|| # EoT-Clan BF3 Leaderboard                                         # ||
|| # ---------------------------------------------------------------- # ||
|| # Dieses Copyright darf nicht entfernet werden                     # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # -----------------BF3 Leaderboard is a free Software--------------# ||
|| #                   http://eot-clan.net                            # ||
|| #################################################################### ||
\*======================================================================*/

define('BROWSER', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2');


class BattlelogApiCurl
{
	
	 // Default URL and json Datas 
	 function Url($url){
      $ch = curl_init("http://battlelog.battlefield.com/{$url}");
          curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				    'Expect:',
				    'User-Agent: '.BROWSER,
				    'Accept: */*',
				    'Accept-Language: en-us,en;q=0.5',
				    'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
				    'X-Requested-With: XMLHttpRequest',
				    'X-AjaxNavigation: 1'
		      ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        $jData = curl_exec($ch);
        curl_close($ch);
       
       return $jData;
   }
   
   //Battlereports from Soldier
   function BattleReport($Soldiername){
     $data = $this->Url("bf3/user/{$Soldiername}/");
     $data = json_decode($data, true);
      if ($data['template'] == "profile.overview"){
       $Reportscount = $data['context']['gameReportPreviewCount'];
     
       $reports_key = array_keys($data['context']['gameReportPreviewGroups']);
     
        $i = 0;
        $count = array();
        foreach ($reports_key as $aCounter){
     	    $counter = ++$i;
     	    $count[] = count($data['context']['gameReportPreviewGroups'][$counter-1]);
        } 
     
          $arrayK = array();
          foreach ($count as $key => $reports){
     	      if ($reports >= 1){
             $arrayK[$key] = array_keys($data['context']['gameReportPreviewGroups'][$key]);  
            }
          }
     
             $array = array();
             $array_number = array_keys($arrayK);
            foreach ($array_number as $key => $number){
      	       $array[] = $data['context']['gameReportPreviewGroups'][$number];
            }   
      }
      else
      {
        $array = array("status" => "error");
      }  
     return $array;
   }
   
   
   //Battlereport Details from Soldier
   function BattleReportDetail($SoldierID,$ReportID,$platform){
       $report = $this->Url("/bf3/battlereport/show/{$ReportID}/{$platform}/{$SoldierID}/");
       $report = json_decode($report, true);
       $generalReport = $this->Url("/bf3/battlereport/loadgeneralreport/{$ReportID}/{$platform}/");
       $generalReport = json_decode($generalReport, true);
      if ($generalReport['gameReport'] != ""){
       $playersReport = $this->Url("/bf3/battlereport/loadplayerreport/{$ReportID}/{$platform}/{$SoldierID}/");
       $playersReport = json_decode($playersReport, true);
       $aReport["general"] = $generalReport;
       $aReport["detail"] = $playersReport;
      }else{
       $aReport = array("status" => "0");
      }
     return  $aReport;
   }
   
   
    //Dogtags from Soldier
    function Dogtags($SoldierName,$SoldierID,$UserID){
       $report = $this->Url("/bf3/soldier/dogtagsPopulateStats/$SoldierName/$SoldierID/$UserID/1/");
       $report = json_decode($report, true);
       
     return  $report;
   }
   
   
    //ALL Weapons from Soldier
    function Weapons($SoldierID){
       $Weapons = $this->Url("/bf3/weaponsPopulateStats/{$SoldierID}/1/");
       $Weapon = json_decode($Weapons, true);
        $i=0;
        
         foreach ($Weapon['data']['mainWeaponStats'] as $wea){
       	    $i++; 
       	  $weapons['weapon'][$wea['code']] = array(   	   
       	   'time' => $wea['timeEquipped'],
       	   'kills' => $wea['kills'],
       	   'shots' => $wea['shotsFired'],
       	   'headshots' => $wea['headshots'],
       	   'hits' => $wea['shotsHit'],
       	   'stars' => array(
       	        'count' => $wea['serviceStars'],
       	        'curr' => $wea['serviceStarsProgress'],
       	        'need' => 100 -$wea['serviceStarsProgress']
       	    )
       	   );   	   
       	 }
       	 
       /*	foreach ($Weapon['data']['mainWeaponStats'] as $wea){
       	    $i++; 
       	  $weapons['gadgets'][$wea['code']] = array(   	   
       	   'time' => $wea['timeEquipped'],
       	   'kills' => $wea['kills'],
       	   'shots' => $wea['shotsFired'],
       	   'headshots' => $wea['headshots'],
       	   'hits' => $wea['shotsHit'],
       	   'stars' => array(
       	        'count' => $wea['serviceStars'],
       	        'curr' => $wea['serviceStarsProgress'],
       	        'need' => 100 -$wea['serviceStarsProgress']
       	    )
       	   );   	   
       	 }*/
       	      	  
     return  $Weapon;
   }
   
   function Iteminfo($Soldiername,$item,$SoldierID){     
       $Item = $this->Url("/bf3/statsitemPopulateStats/iteminfo/{$Soldiername}/{$SoldierID}/{$item}/1/");
       $Item = json_decode($Item, true);	   
       	 
     return  $Item;
   }
   
   
   
    //Server Datas from all Gameservers
    function ServerData($serverID){
		$serverInfo = $this->Url("bf3/servers/show/{$serverID}/?json=1");
		$data = json_decode($serverInfo, true);
		$data = $data['message'];
		$server = $data['SERVER_INFO'];
		$server['players'] = $data['SERVER_PLAYERS'];
		$data = $server;
		
		  if (!is_array($data) || !array_key_exists('guid', $data)){
			  $aServerData = array('message' => 'error');
	    }else{
		   $aServerData = array(
		       'message' => 'ok',
				   'id'			=> $data['guid'],
				   'guid'			=> $data['guid'],
				   'name'			=> $data['name'],
				   'ip'			=> $data['ip'],
				   'port'			=> $data['port'],
				   'numPlayers'	=> $data['numPlayers'],
				   'maxPlayers'	=> $data['maxPlayers'],
				   'numQueued'		=> $data['numQueued'],
				   'passworded'	=> $data['hasPassword'],
				   'ranked'		=> $data['ranked'],
				   'punkbuster'	=> $data['punkbuster'],
				   'map'			=> $data['map'],
				   'preset'		=> $data['preset'],
				   'country'		=> $data['country'],
				   'region'		=> $data['region'],
				   'settings'		=> array(
						   'showHud'				=> $data['settings']['vhud'] == 1,
						   'autobalance'			=> $data['settings']['vaba'] == 1,
						   'bulletDamage'			=> $data['settings']['vbdm'],
						   'showMinimap'			=> $data['settings']['vmin'] == 1,
						   'thirdPersonVehicleCam'	=> $data['settings']['v3ca'] == 1,
						   'vehicles'				=> $data['settings']['vvsa'] == 1,
						   'healthRegen'			=> $data['settings']['vrhe'] == 1,
						   'tksBeforeKick'			=> $data['settings']['vtkc'],
						   'killCam'				=> $data['settings']['vkca'] == 1,
						   'minimapSpotting'		=> $data['settings']['vmsp'] == 1,
						   'playerHealth'			=> $data['settings']['vshe'],
						   'downTime'				=> $data['settings']['vpmd'],
						   'friendlyFire'			=> $data['settings']['vffi'] == 1,
						   '3dSpotting'			=> $data['settings']['v3sp'] == 1,
						   'showEnemyNameTags'		=> $data['settings']['vnta'] == 1,
						   'idleKickSeconds'		=> $data['settings']['vnit'],
						   'kicksToBan'			=> $data['settings']['vtkk'],
						   'respawnTime'			=> $data['settings']['vprt'],
						   'squadLeaderSpawnOnly'	=> $data['settings']['osls'] == 1
				   ),
				   'mapRotation'	=> array(),
				   'players'		=> array()
		     );
		
		   if (is_array($data['maps'])){
			   foreach ($data['maps'] as $map){
				    $aServerData['mapRotation'][] = array(
						   'name'		=> $map['map'],
						   'mode'		=> $map['mapMode']
				     );
			   }
		   }
		
		    if (is_array($data['players'])){
			    foreach ($data['players'] as $player){
				    $aServerData['players'][] = array(
						    'id'		=> $player['personaId'],
						    'name'		=> $player['persona']['personaName'],
						    'gravatar'	=> $player['persona']['user']['gravatarMd5']
				     );
			    }
		    }
	    }
		  return $aServerData;
		  
	  }
	  
	  
	  function PonServer($serverID){
		$pServer = $this->Url("bf3/servers/getNumPlayersOnServer/{$serverID}/");
		$pServer = json_decode($pServer, true);
		
		  return $pServer;
		  
	  }
   
    function SoldierInfo($Soldiername)
	{
		  $data = $this->Url("/bf3/user/{$Soldiername}/");
			$data = json_decode($data, true);
			$aData[] = $data['context']['profileCommon'];
			$aData[] = $data['context']['soldiersBox'];
		return $aData;
	}
	
	
	function GameExpantions($Soldiername)
	{
		  $data = $this->Url("/bf3/user/{$Soldiername}/");
			$data = json_decode($data, true);
			$data = $data['context']['userGameExpansions'];
		return $data;
	}
	
	
	
	 function Friendlist($Soldiername)
	{
		  $data = $this->Url("/bf3/user/{$Soldiername}/friends/");
			$data = json_decode($data, true);
			if ($data['template'] == 'main.errorfourofour'){
				$aData['own'] = array("error");
			}else{
			  $aData['own'][0]['user'] = $data['context']['profileCommon']['user'];
			  $aData['friends'] = $data['context']['friends'];
      }
		return $aData;
	}
	
	
	 
  
    function SoldierDATA($SoldierID)
	{
		  $data = $this->Url("bf3/overviewPopulateStats/{$SoldierID}/None/1/");
			$data = json_decode($data, true);
			#$aData[] = $data['context']['profileCommon'];
			#$aData[] = $data['context']['soldiersBox'];
		return $data;
	}
   
       function SoldierAWARDS($SoldierID)
	{
		  $data = $this->Url("/bf3/awardsPopulateStats/{$SoldierID}/1/");
			$data = json_decode($data, true);
		return $data;
	}
    
   
}