<?php
/*======================================================================*\
|| #################################################################### ||
|| # EoT-Clan BF3 Leaderboard                                         # ||
|| # ---------------------------------------------------------------- # ||
|| # Dieses Copyright darf nicht entfernt werden                      # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # -----------------BF3 Leaderboard is a free Software--------------# ||
|| #                     http://eot-clan.net                          # ||
|| #################################################################### ||
\*======================================================================*/
	require_once ('../inc/config.php');
	require_once ('../language/'.$row['language'].'.php');
  require_once ('../inc/BattlelogApi/battlelog.api.php');
  
  $_GET = security::escape($_GET);
  $_POST = security::escape($_POST);

       $battlelog = new BattlelogApiCurl;

      $sUTime = time();
      $arDetails = $battlelog->Friendlist($row['OnlinePlayers']);
      
   if ($arDetails['own'][0] == "error"){
      	$message = LANG_UPDATE_ONLINE_PLAYER_ERROR_1;
   }else{   

      $arDetails = array_merge($arDetails['own'],$arDetails['friends']);
      $pArray = "";
      #echo '<pre>';
      #print_r($arDetails);
      #echo '</pre>';
     
      $aSoldiers = array();
      $sSql = "SELECT soldiername FROM ".DBPrefix."generalStats";
      $rResult   = mysql_query($sSql) or $bError .= "\nError in Query: " . mysql_error() . ' in SQL: ' . print_r($sSql, true);
      while($aData = mysql_fetch_assoc($rResult)){
      	$aSoldiers[] = $aData['soldiername'];
      }
      
      if ($row['platform'] == 'pc'){
      	$field = 'soldiername';
      }else{
      	$field = 'persona';
      }
      $i=0;
      if (is_array($arDetails)) foreach ($arDetails as $friends){
      	
      	if (in_array($friends['user']['username'],$aSoldiers)){
      		++$i;
      		#print_r($friends['user']['username'].'<br />');
      		 if (empty($friends["user"]["presence"]["isPlaying"]) or $friends["user"]["presence"]["isPlaying"] == ""){
    	           $sSql = "UPDATE ".DBPrefix."generalStats SET is_online = '{$friends['user']['presence']['isOnline']}',lastServer_uTime = '{$sUTime}', gravatarMD5 = '{$friends['user']['gravatarMd5']}' WHERE {$field}='{$friends['user']['username']}'";
    	           mysql_query($sSql) or die (mysql_error());
           }else{
                 $sName = addslashes($friends["user"]["presence"]["serverName"]);
                 $guid = addslashes($friends["user"]["presence"]["serverGuid"]);
                 $user = addslashes($friends['user']['username']);
              if ($guid != ""){
                   $sSql = "UPDATE ".DBPrefix."generalStats SET 
                             is_online = '2',
                             lastServer_uTime = '{$sUTime}',
                             lastServerName = '{$sName}',
                             lastServerID = '{$guid}',
                             gravatarMD5 = '{$friends['user']['gravatarMd5']}',
                             lastPlayingTime = '{$sUTime}'
                           WHERE 
                            {$field}='{$user}'";
    	             mysql_query($sSql) or die (mysql_error());
    	          
    	          $sql = "SELECT soldiername,pid FROM ".DBPrefix."generalStats WHERE {$field}='{$user}'";
                $result   = mysql_query($sql)or die (mysql_error());  
    	          $adata = mysql_fetch_assoc($result);
    	        }     
              $pArray[] = $adata['pid'];
           } 
      	}
      }
     
     
   if ($row['platform'] == 'pc'){
      $ii = 0;
    if (is_array($pArray)) foreach ($pArray as $playerID){
++$ii;
    	   $sSql = "SELECT ServerID FROM ".DBPrefix."ServerHistory WHERE stats_pid = {$playerID} ";
       $rResult   = mysql_query($sSql) or die (mysql_error().'1');
      $aServers = array();
      while($aSData = mysql_fetch_assoc($rResult)){ 
      	$aServers[] = $aSData['ServerID'];
      }
      
      $sSql = "SELECT lastServerID,lastServerName FROM ".DBPrefix."generalStats WHERE pid = {$playerID}";
           $rResult   = mysql_query($sSql) or $bError .= "\nError in Query: " . mysql_error() . ' in SQL: ' . print_r($sSql, true);
           $aData = mysql_fetch_assoc($rResult); 
           $ServerName = addslashes($aData['lastServerName']);
      if (in_array($aData['lastServerID'],$aServers)){
      	$sSql = "UPDATE ".DBPrefix."ServerHistory SET 
                 LastVisit = {$sUTime},
                 ServerName = '{$ServerName}'
                WHERE 
                 stats_pid='{$playerID}' AND ServerID='{$aData['lastServerID']}'";
    	  mysql_query($sSql) or die (mysql_error().'2');
    	}elseif ($aData['lastServerID'] != ""){
    		$sSql = "INSERT INTO ".DBPrefix."ServerHistory 
    		          (stats_pid,ServerName,ServerID,FirstVisit,LastVisit) 
    		         VALUES 
    		          ({$playerID},'{$ServerName}','{$aData['lastServerID']}',{$sUTime},{$sUTime})";
    	  mysql_query($sSql) or die (mysql_error().'3');
      }     
    }
    $message = LANG_UPDATE_ONLINE_PLAYER1.$i.LANG_UPDATE_ONLINE_PLAYER2.$ii.LANG_UPDATE_ONLINE_PLAYER3;
  }    
 }   
     

     
     
   
    ?>
	<html>
		<head>
			<title><?php echo LANG_UPDATE_TITLE; ?></title>
			<link rel="stylesheet" type="text/css" href="../css/style.php" media="screen,projection" /> 
		</head>
		<table class="defaultUpdate" style="margin-left: -450px;margin-top: -100px;position: absolute;left: 50%;top: 50%; cellspacing="0" cellpadding="0">
			<tr>
				<td class="head" colspan="5"><?php echo LANG_UPDATE_HEAD ?></td>
			</tr>
			<tr>
				<td class="result">
					<span>
					<br /><br /><b><?php echo $message ?></b><br /><br />
					</span>
				</td>
			</tr>
		</table>
	</html>