<?php
// vous n etes pas sense modifier ce fichier sauf si vous avez besoin d' y ajouter des fonctions
// allez dans tm_gery_config.php pour configurer ce programme

require 'includes/tm_gery_config.php';		// charge tm_gery_config (necessaire pour configurer tm_gery)
require 'includes/GbxRemote.inc.php';		// charge GbxRemote (necessaire pour converser avec le serveur)
require 'includes/tm_gery_lang.php';		// charge tm_gery_lang (necessaire pour les messages)
require 'includes/plugin_manager.php';		// include the DedDerek plugin manager system

$login = 'SuperAdmin';						// ne pas toucher (login pour se connecter au serveur)

$max_exec_time = 0;						// temps maxi d' execution du programme

$first = true;
$NbLaps = 1;

$PlayerLanguage=array();
$PlayerAccueil=array();
$restart=false;

$PlayerScript=array();
$PlayerAccount=array();

$Bill = array('BillMsg','BillType','Login','ToLogin');
$Pari = array('BillId','Score','Coppers','Login','NickName','Visee','Actuelle','Payed','Ok');
$PariCount = 0;

$Duel = array('BillId','Score','Coppers','Login','NickName','ToLogin','ToNickName','Payed','Ok','Coef');
$DuelCount = 0;
$st = '$z';                                                 

$CurrentChallenge = array('Name','UId','Author','Environnement','Mood','BronzeTime','SilverTime','GoldTime','AuthorTime','CopperPrice','LapRace');
$record = array('Time' => "", 'Author' => "", 'Login' => "", 'Date' => "");

$messages['help'] = 	'/help, /time, /list num_page, /listlogin login,'." \n\r".
			'/record, /rec, /top5, /top position (>5),'." \n\r".
			'/srank, /mrank, /rankmap, /moyenne (/average),'." \n\r".
			'/lol, /cu, /hi, /lu, /bye, /afk,'." \n\r".
			'/playerlist, /msg tologin text, /mylang,'." \n\r".
			'/exchange tmnforever|united|nations|sunrise|original number,'." \n\r".
//			'/vote 0-20 (/vote=>note), /choosenext map, /next,';
			'/vote 0-20 (/vote=>note), /choosenext map, /next,'."\n\r";	//DedDerek

//$messages['helptmu'] = 	'/don nbcoppers login (no login = serveur),'." \n\r".
$messages['helptmu'] = 	"\n\r".'/don nbcoppers login (no login = serveur),'." \n\r".	//DedDerek
			'/pari nbcoppers scoremini (/pari = /bet),'." \n\r".
			'/duel nbcoppers login';

$messages['helpadm'] = 	'/gonext, /restart, /cancel, /end, /delmap,'." \n\r".
			'/ta, /round, /laps, /stunts, /team, /cup,'." \n\r".
			'/Kick login, /Ban, /UnBan, /BlackList, /UnBlackList,'." \n\r".
			'/AddGuest, /RemoveGuest, /die, /lang, /shutdown,'." \n\r".
			'/set, /get, /delrec login, /varlist, /pub'." \n\r".
			'/SaveMatchSettings, /LoadMatchSettings, /ListMatchSettings';

$messages['helpadmtmn'] = '/Ignore, /UnIgnore, /version';

$messages['helpadmtmu'] = '/coppers';

$RankServer = array ('Login' =>  0);
$RankMap = array ('filename' =>  0);
$RankMap2 = array ('filename' =>  0);
$RankMappeur = array ('Login' =>  0);
$RankMappeur2 = array ('Login' =>  0);
$RecordLogin = array ('Login' =>  0);

$TracksDirectory = "";

$wg=false;
$wgprice=10;
$wgindex=0;

$MaxPlayer=250;

$conn_id = 0;

$NickName=' ';
$Login=' ';
$BestTime=0;
$DateRec='?';
$Note=-1;
$NbVote=0;
$Moyenne= 0;

$Vote = array('Login');
$VoteCount = 0;

$TopNickName= array();
$TopLogin= array();
$TopBestTime= array();
$TopDateRec= array();

$ChatLines = "";
$chat['command'] = "";
$chat['param'] = "";
$chat['Author']="";

$client = "";
$NextChallengeInfo= array();
$NextChallengeType="";

$PlayerList = array();
$CurrentGameMode = -1;
$CurrentGameInfo = array();

$VoteNext = false;
$VoteNextLogin = array('Login');
$VoteNextOk = 0;
$VoteNextMap = '';
$VoteNextMapName = '';

$Server_OStatus='';

$now = 0;
$pub = 0;
$WarmUp = true;
$OWarmUp = true;

$RoundBegan = False; //indique que le CallBack BeginRound est passé

$calls=array();
$retcalls=array();

$Inj = array('BillId','Login','NickName');
$InjureCount=0;

$infos=array();

$norecord=0;

//ne pas toucher svp ===
$TMGeryVersion = 'VG1HZXJ5IHYyMDEwLTA3LTE2ICgkbFtodHRwOi8vdHJhY2ttYW5pYS5nZXJ5LnBlcnNvLnNmci5mcl1odHRwOi8vdHJhY2ttYW5pYS5nZXJ5LnBlcnNvLnNmci5mciRsKQ==';
//===================

function information ( &$infos ) {
global $txt;
//'0'=tous les TM, '1'=pour united seulement
$infos=array(
			'0', '$0f0/time $fff'.txtbal('pour connaitre l heure du serveur'),
			'0', '$0f0/rec $fff'.txtbal('pour connaitre le record de la map'),
			'0', '$0f0/top5 $fff'.txtbal('pour connaitre le TOP5 de la map'),
			'0', '$0f0/top $fff'.txtbal('pour connaitre tous les records de la map'),
			'0', '$0f0/vote $fff'.txtbal('pour voter'),
			'0', '$0f0/exchange $fff'.txtbal('pour ajouter des maps de tm-exchange au serveur'),
			'0', '$0f0/choosenext $fff'.txtbal('pour proposer la map suivante'),
			'0', '$0f0/srank $fff'.txtbal('pour connaitre son rang serveur'),
			'0', '$0f0/mrank $fff'.txtbal('pour connaitre le rang des mappeurs du serveur'),
			'0', '$0f0/rankmap $fff'.txtbal('pour connaitre le classement des maps serveur'),
			'0', '$0f0/moyenne $fff'.txtbal('pour connaitre la note moyenne des maps du serveur'),
			'0', '$0f0/list $fff'.txtbal('pour connaitre la liste des maps du serveur'),
			'0', '$0f0/listlogin $fff'.txtbal('pour connaitre la liste des maps d un mappeur'),
			'0', '$0f0/mylang $fff'.txtbal('pour choisir sa langue'),
			'1', '$0f0/pari $fff'.txtbal('pour parier'),
			'1', '$0f0/duel $fff'.txtbal('pour engager un duel'),
			'1', '$0f0/don $fff'.txtbal('pour faire un don de coppers'),
		);

}

function addCall() {
global $calls;
global $max_exec_time;

	$args = func_get_args();
	$methodName = array_shift($args);
	$struct = array('methodName' => $methodName, 'params' => $args);
	$calls[count($calls)] = $struct;
	if(count($calls)>10) {
		multiquery();
		set_time_limit ($max_exec_time);
	}
	return (count($calls) - 1);
}

function multiquery() {
global $calls;
global $client;
global $retcalls;

if(count($calls)>0){
	$multicalls = array();
	$retcalls = array();

	if(count($calls)>10)	$multicalls = array_chunk($calls,5);
	else	$multicalls[0] = &$calls;
		
	foreach($multicalls as $key => &$multicall){

		if (!$client->query('system.multicall', $multicall)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else {
			$res = $client->getResponse();
			$retcalls = array_merge($retcalls,$res);
		}
	}
	$calls = array();
}
}

function txtbal ($text) {
	return '<t>'.$text.'</t>';
}

function translate ($msg, $code) {
global $txtl;
global $lang;
global $codelang;

	if (!in_array($code,$codelang,true)) $code=$lang;

	$str=$msg;
	do {
//		$tmp=strpos($str,'<t>');
	
		$tmp=strstr($str,'<t>');
		if ($tmp===FALSE) break;	//plus rien a faire

		$stop=strpos($tmp,'</');
		$totrans = substr($tmp,3,$stop-3);
//		if (array_key_exists($totrans,$txtl['_'.$code])) {
		if (isset($txtl['_'.$code][$totrans])) {
			$str=str_replace('<t>'.$totrans.'</t>',$txtl['_'.$code][$totrans],$str);
		}
		else {
			$str=str_replace('<t>'.$totrans.'</t>',$totrans,$str);
		}
	} while(true);
	
	return $str;
}

$ModifVar = array('use_ftp','maxtop','cadeau','ftp_t_status',
		'cote','copperreserve','coppermin','coppermax',
		'amende','Note','NbVote','VoteNextSeuil',
		'wgminprice','wgmaxprice','wgfreq','wgplayer',
		'use_exchange','auto_savereplay','racetype',
		'norecord'
		);

function ModifVariable ($Var,$Val) {
global $conn_id;
global $ModifVar;
global $use_ftp;
global $maxtop;
global $cadeau;
global $ftp_t_status;
global $cote;
global $copperreserve;
global $coppermin;
global $coppermax;
global $amende;
global $Note;
global $NbVote;
global $VoteNextSeuil;

global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;

global $wgminprice;
global $wgmaxprice;
global $wgfreq;
global $wgplayer;

global $use_exchange;
global $auto_savereplay;

global $racetype;

global $norecord;

	if ($Var=='use_ftp') {
		$use_ftp=intval($Val);
		if (!$use_ftp && $conn_id) {
			// Fermeture de la connexion
			ftp_close($conn_id);  
			$conn_id = 0; 
		}
	}
	if ($Var=='maxtop') {
		for ($i=$maxtop;$i<intval($Val);$i++) {
			$TopNickName[$i]=' ';
			$TopLogin[$i]=' ';
			$TopBestTime[$i]=0;
			$TopDateRec[$i]='?';
		}
		$maxtop=intval($Val);
		SaveRec();
	}
	if ($Var=='cadeau') $cadeau=intval($Val);
	if ($Var=='ftp_t_status') $ftp_t_status=intval($Val);
	if ($Var=='cote') $cote=floatval($Val);
	if ($Var=='copperreserve') $copperreserve=intval($Val);
	if ($Var=='coppermin') $coppermin=intval($Val);
	if ($Var=='coppermax') $coppermax=intval($Val);
	if ($Var=='amende') $amende=intval($Val);
	if ($Var=='Note') {
		$Note=intval($Val);
		SaveRec();
	}
	if ($Var=='NbVote') {
		$NbVote=intval($Val);
		SaveRec();
	}
	if ($Var=='VoteNextSeuil') $VoteNextSeuil=floatval($Val);

	if ($Var=='wgminprice') $wgminprice=intval($Val);
	if ($Var=='wgmaxprice') $wgmaxprice=intval($Val);
	if ($Var=='wgfreq') $wgfreq=intval($Val);
	if ($Var=='wgplayer') $wgplayer=intval($Val);
	if ($Var=='use_exchange') $use_exchange=intval($Val);
	if ($Var=='auto_savereplay') $auto_savereplay=intval($Val);
	if ($Var=='racetype') $auto_savereplay=intval($Val);
	if ($Var=='norecord') $norecord=intval($Val);
}

function server_ranking ($ChallengeList) {
//global $CurrentGameInfo;
global $client;
global $RankServer;
global $reprecord;
global $maxtop;
global $RecordLogin;
global $rank_ext;


	echo "Calcul rang serveur: ";

if (!$rank_ext) {
//	$NbChallenge = $CurrentGameInfo['NbChallenge'];
//	if ($NbChallenge > 0) {
//		if (!@$client->query('GetChallengeList',$NbChallenge , 0)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//			return false;
//		}
//	}
//	else   return false;
   
//	$ChallengeList = $client->getResponse();

/*
	$points=0;
	$RankServer = array();
	$RecordLogin = array();
	foreach ($ChallengeList as $Challenge) {
		$filename=$Challenge['UId'];
		if(LireFichier($reprecord.$filename,$result)) {
			$tmp=strstr($result,'<Login>');
			$tmp=str_replace('<Login>','',$tmp);
			$stop=strpos($tmp,'</');
			if ($stop > 0) $Login = substr($tmp,0,$stop); else $Login = ' ';
			if ($Login != ' '){
				if (array_key_exists($Login, $RankServer)) {
					$points = $RankServer[$Login];
					$RankServer[$Login] = $points + $maxtop;
				}else{   
					$RankServer["$Login"] = 0;
					$points = $RankServer[$Login];
					$RankServer[$Login] = $points + $maxtop;
				}
				if (array_key_exists($Login, $RecordLogin)) {
					$RecordLogin[$Login] = $RecordLogin[$Login] + 1;
				}else{
					$RecordLogin["$Login"] = 1;
				}
			}
			for ($i=2;$i<=$maxtop;$i++) {
				$tmp=strstr($result,'<Top'.$i.'Login>');
				$tmp=str_replace('<Top'.$i.'Login>','',$tmp);
				$stop=strpos($tmp,'</');
				if ($stop > 0) $Login = substr($tmp,0,$stop); else $Login = ' ';
				if ($Login != ' '){
					if (array_key_exists($Login, $RankServer)) {
						$points = $RankServer[$Login];
						$RankServer[$Login] = $points + ($maxtop + 1 - $i) ;
					}else{   
						$RankServer["$Login"] = 0;
						$points = $RankServer[$Login];
						$RankServer[$Login] = $points + ($maxtop + 1 - $i);
					}
				}
			}   
		}
		usleep(1);
	}
   
	arsort($RankServer);
*/
	$points=0;
	$RankServer = array();
	$RecordLogin = array();
	foreach ($ChallengeList as $Challenge) {
		$filename=$Challenge['UId'];
		if(LireFichier($reprecord.$filename,$result)) {
			$tmp=strstr($result,'<Login>');
			$tmp=str_replace('<Login>','',$tmp);
			$stop=strpos($tmp,'</');
			if ($stop > 0) $Login = substr($tmp,0,$stop); else $Login = ' ';
			if ($Login != ' '){
				//if (array_key_exists($Login, $RankServer)) {
				if (isset($RankServer[$Login] )) {
					$RankServer[$Login] += $maxtop;
				}else{   
					$RankServer["$Login"] = $maxtop;
				}
				//if (array_key_exists($Login, $RankServer)) {
				if (isset($RecordLogin[$Login] )) {
					$RecordLogin[$Login] += 1;
				}else{
					$RecordLogin["$Login"] = 1;
				}
			}
			//echo "$Login\n\r";
			$nb=preg_match_all("|<Top(\d+)Login>(.*)</Top\\1Login>|", $result, $matches);
			// indice de depart = 0 pour le second
			//for ($i=2;$i<=$maxtop;$i++) {
			$nbpoints=$maxtop-1;
			for ($i=0; ($i<=$maxtop -2)&&($i<count($matches[2])); $i++, $nbpoints--) {
//			for ($i=0; $i<=$maxtop -2; $i++, $nbpoints--) {
				//echo "nbpoints: $nbpoints\n\r";
				//$tmp=strstr($result,'<Top'.$i.'Login>');
				//$tmp=str_replace('<Top'.$i.'Login>','',$tmp);
				//$stop=strpos($tmp,'</');
				//if ($stop > 0) $Login = substr($tmp,0,$stop); else $Login = ' ';
				$Login = $matches[2][$i];
				if ($Login != ' '){
					//if (array_key_exists($Login, $RankServer)) {
					//    $points = $RankServer[$Login];
					//    //$RankServer[$Login] = $points + ($maxtop + 1 - $i - 2) ;
					//    $RankServer[$Login] = $points + $nbpoints;
					//}else{   
					//    $RankServer["$Login"] = 0;
					//    $points = $RankServer[$Login];
					//    //$RankServer[$Login] = $points + ($maxtop + 1 - $i - 2);
					//    $RankServer[$Login] = $points + $nbpoints;
					//}
					//if ( !array_key_exists($Login, $RankServer)) {
					//:    $RankServer[$Login] = 0;
					//}
					if( !isset($RankServer[$Login]) ) {
						$RankServer["$Login"] = 0;
					}
					$RankServer[$Login] += $nbpoints;
				}
				//usleep(1);
			} 
			//echo 'nb: '.$nb."\n\r";
			//print_r($matches);
			//echo "classement:\n\r";
			//print_r($RankServer);
		}
		usleep(1);
	}
   
	arsort($RankServer);
}
else {
	if ( LireFichier( 'srank.xml', $buffer ) ) {
		$RankServer = array();
		$RecordLogin = array();
		$a = preg_match_all('#<login>(.*)</login>#', $buffer, $matches);
		$b = preg_match_all('#<pts>(.*)</pts>#', $buffer, $matches2);
		$c = preg_match_all('#<nbrec>(.*)</nbrec>#', $buffer, $matches3);
		$i=0;
		foreach( $matches[1] as $login ) {
			$RankServer[$login] = intval($matches2[1][$i]);
			$RecordLogin[$login] = intval($matches3[1][$i]);
			$i++;
		}
	}
}

	echo "OK \n\r";
}

function map_ranking ($ChallengeList) {
//global $CurrentGameInfo;
global $client;
global $RankMap;
global $RankMap2;
global $reprecord;
global $Moyenne;
global $rank_ext;

	echo "Calcul rang map : ";

if (!$rank_ext) {
//	$NbChallenge = $CurrentGameInfo['NbChallenge'];
//	if ($NbChallenge > 0) {
//		if (!@$client->query('GetChallengeList',$NbChallenge , 0)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//			return false;
//		}
//	}
//	else   return false;
	
//	$ChallengeList = $client->getResponse();

	$RankMap = array();
	$Moyenne = 0;
	$NbMap = 0;
	foreach ($ChallengeList as $Challenge) {
		$filename=$Challenge['UId'];
		if(LireFichier($reprecord.$filename,$result)) {
			$tmp=strstr($result,'<Note>');
			$tmp=str_replace('<Note>','',$tmp);
			$stop=strpos($tmp,'</');
			if ($stop > 0) $Note1 = substr($tmp,0,$stop); else $Note1 = '-1';
			$tmp=strstr($result,'<NbVote>');
			$tmp=str_replace('<NbVote>','',$tmp);
			$stop=strpos($tmp,'</');
			if ($stop > 0) $Vote1 = substr($tmp,0,$stop); else $Vote1 = '0';
			if ($Note1 != '-1'){
				$Moyenne = $Moyenne + $Note1;
				$NbMap++;
			}
			if ($Note1 != '-1' && $Vote1 >=5){  
					$RankMap[$filename] = $Note1;
					$RankMap2[$filename] = $Vote1;
			}
		}
		usleep(1);
	}
	
	if ($NbMap) $Moyenne = $Moyenne / $NbMap;
	
	arsort($RankMap);
}
else {
	if ( LireFichier( 'rankmap.xml', $buffer ) ) {
		$RankMap = array();
		$m = preg_match_all('#<moyenne>(.*)</moyenne>#', $buffer, $matches1);
		foreach( $matches1[1] as $moyenne ) {
			$Moyenne = floatval($moyenne);
		}
		$a = preg_match_all('#<uid>(.*)</uid>#', $buffer, $matches);
		$b = preg_match_all('#<note>(.*)</note>#', $buffer, $matches2);
		$c = preg_match_all('#<nbvote>(.*)</nbvote>#', $buffer, $matches3);
		$i=0;
		foreach( $matches[1] as $uid ) {
			$RankMap[$uid] = floatval($matches2[1][$i]);
			$RankMap2[$uid] = intval($matches3[1][$i]);
			$i++;
		}
	}
}

	echo "OK \n\r";
}

function mappeur_ranking ($ChallengeList) {
//global $CurrentGameInfo;
global $client;
global $RankMappeur;
global $RankMappeur2;
global $reprecord;
global $rank_ext;

	echo "Calcul rang mappeur : ";

if (!$rank_ext) {
//	$NbChallenge = $CurrentGameInfo['NbChallenge'];
//	if ($NbChallenge > 0) {
//		if (!@$client->query('GetChallengeList',$NbChallenge , 0)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//			return false;
//		}
//	}
//	else   return false;
	
//	$ChallengeList = $client->getResponse();

	$moyen = 0;
	$RankMappeur = array();
	$RankMappeur2 = array();
	foreach ($ChallengeList as $Challenge) {
		$filename=$Challenge['UId'];
		if(LireFichier($reprecord.$filename,$result)) {
			$tmp=strstr($result,'<Note>');
			$tmp=str_replace('<Note>','',$tmp);
			$stop=strpos($tmp,'</');
			if ($stop > 0) $Note1 = substr($tmp,0,$stop); else $Note1 = '-1';
			$tmp=strstr($result,'<Author>');
			$tmp=str_replace('<Author>','',$tmp);
			$stop=strpos($tmp,'</');
			if ($stop > 0) $Author = substr($tmp,0,$stop); else $Author = ' ';
			if ($Note1 != '-1'){
				if (isset($RankMappeur[$Author])) {
//				if (array_key_exists($Author, $RankMappeur)) {
					$NbOccu = $RankMappeur2[$Author];
					$moyen = $RankMappeur[$Author];
					$RankMappeur[$Author] = ($moyen*$NbOccu + intval($Note1))/($NbOccu+1);
					$RankMappeur2[$Author]++;
				}else{
					$RankMappeur2["$Author"] = 1;
					$RankMappeur["$Author"] = 0;
					$points = $RankMappeur[$Author];
					$RankMappeur[$Author] = $Note1;
				}
			}
		}
		usleep(1);
	}
	
	arsort($RankMappeur);
}
else {
	if ( LireFichier( 'mrank.xml', $buffer ) ) {
		$RankMappeur = array();
		$RankMappeur2 = array();
		$a = preg_match_all('#<login>(.*)</login>#', $buffer, $matches);
		$b = preg_match_all('#<note>(.*)</note>#', $buffer, $matches2);
		$c = preg_match_all('#<nbmap>(.*)</nbmap>#', $buffer, $matches3);
		$i=0;
		foreach( $matches[1] as $login ) {
			$RankMappeur[$login] = floatval($matches2[1][$i]);
			$RankMappeur2[$login] = intval($matches3[1][$i]);
			$i++;
		}
	}
}

	echo "OK \n\r";
}

function purgeNick ($nick) {
	$str=$nick;
	$str=str_replace('$o','',$str);
	$str=str_replace('$O','',$str);
	$str=str_replace('$w','',$str);
	$str=str_replace('$W','',$str);
	$str=str_replace('$n','',$str);
	$str=str_replace('$N','',$str);
	$str=str_replace('$i','',$str);
	$str=str_replace('$I','',$str);
	return $str;
}

function GetVariable ($Var) {
global $use_ftp;
global $maxtop;
global $cadeau;
global $ftp_t_status;
global $cote;
global $copperreserve;
global $coppermin;
global $coppermax;
global $amende;
global $Note;
global $NbVote;
global $VoteNextSeuil;

global $wgminprice;
global $wgmaxprice;
global $wgfreq;
global $wgplayer;

global $use_exchange;
global $auto_savereplay;

global $racetype;

global $norecord;

	if ($Var=='use_ftp') return $use_ftp;
	if ($Var=='maxtop') return $maxtop;
	if ($Var=='cadeau') return $cadeau;
	if ($Var=='ftp_t_status') return $ftp_t_status;
	if ($Var=='cote') return $cote;
	if ($Var=='copperreserve') return $copperreserve;
	if ($Var=='coppermin') return $coppermin;
	if ($Var=='coppermax') return $coppermax;
	if ($Var=='amende') return $amende;
	if ($Var=='Note') return $Note;
	if ($Var=='NbVote') return $NbVote;
	if ($Var=='VoteNextSeuil') return $VoteNextSeuil;

	if ($Var=='wgminprice') return $wgminprice;
	if ($Var=='wgmaxprice') return $wgmaxprice;
	if ($Var=='wgfreq') return $wgfreq;
	if ($Var=='wgplayer') return $wgplayer;

	if ($Var=='use_exchange') return $use_exchange;
	if ($Var=='auto_savereplay') return $auto_savereplay;

	if ($Var=='racetype') return $racetype;
	
	if ($Var=='norecord') return $norecord;
}

function Injure ($login,$nick,$chatline) {
global $client;
global $sunrise;
global $amende;
global $Bill;
global $Prohibe;
global $Inj;
global $InjureCount;
global $messages;
global $txt;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerAccount;

	if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

	foreach($Prohibe as $mot) {
		if (stristr(stripColors($chatline,1),$mot)) {
			if ($amende<=0) {
				SendMsgToLogin ('$0f0'.$txtl['_'.$PlayerLanguage[$login]]['MOT INTERDIT'],$login);
				return;
			}
			elseif (($sunrise == 2) && ($PlayerAccount[$login]==3)) { //mode tmu et player tmu
				if (!$client->query("SendBill",purgelogin($login),$amende,'$0f0'.$txtl['_'.$PlayerLanguage[$login]]['MOT INTERDIT'],'')) {
					SendMsgToLogin ('$0f0'.$txtl['_'.$PlayerLanguage[$login]]['MOT INTERDIT'],$login);
					Error($client->getErrorMessage(), $client->getErrorCode());
				}else{
					$BillId = $client->getResponse();
	
					$msg = '$m'.purgeNick($nick).'$z$fff '.txtbal('paye').' $0f0'.$amende.'$fff coppers '.txtbal('pour grossierete');
					
					$Bill['BillMsg'][$BillId] = $msg;
					$Bill['BillType'][$BillId] = 'amende';
					$Bill['Login'][$BillId] = purgelogin($login);
					$Bill['ToLogin'][$BillId] = '';
					$Inj['BillId'][$InjureCount] = $BillId;
					$Inj['Login'][$InjureCount] = purgelogin($login);
					$Inj['NickName'][$InjureCount] = $nick;
					$InjureCount++;
	       			}
			}
			else {
				SendMsgToLogin ('$0f0'.$txtl['_'.$PlayerLanguage[$login]]['MOT INTERDIT'],$login);
				if (!$client->query("Kick",$login)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					$msg = '$m'.purgeNick($nick).'$z$fff '.txtbal('kicked').' '.txtbal('pour grossierete');
					ChatSendServerMessage($msg);
				}
			}
		}
	}
}

function Recompense($login,$Nick,$cop) {
global $client;
global $sunrise;
global $msg_cadeau;
global $messages;
global $Bill;
global $copperreserve;
global $txt;
global $PlayerAccount;

	if ($sunrise != 2) return;	//mode tmu seulement
	if (!$PlayerAccount[$login]) return;	//player tmu seulement

	$Coppers=0;
	if (!$client->query("GetServerCoppers")) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}	
	else {
		$Coppers = $client->getResponse();
		echo "Coppers restants: " . $Coppers . "\n\r";
	}
	if ($Coppers > ($copperreserve+$cop)) {
		if (!$client->query("Pay",$login,$cop,$msg_cadeau)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
		else {
			$BillId = $client->getResponse();
			echo "cadeau de ".$cop." coppers a ".$login." BillId : " . $BillId . "\n\r";
			$msg = purgeNick($Nick).' $z$fff'.txtbal('gagne').' $0f0'.$cop.'$fff coppers';
			$Bill['BillMsg'][$BillId] = $msg;
			$Bill['BillType'][$BillId] = 'don';
			$Bill['Login'][$BillId] = '';
			$Bill['ToLogin'][$BillId] = $login;
		}
	}
	else	echo "reserve de coppers atteinte !!!!!!!\n\r";
}

function RecompenseBonus($login,$Nick,$cop,$spscore) {
global $client;
global $sunrise;
global $msg_cadeau;
global $messages;
global $Bill;
global $copperreserve;
global $txt;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerAccount;

	if ($sunrise != 2) return;	//mode tmu seulement
	if (!$PlayerAccount[$login]) return;	//player tmu seulement

	if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

	if (rand(0,1)==0) {
		$msg = ' $z$fff'.$txtl['_'.$PlayerLanguage[$login]]['bravo mais ce score bonus ne rapporte rien :)'];
		ChatSendServerMessageToLogin( $msg, $login);
		return;
	}

	$Coppers=0;
	if (!$client->query("GetServerCoppers")) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}	
	else {
		$Coppers = $client->getResponse();
		echo "Coppers restants: " . $Coppers . "\n\r";
	}
	if ($Coppers > ($copperreserve+$cop)) {
		if (!$client->query("Pay",$login,$cop,$msg_cadeau)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
		else {
			$BillId = $client->getResponse();
			echo "score bonus ".MwTimeToString($spscore)." cadeau de ".$cop." coppers a ".$login." BillId : " . $BillId . "\n\r";
			$msg = purgeNick($Nick).' $z$fff'.txtbal('gagne').' $0f0'.$cop.'$fff coppers '.txtbal('pour score bonus').' $0f0'.MwTimeToString($spscore);
			$Bill['BillMsg'][$BillId] = $msg;
			$Bill['BillType'][$BillId] = 'don';
			$Bill['Login'][$BillId] = '';
			$Bill['ToLogin'][$BillId] = $login;
		}
	}
	else	echo "reserve de coppers atteinte !!!!!!!\n\r";
}

function PariValidation($login,$score) {
global $sunrise;
global $Pari;
global $PariCount;
global $CurrentGameMode;

	if ($sunrise != 2) return;

	for ($i=0;$i<$PariCount;$i++) {
		if ($Pari['Login'][$i]==$login) {
			if ($Pari['Payed'][$i]) {
				if (($Pari['Score'][$i]<=$score)&&($CurrentGameMode==4)) {
					$Pari['Ok'][$i]=true;
					echo "Pari de ".$login." valide\n\r";
					SavePari($i+1);
				}
				if (($Pari['Score'][$i]>=$score)&&($CurrentGameMode!==4)) {
					$Pari['Ok'][$i]=true;
					echo "Pari de ".$login." valide\n\r";
					SavePari($i+1);
				}
			}
		}
	}
}

function PariGain() {
global $sunrise;
global $Pari;
global $PariCount;
global $client;
global $cote;
global $messages;
global $Bill;
global $maxtop;
global $txt;
global $txtl;
global $PlayerLanguage;
global $lang;

	if ($sunrise != 2) return;

	for ($i=0;$i<$PariCount;$i++) {
		if ($Pari['Ok'][$i]) {
			if (!isset($PlayerLanguage[$Pari['Login'][$i]])) $PlayerLanguage[$Pari['Login'][$i]]=$lang;
			$part=intval($Pari['Coppers'][$i]+($cote*$Pari['Coppers'][$i]/($Pari['Visee'][$i]/$Pari['Actuelle'][$i])/$maxtop));
			if (!$client->query("Pay",$Pari['Login'][$i],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Pari['Login'][$i]]]['PARI sur'].' '.MwTimeToString($Pari['Score'][$i]).' '.$txtl['_'.$PlayerLanguage[$Pari['Login'][$i]]]['tenu'])) {
				Error($client->getErrorMessage(), $client->getErrorCode());
			}	
			else {
				$BillId = $client->getResponse();
				echo "gain de ".$part." coppers a ".$Pari['Login'][$i]." BillId : " . $BillId . "\n\r";
				$msg = purgeNick ($Pari['NickName'][$i]).' $z$fff'.txtbal('gagne').' $0f0'.$part.'$fff coppers '.txtbal('sur pari');
				$Bill['BillMsg'][$BillId] = $msg;
				$Bill['BillType'][$BillId] = 'don';
				$Bill['Login'][$BillId] = '';
				$Bill['ToLogin'][$BillId] = $Pari['Login'][$i];
			}
		}
	}
	$PariCount=0;
	SavePari($PariCount);
}

function DuelValidation($login,$score) {
global $sunrise;
global $Duel;
global $DuelCount;
global $CurrentGameMode;
global $client;
global $messages;
global $txt;

	if ($sunrise != 2) return;

	for ($i=0;$i<$DuelCount;$i++) {
		if ($Duel['Login'][$i]==$login) {
			if ($Duel['Payed'][$i]) {

				if ((intval($Duel['Score'][$i])<$score)&&($CurrentGameMode==4)) {
					$Duel['Score'][$i]=intval($score);
					echo "score de $login $score \n\r";
					SaveDuel($i+1);
				}
				if (((intval($Duel['Score'][$i])>$score)||(intval($Duel['Score'][$i])==0))&&($CurrentGameMode!==4)) {
					$Duel['Score'][$i]=intval($score);
					SaveDuel($i+1);
					echo "score de $login $score \n\r";
				}

				for ($j=0;$j<$DuelCount;$j++) {
					if ($Duel['Login'][$j]==$Duel['ToLogin'][$i]) {
						if ($Duel['Payed'][$j]) {
							$reprend = false;
							if ((intval($Duel['Score'][$j])<=$score)&&($CurrentGameMode==4)) {
								if ($Duel['Ok'][$i]==false) $reprend = true;
								$Duel['Ok'][$i]=true;
								$Duel['Coef'][$i]=1;
								$Duel['Coef'][$j]=1;
								echo "Duel de ".$login." valide\n\r";
								SaveDuel($i+1);
								SaveDuel($j+1);
							}
							if ((intval($Duel['Score'][$j])<$score)&&($CurrentGameMode==4)) {
								if ($Duel['Ok'][$j]==false) {
									$msg = '$z'.purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('ridiculise').' $z'.purgeNick($Duel['NickName'][$j]);
								}
								else {
									if ($reprend) {
										$msg = '$z'.purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('rattrape').' $z'.purgeNick($Duel['NickName'][$j]);
									}
									else {
										$msg = '$z'.purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('depasse').' $z'.purgeNick($Duel['NickName'][$j]);
									}
								}
								ChatSendServerMessage($msg);

								$Duel['Ok'][$j]=false;
								$Duel['Coef'][$i]=2;
								$Duel['Coef'][$j]=1;
								echo "Duel de ".$login." valide et gagnant\n\r";
								SaveDuel($i+1);
								SaveDuel($j+1);
							}
							if (((intval($Duel['Score'][$j])>=$score)||(intval($Duel['Score'][$j])==0))&&($CurrentGameMode!==4)) {
								if ($Duel['Ok'][$i]==false) $reprend = true;
								$Duel['Ok'][$i]=true;
								$Duel['Coef'][$i]=1;
								$Duel['Coef'][$j]=1;
								echo "Duel de ".$login." valide\n\r";
								SaveDuel($i+1);
								SaveDuel($j+1);
							}
							if (((intval($Duel['Score'][$j])>$score)||(intval($Duel['Score'][$j])==0))&&($CurrentGameMode!==4)) {
								if ($Duel['Ok'][$j]==false) {
									$msg = '$z'.purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('ridiculise').' $z'.purgeNick($Duel['NickName'][$j]);
								}
								else {
									if ($reprend) {
										$msg = '$z'.purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('rattrape').' $z'.purgeNick($Duel['NickName'][$j]);
									}
									else {
										$msg = '$z'.purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('depasse').' $z'.purgeNick($Duel['NickName'][$j]);
									}
								}
								ChatSendServerMessage($msg);

								$Duel['Ok'][$j]=false;
								$Duel['Coef'][$i]=2;
								$Duel['Coef'][$j]=1;
								echo "Duel de ".$login." valide et gagnant\n\r";
								SaveDuel($i+1);
								SaveDuel($j+1);
							}
						}
					}
				}
			}
		}
	}
}

function DuelGain() {
global $sunrise;
global $Duel;
global $DuelCount;
global $client;
global $cote;
global $messages;
global $Bill;
global $maxtop;
global $txt;
global $txtl;
global $PlayerLanguage;
global $lang;

	if ($sunrise != 2) return;

	for ($i=0;$i<$DuelCount;$i++) {
		if ($Duel['Ok'][$i] && $Duel['Payed'][$i]){
			$part=intval($Duel['Coppers'][$i])*intval($Duel['Coef'][$i]);
			if (!isset($PlayerLanguage[$Duel['Login'][$i]])) $PlayerLanguage[$Duel['Login'][$i]]=$lang;

			if (!$client->query("Pay",$Duel['Login'][$i],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Duel['Login'][$i]]]['Duel avec'].' '.$Duel['ToNickName'][$i])) {
				Error($client->getErrorMessage(), $client->getErrorCode());
			}	
			else {
				$BillId = $client->getResponse();
				echo "gain de ".$part." coppers a ".$Duel['Login'][$i]." BillId : " . $BillId . "\n\r";
				$msg = purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('gagne').' $0f0'.$part.'$fff coppers '.txtbal('sur duel');
				$Bill['BillMsg'][$BillId] = $msg;
				$Bill['BillType'][$BillId] = 'don';
				$Bill['Login'][$BillId] = '';
				$Bill['ToLogin'][$BillId] = $Duel['Login'][$i];
			}
		}
	}
	$DuelCount=0;
	SaveDuel($DuelCount);
}

function isadmin($login) {
global $admin;

	$found = false;
	foreach ($admin as $adm) {
		if ($adm == purgelogin($login)) $found = true;
	}
	return $found;
}

function isadmin2($login) {
global $admin2;

	$found = false;
	foreach ($admin2 as $adm) {
		if ($adm == purgelogin($login)) $found = true;
	}
	return $found;
}

function searchmap ($text , &$result, &$result2) {
global $CurrentGameInfo;
global $client;

	echo "recherche Challenge [" . $text . "]\n\r";

	$NbChallenge = $CurrentGameInfo['NbChallenge'];
	if ($NbChallenge > 0) {
		if (!@$client->query('GetChallengeList',$NbChallenge + 1 , 0)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			return 0;
		}
	}
	else	return 0;
	
	$ChallengeList = $client->getResponse();

	$found = 0;
	foreach ($ChallengeList as $Challenge) {
		$ChallengeName = stripColors($Challenge['Name'],1); 
		if (stristr($ChallengeName, $text)) {
//			if (!$found) {
				$result = $Challenge['FileName'];
				$result2 = $ChallengeName;
//			}
			echo "Challenge trouve : [" . $ChallengeName . "]\n\r";
			if (strcasecmp($ChallengeName , $text)==0) {$found=1; break;}
			$found++;
		}
	}
	return $found;
}


function searchmapTMX ($tmx, $num, &$ChallengeType) {
global $client;
global $TracksDirectory;

	$result=file_get_contents('http://'.$tmx.'.tm-exchange.com/get.aspx?action=trackgbx&id='.$num);
	if ($result) {
		$tmp=strstr($result,'<ident');
		$tmp=strstr($tmp,'name="');
		$tmp=substr($tmp,0,200);
		$tmp=str_replace('name="','',$tmp);
		$stop=strpos($tmp,'"');
		if ($stop > 0) {
			$xname=substr($tmp,0,$stop);
		} else {
			$xname="";
		}
//		echo $xname."\n\r";

		$tmp=strstr($result,'<ident');
		$tmp=strstr($tmp,'author="');
		$tmp=substr($tmp,0,40);
		$tmp=str_replace('author="','',$tmp);
		$stop=strpos($tmp,'"');
		if ($stop > 0) {
			$xauthor=substr($tmp,0,$stop);
		} else {
			$xauthor="";
		}
//		echo $xauthor."\n\r";

		$tmp=strstr($result,'<desc');
		$tmp=strstr($tmp,'type="');
		$tmp=substr($tmp,0,20);
		$tmp=str_replace('type="','',$tmp);
		$stop=strpos($tmp,'"');
		if ($stop > 0) {
			$xtype=substr($tmp,0,$stop);
		} else {
			$xtype="";
		}
//		echo $xtype."\n\r";

		$tmp=strstr($result,'<desc');
		$tmp=strstr($tmp,'envir="');
		$tmp=substr($tmp,0,20);
		$tmp=str_replace('envir="','',$tmp);
		$stop=strpos($tmp,'"');
		if ($stop > 0) {
			$xenvir=substr($tmp,0,$stop);
		} else {
			$xenvir="";
		}
//		echo $xenvir."\n\r";

		if ($xname != "" && $xtype != "" && $xauthor != "" && $xenvir != "") {
			$file = 'Challenges//Downloaded//'.$tmx.'-exchange-'.$num.'.Challenge.Gbx';
			file_put_contents($TracksDirectory.$file,$result);
			$ChallengeType=$xtype;
			$ChallengeAuthor=$xauthor;
			$ChallengeName=$xname;
			$ChallengeEnv=$xenvir;
			return $file;
		}
		else {
			echo "fichier gbx ?\n\r";
			return "";
		}

	}
	else {
		echo "fichier existe ?\n\r";
		return "";
	}
}

function getposition ($login) {
global $TopLogin;
global $maxtop;

	$position=-1;
	for ($i=0; $i<$maxtop; $i++) if ($TopLogin[$i]==purgelogin($login)) {$position=$i; break;}
	return $position+1;
}

function getpositionscore ($score) {
global $maxtop;
global $TopBestTime;
global $CurrentGameMode;

	$position=-1;
	if ($CurrentGameMode==4) {
		for ($i=0; $i<$maxtop; $i++) {
			if ($score<=$TopBestTime[$i]) {$position=$i; break;}
		}
	}
	elseif ($CurrentGameMode!==4) {
		for ($i=0; $i<$maxtop; $i++) {
			if ($score>=$TopBestTime[$i]) {$position=$i; break;}
		}
	}
	return $position+1;
}

function TestStunt($ChallengeFileName)
{
	$pos = getchallengetype($ChallengeFileName);
	if ($pos !== "Stunts") return 0; else return 1;
}

function TestLaps($ChallengeFileName)
{
global $client;

		if (!@$client->query('GetChallengeInfo', $ChallengeFileName)) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		   return 0;
		}
		else {
			$ChallengeInfo = $client->getResponse();
			$LapRace = $ChallengeInfo['LapRace'];
			if ($LapRace) return 1; else return 0;
		}
}

function getchallengetype($ChallengeFileName)
{
global $client;
global $TracksDirectory;

	if(LireFichier($TracksDirectory.$ChallengeFileName,$result)) {
		$tmp=strstr($result,'<desc');
		$tmp=strstr($tmp,'type="');
		$tmp=substr($tmp,0,20);
		$tmp=str_replace('type="','',$tmp);
		$stop=strpos($tmp,'"');
		if ($stop > 0) return substr($tmp,0,$stop); else return "";
	}

	return "";
}

function getnblaps($ChallengeFileName)
{
global $client;
global $TracksDirectory;

	if(LireFichier($TracksDirectory.$ChallengeFileName,$result)) {
		$tmp=strstr($result,'<desc');
		$tmp=strstr($tmp,'nblaps="');
		$tmp=substr($tmp,0,20);
		$tmp=str_replace('nblaps="','',$tmp);
		$stop=strpos($tmp,'"');
		if ($stop > 0) return substr($tmp,0,$stop); else return "";
	}

	return "";
}

function save_ftp2($remote_file,$file) {
global $use_ftp;
global $ftp_server;
global $ftp_user;
global $ftp_pass;
global $conn_id;

	// Mise en place d'une connexion basique
	if (!$conn_id) {
		$conn_id = @ftp_connect($ftp_server); 
		if ($conn_id) {
			// Définission du délai de connexion à 2 secondes
			if (!@ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 2)) {
		    		echo "ftp_set_option echec\n";
			}
			// Tentative d'identification
			if (!@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
				echo "Connexion impossible en tant que $ftp_user\n";
				// Fermeture de la connexion
				ftp_close($conn_id);  
				$conn_id = 0; 
			}
			else {
				// Activation du mode passif
				if (!@ftp_pasv($conn_id, true)) {
					echo "ftp_pasv echec\n";
					ftp_close($conn_id);  
					$conn_id = 0; 
				}
			}
		}
		else {
			echo "Couldn't connect to $ftp_server\n\r";
		}
	}

	if ($conn_id) {
			// ecrit un fichier
			if (!@ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
//				echo "erreur ecriture fichier $file\n";
				// Fermeture de la connexion
				ftp_close($conn_id);  
				$conn_id = 0; 
			}
			else unlink($file);
	}
}

function save_ftp($remote_file,$file,$force) {
global $use_ftp;
global $ftp_server;
global $ftp_user;
global $ftp_pass;
global $ftp_ext;
global $repftptmp;
global $ftp_perm;

	if (!$use_ftp) return;

	if ($ftp_ext || $force) {
		if (!copy($file, $repftptmp.$file)) {
			echo "La copie du fichier $file dans $repftptmp.$file n'a pas réussi...\n\r";
		}
		return;
	}

	if ($ftp_perm) {
		save_ftp2($remote_file,$file);
		return;
	}

	// Mise en place d'une connexion basique
	$conn_id = @ftp_connect($ftp_server); 
	if ($conn_id) {
		// Définission du délai de connexion à 2 secondes
		if (!@ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 2)) {
		    echo "ftp_set_option echec\n";
		}
		// Tentative d'identification
		if (!@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
		    echo "Connexion impossible en tant que $ftp_user\n";
		}
		else {
			// Activation du mode passif
			if (!@ftp_pasv($conn_id, true)) {
				echo "ftp_pasv echec\n";
			}
			else {
				// ecrit un fichier
				if (!@ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
//					echo "erreur ecriture fichier $file\n";
				}
				else unlink($file);
			}
		}
		// Fermeture de la connexion
		ftp_close($conn_id);  
	}
	else echo "Couldn't connect to $ftp_server\n\r";
}

function Etat_Serveur() {
global $client;
global $PlayerList;
global $ChatLines;
global $CurrentChallenge;
global $CurrentGameMode;
global $CurrentGameInfo;
global $remote_status;
global $local_status;
global $use_ftp;
global $MaxPlayer;
global $TracksDirectory;
global $remote_maplist;
global $local_maplist;
global $repplayer;
global $reprecord;
global $repftptmp;
global $ftpplayer;
global $ftprecord;
global $ftp_ext;

	$handle = fopen($local_status, 'wb');
	if($handle) {
		fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
		fprintf($handle,"\n");
		fprintf($handle,'<status>');
		fprintf($handle,"\n");
	}

	if ($PlayerList=="") {
		if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
			Error($client->getErrorMessage(), $client->getErrorCode());
		}else{
			$PlayerList = $client->getResponse();
		}
	}

	$i=0;
	foreach ($PlayerList as $Player ) {
		$i++;
		if($handle) {
			fprintf($handle,'<login'.$i.'>');
			fprintf($handle,"%s",purgelogin($Player['Login']));
			fprintf($handle,'</login'.$i.'>');
			fprintf($handle,"\n");
		}
	}

	if($handle) {
		fprintf($handle,'<nbplayer>');
		fprintf($handle,"%s",$i);
		fprintf($handle,'</nbplayer>');
		fprintf($handle,"\n");
	}

	if ($CurrentGameMode == -1) {
		if (!@$client->query('GetCurrentGameInfo')) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$CurrentGameInfo = $client->getResponse();
		}
	}

	$CurrentGameMode = $CurrentGameInfo['GameMode'];

	if($handle) {
		fprintf($handle,'<mode>');
		fprintf($handle,"%s",$CurrentGameMode);
		fprintf($handle,'</mode>');
		fprintf($handle,"\n");
	}


	if ($CurrentChallenge['UId']=="") {
		if(!@$client->query("GetCurrentChallengeInfo")){
			Error($client->getErrorMessage(), $client->getErrorCode());
		}else{
			$CurrentChallenge = $client->getResponse();
		}
	}

	$CurrentChallengeUId=$CurrentChallenge['UId'];

	if($handle) {
		fprintf($handle,'<uid>');
		fprintf($handle,"%s",$CurrentChallengeUId);
		fprintf($handle,'</uid>');
		fprintf($handle,"\n");
	}


//	if ($ChatLines=="") {
		if(!@$client->query("GetChatLines")){
			Error($client->getErrorMessage(), $client->getErrorCode());
		}else{
			$ChatLines = $client->getResponse();
		}
//	}

	$i=0;
	foreach ($ChatLines as $ChatLine ) {
		$i++;
		if($handle) {
			fprintf($handle,'<chat'.$i.'>');
			fprintf($handle,"%s",$ChatLine);
			fprintf($handle,'</chat'.$i.'>');
			fprintf($handle,"\n");
		}
	}

	if($handle) {
		fprintf($handle,'</status>');
		fprintf($handle,"\n");

		fclose($handle);
	}


	$NbChallenge = $CurrentGameInfo['NbChallenge'];
	if ($NbChallenge > 0) {
		if (!@$client->query('GetChallengeList',$NbChallenge , 0)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else {
			$ChallengeList = $client->getResponse();

			$handle = fopen($local_maplist, 'wb');
			if($handle) {
				fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
				fprintf($handle,"\n");
				fprintf($handle,'<playlist>');
				fprintf($handle,"\n");

				foreach ($ChallengeList as $Challenge ) {
					fprintf($handle,'<ident>');
					fprintf($handle,"%s",$Challenge['UId']);
					fprintf($handle,'</ident>');
					fprintf($handle,"\n");
				}

				fprintf($handle,'</playlist>');
				fprintf($handle,"\n");

				fclose($handle);
			}
		}
	}

	if ($use_ftp==1) {
		echo "[".date("H:i:s")."]". " envoi status serveur vers ftp\n\r";
//		save_ftp($remote_status,$local_status);
//		save_ftp($remote_maplist,$local_maplist);
		save_ftp($remote_status,$local_status, True);
		save_ftp($remote_maplist,$local_maplist, True);
		if ($ftp_ext==0) {
			if ($handle = @opendir($repftptmp.$repplayer)) {
			//    echo "Directory handle: $handle\n\r";
			//    echo "Files\n\r>";
				while (false !== ($file = readdir($handle))) {
					if ( is_file($repftptmp.$repplayer.$file)) { 
						save_ftp($ftpplayer.$file, $repftptmp.$repplayer.$file, False);
					}
				}
				closedir($handle);
			}
			if ($handle = @opendir($repftptmp.$reprecord)) {
			//    echo "Directory handle: $handle\n\r";
			//    echo "Files\n\r>";
				while (false !== ($file = readdir($handle))) {
					if ( is_file($repftptmp.$reprecord.$file)) { 
						save_ftp($ftprecord.$file, $repftptmp.$reprecord.$file, False);
					}
				}
			
				closedir($handle);
			}
			if ($handle = @opendir($repftptmp)) {
			//    echo "Directory handle: $handle\n\r";
			//    echo "Files\n\r>";
				while (false !== ($file = readdir($handle))) {
					if ( is_file($repftptmp.$file)) { 
						if ($file == $local_status) save_ftp($remote_status, $repftptmp.$file, False);
						if ($file == $local_maplist) save_ftp($remote_maplist, $repftptmp.$file, False);
					}
				}
			
				closedir($handle);
			}
		}
	}

}

function SavePari($indice) {
global $Pari;
global $PariCount;
global $Bill;

	$file = 'PariCount.xml';
	$handle = fopen($file, 'wb');
	if($handle) {
		fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
		fprintf($handle,"\n");
		fprintf($handle,'<paricount>');
		fprintf($handle,"%s",$PariCount);
		fprintf($handle,'</paricount>');
		fprintf($handle,"\n");
		fclose($handle);
	}

	if ($indice) {
		$file = 'Pari'.$indice.'.xml';
		$handle = fopen($file, 'wb');
		if($handle) {
			fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillId>');
			fprintf($handle,"%s",$Pari['BillId'][$indice-1]);
			fprintf($handle,'</BillId>');
			fprintf($handle,"\n");

			fprintf($handle,'<Score>');
			fprintf($handle,"%s",$Pari['Score'][$indice-1]);
			fprintf($handle,'</Score>');
			fprintf($handle,"\n");

			fprintf($handle,'<Coppers>');
			fprintf($handle,"%s",$Pari['Coppers'][$indice-1]);
			fprintf($handle,'</Coppers>');
			fprintf($handle,"\n");

			fprintf($handle,'<Login>');
			fprintf($handle,"%s",$Pari['Login'][$indice-1]);
			fprintf($handle,'</Login>');
			fprintf($handle,"\n");

			fprintf($handle,'<NickName>');
			fprintf($handle,"%s",$Pari['NickName'][$indice-1]);
			fprintf($handle,'</NickName>');
			fprintf($handle,"\n");

			fprintf($handle,'<Visee>');
			fprintf($handle,"%s",$Pari['Visee'][$indice-1]);
			fprintf($handle,'</Visee>');
			fprintf($handle,"\n");

			fprintf($handle,'<Actuelle>');
			fprintf($handle,"%s",$Pari['Actuelle'][$indice-1]);
			fprintf($handle,'</Actuelle>');
			fprintf($handle,"\n");

			fprintf($handle,'<Payed>');
			fprintf($handle,"%s",$Pari['Payed'][$indice-1]);
			fprintf($handle,'</Payed>');
			fprintf($handle,"\n");

			fprintf($handle,'<Ok>');
			fprintf($handle,"%s",$Pari['Ok'][$indice-1]);
			fprintf($handle,'</Ok>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillMsg>');
			fprintf($handle,"%s",$Bill['BillMsg'][$Pari['BillId'][$indice-1]]);
			fprintf($handle,'</BillMsg>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillType>');
			fprintf($handle,"%s",$Bill['BillType'][$Pari['BillId'][$indice-1]]);
			fprintf($handle,'</BillType>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillLogin>');
			fprintf($handle,"%s",$Bill['Login'][$Pari['BillId'][$indice-1]]);
			fprintf($handle,'</BillLogin>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillToLogin>');
			fprintf($handle,"%s",$Bill['ToLogin'][$Pari['BillId'][$indice-1]]);
			fprintf($handle,'</BillToLogin>');
			fprintf($handle,"\n");

			fclose($handle);
		}
	}

}

function ReadPari() {
global $Pari;
global $PariCount;
global $Bill;

	if(LireFichier('PariCount.xml',$result)) {
		//echo "ReadPari : ".$result;
		$tmp=strstr($result,'<paricount>');
		$tmp=str_replace('<paricount>','',$tmp);
		$stop=strpos($tmp,'</');
		$PariCount = substr($tmp,0,$stop);
	}
	else $PariCount=0;

	for ($i=0;$i<$PariCount;$i++) {
		if(LireFichier('Pari'.($i+1).'.xml',$result)) {
			//echo "ReadPari : ".$result;
			$tmp=strstr($result,'<BillId>');
			$tmp=str_replace('<BillId>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['BillId'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Score>');
			$tmp=str_replace('<Score>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['Score'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Coppers>');
			$tmp=str_replace('<Coppers>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['Coppers'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Login>');
			$tmp=str_replace('<Login>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['Login'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<NickName>');
			$tmp=str_replace('<NickName>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['NickName'][$i] = substr($tmp,0,$stop);


			$tmp=strstr($result,'<Visee>');
			$tmp=str_replace('<Visee>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['Visee'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Actuelle>');
			$tmp=str_replace('<Actuelle>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['Actuelle'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Payed>');
			$tmp=str_replace('<Payed>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['Payed'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Ok>');
			$tmp=str_replace('<Ok>','',$tmp);
			$stop=strpos($tmp,'</');
			$Pari['Ok'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillMsg>');
			$tmp=str_replace('<BillMsg>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['BillMsg'][$Pari['BillId'][$i]] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillType>');
			$tmp=str_replace('<BillType>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['BillType'][$Pari['BillId'][$i]] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillLogin>');
			$tmp=str_replace('<BillLogin>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['Login'][$Pari['BillId'][$i]] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillToLogin>');
			$tmp=str_replace('<BillToLogin>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['ToLogin'][$Pari['BillId'][$i]] = substr($tmp,0,$stop);
		}
		else {
			$Pari['BillId'][$i] = 0;
			$Pari['Score'][$i] = 0;
			$Pari['Coppers'][$i] = 0;
			$Pari['Login'][$i] = '';
			$Pari['NickName'][$i] = '';
			$Pari['Visee'][$i] = 0;
			$Pari['Actuelle'][$i] = 0;
			$Pari['Payed'][$i] = false;
			$Pari['Ok'][$i] = false;
			$Bill['BillMsg'][$Pari['BillId'][$i]] = '?';
			$Bill['BillType'][$Pari['BillId'][$i]] = '?';
			$Bill['Login'][$Pari['BillId'][$i]] = '';
			$Bill['ToLogin'][$Pari['BillId'][$i]] = '';
		}
	}

}

function SaveDuel($indice) {
global $Duel;
global $DuelCount;
global $Bill;

	$file = 'DuelCount.xml';
	$handle = fopen($file, 'wb');
	if($handle) {
		fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
		fprintf($handle,"\n");
		fprintf($handle,'<duelcount>');
		fprintf($handle,"%s",$DuelCount);
		fprintf($handle,'</duelcount>');
		fprintf($handle,"\n");
		fclose($handle);
	}

	if ($indice) {
		$file = 'Duel'.$indice.'.xml';
		$handle = fopen($file, 'wb');
		if($handle) {
			fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillId>');
			fprintf($handle,"%s",$Duel['BillId'][$indice-1]);
			fprintf($handle,'</BillId>');
			fprintf($handle,"\n");

			fprintf($handle,'<Score>');
			fprintf($handle,"%s",$Duel['Score'][$indice-1]);
			fprintf($handle,'</Score>');
			fprintf($handle,"\n");

			fprintf($handle,'<Coppers>');
			fprintf($handle,"%s",$Duel['Coppers'][$indice-1]);
			fprintf($handle,'</Coppers>');
			fprintf($handle,"\n");

			fprintf($handle,'<Login>');
			fprintf($handle,"%s",$Duel['Login'][$indice-1]);
			fprintf($handle,'</Login>');
			fprintf($handle,"\n");

			fprintf($handle,'<NickName>');
			fprintf($handle,"%s",$Duel['NickName'][$indice-1]);
			fprintf($handle,'</NickName>');
			fprintf($handle,"\n");

			fprintf($handle,'<ToLogin>');
			fprintf($handle,"%s",$Duel['ToLogin'][$indice-1]);
			fprintf($handle,'</ToLogin>');
			fprintf($handle,"\n");

			fprintf($handle,'<ToNickName>');
			fprintf($handle,"%s",$Duel['ToNickName'][$indice-1]);
			fprintf($handle,'</ToNickName>');
			fprintf($handle,"\n");

			fprintf($handle,'<Payed>');
			fprintf($handle,"%s",$Duel['Payed'][$indice-1]);
			fprintf($handle,'</Payed>');
			fprintf($handle,"\n");

			fprintf($handle,'<Ok>');
			fprintf($handle,"%s",$Duel['Ok'][$indice-1]);
			fprintf($handle,'</Ok>');
			fprintf($handle,"\n");

			fprintf($handle,'<Coef>');
			fprintf($handle,"%s",$Duel['Coef'][$indice-1]);
			fprintf($handle,'</Coef>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillMsg>');
			fprintf($handle,"%s",$Bill['BillMsg'][$Duel['BillId'][$indice-1]]);
			fprintf($handle,'</BillMsg>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillType>');
			fprintf($handle,"%s",$Bill['BillType'][$Duel['BillId'][$indice-1]]);
			fprintf($handle,'</BillType>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillLogin>');
			fprintf($handle,"%s",$Bill['Login'][$Duel['BillId'][$indice-1]]);
			fprintf($handle,'</BillLogin>');
			fprintf($handle,"\n");

			fprintf($handle,'<BillToLogin>');
			fprintf($handle,"%s",$Bill['ToLogin'][$Duel['BillId'][$indice-1]]);
			fprintf($handle,'</BillToLogin>');
			fprintf($handle,"\n");

			fclose($handle);
		}
	}

}

function ReadDuel() {
global $Duel;
global $DuelCount;
global $Bill;

	if(LireFichier('DuelCount.xml',$result)) {
		//echo "ReadDuel : ".$result;
		$tmp=strstr($result,'<duelcount>');
		$tmp=str_replace('<duelcount>','',$tmp);
		$stop=strpos($tmp,'</');
		$DuelCount = substr($tmp,0,$stop);
	}
	else $DuelCount=0;

	for ($i=0;$i<$DuelCount;$i++) {
		if(LireFichier('Duel'.($i+1).'.xml',$result)) {
			//echo "ReadDuel : ".$result;
			$tmp=strstr($result,'<BillId>');
			$tmp=str_replace('<BillId>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['BillId'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Score>');
			$tmp=str_replace('<Score>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['Score'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Coppers>');
			$tmp=str_replace('<Coppers>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['Coppers'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Login>');
			$tmp=str_replace('<Login>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['Login'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<NickName>');
			$tmp=str_replace('<NickName>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['NickName'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<ToLogin>');
			$tmp=str_replace('<ToLogin>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['ToLogin'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<ToNickName>');
			$tmp=str_replace('<ToNickName>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['ToNickName'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Payed>');
			$tmp=str_replace('<Payed>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['Payed'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Ok>');
			$tmp=str_replace('<Ok>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['Ok'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<Coef>');
			$tmp=str_replace('<Coef>','',$tmp);
			$stop=strpos($tmp,'</');
			$Duel['Coef'][$i] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillMsg>');
			$tmp=str_replace('<BillMsg>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['BillMsg'][$Duel['BillId'][$i]] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillType>');
			$tmp=str_replace('<BillType>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['BillType'][$Duel['BillId'][$i]] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillLogin>');
			$tmp=str_replace('<BillLogin>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['Login'][$Duel['BillId'][$i]] = substr($tmp,0,$stop);

			$tmp=strstr($result,'<BillToLogin>');
			$tmp=str_replace('<BillToLogin>','',$tmp);
			$stop=strpos($tmp,'</');
			$Bill['ToLogin'][$Duel['BillId'][$i]] = substr($tmp,0,$stop);
		}
		else {
			$Duel['BillId'][$i] = 0;
			$Duel['Score'][$i] = 0;
			$Duel['Coppers'][$i] = 0;
			$Duel['Login'][$i] = '';
			$Duel['NickName'][$i] = '';
			$Duel['ToLogin'][$i] = '';
			$Duel['ToNickName'][$i] = '';
			$Duel['Payed'][$i] = false;
			$Duel['Ok'][$i] = true;
			$Duel['Coef'][$i] = 1;
			$Bill['BillMsg'][$Duel['BillId'][$i]] = '?';
			$Bill['BillType'][$Duel['BillId'][$i]] = '?';
			$Bill['Login'][$Duel['BillId'][$i]] = '';
			$Bill['ToLogin'][$Duel['BillId'][$i]] = '';
		}
	}

}

function MwTimeToString($MwTime) 
{
global $CurrentGameMode;

	if ($MwTime < 0) {
		return "???";
	} else {
		if ($CurrentGameMode !== 4) {
			$minutes = sprintf("%02s",floor($MwTime/(1000*60)));
			$secondes = sprintf("%02s",floor(($MwTime-$minutes*60*1000)/1000));
			$mseconds = substr($MwTime,strlen($MwTime)-3,2);
			return $minutes.":".$secondes.".".$mseconds;
		} else return $MwTime;
	}
}

function LireFichier($file,&$result){
	$buffer = '';
	if (!file_exists($file)) return False;
	$buffer=file_get_contents($file);
	if( $buffer ){
		$result=$buffer;
		return True; 
	}else{
		return False;
	}
}

function SendDisplayManialinkInfo ($text, $timeout) {
//global $client;
global $PlayerList;
global $PlayerLanguage;
global $lang;
global $PlayerScript;

//fenetre en haut de l ecran avec texte

	foreach ($PlayerList as $Player) {
		$login=$Player['Login'];
		if ($PlayerScript[$login] == '1') {
			if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

/*
		$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink posx='0.72' posy='0.66'> 
  <type>default</type> 
  <format textsize='4'/> 
  <background bgcolor='7770' bgborderx='0.0' bgbordery='0.0'/> 
  <line height='0.2'><cell width='1.4'><text halign='left' textcolor='FF0F'><![CDATA[".translate($text,$PlayerLanguage[$login])."]]></text></cell></line> 
</manialink>";
*/
			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink posx='0.78' posy='0.74'> 
  <type>default</type> 
  <format textsize='4'/> 
  <background bgcolor='7770' bgborderx='0.0' bgbordery='0.0'/> 
  <line height='0.2'><cell width='1.4'><text halign='left' textcolor='FF0F'><![CDATA[".translate($text,$PlayerLanguage[$login])."]]></text></cell></line> 
</manialink>";

			addCall("SendDisplayManialinkPageToLogin", $login, $xml, $timeout, false);
//		if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, $timeout, false)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}	
		}
	}
	multiquery();

}

function SendDisplayManialinkPageToLogin ($login, $text, $timeout) {
global $client;

//fenetre au milieu de l ecran avec texte

/*
$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink posx='0.5' posy='0.84'> 
  <type>default</type> 
  <format textsize='4'/> 
  <background bgcolor='777A' bgborderx='0.03' bgbordery='0.03'/> 
  <line height='1.0'><cell width='1.0'><text halign='left' textcolor='FF0F'><![CDATA[".$text."]]></text></cell></line> 
  <line><cell height='0.04' width='1.0'><text halign='center' action='99' textcolor='F00F'>Ok</text></cell></line> 
</manialink>";
*/
$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='List'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-40 22 0'>
	<quad  sizen='82 23'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
	<label sizen='80 3'  posn='0 0 0' halign='left' style='TextTitle1'><![CDATA[".$text."]]></label>
<label sizen='80 3'  posn='40 -20 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
  </frame>
</manialink>";

	if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, $timeout, true)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}	

}

function SendDisplayManialinkPageToLogin2 ($login, $text, $timeout) {
global $client;

//fenetre au milieu de l ecran avec texte

/*
$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink posx='0.5' posy='0.74'> 
  <type>default</type> 
  <format textsize='2'/> 
  <background bgcolor='777A' bgborderx='0.03' bgbordery='0.03'/> 
  <line height='1.0'><cell width='1.0'><text halign='left' textcolor='FF0F'><![CDATA[".$text."]]></text></cell></line> 
  <line><cell height='0.04' width='1.0'><text halign='center' action='99' textcolor='F00F'>Ok</text></cell></line> 
</manialink>";
*/

$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='List'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-40 43 0'>
	<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
	<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$text."]]></label>
<label sizen='80 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
  </frame>
</manialink>";

	if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, $timeout, true)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}	

}

function SendDisplayManialinkAcceuil ($login, $text, $timeout) {
global $client;

//fenetre au milieu de l ecran avec texte

$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='Accu'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-40 43 0'>
	<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
	<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$text."]]></label>
<label sizen='80 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
  </frame>
</manialink>";

	if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, $timeout, true)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}	

}

function SendDisplayManialinkImage ($image,$timeout) {
global $client;

//fenetre avec image dedans

$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink posx='-0.4' posy='-0.4'> 
  <type>default</type> 
  <format textsize='1'/> 
  <background bgcolor='CCCE' bgborderx='0.00' bgbordery='0.00'/> 
  <line height='0.0'>
	<cell width='0.0'> 
		<icon width='0.25' height='0.25' halign='center' >
		".$image."
		</icon>
	</cell>
  </line>
</manialink>";

	if (!$client->query("SendDisplayManialinkPage", $xml, $timeout, true)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}	

}

function SendManiaVoteOk ($NextMapName) {
global $client;
global $txt;
global $CurrentGameInfo;
global $PlayerList;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerScript;
global $ScoreTable;
global $CurrentGameMode;

//fenetres avec message ok pour changer la map suivante

	foreach ($PlayerList as $Player) {
		$login=$Player['Login'];
		if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;
		
		if ($PlayerScript[$login] == '1') {
			$msg = txtbal('ok pour changer la map suivante').' ? $z'."\n\r".$NextMapName;
			$xml = "<manialink posx='1.0' posy='0.35' id='Next'> 
					<type>default</type> 
					<format textsize='2'/> 
					<background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
					<line>
					<cell height='0.02' width='1.0'><text halign='left' textcolor='FFFF'><![CDATA[".translate($msg,$PlayerLanguage[$login])."]]></text></cell>
					</line>
					<line>
					<cell height='0.02' width='0.25'><text halign='center' action='97' textcolor='0F0F'>Yes</text></cell>
					</line>
					<line>
					<cell height='0.02' width='0.25'><text halign='center' action='99' textcolor='F00F'>No</text></cell>
					</line>
					</manialink>
					<custom_ui>
					<notice visible='false'/>
					<challenge_info visible='true'/>
					<chat visible='true'/>
					<checkpoint_list visible='true'/>
					<round_scores visible='true'/>"; 
			//table de score standard pour round, team et cup
			if (($CurrentGameMode == 0) || ($CurrentGameMode == 2) || ($CurrentGameMode == 5) || ($ScoreTable)) $xml .= "<scoretable visible='true'/>"; else $xml .= "<scoretable visible='false'/>";
			$xml .= "<global visible='true'/>
					</custom_ui>
					";
		}
		else {
			$xml = "<manialink posx='1.0' posy='0.35' id='Next'></manialink>
					<custom_ui>
					<notice visible='true'/>
					<challenge_info visible='true'/>
					<chat visible='true'/>
					<checkpoint_list visible='true'/>
					<round_scores visible='true'/>
					<scoretable visible='true'/>
					<global visible='true'/>
					</custom_ui>
					";
		}


		addCall("SendDisplayManialinkPageToLogin", $login, $xml, 0, true);
//		if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}	
	}
	multiquery();

}

function SendManiaClearVoteOk () {
global $client;

//efface fenetres avec message ok pour changer la map suivante

		$xml = "<manialink posx='1.0' posy='0.35' id='Next'></manialink>";

		if (!$client->query("SendDisplayManialinkPage", $xml, 0, true)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	

}

function SendManiaDuelOk ($login, $msg) {
global $client;
global $txt;
global $CurrentGameInfo;
global $PlayerList;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerScript;

		$ret = false;

//fenetres avec message ok pour changer accepter un duel

		if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;
		
		if ($PlayerScript[$login] == '1') {
			$xml = "<manialink posx='1.0' posy='0.195' id='Duel'> 
  <type>default</type> 
  <format textsize='2'/> 
  <background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
  <line>
<cell height='0.02' width='1.0'><text halign='left' textcolor='FFFF'><![CDATA[".translate($msg,$PlayerLanguage[$login])."]]></text></cell>
</line>
<line>
<cell height='0.02' width='0.25'><text halign='center' action='94' textcolor='0F0F'>Yes</text></cell>
</line>
<line>
<cell height='0.02' width='0.25'><text halign='center' action='93' textcolor='F00F'>No</text></cell>
</line>
</manialink>
";
			if (@!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
			}	
			else {
				$ret = true;
			}
		}
		
		return $ret;
}

function SendManiaTopNext ($text, $text2) {
//$text=TOP5 $text2=next
global $client;
global $txt;
global $CurrentGameInfo;
global $PlayerList;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerScript;

//fenetre en haut avec a gauche TOP5 et a droite avec info Next map (et vote en bas au milieu)

if ($CurrentGameInfo['ChatTime']>0) {
	foreach ($PlayerList as $Player) {
		$login=$Player['Login'];
		if ($PlayerScript[$login] == '1') {
			if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='Top'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-39 47 0'>
	<quad  sizen='39 18'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow2' />
	<label sizen='37 16'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$text."]]></label>
  </frame>
</manialink>";
/*
<manialink>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-56 -26 0'>
	<quad  sizen='32 4'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow1' />
	<label sizen='30 4'  posn='0 0 0' halign='left' style='TextTitle3' >".'$0f0'.$txtl['_'.$PlayerLanguage[$login]]['Votez svp']."</label>
</frame>
</manialink>
<manialink>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-24 -26 0'>
	<quad  sizen='46 4'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow1' />
	<label sizen='3 2'  posn='2 0 0' halign='center' style='TextValueSmall' action='0' >0</label>
	<label sizen='3 2'  posn='6 0 0' halign='center' style='TextValueSmall' action='2' >2</label>
	<label sizen='3 2'  posn='10 0 0' halign='center' style='TextValueSmall' action='4' >4</label>
	<label sizen='3 2'  posn='14 0 0' halign='center' style='TextValueSmall' action='6' >6</label>
	<label sizen='3 2'  posn='18 0 0' halign='center' style='TextValueSmall' action='8' >8</label>
	<label sizen='3 2'  posn='22 0 0' halign='center' style='TextValueSmall' action='10' >10</label>
	<label sizen='3 2'  posn='26 0 0' halign='center' style='TextValueSmall' action='12' >12</label>
	<label sizen='3 2'  posn='30 0 0' halign='center' style='TextValueSmall' action='14' >14</label>
	<label sizen='3 2'  posn='34 0 0' halign='center' style='TextValueSmall' action='16' >16</label>
	<label sizen='3 2'  posn='38 0 0' halign='center' style='TextValueSmall' action='18' >18</label>
	<label sizen='3 2'  posn='42 0 0' halign='center' style='TextValueSmall' action='20' >20</label>
</frame>
</manialink>";
*/
			$xml2 = "<manialink id='Next'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='0 47 0'>
	<quad  sizen='41 18'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow2' />
	<label sizen='39 19'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$text2."]]></label>
  </frame>
</manialink>";

			$xml3 = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='Best'></manialink>
<manialink id='List'></manialink>
<manialink id='Duel'></manialink>
<manialink id='Vote'></manialink>";//effacer les fenetres de commande et de vote
		
			addCall("SendDisplayManialinkPageToLogin", $login, $xml.$xml2.$xml3, $CurrentGameInfo['ChatTime']+3000, false);
//			if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml.$xml2, $CurrentGameInfo['ChatTime']+3000, false)) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}	
		}
	}
	multiquery();
}

}

function SendManiaBottomVote ($PlayerLogin, $solo) {
global $client;
global $txt;
global $CurrentGameInfo;
global $PlayerList;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerScript;
global $ScoreTable;
global $CurrentGameMode;

//fenetres en bas a gauche avec message votez et boutons vote

if (!$solo) {
	foreach ($PlayerList as $Player) {
		$login=$Player['Login'];
		if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

		if ($PlayerScript[$login] == '1') {
			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
					<manialink posx='0.98' posy='-0.72' id='Vote'> 
					<type>default</type> 
					<format textsize='1'/> 
					<background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
					<line>
					<cell height='0.02' width='0.29'><text halign='center' textcolor='0F0F'>".$txtl['_'.$PlayerLanguage[$login]]['Votez svp']."</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='0' textcolor='F00F'>0</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='2' textcolor='FFFF'>2</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='4' textcolor='F00F'>4</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='6' textcolor='FFFF'>6</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='8' textcolor='F00F'>8</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='10' textcolor='FFFF'>10</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='12' textcolor='F00F'>12</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='14' textcolor='FFFF'>14</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='16' textcolor='F00F'>16</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='18' textcolor='FFFF'>18</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='20' textcolor='F00F'>20</text></cell>
					</line>
					</manialink>
					<custom_ui>
						<notice visible='false'/>
						<challenge_info visible='true'/>
						<chat visible='true'/>
						<checkpoint_list visible='true'/>
						<round_scores visible='true'/>";
			//table de score standard pour round, team et cup
			if (($CurrentGameMode == 0) || ($CurrentGameMode == 2) || ($CurrentGameMode == 5) || ($ScoreTable)) $xml .= "<scoretable visible='true'/>"; else $xml .= "<scoretable visible='false'/>";
			$xml .= "<global visible='true'/>
					</custom_ui>
					";
			$couleur="0F0";
		}
		else {
			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
					<manialink posx='0.98' posy='-0.72' id='Vote'></manialink>
					<custom_ui>
						<notice visible='true'/>
						<challenge_info visible='true'/>
						<chat visible='true'/>
						<checkpoint_list visible='true'/>
						<round_scores visible='true'/>
						<scoretable visible='true'/>
						<global visible='true'/>
					</custom_ui>
					";
			$couleur="F00";
		}

//fenetres en haut a gauche avec texte TMGery pour activer/desactiver les affichages du script
		$xmlgery = "<manialink posx='1.002' posy='0.75' id='Gery'> 
  <type>default</type> 
  <format textsize='1'/> 
  <background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
  <line>
<cell height='0.02' width='0.08'><text halign='center' action='98' textcolor='".$couleur."F'>TMGery</text></cell>
</line>
</manialink>";

		addCall("SendDisplayManialinkPageToLogin", $login, $xml.$xmlgery, 0, true);
//		if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}	
	}
	multiquery();
}
else {
		if (!isset($PlayerLanguage[$PlayerLogin])) $PlayerLanguage[$PlayerLogin]=$lang;

		if ($PlayerScript[$PlayerLogin] == '1') {
			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
					<manialink posx='0.98' posy='-0.72' id='Vote'> 
					<type>default</type> 
					<format textsize='1'/> 
					<background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
					<line>
					<cell height='0.02' width='0.29'><text halign='center' textcolor='0F0F'>".$txtl['_'.$PlayerLanguage[$PlayerLogin]]['Votez svp']."</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='0' textcolor='F00F'>0</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='2' textcolor='FFFF'>2</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='4' textcolor='F00F'>4</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='6' textcolor='FFFF'>6</text></cell>
					<cell height='0.02' width='0.04'><text halign='center' action='8' textcolor='F00F'>8</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='10' textcolor='FFFF'>10</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='12' textcolor='F00F'>12</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='14' textcolor='FFFF'>14</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='16' textcolor='F00F'>16</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='18' textcolor='FFFF'>18</text></cell>
					<cell height='0.02' width='0.05'><text halign='center' action='20' textcolor='F00F'>20</text></cell>
					</line>
					</manialink>
					<custom_ui>
						<notice visible='false'/>
						<challenge_info visible='true'/>
						<chat visible='true'/>
						<checkpoint_list visible='true'/>
						<round_scores visible='true'/>";
			//table de score standard pour round, team et cup
			if (($CurrentGameMode == 0) || ($CurrentGameMode == 2) || ($CurrentGameMode == 5) || ($ScoreTable)) $xml .= "<scoretable visible='true'/>"; else $xml .= "<scoretable visible='false'/>";
			$xml .= "<global visible='true'/>
					</custom_ui>
					";
			$couleur="0F0";
		}
		else {
			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
					<manialink posx='0.98' posy='-0.72' id='Vote'></manialink>
					<custom_ui>
						<notice visible='true'/>
						<challenge_info visible='true'/>
						<chat visible='true'/>
						<checkpoint_list visible='true'/>
						<round_scores visible='true'/>
						<scoretable visible='true'/>
						<global visible='true'/>
					</custom_ui>
					";
			$couleur="F00";
		}

//fenetres en haut a gauche avec texte TMGery pour activer/desactiver les affichages du script
		$xmlgery = "<manialink posx='1.002' posy='0.75' id='Gery'> 
					<type>default</type> 
					<format textsize='1'/> 
					<background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
					<line>
					<cell height='0.02' width='0.08'><text halign='center' action='98' textcolor='".$couleur."F'>TMGery</text></cell>
					</line>
					</manialink>";

		if (!$client->query("SendDisplayManialinkPageToLogin", $PlayerLogin, $xml.$xmlgery, 0, true)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
}

}

function SendManiaBottomNext ($text, $text2) {
//$text=top20 $text2=next
global $client;
global $txt;
global $CurrentGameInfo;
global $PlayerList;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerScript;

//fenetres en bas avec a droite TOP20 et info Next map (+ vote au milieu)

if ($CurrentGameInfo['ChatTime']>0) {
	foreach ($PlayerList as $Player) {
		$login=$Player['Login'];
		if ($PlayerScript[$login] == '1') {
			if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

/*
			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink posx='-0.6' posy='0.20'> 
  <type>default</type> 
  <format textsize='2'/> 
  <background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
  <line height='0.24'><cell width='1.0'><text halign='left' textcolor='FF0F'><![CDATA[".$text."]]></text></cell></line> 
</manialink>
<manialink posx='0.98' posy='-0.42'> 
  <type>default</type> 
  <format textsize='2'/> 
  <background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
  <line>
<cell height='0.02' width='0.41'><text halign='center' textcolor='0F0F'>".$txtl['_'.$PlayerLanguage[$login]]['Votez svp']."</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='0' textcolor='F00F'>0</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='1' textcolor='FFFF'>1</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='2' textcolor='F00F'>2</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='3' textcolor='FFFF'>3</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='4' textcolor='F00F'>4</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='5' textcolor='FFFF'>5</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='6' textcolor='F00F'>6</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='7' textcolor='FFFF'>7</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='8' textcolor='F00F'>8</text></cell>
<cell height='0.02' width='0.03'><text halign='center' action='9' textcolor='FFFF'>9</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='10' textcolor='F00F'>10</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='11' textcolor='FFFF'>11</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='12' textcolor='F00F'>12</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='13' textcolor='FFFF'>13</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='14' textcolor='F00F'>14</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='15' textcolor='FFFF'>15</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='16' textcolor='F00F'>16</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='17' textcolor='FFFF'>17</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='18' textcolor='F00F'>18</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='19' textcolor='FFFF'>19</text></cell>
<cell height='0.02' width='0.04'><text halign='center' action='20' textcolor='F00F'>20</text></cell>
</line>
</manialink>";
*/
			$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='Top'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='41 16 0'>
	<quad  sizen='24 56'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='NavButton' />
	<label sizen='11 20'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$text.'$z'."\n\r ]]></label>
  </frame>
</manialink>";
/*
<manialink>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-56 -26 0'>
	<quad  sizen='32 4'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow1' />
	<label sizen='30 4'  posn='0 0 0' halign='left' style='TextTitle3' >".'$0f0'.$txtl['_'.$PlayerLanguage[$login]]['Votez svp']."</label>
</frame>
</manialink>
<manialink>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-24 -26 0'>
	<quad  sizen='46 4'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow1' />
	<label sizen='3 2'  posn='2 0 0' halign='center' style='TextValueSmall' action='0' >0</label>
	<label sizen='3 2'  posn='6 0 0' halign='center' style='TextValueSmall' action='2' >2</label>
	<label sizen='3 2'  posn='10 0 0' halign='center' style='TextValueSmall' action='4' >4</label>
	<label sizen='3 2'  posn='14 0 0' halign='center' style='TextValueSmall' action='6' >6</label>
	<label sizen='3 2'  posn='18 0 0' halign='center' style='TextValueSmall' action='8' >8</label>
	<label sizen='3 2'  posn='22 0 0' halign='center' style='TextValueSmall' action='10' >10</label>
	<label sizen='3 2'  posn='26 0 0' halign='center' style='TextValueSmall' action='12' >12</label>
	<label sizen='3 2'  posn='30 0 0' halign='center' style='TextValueSmall' action='14' >14</label>
	<label sizen='3 2'  posn='34 0 0' halign='center' style='TextValueSmall' action='16' >16</label>
	<label sizen='3 2'  posn='38 0 0' halign='center' style='TextValueSmall' action='18' >18</label>
	<label sizen='3 2'  posn='42 0 0' halign='center' style='TextValueSmall' action='20' >20</label>
</frame>
</manialink>";
*/







//			$xml2 = "<manialink posx='-0.38' posy='-0.22'> 
/*			$xml2 = "<manialink posx='-0.38' posy='-0.42'> 
  <type>default</type> 
  <format textsize='2'/> 
  <background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
  <line height='0.24'><cell width='1.97'><text halign='left' textcolor='FF0F'><![CDATA[".$text2."]]></text></cell></line> 
</manialink>";
*/
			$xml2 = "<manialink id='Next'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='24 47 0'>
	<quad  sizen='40 18'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow2' />
	<label sizen='30 20'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$text2."]]></label>
  </frame>
</manialink>";

			$xml3 = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='Best'></manialink>
<manialink id='List'></manialink>
<manialink id='Duel'></manialink>
<manialink id='Vote'></manialink>";//effacer les fenetres de commande et de vote
		
		
			addCall("SendDisplayManialinkPageToLogin", $login, $xml.$xml2.$xml3, $CurrentGameInfo['ChatTime']+3000, false);
//			if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml.$xml2, $CurrentGameInfo['ChatTime']+3000, false)) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}
		}
	}
	multiquery();
}

}

function SendManiaPodium ($SPlayerRanking) {
//	struct SPlayerRanking {
//		string Login;
//		string NickName;
//		int PlayerId
//
//		int Rank;
//		int BestTime;
//		int[] BestCheckpoints;
//		int Score;
//		int NbrLapsFinished;
//		double LadderScore;
global $client;
global $txt;
global $CurrentGameInfo;
global $PlayerList;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerScript;
global $colors;
global $CurrentGameMode;
global $ScoreTable;

	if (($CurrentGameMode == 0) || ($CurrentGameMode == 2) || ($CurrentGameMode == 5)) return;	// rien si round, team  ou cup 

//print_r($SPlayerRanking);
$text="";
foreach ($SPlayerRanking as $player) {
	$login = $player['Login'];
	$nick = $player['NickName'];
	$rank = $player['Rank'];
	if ($CurrentGameMode==4) $score = $player['Score']; else $score = MwTimeToString($player['BestTime']);
	if ($rank>20) break;
	if (($score <= 0) && ($player['BestTime'] <= 0)) break;
	if ($rank>0)$text .= '$z' . $colors['interact'] . $rank . '. ' . $colors['highlight'] . $score . ' $z' . purgeNick($nick) . '$z' . "\n\r" ;
}

//fenetres coté gauche avec le classement du run en cours

if ($CurrentGameInfo['ChatTime']>0) {
	foreach ($PlayerList as $Player) {
		$login=$Player['Login'];
		if ($PlayerScript[$login] == '1') {
			if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

			if (!$ScoreTable) 
				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='Top10'>
						<timeout>0</timeout>
						<type>default</type>
						<frame posn='-63.5 32 0'>
							<quad  sizen='4 4'  posn='2 -1 0' halign='center'  valign='center'   style='BgRaceScore2' substyle='Podium' />
							<quad  sizen='24 56'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='NavButton' />
							<label sizen='11 20'  posn='0 -3 0' halign='left' style='TextStaticSmall'><![CDATA[".$text."\n\r ]]></label>
						</frame>
						</manialink>";
			else $xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='Top10'></manialink>";

			addCall("SendDisplayManialinkPageToLogin", $login, $xml, $CurrentGameInfo['ChatTime']+3000, false);
//			if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, false)) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}
		}
	}
	multiquery();
}

}

function SendManiaTOP10 ($playerlogin) {
//	struct SPlayerRanking {
//		string Login;
//		string NickName;
//		int PlayerId
//
//		int Rank;
//		int BestTime;
//		int[] BestCheckpoints;
//		int Score;
//		int NbrLapsFinished;
//		double LadderScore;
global $client;
global $txt;
global $CurrentGameInfo;
global $PlayerList;
global $txtl;
global $PlayerLanguage;
global $lang;
global $PlayerScript;
global $colors;
global $CurrentGameMode;
global $LiveTOP10;

	if (!$LiveTOP10) return;

	if (($CurrentGameMode == 0) || ($CurrentGameMode == 2) || ($CurrentGameMode == 5)) return;	// rien si round, team  ou cup 

	if (!$client->query("GetCurrentRanking", 10, 0)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
		return;
	}
	$SPlayerRanking = $client->getResponse();
	
	
//print_r($SPlayerRanking);
$text="";
$found=false;
foreach ($SPlayerRanking as $player) {
	$login = $player['Login'];
	$nick = $player['NickName'];
	$rank = $player['Rank'];
	if ($CurrentGameMode==4) $score = $player['Score']; else $score = MwTimeToString($player['BestTime']);
	if ($login==$playerlogin) $found=true;
	if ($rank>10) break;
	if (($score <= 0) && ($player['BestTime'] <= 0)) break;
	if ($rank>0) {
		$text .= '$z' . $colors['interact'] . $rank . '. ' . $colors['highlight'] . $score . ' $z';
		if (strlen(stripColors($nick, 1)) > 8) $text .= '$n';
		$text .= purgeNick($nick) . '$z' . "\n\r" ;
	}	
}

//fenetres coté gauche avec le classement du run en cours

if ($CurrentGameInfo['ChatTime']>0) {
	foreach ($PlayerList as $Player) {
		$login=$Player['Login'];
		if ($found || (!$found && ($login==$playerlogin))) {
			if ($PlayerScript[$login] == '1') {
				if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='Top10'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-63.5 4.5 0'>
	<quad  sizen='4 4'  posn='2 -1 0' halign='center'  valign='center'   style='BgRaceScore2' substyle='Podium' />
	<quad  sizen='17 30'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='NavButton' />
	<label sizen='7.7 20'  posn='0 -3 0' halign='left' style='TextStaticSmall'><![CDATA[".$text."\n\r ]]></label>
  </frame>
</manialink>";

				addCall("SendDisplayManialinkPageToLogin", $login, $xml, 0, false);
//				if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, false)) {
//					Error($client->getErrorMessage(), $client->getErrorCode());
//				}
			}
			if (!$found) break;
		}
	}
	multiquery();
}

}

function FormaterList ($heure, $env, $auteur, $map, $ligne, $action, $NbChallenge) {
//ligne demarre a 0
//action est le code retourne par la ligne si on clique dessus
/*
$str="<label sizen='8 3'  posn='0 ".((-3*$ligne)-1)." 0' halign='left' valign='center' style='TextStaticSmall' action='".$action."' ><![CDATA[".$heure."]]></label>";
$str.="<label sizen='8 3'  posn='8 ".((-3*$ligne)-1)." 0' halign='left' valign='center' style='TextValueSmall' action='".($action+2*$NbChallenge)."' ><![CDATA[".$env."]]></label>";
$str.="<label sizen='23 3'  posn='16 ".((-3*$ligne)-1)." 0' halign='left' valign='center' style='TextValueSmall' action='".($action+$NbChallenge)."' ><![CDATA[".$auteur."]]></label>";
$str.="<label sizen='41 3'  posn='39 ".((-3*$ligne)-1)." 0' halign='left' valign='center' style='TextValueSmall' action='".$action."' ><![CDATA[".$map."]]></label>";
*/
$str="<label sizen='8 3'  posn='0 ".((-3*$ligne)-1)." 0' halign='left' valign='center' style='TextStaticSmall' action='".$action."' ><![CDATA[".$heure."]]></label>";
$str.="<label sizen='41 3'  posn='8 ".((-3*$ligne)-1)." 0' halign='left' valign='center' style='TextValueSmall' action='".$action."' ><![CDATA[".$map."]]></label>";
$str.="<label sizen='23 3'  posn='49 ".((-3*$ligne)-1)." 0' halign='left' valign='center' style='TextValueSmall' action='".($action+$NbChallenge)."' ><![CDATA[".$auteur."]]></label>";
$str.="<label sizen='8 3'  posn='80 ".((-3*$ligne)-1)." 0' halign='right' valign='center' style='TextValueSmall' action='".($action+2*$NbChallenge)."' ><![CDATA[".$env."]]></label>";
return $str;
}

function SendMsgToLogin ($msg, $login){
global $Server_Status;
global $sunrise;
global $client;
global $messages;

	if ($Server_Status['Name']=='Running - Play' && !$sunrise){
//		if (!$client->query("SendHideServerMessageToLogin", $login)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}
//		if (!$client->query("SendDisplayServerMessageToLogin", $login, $msg,"OK","",0)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}
		SendDisplayManialinkPageToLogin ($login, $msg, 0);
	}
	else if ($Server_Status['Name']=='Running - Play' && $sunrise == 2){
		SendDisplayManialinkPageToLogin ($login, $msg, 0);
	}
	else {
		ChatSendServerMessageToLogin($msg, $login);
	}

}

function SendMsgToLogin2 ($msg, $login){
global $Server_Status;
global $sunrise;
global $client;
global $messages;

	if ($Server_Status['Name']=='Running - Play' && !$sunrise){
//		if (!$client->query("SendHideServerMessageToLogin", $login)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}
//		if (!$client->query("SendDisplayServerMessageToLogin", $login, $msg,"OK","",0)) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}
		SendDisplayManialinkPageToLogin2 ($login, $msg, 0);
	}
	else if ($Server_Status['Name']=='Running - Play' && $sunrise == 2){
		SendDisplayManialinkPageToLogin2 ($login, $msg, 0);
	}
	else {
		ChatSendServerMessageToLogin($msg, $login);
	}

}

function GetLastNickName($logname,&$result){
global $repplayer;

	$chunksize = 8192;
	$buffer = '';
	if (!file_exists($repplayer.$logname)) return False;
	$handle = fopen($repplayer.$logname, 'rb');
	if(!$handle) return False;
	$buffer=fread($handle, $chunksize);
	$stat = fclose($handle); 
	if($stat && $buffer ){
		$tmp=strstr($buffer,'<NickName>');
		$tmp=str_replace('<NickName>','',$tmp);
		$stop=strpos($tmp,'</');
		if ($stop>0) {
			$result = substr($tmp,0,$stop);
			return True; 
		}
		else {
			return False;
		}
	}
	else {
		return False;
	}
}

function GetMapName($mapuid,&$result){
global $reprecord;

	if(LireFichier($reprecord.$mapuid,$resultat)) {
		$tmp=strstr($resultat,'<TrackName>');
		$tmp=str_replace('<TrackName>','',$tmp);
		$stop=strpos($tmp,'</');
		if ($stop > 0) $result = substr($tmp,0,$stop); else $result = ' ';
		return True;
	}
}

function console($text){
	echo "[".date("H:i:s")."]". $text ."\n\r";
	flush();
}

function stripColors($str,$strip){
   	if ($strip==0) return $str;
	$str = "a".$str;
	$str = str_replace('$i','',$str);
	$str = str_replace('$I','',$str);
	$str = str_replace('$w','',$str);
	$str = str_replace('$W','',$str);
	$str = str_replace('$s','',$str);
	$str = str_replace('$S','',$str);
	$str = str_replace('$z','',$str);
	$str = str_replace('$Z','',$str);
	$str = str_replace('$n','',$str);
	$str = str_replace('$N','',$str);
	$str = str_replace('$m','',$str);
	$str = str_replace('$M','',$str);
	$str = str_replace('$g','',$str);
	$str = str_replace('$G','',$str);
	$str = str_replace('$o','',$str);
	$str = str_replace('$O','',$str);
//	$str = str_replace("\n",' ',$str);
//	$str = str_replace("\r",' ',$str);

	$found = true;
	while ($found) {
		$found = false;
		$start_a = strpos($str, '$l[');
		if ( $start_a > 0) {
			$end_a = strpos($str, ']');
			if ( $end_a > $start_a) {
				$tmp = substr($str, $start_a, $end_a - $start_a +1);
				$str = str_replace ($tmp, '', $str);	
				$found = true;
			}
		}
		$start_a = strpos($str, '$L[');
		if ( $start_a > 0) {
			$end_a = strpos($str, ']');
			if ( $end_a > $start_a) {
				$tmp = substr($str, $start_a, $end_a - $start_a +1);
				$str = str_replace ($tmp, '', $str);	
				$found = true;
			}
		}
		$start_a = strpos($str, '$h[');
		if ( $start_a > 0) {
			$end_a = strpos($str, ']');
			if ( $end_a > $start_a) {
				$tmp = substr($str, $start_a, $end_a - $start_a +1);
				$str = str_replace ($tmp, '', $str);	
				$found = true;
			}
		}
		$start_a = strpos($str, '$H[');
		if ( $start_a > 0) {
			$end_a = strpos($str, ']');
			if ( $end_a > $start_a) {
				$tmp = substr($str, $start_a, $end_a - $start_a +1);
				$str = str_replace ($tmp, '', $str);	
				$found = true;
			}
		}
	}

	$str = str_replace('$$','$',$str);
	$str = str_replace('$l','',$str);
	$str = str_replace('$L','',$str);
	$str = str_replace('$h','',$str);
	$str = str_replace('$H','',$str);

	$i=0;
	while($start = strpos($str,'$')){
		$i++;
		$color = substr($str, $start, 4);
		$str = str_replace($color, '', $str);
	}
	return substr($str,1);
}

function getCommand($str, $max_params=0){

global $welcome_msg;
global $annonce;
global $st;
global $colors;
global $messages;
global $CurrentChallenge;
global $record;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $chat;

	$chat['command'] = "";
	$chat['params'] = array();

	$str = trim($str);
	$str = ltrim($str);
	if(substr($str, 0, 1) == '/'){
		$end = strpos($str, " ");
		if(!$end){
			$chat['command'] = trim(substr($str, 1));
		}else{
			$chat['command'] = trim(substr($str, 1, $end));
			// get all params
			$i = 0;
			while(strpos($str, " ", $end+1)>0 && $i<=$max_params){
		                $end_param = strpos($str, " ", $end+1);
                		$chat['params'][$i] = substr($str, $end+1, $end_param - ($end+1));
		                $end = $end_param;
		                $i++;
			}
			$chat['params'][$i] = substr($str, $end+1);
		}
	}
	return $chat;
}

function getNextChallenge($info)
{
global $client;
global $NextChallengeInfo;
global $CurrentGameInfo;
global $CurrentGameMode;
global $NextChallengeType;
global $restart;
global $racetype;
global $sunrise;
global $TracksDirectory;

		if (!@$client->query('GetCurrentChallengeIndex')) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$CurrentChallengeIndex = $client->getResponse();
		}
		if (!@$client->query('GetCurrentGameInfo')) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$CurrentGameInfo = $client->getResponse();
			$NbChallenge = $CurrentGameInfo['NbChallenge'];
			$CurrentGameMode = $CurrentGameInfo['GameMode'];
		}
		

		if (!@$client->query('GetNextGameInfo')) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$NextGameInfo = $client->getResponse();
			$NextGameMode = $NextGameInfo['GameMode'];
			if ($NextGameMode==0) $ModeText = '-Round-';
			if ($NextGameMode==1) $ModeText = '-TimeAttack-';
			if ($NextGameMode==2) $ModeText = '-Team-';
			if ($NextGameMode==3) $ModeText = '-Laps-';
			if ($NextGameMode==4) $ModeText = '-Stunts-';
			if ($NextGameMode==5) $ModeText = '-Cup-';
		}

		if (($CurrentChallengeIndex + 1) >= $NbChallenge) {
			$NextChallengeIndex = 0;
		}
		else
		{
			$NextChallengeIndex = $CurrentChallengeIndex + 1;
		}


	$found=false;
	$NextIndex=$NextChallengeIndex;

	while (!$found) {
		if ($NextIndex == $CurrentChallengeIndex) {$found = true; break;}
		if (!@$client->query('GetChallengeList',1 , $NextIndex)) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$ChallengeList = $client->getResponse();
			$NextChallengeFileName = $ChallengeList[0]['FileName'];
			if ($NextGameMode==4) {
				if (TestStunt($NextChallengeFileName)) {$found = true; break;}
			}
			elseif ($NextGameMode==3) {
				if (TestLaps($NextChallengeFileName)) {$found = true; break;}
			}
			else {$found = true; break;}
		}
		if (($NextIndex + 1) >= $NbChallenge) {
			$NextIndex = 0;
		}
		else
		{
			$NextIndex = $NextIndex + 1;
		}
	}

	if ($found) $NextChallengeIndex = $NextIndex;


		if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$ChallengeList = $client->getResponse();
			$NextChallengeFileName = $ChallengeList[0]['FileName'];

			if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
			   Error($client->getErrorMessage(), $client->getErrorCode());
			}

			$NextChallengeInfo = $client->getResponse();
			$NextEnvironnement = $NextChallengeInfo['Environnement'];

			if (!TestStunt($NextChallengeFileName)) {
				if ($NextGameMode==4){
					if (!$restart) {
						if (!@$client->query('SetGameMode',$racetype )) {	//race
							Error($client->getErrorMessage(), $client->getErrorCode());
						}
					}
					else if (!$info) $restart=false;
					$MsgNext = True;
//					$ModeText = '-TimeAttack-';
					if ($racetype==0) $ModeText = '-Round-';
					if ($racetype==1) $ModeText = '-TimeAttack-';
					if ($racetype==2) $ModeText = '-Team-';
					if ($racetype==3) $ModeText = '-Laps-';
					if ($racetype==4) $ModeText = '-Cup-';
				}
			}
			else {
				if ($NextGameMode!==4){
					if (!$restart) {
						if (!@$client->query('SetGameMode',4 )) {	//stunt
							Error($client->getErrorMessage(), $client->getErrorCode());
						}
					}
					else if (!$info) $restart=false;
					$MsgNext = True;
					$ModeText = '-Stunts-';
				}
			}
		}
		$NextChallengeType = str_replace ("-","",$ModeText);
		$ModeText .= $NextEnvironnement . ": ";
		return $ModeText;
}

function getListChallenge($page)
{
global $CurrentGameInfo;
global $client;
global $sunrise;
global $Server_Status;
global $now;

	if (!@$client->query('GetCurrentChallengeIndex')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentChallengeIndex = $client->getResponse();
	}
	$NbChallenge = 0;
	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$NbChallenge = $CurrentGameInfo['NbChallenge'];
	}
		
	$ListChallenge="";

	if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=28;
	elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=28;
	else $max=10;

	if (($page+1)>ceil($NbChallenge/$max)) $page=ceil($NbChallenge/$max)-1;
	if ($page<0) $page=0;

	if (($page+1)==ceil($NbChallenge/$max)) $nbaffiche = round(fmod($NbChallenge,$max));
	else $nbaffiche = $max;

	if ($nbaffiche == 0) $nbaffiche = $max;

	if (($CurrentChallengeIndex + 1) >= $NbChallenge) {
		$NextChallengeIndex = 0;
	}
	else
	{
		$NextChallengeIndex = $CurrentChallengeIndex + 1;
	}

	$found=false;
	$NextIndex=$NextChallengeIndex;
	$j=0;

	while (!$found) {

		if ($j<($page*$max)) $j++; else {$found = true; break;}
		if (($NextIndex + 1) >= $NbChallenge) {
			$NextIndex = 0;
		}
		else
		{
			$NextIndex = $NextIndex + 1;
		}
	}

	if ($found) $NextChallengeIndex = $NextIndex;

	for ($i=0; $i<$max; $i++) {

		if ($i==$nbaffiche)	{ $ListChallenge .= "\n\r" . '$z$w$0f0. . . . . . .'; break; }

		if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$ChallengeList = $client->getResponse();
			$NextChallengeFileName = $ChallengeList[0]['FileName'];

			if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
			   Error($client->getErrorMessage(), $client->getErrorCode());
			}

			$NextChallengeInfo = $client->getResponse();
			$NextChallengeAuthor = sprintf("%-30s",$NextChallengeInfo['Author']);
			$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
			$NextChallengeEnv = sprintf("%-10s",$NextChallengeInfo['Environnement']);

			if ($sunrise == 2) {
//				$NextChallengeType = getchallengetype($NextChallengeFileName);
				$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
						. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//						. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
						. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
			}
			elseif ($sunrise == 0) {
//				$NextChallengeType = getchallengetype($NextChallengeFileName);
				$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
						. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//						. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
						. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
			}
			else {
				$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
						. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor;
			}
		}

		if (($NextChallengeIndex + 1) >= $NbChallenge) {
			$NextChallengeIndex = 0;
		}
		else
		{
			$NextChallengeIndex = $NextChallengeIndex + 1;
		}

	}

	return $ListChallenge;
}

function getListChallenge2($page, $login)
{
global $CurrentGameInfo;
global $client;
global $sunrise;
global $Server_Status;
global $now;

	if (!@$client->query('GetCurrentChallengeIndex')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentChallengeIndex = $client->getResponse();
	}
	$NbChallenge = 0;
	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$NbChallenge = $CurrentGameInfo['NbChallenge'];
	}
		
	$ListChallenge="";

	if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=24;
	elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=24;
	else $max=10;

	if (($page+1)>ceil($NbChallenge/$max)) $page=ceil($NbChallenge/$max)-1;
	if ($page<0) $page=0;

	if (($page+1)==ceil($NbChallenge/$max)) $nbaffiche = round(fmod($NbChallenge,$max));
	else $nbaffiche = $max;

	if ($nbaffiche == 0) $nbaffiche = $max;

	if (($CurrentChallengeIndex + 1) >= $NbChallenge) {
		$NextChallengeIndex = 0;
	}
	else
	{
		$NextChallengeIndex = $CurrentChallengeIndex + 1;
	}

	$found=false;
	$NextIndex=$NextChallengeIndex;
	$j=0;

	while (!$found) {

		if ($j<($page*$max)) $j++; else {$found = true; break;}
		if (($NextIndex + 1) >= $NbChallenge) {
			$NextIndex = 0;
		}
		else
		{
			$NextIndex = $NextIndex + 1;
		}
	}

	if ($found) $NextChallengeIndex = $NextIndex;

	if ($max==10) {
		for ($i=0; $i<$max; $i++) {

			if ($i==$nbaffiche)	{ $ListChallenge .= "\n\r" . '$z$w$0f0. . . . . . .'; break; }
	
			if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			}
			else
			{
				$ChallengeList = $client->getResponse();
				$NextChallengeFileName = $ChallengeList[0]['FileName'];
				$NextChallengeAuthor = $ChallengeList[0]['Author'];
				$NextChallengeName = purgeNick($ChallengeList[0]['Name']);
				$NextChallengeEnv = $ChallengeList[0]['Environnement'];
	
/*
				if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
				}
	
				$NextChallengeInfo = $client->getResponse();
				$NextChallengeAuthor = $NextChallengeInfo['Author'];
				$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
				$NextChallengeEnv = $NextChallengeInfo['Environnement'];
*/
	
				if ($sunrise == 2) {
//					$NextChallengeType = getchallengetype($NextChallengeFileName);
					$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
							. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//							. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
							. '$z$fff - ' . $NextChallengeAuthor . '$z - ' . $NextChallengeName ;
				}
				elseif ($sunrise == 0) {
//					$NextChallengeType = getchallengetype($NextChallengeFileName);
					$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
							. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//							. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
							. '$z$fff - ' . $NextChallengeAuthor . '$z - ' . $NextChallengeName ;
				}
				else {
					$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
							. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor;
				}
			}
	
			if (($NextChallengeIndex + 1) >= $NbChallenge) {
				$NextChallengeIndex = 0;
			}
			else
			{
				$NextChallengeIndex = $NextChallengeIndex + 1;
			}
		}
		SendMsgToLogin2 ($ListChallenge, $login);
	}
	else {
		for ($i=0; $i<$max; $i++) {

			if ($i==$nbaffiche)	{ 
				$ListChallenge .= FormaterList ('$z$w$0f0. . . . . . .', '.', '.', '.', $i, 99, $NbChallenge);
//				$ListChallenge .= "\n\r" . '$z$w$0f0. . . . . . .'; 
				break; 
			}
	
			if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			}
			else
			{
				$ChallengeList = $client->getResponse();
				$NextChallengeFileName = $ChallengeList[0]['FileName'];
				$NextChallengeAuthor = $ChallengeList[0]['Author'];
				$NextChallengeName = purgeNick($ChallengeList[0]['Name']);
				$NextChallengeEnv = $ChallengeList[0]['Environnement'];
	
/*
				if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
				}
	
				$NextChallengeInfo = $client->getResponse();
				$NextChallengeAuthor = $NextChallengeInfo['Author'];
				$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
				$NextChallengeEnv = $NextChallengeInfo['Environnement'];
*/
	
				if ($sunrise == 2) {
					$ListChallenge .= FormaterList ('$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000), 
								'$fff ' . $NextChallengeEnv, '$z$fff' . $NextChallengeAuthor, '$z ' . $NextChallengeName, $i, 100+$NextChallengeIndex, $NbChallenge);
/*
				$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
							. '$fff ' . $NextChallengeEnv 
							. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
*/							
				}
				elseif ($sunrise == 0) {
					$ListChallenge .= FormaterList ('$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000), 
								'$fff ' . $NextChallengeEnv, '$z$fff' . $NextChallengeAuthor, '$z ' . $NextChallengeName, $i, 100+$NextChallengeIndex, $NbChallenge);
/*
				$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
							. '$fff ' . $NextChallengeEnv 
							. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
*/							
				}
			}
	
			if (($NextChallengeIndex + 1) >= $NbChallenge) {
				$NextChallengeIndex = 0;
			}
			else
			{
				$NextChallengeIndex = $NextChallengeIndex + 1;
			}
		}
		$xml = "<?xml version='1.0' encoding='utf-8' ?> 
				<manialink id='List'>
				<timeout>0</timeout>
				<type>default</type>
				<frame posn='-40 43 0'>
				<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
				".$ListChallenge."
				<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".($page-1+10001)."' ><![CDATA[<<]]></label>
				<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
				<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".($page+1+10001)."' ><![CDATA[>>]]></label>
				</frame>
				</manialink>";

		if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	

	}
}

function getListLoginChallenge($login)
{
global $CurrentGameInfo;
global $client;
global $sunrise;
global $Server_Status;
global $now;

	$NextChallengeIndex=0;

	if (!@$client->query('GetCurrentChallengeIndex')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$NextChallengeIndex = $client->getResponse();
	}

	$NbChallenge = 0;
	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$NbChallenge = $CurrentGameInfo['NbChallenge'];
	}
		
	$ListChallenge="";

	if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=28;
	elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=28; 
	else $max=10;

	$i=0;
	for ($j=0; $i<$max && $j<$NbChallenge; $j++) {

		if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$ChallengeList = $client->getResponse();
			$NextChallengeFileName = $ChallengeList[0]['FileName'];

			if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
			   Error($client->getErrorMessage(), $client->getErrorCode());
			}

			$NextChallengeInfo = $client->getResponse();
			$NextChallengeAuthor = $NextChallengeInfo['Author'];
			$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
			$NextChallengeEnv = sprintf("%-10s",$NextChallengeInfo['Environnement']);

			if (strcmp($NextChallengeInfo['Author'],$login)==0) {

				if ($sunrise == 2) {
//					$NextChallengeType = getchallengetype($NextChallengeFileName);
					$ListChallenge .= "\n\r" . '$z$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
							. '$z ' . $NextChallengeName ;//. '$z$fff' . " - " . $NextChallengeAuthor ;
				}
				elseif ($sunrise == 0) {
//					$NextChallengeType = getchallengetype($NextChallengeFileName);
					$ListChallenge .= "\n\r" . '$z$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
							. '$z ' . $NextChallengeName ;//. '$z$fff' . " - " . $NextChallengeAuthor ;
				}
				else {
					$ListChallenge .= "\n\r" . '$z ' . $NextChallengeName ;//. '$z$fff' . " - " . $NextChallengeAuthor;
				}
				$i++;
			}
		}

		if (($NextChallengeIndex + 1) >= $NbChallenge) {
			$NextChallengeIndex = 0;
		}
		else
		{
			$NextChallengeIndex = $NextChallengeIndex + 1;
		}

	}

	return $ListChallenge;
}

function getListLoginChallenge2($page, $login, $qui)
{
global $CurrentGameInfo;
global $client;
global $sunrise;
global $Server_Status;
global $now;

	if (!@$client->query('GetCurrentChallengeIndex')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentChallengeIndex = $client->getResponse();
	}
	$NbChallenge = 0;
	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$NbChallenge = $CurrentGameInfo['NbChallenge'];
	}
		
	$ListChallenge="";

	if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=24;
	elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=24;
	else $max=10;

	if (($page+1)>ceil($NbChallenge/$max)) $page=ceil($NbChallenge/$max)-1;
	if ($page<0) $page=0;

	if (($page+1)==ceil($NbChallenge/$max)) $nbaffiche = round(fmod($NbChallenge,$max));
	else $nbaffiche = $max;

	if ($nbaffiche == 0) $nbaffiche = $max;

	if (($CurrentChallengeIndex + 1) >= $NbChallenge) {
		$NextChallengeIndex = 0;
	}
	else
	{
		$NextChallengeIndex = $CurrentChallengeIndex + 1;
	}

	$found=false;
	$NextIndex=$NextChallengeIndex;
	$j=0;

	while (!$found) {

		if ($j<($page*$max)) $j++; else {$found = true; break;}
		if (($NextIndex + 1) >= $NbChallenge) {
			$NextIndex = 0;
		}
		else
		{
			$NextIndex = $NextIndex + 1;
		}
	}

	if ($found) $NextChallengeIndex = $NextIndex;

	if ($max==10) {
		$k=0;
		for ($i=0; $i<$NbChallenge && $k<$max; $i++) {

//			if ($i==$nbaffiche)	{ $ListChallenge .= "\n\r" . '$z$w$0f0. . . . . . .'; break; }
	
			if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			}
			else
			{
				$ChallengeList = $client->getResponse();
				$NextChallengeFileName = $ChallengeList[0]['FileName'];
				$NextChallengeAuthor = $ChallengeList[0]['Author'];
				$NextChallengeName = purgeNick($ChallengeList[0]['Name']);
				$NextChallengeEnv = $ChallengeList[0]['Environnement'];
	
/*
				if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
				}
	
				$NextChallengeInfo = $client->getResponse();
				$NextChallengeAuthor = $NextChallengeInfo['Author'];
				$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
				$NextChallengeEnv = $NextChallengeInfo['Environnement'];
	
				if (strcmp($NextChallengeInfo['Author'],$qui)==0) {
*/
				if (strcmp($ChallengeList[0]['Author'],$qui)==0) {
					if ($sunrise == 2) {
//						$NextChallengeType = getchallengetype($NextChallengeFileName);
						$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//								. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
								. '$z$fff - ' . $NextChallengeAuthor . '$z - ' . $NextChallengeName ;
					}
					elseif ($sunrise == 0) {
//						$NextChallengeType = getchallengetype($NextChallengeFileName);
						$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//								. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
								. '$z$fff - ' . $NextChallengeAuthor . '$z - ' . $NextChallengeName ;
					}
					else {
						$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor;
					}
					$k++;
				}
			}
	
			if (($NextChallengeIndex + 1) >= $NbChallenge) {
				$NextChallengeIndex = 0;
			}
			else
			{
				$NextChallengeIndex = $NextChallengeIndex + 1;
			}
		}
		SendMsgToLogin2 ($ListChallenge, $login);
	}
	else {
		$k=0;
		for ($i=0; $i<$NbChallenge && $k<$max; $i++) {

/*
			if ($i==$nbaffiche)	{ 
				$ListChallenge .= FormaterList ('$z$w$0f0. . . . . . .', '.', '.', '.', $i, 99, $NbChallenge);
//				$ListChallenge .= "\n\r" . '$z$w$0f0. . . . . . .'; 
				break; 
			}
*/	
			if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			}
			else
			{
				$ChallengeList = $client->getResponse();
				$NextChallengeFileName = $ChallengeList[0]['FileName'];
				$NextChallengeAuthor = $ChallengeList[0]['Author'];
				$NextChallengeName = purgeNick($ChallengeList[0]['Name']);
				$NextChallengeEnv = $ChallengeList[0]['Environnement'];
	
/*
				if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
				}
	
				$NextChallengeInfo = $client->getResponse();
				$NextChallengeAuthor = $NextChallengeInfo['Author'];
				$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
				$NextChallengeEnv = $NextChallengeInfo['Environnement'];

	
				if (strcmp($NextChallengeInfo['Author'],$qui)==0) {
*/				
				if (strcmp($ChallengeList[0]['Author'],$qui)==0) {
					if ($sunrise == 2) {
						$ListChallenge .= FormaterList ('$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000), 
									'$fff ' . $NextChallengeEnv, '$z$fff' . $NextChallengeAuthor, '$z ' . $NextChallengeName, $k, 100+$NextChallengeIndex, $NbChallenge);
/*
					$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv 
								. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
*/							
					}
					elseif ($sunrise == 0) {
						$ListChallenge .= FormaterList ('$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000), 
									'$fff ' . $NextChallengeEnv, '$z$fff' . $NextChallengeAuthor, '$z ' . $NextChallengeName, $k, 100+$NextChallengeIndex, $NbChallenge);
/*
					$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv 
								. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
*/							
					}
					$k++;
				}
			}
	
			if (($NextChallengeIndex + 1) >= $NbChallenge) {
				$NextChallengeIndex = 0;
			}
			else
			{
				$NextChallengeIndex = $NextChallengeIndex + 1;
			}
		}
		$xml = "<?xml version='1.0' encoding='utf-8' ?> 
				<manialink id='List'>
				<timeout>0</timeout>
				<type>default</type>
				<frame posn='-40 43 0'>
				<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
				".$ListChallenge."
				<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
				</frame>
				</manialink>";

		if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	

	}
}

function getListEnvChallenge($Env)
{
global $CurrentGameInfo;
global $client;
global $sunrise;
global $Server_Status;
global $now;

	$NextChallengeIndex=0;

	if (!@$client->query('GetCurrentChallengeIndex')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$NextChallengeIndex = $client->getResponse();
	}

	$NbChallenge = 0;
	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$NbChallenge = $CurrentGameInfo['NbChallenge'];
	}
		
	$ListChallenge="";

	if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=28;
	elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=28; 
	else $max=10;

	$i=0;
	for ($j=0; $i<$max && $j<$NbChallenge; $j++) {

		if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$ChallengeList = $client->getResponse();
			$NextChallengeFileName = $ChallengeList[0]['FileName'];

			if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
			   Error($client->getErrorMessage(), $client->getErrorCode());
			}

			$NextChallengeInfo = $client->getResponse();
			$NextChallengeAuthor = sprintf("%-20s",$NextChallengeInfo['Author']);
			$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
			$NextChallengeEnv = sprintf("%-10s",$NextChallengeInfo['Environnement']);

			if (strcmp($NextChallengeInfo['Environnement'],$Env)==0) {

				if ($sunrise == 2) {
//					$NextChallengeType = getchallengetype($NextChallengeFileName);
					$ListChallenge .= "\n\r" . '$fff ' //. $NextChallengeEnv . '.' . $NextChallengeType
//						. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
						. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
				}
				elseif ($sunrise == 0) {
//					$NextChallengeType = getchallengetype($NextChallengeFileName);
					$ListChallenge .= "\n\r" . '$fff ' //. $NextChallengeEnv . '.' . $NextChallengeType
//						. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
						. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
				}
				else {
					$ListChallenge .= "\n\r" . '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor;
				}
				$i++;
			}
		}

		if (($NextChallengeIndex + 1) >= $NbChallenge) {
			$NextChallengeIndex = 0;
		}
		else
		{
			$NextChallengeIndex = $NextChallengeIndex + 1;
		}

	}

	return $ListChallenge;
}

function getListEnvChallenge2($page, $login, $quoi)
{
global $CurrentGameInfo;
global $client;
global $sunrise;
global $Server_Status;
global $now;

	if (!@$client->query('GetCurrentChallengeIndex')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentChallengeIndex = $client->getResponse();
	}
	$NbChallenge = 0;
	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$NbChallenge = $CurrentGameInfo['NbChallenge'];
	}
		
	$ListChallenge="";

	if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=24;
	elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=24;
	else $max=10;

	if (($page+1)>ceil($NbChallenge/$max)) $page=ceil($NbChallenge/$max)-1;
	if ($page<0) $page=0;

	if (($page+1)==ceil($NbChallenge/$max)) $nbaffiche = round(fmod($NbChallenge,$max));
	else $nbaffiche = $max;

	if ($nbaffiche == 0) $nbaffiche = $max;

	if (($CurrentChallengeIndex + 1) >= $NbChallenge) {
		$NextChallengeIndex = 0;
	}
	else
	{
		$NextChallengeIndex = $CurrentChallengeIndex + 1;
	}

	$found=false;
	$NextIndex=$NextChallengeIndex;
	$j=0;

	while (!$found) {

		if ($j<($page*$max)) $j++; else {$found = true; break;}
		if (($NextIndex + 1) >= $NbChallenge) {
			$NextIndex = 0;
		}
		else
		{
			$NextIndex = $NextIndex + 1;
		}
	}

	if ($found) $NextChallengeIndex = $NextIndex;

	if ($max==10) {
		$k=0;
		for ($i=0; $i<$NbChallenge && $k<$max; $i++) {

//			if ($i==$nbaffiche)	{ $ListChallenge .= "\n\r" . '$z$w$0f0. . . . . . .'; break; }
	
			if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			}
			else
			{
				$ChallengeList = $client->getResponse();
				$NextChallengeFileName = $ChallengeList[0]['FileName'];
				$NextChallengeAuthor = $ChallengeList[0]['Author'];
				$NextChallengeName = purgeNick($ChallengeList[0]['Name']);
				$NextChallengeEnv = $ChallengeList[0]['Environnement'];
	
/*				if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
				}
	
				$NextChallengeInfo = $client->getResponse();
				$NextChallengeAuthor = $NextChallengeInfo['Author'];
				$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
				$NextChallengeEnv = $NextChallengeInfo['Environnement'];
	
				if (strcmp($NextChallengeInfo['Environnement'],$quoi)==0) {
*/
				if (strcmp($ChallengeList[0]['Environnement'],$quoi)==0) {
					if ($sunrise == 2) {
//						$NextChallengeType = getchallengetype($NextChallengeFileName);
						$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//								. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
								. '$z$fff - ' . $NextChallengeAuthor . '$z - ' . $NextChallengeName ;
					}
					elseif ($sunrise == 0) {
//						$NextChallengeType = getchallengetype($NextChallengeFileName);
						$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv //. '.' . $NextChallengeType
//								. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor ;
								. '$z$fff - ' . $NextChallengeAuthor . '$z - ' . $NextChallengeName ;
					}
					else {
						$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$z ' . $NextChallengeName . '$z$fff' . " - " . $NextChallengeAuthor;
					}
					$k++;
				}
			}
	
			if (($NextChallengeIndex + 1) >= $NbChallenge) {
				$NextChallengeIndex = 0;
			}
			else
			{
				$NextChallengeIndex = $NextChallengeIndex + 1;
			}
		}
		SendMsgToLogin2 ($ListChallenge, $login);
	}
	else {
		$k=0;
		for ($i=0; $i<$NbChallenge && $k<$max; $i++) {

/*
			if ($i==$nbaffiche)	{ 
				$ListChallenge .= FormaterList ('$z$w$0f0. . . . . . .', '.', '.', '.', $i, 99, $NbChallenge);
//				$ListChallenge .= "\n\r" . '$z$w$0f0. . . . . . .'; 
				break; 
			}
*/	
			if (!@$client->query('GetChallengeList',1 , $NextChallengeIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			}
			else
			{
				$ChallengeList = $client->getResponse();
				$NextChallengeFileName = $ChallengeList[0]['FileName'];
				$NextChallengeAuthor = $ChallengeList[0]['Author'];
				$NextChallengeName = purgeNick($ChallengeList[0]['Name']);
				$NextChallengeEnv = $ChallengeList[0]['Environnement'];
	
/*				if (!@$client->query('GetChallengeInfo', $NextChallengeFileName)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
				}
	
				$NextChallengeInfo = $client->getResponse();
				$NextChallengeAuthor = $NextChallengeInfo['Author'];
				$NextChallengeName = purgeNick($NextChallengeInfo['Name']);
				$NextChallengeEnv = $NextChallengeInfo['Environnement'];
	
				if (strcmp($NextChallengeInfo['Environnement'],$quoi)==0) {
*/
				if (strcmp($ChallengeList[0]['Environnement'],$quoi)==0) {
					if ($sunrise == 2) {
						$ListChallenge .= FormaterList ('$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000), 
									'$fff ' . $NextChallengeEnv, '$z$fff' . $NextChallengeAuthor, '$z ' . $NextChallengeName, $k, 100+$NextChallengeIndex, $NbChallenge);
/*
					$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv 
								. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
*/							
					}
					elseif ($sunrise == 0) {
						$ListChallenge .= FormaterList ('$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000), 
									'$fff ' . $NextChallengeEnv, '$z$fff' . $NextChallengeAuthor, '$z ' . $NextChallengeName, $k, 100+$NextChallengeIndex, $NbChallenge);
/*
					$ListChallenge .= "\n\r" . '$z$0ff' . date('H:i:s', $now+($j+$i+1)*($CurrentGameInfo['TimeAttackLimit']+$CurrentGameInfo['ChatTime']+36000)/1000) 
								. '$fff ' . $NextChallengeEnv 
								. '$z$fff' . $NextChallengeAuthor . '$z ' . $NextChallengeName ;
*/							
					}
					$k++;
				}
			}
	
			if (($NextChallengeIndex + 1) >= $NbChallenge) {
				$NextChallengeIndex = 0;
			}
			else
			{
				$NextChallengeIndex = $NextChallengeIndex + 1;
			}
		}
		$xml = "<?xml version='1.0' encoding='utf-8' ?> 
				<manialink id='List'>
				<timeout>0</timeout>
				<type>default</type>
				<frame posn='-40 43 0'>
				<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
				".$ListChallenge."
				<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
				</frame>
				</manialink>";

		if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	

	}
}

function getUserLogin($nick){
global $client;
global $PlayerList;
global $MaxPlayer;

	if ($PlayerList=="") {
		if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
			Error($client->getErrorMessage(), $client->getErrorCode());
		}else{
			$PlayerList = $client->getResponse();
		}
	}

	$find = False;
	if (!$PlayerList) return "";
	foreach ($PlayerList as $Player ) {
		if(strstr($Player["NickName"], $nick)) {
//			echo "Player login: ".$Player['Login']."\n\r";
			$find = True;
			break;
		}
	}
	if (!$find) return ""; else return $Player["Login"];
}

function getNick($lastchat){
global $client;
global $chat;
global $ChatLines;


	$chat['Author']="";
	if ($lastchat=="") return "";

	if(!@$client->query("GetChatLines")){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$ChatLines = $client->getResponse();
	}

	for($i=sizeof($ChatLines)-1;$i>0;$i--){
		$str= $ChatLines[$i];

		$start_a = strpos($str, '[$<');
		$start = strpos($str, '$>]');
		$tmp= substr($str, $start_a+3, $start - ($start_a+3));
		if (strstr($ChatLines[$i],$lastchat)) {
			$chat['Author'] = $tmp;
			break;
		} 
	}
	return $chat['Author'];
}

function ChatSendServerMessage ($msg) {
global $client;
global $messages;
global $PlayerList;
global $PlayerLanguage;

	foreach ($PlayerList as $Player) {
		addCall("ChatSendServerMessageToLogin", $messages['pref'].translate($msg,$PlayerLanguage[$Player['Login']]),$Player['Login']);
//		if(!$client->query("ChatSendServerMessageToLogin", $messages['pref'].translate($msg,$PlayerLanguage[$Player['Login']]),$Player['Login'])){
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}
//		usleep(1);
	}
	multiquery();
}

function ChatSendServerMessageToLogin ($msg, $login) {
global $client;
global $messages;
global $PlayerLanguage;

	if(!$client->query("ChatSendServerMessageToLogin", $messages['pref'].translate($msg,$PlayerLanguage[$login]), $login)){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}
}

function getrec ($login) {
global $colors;
global $txtl;
global $PlayerLanguage;
global $RankServer;
global $record;
global $TopBestTime;
global $TopDateRec;
global $st;
global $NbVote;
global $Note;
global $CurrentChallenge;

	if($record['Time'] == 0){
		$msg = $st . $colors['interact'] . $txtl['_'.$PlayerLanguage[$login]]['pas de record sur'].' ' . $colors['highlight'] . stripColors($CurrentChallenge['Name'],0);
	}
	else {
		$msg = $st . $colors['interact'] . $txtl['_'.$PlayerLanguage[$login]]['record'].' ' . $colors['highlight'] . MwTimeToString($record['Time'])  . $colors['interact'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['le'].' ' . $colors['highlight'] . $record['Date'] . $colors['interact'] . "\n\r" . $txtl['_'.$PlayerLanguage[$login]]['par'].' ' . $colors['highlight'] . $record['Author']  . $st . $colors['interact'] . ' ( ' . $record['Login'] . ' )';
	}
	$position=getposition($login);
	if ($position > 1) {
		$msg .= "\n\r" . $st . $colors['track_round'] . $txtl['_'.$PlayerLanguage[$login]]['votre record'].' ' . $colors['highlight'] . MwTimeToString($TopBestTime[$position-1])  . $colors['track_round'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['le'].' ' . $colors['highlight'] . $TopDateRec[$position-1]   . $colors['track_round'] . ' TOP' . $colors['highlight'] . $position;
	}
	$i=0;
	reset($RankServer);
	foreach ($RankServer as $key => $val){
		$i++;
		if  ($key == purgelogin($login)){ 
			$msg .= "\n\r" . $st . $colors['track_round'] . $txtl['_'.$PlayerLanguage[$login]]['votre rang serveur est'].' ' . $colors['highlight'] . $i . $colors['track_round'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . $val . $colors['track_round'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['pts'] ;
			break;
		}
	}        
	if ($NbVote>0) {
		if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login] = $lang;
		$msg .= "\n\r". $st .  $colors['track_round'] . $txtl['_'.$PlayerLanguage[$login]]['Note actuelle'].': ' . $colors['highlight'] . round($Note, 1)  . $colors['track_round'] . '/20 '. $txtl['_'.$PlayerLanguage[$login]]['en'].' ' . $colors['highlight'] . $NbVote .  $colors['track_round'] . ' '. $txtl['_'.$PlayerLanguage[$login]]['vote(s)'];
	}
			
	SendMsgToLogin ($msg, $login);					
}

function AfficheRec () {	//affiche 8 s les stats de la  map dans les 30 premieres sec
global $colors;
global $txtl;
global $PlayerLanguage;
global $RankServer;
global $record;
global $TopBestTime;
global $TopDateRec;
global $st;
global $NbVote;
global $Note;
global $PlayerScript;
global $sunrise;
global $PlayerList;
global $now;
global $CurrentGameMode;
global $CurrentChallenge;

if (($sunrise != 0) && ($sunrise != 2)) return;
if (($CurrentGameMode == 0) || ($CurrentGameMode == 2) || ($CurrentGameMode == 5)) return;	// rien si round, team ou cup 

foreach ($PlayerList as $Player) {
	$login = $Player['Login'];

	if ($PlayerScript[$login] !== '1') continue;
	
	if($record['Time'] == 0){
		$msg = $st . $colors['interact'] . $txtl['_'.$PlayerLanguage[$login]]['pas de record sur'].' ' . $colors['highlight'] . stripColors($CurrentChallenge['Name'],0);
	}
	else {
		$msg = $st . $colors['interact'] . $txtl['_'.$PlayerLanguage[$login]]['record'].' ' . $colors['highlight'] . MwTimeToString($record['Time'])  . $colors['interact'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['le'].' ' . $colors['highlight'] . $record['Date'] . $colors['interact'] . "\n\r" . $txtl['_'.$PlayerLanguage[$login]]['par'].' ' . $colors['highlight'] . $record['Author']  . $st . $colors['interact'] . ' ( ' . $record['Login'] . ' )';
	}
	$position=getposition($login);
	if ($position > 1) {
		$msg .= "\n\r" . $st . $colors['track_round'] . $txtl['_'.$PlayerLanguage[$login]]['votre record'].' ' . $colors['highlight'] . MwTimeToString($TopBestTime[$position-1])  . $colors['track_round'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['le'].' ' . $colors['highlight'] . $TopDateRec[$position-1]   . $colors['track_round'] . ' TOP' . $colors['highlight'] . $position;
	}
	$i=0;
	reset($RankServer);
	foreach ($RankServer as $key => $val){
		$i++;
		if  ($key == purgelogin($login)){ 
			$msg .= "\n\r" . $st . $colors['track_round'] . $txtl['_'.$PlayerLanguage[$login]]['votre rang serveur est'].' ' . $colors['highlight'] . $i . $colors['track_round'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . $val . $colors['track_round'] . ' '.$txtl['_'.$PlayerLanguage[$login]]['pts'] ;
			break;
		}
	}        
	if ($NbVote>0) {
		if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login] = $lang;
		$msg .= "\n\r". $st .  $colors['track_round'] . $txtl['_'.$PlayerLanguage[$login]]['Note actuelle'].': ' . $colors['highlight'] . round($Note, 1)  . $colors['track_round'] . '/20 '. $txtl['_'.$PlayerLanguage[$login]]['en'].' ' . $colors['highlight'] . $NbVote .  $colors['track_round'] . ' '. $txtl['_'.$PlayerLanguage[$login]]['vote(s)'];
	}
	
//	SendDisplayManialinkPageToLogin ($login, $msg, 8000);		

	$xml = "<?xml version='1.0' encoding='utf-8' ?> 
<manialink id='Rec'>
 <timeout>0</timeout>
 <type>default</type>
  <frame posn='-35 35 0'>
	<quad  sizen='72 18'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
	<label sizen='70 3'  posn='35 0 0' halign='center' style='TextTitle2'><![CDATA[".$msg."]]></label>
  </frame>
</manialink>";

	addCall("SendDisplayManialinkPageToLogin",$login, $xml, 8000, true);		
}
multiquery();
}

function afficheAide ($login) {
global $client;
global $sunrise;

	$xml = "<?xml version='1.0' encoding='utf-8' ?> 
			<manialink id='List'>
			<timeout>0</timeout>
			<type>default</type>
			<frame posn='-40 43 0'>
			<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
			<label sizen='40 3'  posn='20 -1 0' halign='center' valign='center' style='TextValueSmall' action='60' >help</label>
			<label sizen='40 3'  posn='60 -1 0' halign='center' valign='center' style='TextValueSmall' action='61' >time</label>
			<label sizen='40 3'  posn='20 -4 0' halign='center' valign='center' style='TextValueSmall' action='62' >list</label>
			<label sizen='40 3'  posn='60 -4 0' halign='center' valign='center' style='TextValueSmall' action='63' >record</label>
			<label sizen='40 3'  posn='20 -7 0' halign='center' valign='center' style='TextValueSmall' action='64' >top</label>
			<label sizen='40 3'  posn='60 -7 0' halign='center' valign='center' style='TextValueSmall' action='65' >srank</label>
			<label sizen='40 3'  posn='20 -10 0' halign='center' valign='center' style='TextValueSmall' action='66' >mrank</label>
			<label sizen='40 3'  posn='60 -10 0' halign='center' valign='center' style='TextValueSmall' action='67' >rankmap</label>
			<label sizen='40 3'  posn='20 -13 0' halign='center' valign='center' style='TextValueSmall' action='68' >moyenne</label>
			<label sizen='40 3'  posn='60 -13 0' halign='center' valign='center' style='TextValueSmall' action='69' >playerlist</label>
			<label sizen='40 3'  posn='20 -16 0' halign='center' valign='center' style='TextValueSmall' action='70' >next</label>
			";
			
	if (isadmin($login) || isadmin2($login)) {
		$xml .= "
			<label sizen='40 3'  posn='20 -25 0' halign='center' valign='center' style='TextValueSmall' action='30' >gonext</label>
			<label sizen='40 3'  posn='60 -25 0' halign='center' valign='center' style='TextValueSmall' action='31' >restart</label>
			<label sizen='40 3'  posn='20 -28 0' halign='center' valign='center' style='TextValueSmall' action='32' >cancel</label>
			<label sizen='40 3'  posn='60 -49 0' halign='center' valign='center' style='TextValueSmall' action='60000' >vox</label>
			";
	}
	if (isadmin($login)) {
		$xml .= "
			<label sizen='40 3'  posn='60 -28 0' halign='center' valign='center' style='TextValueSmall' action='33' >end</label>
			<label sizen='40 3'  posn='20 -31 0' halign='center' valign='center' style='TextValueSmall' action='34' >time attack</label>
			<label sizen='40 3'  posn='60 -31 0' halign='center' valign='center' style='TextValueSmall' action='35' >round</label>
			<label sizen='40 3'  posn='20 -34 0' halign='center' valign='center' style='TextValueSmall' action='36' >laps</label>
			<label sizen='40 3'  posn='60 -34 0' halign='center' valign='center' style='TextValueSmall' action='37' >stunts</label>
			<label sizen='40 3'  posn='20 -37 0' halign='center' valign='center' style='TextValueSmall' action='38' >team</label>
			<label sizen='40 3'  posn='60 -37 0' halign='center' valign='center' style='TextValueSmall' action='39' >cup</label>
			<label sizen='40 3'  posn='20 -40 0' halign='center' valign='center' style='TextValueSmall' action='40' >die</label>
			<label sizen='40 3'  posn='60 -40 0' halign='center' valign='center' style='TextValueSmall' action='41' >shutdown</label>
			<label sizen='40 3'  posn='20 -43 0' halign='center' valign='center' style='TextValueSmall' action='42' >varlist</label>
			<label sizen='40 3'  posn='60 -43 0' halign='center' valign='center' style='TextValueSmall' action='43' >pub</label>
			<label sizen='40 3'  posn='20 -46 0' halign='center' valign='center' style='TextValueSmall' action='44' >version</label>
			<label sizen='40 3'  posn='60 -46 0' halign='center' valign='center' style='TextValueSmall' action='45' >coppers</label>
			<label sizen='40 3'  posn='20 -49 0' halign='center' valign='center' style='TextValueSmall' action='46' >ListMatchSettings</label>
			";
	}
			
	if ($sunrise==2) { //tmu
		$xml .= "	
			<label sizen='40 3'  posn='20 -55 0' halign='center' valign='center' style='TextValueSmall' action='71' >don 100</label>
			<label sizen='40 3'  posn='60 -55 0' halign='center' valign='center' style='TextValueSmall' action='72' >don 200</label>
			<label sizen='40 3'  posn='20 -58 0' halign='center' valign='center' style='TextValueSmall' action='73' >don 500</label>
			<label sizen='40 3'  posn='60 -58 0' halign='center' valign='center' style='TextValueSmall' action='74' >don 1000</label>
			<label sizen='40 3'  posn='20 -61 0' halign='center' valign='center' style='TextValueSmall' action='75' >don 2000</label>
			";
	}
			
	$xml .= "<label sizen='80 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
			</frame>
			</manialink>";

	if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}	
}

function playerChat($Player) {
//int PlayerUid, string Login, string Text, bool IsRegistredCmd

global $welcome_msg;
global $annonce;
global $st;
global $colors;
global $messages;
global $CurrentChallenge;
global $record;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $chat;
global $client;
global $NextChallengeInfo;
global $Server_Status;
global $sunrise;
global $maxtop;
global $PlayerList;
global $Bill;
global $Pari;
global $PariCount;
global $CurrentGameMode;
global $coppermin;
global $coppermax;
global $copperreserve;
global $Note;
global $NbVote;
global $VoteCount;
global $Vote;
global $ModifVar;
global $VoteNext;
global $VoteNextLogin;
global $VoteNextOk;
global $VoteNextMap;
global $VoteNextMapName;
global $VoteNextSeuil;
global $wg;
global $wgprice;
global $wgtime;
global $wgindex;
global $wgmot;
global $MaxPlayer;
global $use_exchange;
global $Duel;
global $DuelCount;
global $RankServer;
global $RankMap;
global $RankMap2;
global $RankMappeur;
global $RankMappeur2;
global $RecordLogin;
global $Moyenne;
global $CurrentGameInfo;
global $pub;
global $now;
global $TracksDirectory;
global $txt;
global $lang;
global $infos;
global $txtl;
global $PlayerLanguage;
global $langues;
global $codelang;
global $restart;
global $PlayerScript;
global $TMGeryVersion;
global $PlayerAccount;
global $plugins;	//DedDerek

if ($Player[0]==0) return;	//si Uid serveur c est de l echo

echo "Player ".purgelogin($Player[1])." UId ".$Player[0]." dit ".stripColors($Player[2],1);
echo "\n\r";

$Ignore = false;
if(!@$client->query("GetIgnoreList", $MaxPlayer, 0)){
	Error($client->getErrorMessage(), $client->getErrorCode());
}else{
	$IgnoreList = $client->getResponse();
	foreach ($IgnoreList as $player) {
		if ($player['Login']==$Player[1]) {
			$Ignore = true;
			break;
		}
	}
}

$found=false;
foreach ($PlayerList as $player) {
	if ($Player[1]==$player['Login']) {
		$nick=$player['NickName'];
		$login=$player['Login'];
		$rank=$player['LadderRanking'];
		$account=$PlayerAccount[$login];
		$found=true;
		break;
	}
}

if (!$found) {
	return;
//	$nick=getNick($Player[2]);
//	if ($nick=="") return;
//	$login=getUserLogin($nick);
//	if ($login=="") return;
}

echo "Player ".purgelogin($login)." Nick ".stripColors($nick,1);
echo "\n\r";

if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;

Injure ($login,$nick,$Player[2]);

if ($Player[3] == 1) {
	echo " command";
	echo "\n\r";

		$cmd = getCommand($Player[2]);
		// user requests actual time
		if($cmd['command']=='time'){
			$time = date("H:i:s");
			
			$msg = $st . $colors['interact'] . $txtl['_'.$PlayerLanguage[$login]]['heure serveur'].': ' . $colors['highlight'] . $time;
	
			SendMsgToLogin ($msg, $login);					

		}elseif(($cmd['command']=='record')||($cmd['command']=='rec')){
			getrec ($login);					

		}elseif($cmd['command']=='bye' || $cmd['command']=='cu'){
			if ($Ignore) return;

			if(isset($cmd['params'][0])){
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('dit au revoir a').' ' . $colors['highlight'] . $cmd['params'][0]  . $colors['emotic'] . "!";
			}else{
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('doit partir').' :)';
			}
					
			ChatSendServerMessage($msg);

		}elseif($cmd['command']=='hi' || $cmd['command']=='lu'){
			if ($Ignore) return;

			if(isset($cmd['params'][0])){
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('dit salut a').' ' . $colors['highlight'] . $cmd['params'][0] . $colors['emotic'] .  "!";
			}else{
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('dit salut a tous').'!';
			}
					
			ChatSendServerMessage($msg);

		}elseif($cmd['command']=='lol'){
			if ($Ignore) return;

			if(isset($cmd['params'][0])){
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('rit bien').' ' . $colors['highlight'] . $cmd['params'][0] . $colors['emotic'] . "!";
			}else{
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('est mort de rire').'!';
			}

			ChatSendServerMessage($msg);
					
		}elseif($cmd['command']=='gg'){
			if ($Ignore) return;

			if(isset($cmd['params'][0])){
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('dit bravo a').' ' . $colors['highlight'] . $cmd['params'][0] . $colors['emotic'] . "!";
			}else{
				$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('dit bravo a tous') .'!';
			}

			ChatSendServerMessage($msg);
				
		}elseif($cmd['command']=='afk'){
			$msg = $st . purgeNick($nick) . '$z' . $colors['emotic'] . ' '.txtbal('est parti boire un coup');
				
			ChatSendServerMessage($msg);
					
		}elseif($cmd['command']=='version'){
			$msg = $st . '$eee' . "Script is: ". base64_decode($TMGeryVersion);
				
			ChatSendServerMessageToLogin( $msg, $login);
					
		}elseif($cmd['command']=='serverlogin'){
			;
		}elseif($cmd['command']=='help'){
			if (isadmin($login) || isadmin2($login)) {
				if ($sunrise == 2) $msg = $st . '$fff$w' . $messages['help'] . "\n\r" . $messages['helptmu'] . "\n\r" . $messages['helpadm']  . "\n\r" . $messages['helpadmtmn'] . "\n\r" . $messages['helpadmtmu'];
				elseif ($sunrise == 0) $msg = $st . '$fff$w' . $messages['help'] . "\n\r" . $messages['helpadm'] . "\n\r" . $messages['helpadmtmn'];
				else $msg = $st . '$fff' . $messages['help'] . "\n\r" . "\n\r" . $messages['helpadm'] ;
			}
			else {
				if ($sunrise == 2) $msg = $st . '$fff$w' . $messages['help'] . "\n\r" . $messages['helptmu'];
				elseif ($sunrise == 0) $msg = $st . '$fff$w' . $messages['help'];
				else $msg = $st . '$fff' . $messages['help'];
			}

			SendMsgToLogin2 ($msg, $login);					

		}elseif($cmd['command']=='restart'){

			if (isadmin($login) || isadmin2($login)) {
				if (!@$client->query('SetGameMode',$CurrentGameMode )) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					// restart challenge
					if(!$client->query("ChallengeRestart")){
						Error($client->getErrorMessage(), $client->getErrorCode());
					}
					else {
						if ($Server_Status['Name'] !== 'Running - Finish') $restart=true;
					
						$msg = '$z' . $colors['interact'] . ' '.txtbal('redemarree par un admin');
					
						ChatSendServerMessage($msg);
					}
				}
			}
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}

		}elseif($cmd['command']=='pub'){

			if (isadmin($login)) {
				$pub=1;
			}
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}

		}elseif($cmd['command']=='gonext'){

			if (isadmin($login) || isadmin2($login)) {
				// force next challenge
				if(!$client->query("NextChallenge")){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					$now = time() - $CurrentGameInfo['TimeAttackLimit']/1000;

					$msg = '$z' . $colors['interact'] . ' '.txtbal('passage au challenge suivant force par un admin');
				
					ChatSendServerMessage($msg);
				}
			}
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					
	
			}
		}elseif($cmd['command']=='next'){
			$ModeText = getNextChallenge(true);
			$msg = '$z$fffNext'.$ModeText.$NextChallengeInfo['Name']. '$z$fff - ' . $NextChallengeInfo['Author'];

			SendMsgToLogin ($msg, $login);					

		}elseif($cmd['command']=='list'){
			$page = 0;
			$envs = array('Island','Coast','Bay','Alpine','Speed','Rally','Stadium'); 

			if (!isset($cmd['params'][0]) || (isset($cmd['params'][0]) && (intval($cmd['params'][0])>0))) {
				if (isset($cmd['params'][0])) $page = intval($cmd['params'][0])-1;

//				$msg = getListChallenge($page);
//				SendMsgToLogin2 ($msg, $login);					
				getListChallenge2($page, $login);
			}
			elseif (isset($cmd['params'][0]) && in_array($cmd['params'][0], $envs)) {

//				$msg = getListEnvChallenge($cmd['params'][0]);
//				SendMsgToLogin2 ($msg, $login);					
				getListEnvChallenge2($page, $login, $cmd['params'][0]);
			}
/*
//			$msg = $st . '$z$fff '.$txtl['_'.$PlayerLanguage[$login]]['utilisez'].' $0f0/list num_page $fff'.$txtl['_'.$PlayerLanguage[$login]]['pour la suite'];
			$msg = $st . '$z$fff '.$txtl['_'.$PlayerLanguage[$login]]['utilisez'].' $0f0/list page';

			if ($sunrise != 0) {
//				$msg = $st . '$z$fff '.$txtl['_'.$PlayerLanguage[$login]]['utilisez'].' $0f0/list Island|Coast|Bay|Alpine|Speed|Rally|Stadium';
//				ChatSendServerMessageToLogin($msg, $login);
				$msg .=  '|Island|Coast|Bay|Alpine|Speed|Rally|Stadium';
			}

			ChatSendServerMessageToLogin($msg, $login);
*/
		}elseif($cmd['command']=='listlogin'){
			$page = 0;
			if (isset($cmd['params'][0])) {

/*
				$msg = getListLoginChallenge($cmd['params'][0]);
				if ($msg == "") {
					$msg = '$0f0 '.$txtl['_'.$PlayerLanguage[$login]]['rien avec'].' '.$cmd['params'][0];
					ChatSendServerMessageToLogin($msg, $login);
				}
				else {
*/
					getListLoginChallenge2($page, $login, $cmd['params'][0]);
//					SendMsgToLogin2 ($msg, $login);					
/*				}*/

			}
			else {
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /listlogin login';
				ChatSendServerMessageToLogin($msg, $login);
			}

		}elseif($cmd['command']=='ta'){
			if (isadmin($login)) {
				if (!@$client->query('SetGameMode',1 )) {	//timeattack
			  		Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					if(isset($cmd['params'][0])){ //parametre TimeAttackLimit en nombre de minutes
						if (!@$client->query('SetTimeAttackLimit',intval($cmd['params'][0]*60000) )) {	//set time
							Error($client->getErrorMessage(), $client->getErrorCode());
						}
					}
					if ($Server_Status['Name'] !== 'Running - Finish') $restart=true;
				
					$msg = '$z' . $colors['interact'] . ' '.txtbal('mode time attack force par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='team'){
			if (isadmin($login)) {
				if (!@$client->query('SetGameMode',2 )) {	//team
			  		Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					if(isset($cmd['params'][0])){ //parametre TeamPointsLimit
						if (!@$client->query('SetTeamPointsLimit',intval($cmd['params'][0]) )) {	//set point limit
							Error($client->getErrorMessage(), $client->getErrorCode());
						}
					}		
					if ($Server_Status['Name'] !== 'Running - Finish') $restart=true;
				
					$msg = '$z' . $colors['interact'] . ' '.txtbal('mode team force par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='round'){
			if (isadmin($login)) {
				if (!@$client->query('SetGameMode',0 )) {	//par tours
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					if(isset($cmd['params'][0])){ //parametre RoundPointsLimit
						if (!@$client->query('SetRoundPointsLimit',intval($cmd['params'][0]) )) {	//set points
							Error($client->getErrorMessage(), $client->getErrorCode());
						}
					}		
					if ($Server_Status['Name'] !== 'Running - Finish') $restart=true;
				
					$msg = '$z' . $colors['interact'] . ' '.txtbal('mode round force par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='laps'){
			if (isadmin($login)) {
				if (!@$client->query('SetGameMode',3 )) {	//laps
			  		Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					if(isset($cmd['params'][0])){ // parametre NbLaps
						if (!@$client->query('SetNbLaps',intval($cmd['params'][0]) )) {	//set number laps
							Error($client->getErrorMessage(), $client->getErrorCode());
						}
					}		
					if ($Server_Status['Name'] !== 'Running - Finish') $restart=true;
				
					$msg = '$z' . $colors['interact'] . ' '.txtbal('mode laps force par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='stunts'){
			if (isadmin($login)) {
				if (!@$client->query('SetGameMode',4 )) {	//stunts
			  		Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					if(isset($cmd['params'][0])){ //parametre TimeAttackLimit en nombre de minutes
						if (!@$client->query('SetTimeAttackLimit',intval($cmd['params'][0]*60000) )) {	//set time
							Error($client->getErrorMessage(), $client->getErrorCode());
						}
					}
					if ($Server_Status['Name'] !== 'Running - Finish') $restart=true;
				
					$msg = '$z' . $colors['interact'] . ' '.txtbal('mode stunts force par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='cup'){
			if (isadmin($login)) {
				if (!@$client->query('SetGameMode',5 )) {	//cup
			  		Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					if ($Server_Status['Name'] !== 'Running - Finish') $restart=true;
				
					$msg = '$z' . $colors['interact'] . ' '.txtbal('mode cup force par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='SaveMatchSettings'){
			if (isadmin($login)) {
				if ( isset($cmd['params'][0]) ) {
					$file='MatchSettings//'.$cmd['params'][0];
					if (!$client->query('SaveMatchSettings', $file)) {
						Error($client->getErrorMessage(), $client->getErrorCode());
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
						ChatSendServerMessageToLogin($msg, $login);
					}
					else{
						$msg = '$af0 '.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'];
						ChatSendServerMessageToLogin($msg, $login);
					}
				}
				else {
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /SaveMatchSettings Filename';
					ChatSendServerMessageToLogin($msg, $login);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='LoadMatchSettings'){
			if (isadmin($login)) {
				if ( isset($cmd['params'][0]) ) {
					$file='MatchSettings//'.$cmd['params'][0];
					if (!$client->query('LoadMatchSettings', $file)) {
						Error($client->getErrorMessage(), $client->getErrorCode());
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
						ChatSendServerMessageToLogin($msg, $login);
					}
					else{
						$msg = '$af0 '.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'];
						ChatSendServerMessageToLogin($msg, $login);
					}
				}
				else {
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /LoadMatchSettings Filename';
					ChatSendServerMessageToLogin($msg, $login);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='ListMatchSettings'){
			if (isadmin($login)) {
				$msg = "";
				if ($handle = @opendir($TracksDirectory."MatchSettings//")) {
					//    echo "Directory handle: $handle\n\r";
					//    echo "Files\n\r>";
					while (false !== ($file = readdir($handle))) {
						if ( is_file($TracksDirectory."MatchSettings//".$file)) { 
							$msg .= $file . "\n\r";
						}
					}
					closedir($handle);
				}
				if ($msg == "") {
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
					ChatSendServerMessageToLogin($msg, $login);
				}
				else SendMsgToLogin2 ($msg, $login);
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					
			}
		}elseif($cmd['command']=='lang'){
			if (isadmin($login)) {
				if ( isset($cmd['params'][0]) ) {
//					$langsave = $lang;
//					$lang = $cmd['params'][0];
//					require "includes/tm_gery_lang.php";
//					if ($cmd['params'][0] != $lang) {
//						$lang = $langsave;
					if (!in_array($cmd['params'][0],$codelang,true)) {
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /lang '.$langues;
						ChatSendServerMessageToLogin($msg, $login);
					}
					else{
						$txt = $txtl['_'.$cmd['params'][0]];
						$msg = '$af0 '.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'];
						ChatSendServerMessageToLogin($msg, $login);
						information ($infos);
					}
				}
				else {
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /lang '.$langues;
					ChatSendServerMessageToLogin($msg, $login);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='mylang'){
				if ( isset($cmd['params'][0]) ) {
					if (!in_array($cmd['params'][0],$codelang,true)) {
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /mylang '.$langues;
						ChatSendServerMessageToLogin($msg, $login);
					}
					else{
						$PlayerLanguage[$login] = $cmd['params'][0];
						$msg = '$af0 '.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'];
						ChatSendServerMessageToLogin($msg, $login);
						save_player ($login, $nick, $rank, $PlayerLanguage[$login], $PlayerScript[$login]);
					}
				}
				else {
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /mylang '.$langues;
					ChatSendServerMessageToLogin($msg, $login);
				}
		}elseif($cmd['command']=='die'){
			if (isadmin($login)) {
				die(0);
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='shutdown'){
			if (isadmin($login)) {
				Etat_Serveur();
				if(!@$client->query("StopServer")){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				sleep (5);		
				if(!@$client->query("QuitGame")){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				die(1);
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
		}elseif($cmd['command']=='cancel'){

			if (isadmin($login) || isadmin2($login)) {
				// cancel vote
				if(!$client->query("CancelVote")){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					$VoteNextOk=0;
					$VoteNext=false;
					SendManiaClearVoteOk();

					$msg = '$z' . $colors['interact'] . ' '.txtbal('vote annule par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
					
		}elseif($cmd['command']=='end'){

			if (isadmin($login)) {
				// cancel vote
				if(!$client->query("ForceEndRound")){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					$msg = '$z' . $colors['interact'] . ' '.txtbal('fin de round force par un admin');
				
					ChatSendServerMessage($msg);
				}
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					

			}
					
		}elseif($cmd['command']==$wgmot[$wgindex]){
			if ($Ignore) return;
			if ($account==0) return;	//pas autorisé aux comptes tmn
			if ($wg && ((time()-$wgtime)>2)) {
				if (!$client->query("Pay",purgelogin($login),$wgprice,$txtl['_'.$PlayerLanguage[$login]]['jeu de mots de $0f0GERY'])) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
				else {
					$msg = $st . purgeNick($nick) . '$z$fff '.txtbal('gagne').' $0f0'.$wgprice.'$z$fff coppers';
					ChatSendServerMessage($msg);
					$wg=false;
				}
			} 
			else {
				if ($wg)
					$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['rate']; 
				else
					$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['rate']; 
						
				ChatSendServerMessageToLogin($msg, $login);

			}
					
		}elseif($cmd['command'] == "msg"){
			if ($Ignore) return;
			if(isset($cmd['params'][0]) && isset($cmd['params'][1])){
				$msg = '$ff0['.purgeNick($nick). '$z' .'$m$ff0] '.$cmd['params'][1];

				if(!$client->query("ChatSendServerMessageToLogin", $messages['pref'].$msg, $cmd['params'][0])){
					Error($client->getErrorMessage(), $client->getErrorCode());
	        	                
					$msg = $cmd['params'][1].'$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
					ChatSendServerMessageToLogin($msg, $login);
				}else{
					
					$msg = $cmd['params'][1].'$af0 '.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'];
					ChatSendServerMessageToLogin($msg, $login);
				}
			}
			else{
				
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /msg login message (/playerlist => login)';
				ChatSendServerMessageToLogin($msg, $login);
	       	}
					
		}elseif($cmd['command'] == "Kick" || $cmd['command'] == "Ban" || $cmd['command'] == "Ignore" ||	$cmd['command'] == "UnIgnore" ){
          	if(isset($cmd['params'][0])){
				if (isadmin($login) || isadmin2($login)) {
//					foreach($PlayerList as $Player) {
//						if (purgelogin($Player['Login'])==$cmd['params'][0]) {
							if(!$client->query($cmd['command'], $cmd['params'][0])){
								Error($client->getErrorMessage(), $client->getErrorCode());
								$msg = '$af0 ('.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].')';
								ChatSendServerMessageToLogin($msg, $login);
							}
							else{
								
								$msg = '$af0 ('.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'].')';
								ChatSendServerMessageToLogin($msg, $login);
				
								$msg = '$z' . $colors['interact'] . ' '.txtbal('un admin utilise la commande').' ' . $cmd['command']. ' '.txtbal('sur').' login ' . $cmd['params'][0];
				
								ChatSendServerMessage($msg);
			       			}
//							break;
//						}
//					}

				} 
				else {
					$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
							
					SendMsgToLogin ($msg, $login);					

				}

			}
			else{
				
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /'.$cmd['command'].' login';
				ChatSendServerMessageToLogin($msg, $login);
	       	}
		}elseif($cmd['command'] == "BlackList" || $cmd['command'] == "AddGuest" || $cmd['command'] == "UnBan" ||
			$cmd['command'] == "UnBlackList" || $cmd['command'] == "RemoveGuest"){
          	if(isset($cmd['params'][0])){
				if (isadmin($login)) {
//					foreach($PlayerList as $Player) {
//						if (purgelogin($Player['Login'])==$cmd['params'][0]) {
							if(!$client->query($cmd['command'], $cmd['params'][0])){
								Error($client->getErrorMessage(), $client->getErrorCode());
								$msg = '$af0 ('.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].')';
								ChatSendServerMessageToLogin($msg, $login);
							}
							else{
								
								$msg = '$af0 ('.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'].')';
								ChatSendServerMessageToLogin($msg, $login);
				
								$msg = '$z' . $colors['interact'] . ' '.txtbal('un admin utilise la commande').' ' . $cmd['command']. ' '.txtbal('sur').' login ' . $cmd['params'][0];
				
								ChatSendServerMessage($msg);
			       			}
//							break;
//						}
//					}

				} 
				else {
					$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
							
					SendMsgToLogin ($msg, $login);					

				}

			}
			else{
				
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /'.$cmd['command'].' login';
				ChatSendServerMessageToLogin($msg, $login);
	       	}
					
//		}elseif($cmd['command']=='top5'|| ($cmd['command']=='top' && !isset($cmd['params'][0]))){
		}elseif($cmd['command']=='top5'){

			$msg  = '$z' . $colors['interact'] . '1. ' . $colors['highlight'] . MwTimeToString($record['Time'])  . ' $z'. purgeNick($record['Author']) . '$z' . $colors['interact'] . ' ( ' . $record['Login'] . ' )'."\n\r" ;
			$msg .= '$z' . $colors['interact'] . '2. ' . $colors['highlight'] . MwTimeToString($TopBestTime[1])  . ' $z'. purgeNick($TopNickName[1]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[1] . ' )'."\n\r" ;
			$msg .= '$z' . $colors['interact'] . '3. ' . $colors['highlight'] . MwTimeToString($TopBestTime[2])  . ' $z'. purgeNick($TopNickName[2]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[2] . ' )'."\n\r" ;
			$msg .= '$z' . $colors['interact'] . '4. ' . $colors['highlight'] . MwTimeToString($TopBestTime[3])  . ' $z'. purgeNick($TopNickName[3]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[3] . ' )'."\n\r" ;
			$msg .= '$z' . $colors['interact'] . '5. ' . $colors['highlight'] . MwTimeToString($TopBestTime[4])  . ' $z'. purgeNick($TopNickName[4]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[4] . ' )';

			if ($Server_Status['Name']=='Running - Play' && !$sunrise){
//				if (!$client->query("SendHideServerMessageToLogin", $login)) {
//					Error($client->getErrorMessage(), $client->getErrorCode());
//				}
//				if (!$client->query("SendDisplayServerMessageToLogin", $login, $msg,"OK","",0)) {
//					Error($client->getErrorMessage(), $client->getErrorCode());
//				}
				SendDisplayManialinkPageToLogin ($login, $msg, 0);
			}
			else if ($Server_Status['Name']=='Running - Play' && $sunrise == 2){
				SendDisplayManialinkPageToLogin ($login, $msg, 0);
			}
			else {

				ChatSendServerMessageToLogin($msg, $login);
			}

		}elseif($cmd['command']=='top'){
//			if(isset($cmd['params'][0])){
				if(isset($cmd['params'][0])){
					$index=intval($cmd['params'][0]);
				}
				else {
					$index=1;
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /top position (position>0'.', <='.$maxtop.')';
					ChatSendServerMessageToLogin($msg, $login);
				}
				if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=28; 
				elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=28; 
				else $max=10;
//				if ($index>5 && $index<=$maxtop) {
				if ($index>0 && $index<=$maxtop) {
					$msg="";
					for ($i=$index; $i<=$maxtop && $i<$index+$max;$i++) {
						$msg .= '$z' . $colors['interact'] . $i .'. ' . $colors['highlight'] . MwTimeToString($TopBestTime[$i-1])  . ' $z'. purgeNick($TopNickName[$i-1])  . '$z' . $colors['interact'] . ' ( ' . $TopLogin[$i-1] . ' )'."\n\r" ;
					}				
					if ($Server_Status['Name']=='Running - Play' && !$sunrise){
//						if (!$client->query("SendHideServerMessageToLogin", $login)) {
//							Error($client->getErrorMessage(), $client->getErrorCode());
//						}
//						if (!$client->query("SendDisplayServerMessageToLogin", $login, $msg,"OK","",0)) {
//							Error($client->getErrorMessage(), $client->getErrorCode());
//						}
//						SendDisplayManialinkPageToLogin2 ($login, $msg, 0);
						$moins = $index-$max;
						if ($moins<=0) $moins = 1;
						$plus = $index+$max;
						if ($plus>$maxtop) $plus = $index;
						$xml = "<?xml version='1.0' encoding='utf-8' ?> 
								<manialink id='List'>
								<timeout>0</timeout>
								<type>default</type>
								<frame posn='-40 43 0'>
								<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
								<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
								<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(20001+$moins)."' ><![CDATA[<<]]></label>
								<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
								<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(20001+$plus)."' ><![CDATA[>>]]></label>
								</frame>
								</manialink>";

						if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
							Error($client->getErrorMessage(), $client->getErrorCode());
						}	

					}
					else if ($Server_Status['Name']=='Running - Play' && $sunrise == 2){
//						SendDisplayManialinkPageToLogin2 ($login, $msg, 0);
						$moins = $index-$max;
						if ($moins<=0) $moins = 1;
						$plus = $index+$max;
						if ($plus>$maxtop) $plus = $index;
						$xml = "<?xml version='1.0' encoding='utf-8' ?> 
								<manialink id='List'>
								<timeout>0</timeout>
								<type>default</type>
								<frame posn='-40 43 0'>
								<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
								<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
								<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(20001+$moins)."' ><![CDATA[<<]]></label>
								<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
								<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(20001+$plus)."' ><![CDATA[>>]]></label>
								</frame>
								</manialink>";

						if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
							Error($client->getErrorMessage(), $client->getErrorCode());
						}	
					}
					else {
						ChatSendServerMessageToLogin($msg, $login);
					}
				}
				else{
					
//					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /top position (position >5)';
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /top position (position>0'.', <='.$maxtop.')';
					ChatSendServerMessageToLogin($msg, $login);
				}
/*
			}
			else{
				
//				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /top position (position >5)';
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /top position (position >0)';
				ChatSendServerMessageToLogin($msg, $login);
			}
*/
		}elseif(($cmd['command'] == "choosenext" )||($cmd['command'] == "ok" )){
			if(	(
				(isset($cmd['params'][0]) && ($cmd['command'] == "choosenext")) ||
				(!isset($cmd['params'][0]) && ($cmd['command'] == "ok")) 
				) && ($Server_Status['Name']=='Running - Play')){

				$recherche = "";
				if (isset($cmd['params'][0])) {
					foreach ($cmd['params'] as $tmp) $recherche .= $tmp . " ";
					$recherche = rtrim($recherche);
				}

				if ((isadmin($login) || isadmin2($login)) && ($cmd['command'] !== "ok")) {
					$smap = searchmap( $recherche, $result, $result2);

					if(!$smap){
						
						$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].')';
						ChatSendServerMessageToLogin($msg, $login);
					}
					else{
						if ($smap==1) {
							if(!$client->query("ChooseNextChallenge",$result)){
							
								$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].')';
								ChatSendServerMessageToLogin($msg, $login);
					   		}
							else {
							
								$msg = '$z$ff0'.$txtl['_'.$PlayerLanguage[$login]]['map suivante'].': $z'.$result2;
								ChatSendServerMessageToLogin($msg, $login);
								$VoteNextOk=0;
								$VoteNext=false;
								SendManiaClearVoteOk();
				
								$msg = '$z' . $colors['interact'] . ' '.txtbal('map suivante forcee par un admin').' : $z' . $result2;
				
								ChatSendServerMessage($msg);
							}
						}
						else {
							$msg = '$z$ff0'.$txtl['_'.$PlayerLanguage[$login]]['map suivante'].': $z'.$result2 . '$z$ff0 ?';
							ChatSendServerMessageToLogin($msg, $login);
						}
					}
				} 
				else {
					if ($VoteNext) {
						if($cmd['command'] == "ok") {
							$found=false;
							for ($i=0; $i<$VoteNextOk; $i++) {
								if ($VoteNextLogin[$i]==purgelogin($login)) {$found=true; break;}
							}
							$Nbplayer=count($PlayerList);
							if ($Nbplayer==0) $Nbplayer=1;
							if (!$found) {
								$xml = "<?xml version='1.0' encoding='utf-8'?><manialink id='Next'></manialink>";
								if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
									Error($client->getErrorMessage(), $client->getErrorCode());
								}	
								$VoteNextLogin[$i]=purgelogin($login);
								$VoteNextOk++;
								$reste = ceil($Nbplayer*$VoteNextSeuil)-$VoteNextOk;
								if ($reste > 0) {
									$msg = '$z$0f0'.$reste.'$fff '.txtbal('ok pour changer la map suivante').' $z'.$VoteNextMapName;
									ChatSendServerMessage($msg);
								}
							}
							if (($VoteNextOk/$Nbplayer) >= $VoteNextSeuil) {
								if(!$client->query("ChooseNextChallenge",$VoteNextMap)){
									
									$msg = '$f00 ('.txtbal('echec pour changer la map suivante').')';
									ChatSendServerMessage($msg);
									$VoteNextOk=0;
									$VoteNext=false;
									SendManiaClearVoteOk();
						   		}
								else {
									
									$msg = '$z$ff0'.txtbal('map suivante changee pour').' $z'.$VoteNextMapName;
									ChatSendServerMessage($msg);
									$ModeText = getNextChallenge(true);
									$VoteNextOk=0;
									$VoteNext=false;
									SendManiaClearVoteOk();
								}
							}
						}
						else {
							
							$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /ok';
							ChatSendServerMessageToLogin($msg, $login);
						}
					}
					else {
						if($cmd['command'] == "choosenext") {
							if ($Ignore) return;
							if ( ($CurrentGameMode !== 0) && ($CurrentGameMode !== 5) && ($CurrentGameInfo['TimeAttackLimit'] > 0) && (time() > ($now+($CurrentGameInfo['TimeAttackLimit']/2000)))) { 
							//trop tard si la moitie du temps de la map est passé et pas mode round ou cup
								
								$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['trop tard'];
								ChatSendServerMessageToLogin($msg, $login);
							}
							else {
								$smap = searchmap( $recherche, $result, $result2);

								if(!$smap){
									
									$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].')';
									ChatSendServerMessageToLogin($msg, $login);
								}
								else{
									if ($smap==1) {
									
//										$msg = '$z'.purgeNick($nick).'$z$ff0 '.txtbal('voudrait jouer la map').': $z'. $result2."\n\r".'$z$0f0'.txtbal('utilisez').' /ok';
										$msg = '$z'.purgeNick($nick).'$z$ff0 '.txtbal('voudrait jouer la map').': $z'. $result2;
										ChatSendServerMessage($msg);
										$VoteNextMap=$result;
										$VoteNextMapName=$result2;
										$VoteNext=true;
										SendManiaVoteOk ($VoteNextMapName);
									}
									else {
										$msg = '$z$ff0'.$txtl['_'.$PlayerLanguage[$login]]['map suivante'].': $z'.$result2 . '$z$ff0 ?';
										ChatSendServerMessageToLogin($msg, $login);
									}
								}
							}
						}
					}
				}

			}

			else{
				if ($Server_Status['Name']!=='Running - Play') {
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['trop tard'];
					ChatSendServerMessageToLogin($msg, $login);
				}
				elseif ($VoteNext) {
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /ok';
					ChatSendServerMessageToLogin($msg, $login);
				}
				else {
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /choosenext '.$txtl['_'.$PlayerLanguage[$login]]['nom_meme_partiel_de_la_map'];
					ChatSendServerMessageToLogin($msg, $login);
			   	}
			}
					
		}elseif($cmd['command'] == "delmap" ){
			if(isset($cmd['params'][0]) && ($Server_Status['Name']=='Running - Play')){

				$recherche = "";
				if (isset($cmd['params'][0])) {
					foreach ($cmd['params'] as $tmp) $recherche .= $tmp . " ";
					$recherche = rtrim($recherche);
				}

				if (isadmin($login)) {
					$smap = searchmap( $recherche, $result, $result2);

					if(!$smap){
						
						$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].')';
						ChatSendServerMessageToLogin($msg, $login);
					}
					else{
						if ($smap==1) {
							if(!$client->query("RemoveChallenge",$result)){
							
								$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].')';
								ChatSendServerMessageToLogin($msg, $login);
					   		}
							else {
							
								$msg = '$z'.$result2.'$z$ff0 '.$txtl['_'.$PlayerLanguage[$login]]['detruit'];
								ChatSendServerMessageToLogin($msg, $login);
							}
						}
						else {
							$msg = '$z'.$result2 . '$z$ff0 ?';
							ChatSendServerMessageToLogin($msg, $login);
						}
					}
				} 
				else {
					$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
					SendMsgToLogin ($msg, $login);					
				}

			}

			else{
				if ($Server_Status['Name']!=='Running - Play') {
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['trop tard'];
					ChatSendServerMessageToLogin($msg, $login);
				}
				else {
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /delmap '.$txtl['_'.$PlayerLanguage[$login]]['nom_meme_partiel_de_la_map'];
					ChatSendServerMessageToLogin($msg, $login);
			   	}
			}
					
		}elseif($cmd['command'] == "exchange"){
			if ($use_exchange || isadmin($login)) {
				$found=false;	
				if(isset($cmd['params'][0]) && isset($cmd['params'][1])) {
					if ( (intval($cmd['params'][1])>0) && 
						(($cmd['params'][0]=='united')||
						 ($cmd['params'][0]=='tmnforever')||
						 ($cmd['params'][0]=='nations')||
						 ($cmd['params'][0]=='sunrise')||
						 ($cmd['params'][0]=='original'))
					   ) {
						$num=intval($cmd['params'][1]);
						$tmx=$cmd['params'][0];
						$filename=searchmapTMX($tmx,$num,$ChallengeType);
						if ($filename) 	{
							$found=true;
						}
					}
				}
				if($found){
					//echo "file ".$filename."\n\r";

					if (!@$client->query('AddChallenge', $filename)) {
						Error($client->getErrorMessage(), $client->getErrorCode());
						
						$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
						ChatSendServerMessageToLogin($msg, $login);
					}
					else {
						if (!@$client->query('GetChallengeInfo', $filename)) {
							Error($client->getErrorMessage(), $client->getErrorCode());
							
							$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
							ChatSendServerMessageToLogin($msg, $login);
						}
						else {
							$ChallengeInfo = $client->getResponse();
							$ChallengeName=$ChallengeInfo['Name'];
							$ChallengeEnv=$ChallengeInfo['Environnement'];
							$ChallengeAuthor=$ChallengeInfo['Author'];

							if (!@$client->query('RemoveChallenge', $filename)) {
								Error($client->getErrorMessage(), $client->getErrorCode());
								
								$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
								ChatSendServerMessageToLogin($msg, $login);
							}
							else {
								$dirname = 'Challenges//Downloaded//'.$tmx.'-exchange';
								@!mkdir($TracksDirectory.$dirname);
								$dirname = 'Challenges//Downloaded//'.$tmx.'-exchange//'.$ChallengeAuthor;
								@!mkdir($TracksDirectory.$dirname);

								$file = preg_replace("/[^A-Za-z0-9]/", "_",StripColors($ChallengeName,1));
								$file = 'Challenges//Downloaded//'.$tmx.'-exchange//'.$ChallengeAuthor.'//'.$file.'.Challenge.Gbx';
								if (@!copy($TracksDirectory.$filename,$TracksDirectory.$file)) {
									
									$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
									ChatSendServerMessageToLogin($msg, $login);
								}
								else {
									if (!@$client->query('AddChallenge', $file)) {
										Error($client->getErrorMessage(), $client->getErrorCode());
										
										$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
										ChatSendServerMessageToLogin($msg, $login);
									}
									else {
										$msg = $st . '$z$0ff' . $ChallengeEnv . '.' . $ChallengeType 
												. '$z ' . $ChallengeName . '$z$fff' . " - " . $ChallengeAuthor;
										echo "add ".$msg."\n\r";
										
										$msg = '$0f0'.txtbal('nouvelle map ajoutee de').' '.$tmx.'.tm-exchange.com '.txtbal('par').' '.purgeNick($nick)."\n\r".$msg;
										ChatSendServerMessage($msg);
										
										$msg = $st . $txtl['_'.$PlayerLanguage[$login]]['utilisez'].' $0f0/choosenext $fff'.$txtl['_'.$PlayerLanguage[$login]]['pour proposer la map'];
										ChatSendServerMessageToLogin($msg, $login);
									}
								}
							}
						}
					}

				}
				else{
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /exchange tmnforever|united|nations|sunrise|original numero';
					ChatSendServerMessageToLogin($msg, $login);
				}
			}
			else{
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['pas autorise maintenant']; 
						
				SendMsgToLogin ($msg, $login);					
	       		}					
					
		}elseif($cmd['command'] == "playerlist"){

			if ($PlayerList==""){
				if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}else{
					$PlayerList = $client->getResponse();
				}
			}

			$player = array();
			$msg='$z$w$f00'."player List Nick (Login) (Language):\n\r";
			$i=0;
			foreach($PlayerList as $player){
				if ($i==2) {$msg .= "\n\r"; $i=0;}
				$i++;
//				$msg .= '$ff0[$fff'.$player['PlayerId'].'$m$ff0] '.purgeNick($player['NickName']).' $z$ff0($fff'.$player['Login'].'$m$ff0) '.'$ff0($fff'.$PlayerLanguage[$player['Login']].'$m$ff0) '.'$z, ';
				$msg .= '$ff0'.purgeNick($player['NickName']).' $z$ff0($fff'.$player['Login'].'$m$ff0) '.'$ff0($fff'.$PlayerLanguage[$player['Login']].'$m$ff0) '.'$z, ';
			}

			SendMsgToLogin2 ($msg, $login);					


		}elseif($cmd['command'] == "don"){
			if ($account==0) return;	//pas autorisé aux comptes tmn
			if(($sunrise==2) && isset($cmd['params'][0]) && intval($cmd['params'][0])>0){

				if(isset($cmd['params'][1])) $tologin = $cmd['params'][1]; else $tologin = '';

				if (!$client->query("SendBill",purgelogin($login),intval($cmd['params'][0]),'$0f0'.$txtl['_'.$PlayerLanguage[$login]]['DON de'].' '.purgelogin($login),$tologin)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
	        	                
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
					ChatSendServerMessageToLogin($msg, $login);
				}else{
					$BillId = $client->getResponse();

					$player = array();
    				foreach($PlayerList as $player){
						if ($player['Login']==$login) {$msg = purgeNick($player['NickName']).'$z$fff '.txtbal('donne').' $0f0'.intval($cmd['params'][0]).'$fff coppers '; break;}
				    	}
					if ($tologin=='') $msg .= txtbal('au serveur'); else $msg .= txtbal('au login').' $0f0'.$tologin;
					
					$Bill['BillMsg'][$BillId] = $msg;
					$Bill['BillType'][$BillId] = 'don';
					$Bill['Login'][$BillId] = purgelogin($login);
					$Bill['ToLogin'][$BillId] = $tologin;
	       			}
			}
			else{
				
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /don nbcoppers login (nbcoppers>0 - '.$txtl['_'.$PlayerLanguage[$login]]['pas de login pour le serveur'].')';
				ChatSendServerMessageToLogin($msg, $login);
			}
					
		}elseif($cmd['command'] == "duel"){
			if ($Ignore) return;
			if ($account==0) return;	//pas autorisé aux comptes tmn
			if(($sunrise==2) && isset($cmd['params'][1]) && $cmd['params'][1] != $login && isset($cmd['params'][0]) && intval($cmd['params'][0])>0){
//			if(($sunrise==2) && isset($cmd['params'][1]) && isset($cmd['params'][0]) && intval($cmd['params'][0])>0){ // pour test

				$found=false;	

				for ($i=0;$i<$DuelCount;$i++) {
					if (($Duel['Login'][$i]==purgelogin($login)) || ($Duel['ToLogin'][$i]==purgelogin($login))) {
		        			
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC vous etes deja en duel'];
						ChatSendServerMessageToLogin($msg, $login);
						$found=true;
						break;
					}
					if (($Duel['Login'][$i]==$cmd['params'][1]) || ($Duel['ToLogin'][$i]==$cmd['params'][1])) {
		        			
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC il est deja en duel'];
						ChatSendServerMessageToLogin($msg, $login);
						$found=true;
						break;
					}
				}
				foreach ($PlayerList as $player) {
					if (purgelogin($player['Login'])==$cmd['params'][1]) {
						if ($player['IsSpectator']==1) {
		        				
							$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC il est spectateur'];
							ChatSendServerMessageToLogin($msg, $login);
							$found=true;
							break;
						}
					}
					if ($PlayerAccount[$player['Login']]==0) {
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC']; //joueur TMN
						ChatSendServerMessageToLogin($msg, $login);
						$found=true;
						break;
					}
				}
				if ( ($CurrentGameMode !== 0) && ($CurrentGameMode !== 5) && (time() > ($now+($CurrentGameInfo['TimeAttackLimit']/2000)))) { 
				//trop tard si la moitie du temps de la map est passé et pas mode round ou cup
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['trop tard'];
					ChatSendServerMessageToLogin($msg, $login);
					$found=true;
				}
				
//$found=false;	//pour test

				if (!$found) {
					$tologin = $cmd['params'][1];
					$coppers=intval($cmd['params'][0]);
					$tonick = '';
					$player = array();
					foreach($PlayerList as $player){
						if (purgelogin($player['Login'])==$tologin) {$tonick = $player['NickName']; break;}
					}
					if ($tonick !== '') {
	
						if (!$client->query("SendBill",purgelogin($login),$coppers,'$0f0'.$txtl['_'.$PlayerLanguage[$login]]['DUEL CONTRE'].' '.$tonick,'')) {
							Error($client->getErrorMessage(), $client->getErrorCode());
		        		    		
							$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
							ChatSendServerMessageToLogin($msg, $login);
						}else{
							$BillId = $client->getResponse();
		
							$msg = '$m'.purgeNick($nick).'$z$fff '.txtbal('provoque').' '.purgeNick($tonick).'$z$fff '.txtbal('en duel pour').' $0f0'.$coppers.'$fff coppers ';
	
							$Bill['BillMsg'][$BillId] = $msg;
							$Bill['BillType'][$BillId] = 'duel';
							$Bill['Login'][$BillId] = purgelogin($login);
							$Bill['ToLogin'][$BillId] = $tologin;
							$Duel['BillId'][$DuelCount] = $BillId;
							$Duel['Score'][$DuelCount] = 0;
							$Duel['Coppers'][$DuelCount] = $coppers;
							$Duel['Login'][$DuelCount] = purgelogin($login);
							$Duel['NickName'][$DuelCount] = $nick;
							$Duel['ToLogin'][$DuelCount] = $tologin;
							$Duel['ToNickName'][$DuelCount] = $tonick;
							$Duel['Payed'][$DuelCount] = false;
							$Duel['Ok'][$DuelCount] = true;
							$Duel['Coef'][$DuelCount] = 1;
							$DuelCount++;
							SaveDuel($DuelCount);
						}
					}
					else{
						
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'].': login '.$tologin.' '.$txtl['_'.$PlayerLanguage[$login]]['inconnu'];
						ChatSendServerMessageToLogin($msg, $login);
					}
				}
			}
			else{
				
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /duel nbcoppers login (nbcoppers>0)';
				ChatSendServerMessageToLogin($msg, $login);
			}
					
		}elseif($cmd['command'] == "set"){
			if (isadmin($login)) {
				$found=false;	
				if(isset($cmd['params'][0])) {
					foreach ($ModifVar as $Var) {
						if ($cmd['params'][0]==$Var) {$found=true; break;}
					}
				}
				if($found && isset($cmd['params'][1])){

					ModifVariable($cmd['params'][0],$cmd['params'][1]);
					
					$msg = '$0f0'.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'].': '.$cmd['params'][0].'='.$cmd['params'][1];
					ChatSendServerMessageToLogin($msg, $login);
				}
				else{
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /set variable new_valeur';
					ChatSendServerMessageToLogin($msg, $login);
				}
			}
			else{
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					
	       		}					
					
		}elseif($cmd['command'] == "get"){
			if (isadmin($login)) {
				$found=false;	
				if(isset($cmd['params'][0])) {
					foreach ($ModifVar as $Var) {
						if ($cmd['params'][0]==$Var) {$found=true; break;}
					}
				}
		       		if($found){
					
					
					$msg = '$0f0'.$txtl['_'.$PlayerLanguage[$login]]['SUCCES'].': '.$cmd['params'][0].'='.GetVariable($cmd['params'][0]);
					ChatSendServerMessageToLogin($msg, $login);
				}
				else{
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /get variable';
					ChatSendServerMessageToLogin($msg, $login);
				}
			}
			else{
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					
			}					
					
		}elseif($cmd['command'] == "delrec"){
			if (isadmin($login) || isadmin2($login)) {
				$found=false;	
				if(isset($cmd['params'][0])) {
					for ($i=0;$i<$maxtop;$i++) {
						if ($TopLogin[$i]==$cmd['params'][0]) {
							$position=$i+1;
							$found=true;
							break;
						}
					}
				}
		       		if($found){
					DelRec($position);

					$msg = '$z' . $colors['interact'] . ' '.txtbal('record').' TOP'.$position.' '.txtbal('detruit').' '.txtbal('par un admin');
				
					ChatSendServerMessage($msg);
				}
				else{
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /delrec login';
					ChatSendServerMessageToLogin($msg, $login);
				}
			}
			else{
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					
	       		}					
					
		}elseif($cmd['command'] == "vote"){
			if (!isset($cmd['params'][0])&&($NbVote>0)) {
				
				$msg = '$fff '.$txtl['_'.$PlayerLanguage[$login]]['Note actuelle'].': $0f0'.round($Note, 1).'$fff/20 '.$txtl['_'.$PlayerLanguage[$login]]['en'].' '.$NbVote.' '.$txtl['_'.$PlayerLanguage[$login]]['vote(s)'];
				ChatSendServerMessageToLogin($msg, $login);
			}
          	elseif(isset($cmd['params'][0]) && ctype_digit($cmd['params'][0]) && intval($cmd['params'][0])>=0 && intval($cmd['params'][0])<=20){
				Voter($login, intval($cmd['params'][0]), 1);
			}
			else{
				
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /vote 0-20';
				ChatSendServerMessageToLogin($msg, $login);
	       		}
					
		}elseif($cmd['command'] == "coppers"){
			if (isadmin($login)) {
          			if($sunrise==2){

					if (!$client->query("GetServerCoppers")) {
						Error($client->getErrorMessage(), $client->getErrorCode());
	        		    		
						$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
						ChatSendServerMessageToLogin($msg, $login);
					}	
					else {
						$Coppers = $client->getResponse();
	        		    		
						$msg = '$0f0 coppers: '.$Coppers;
						ChatSendServerMessageToLogin($msg, $login);
					}

				}
				else{
					
					$msg = '$f00 TMU '.$txtl['_'.$PlayerLanguage[$login]]['SEULEMENT'];
					ChatSendServerMessageToLogin($msg, $login);
	       			}					
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					
			}

		}elseif($cmd['command'] == "varlist"){
			if (isadmin($login)) {
				$msg = $st . '$fff'; 
				$i=0;
				foreach ($ModifVar as $varcmd) {
					if ($i==5) {$msg .= "\n\r"; $i=0;}
					$i++;
					$msg .= $varcmd . ', ';
				}
				SendMsgToLogin ($msg, $login);					
			} 
			else {
				$msg = $st . $colors['error'] . $txtl['_'.$PlayerLanguage[$login]]['seulement pour admin']; 
						
				SendMsgToLogin ($msg, $login);					
			}

		}elseif(($cmd['command'] == "pari") || ($cmd['command'] == "bet")){
			if ($Ignore) return;
			if ($account==0) return;	//pas autorisé aux comptes tmn

			if (($sunrise==2) && (!$client->query("GetServerCoppers"))) {
				Error($client->getErrorMessage(), $client->getErrorCode());
	        		
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
				ChatSendServerMessageToLogin($msg, $login);
			}	
			else {
				$Coppers = $client->getResponse();
				if ($Coppers<$copperreserve) {
		        		
					$msg = '$0f0 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC pas assez de coppers dans le serveur'];
					ChatSendServerMessageToLogin($msg, $login);
				}
			}

			$found=false;	
			for ($i=0;$i<$PariCount;$i++) {
				if (($Pari['Login'][$i]==$login) && ($Pari['Payed'][$i]==true)){
		        		
					$msg = '$0f0 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC vous avez deja parie'];
					ChatSendServerMessageToLogin($msg, $login);
					$found=true;
					break;
				}
			}

			$scoremin = $CurrentChallenge['GoldTime'];

			if ($TopBestTime[$maxtop-1]>0) $scoremin = $TopBestTime[$maxtop-1];

			$score=0;
			if (isset($cmd['params'][1])) {
				if ($CurrentGameMode == 4) {
					$score = intval($cmd['params'][1]);
				}
				else {
					if (strlen($cmd['params'][1])==8 && 
						ctype_digit(substr($cmd['params'][1],0,2)) &&
						ctype_digit(substr($cmd['params'][1],3,2)) &&
						ctype_digit(substr($cmd['params'][1],6,2))) {
						$min=intval(substr($cmd['params'][1],0,2));
						$dp=substr($cmd['params'][1],2,1);
						$sec=intval(substr($cmd['params'][1],3,2));
						$pt=substr($cmd['params'][1],5,1);
						$cen=intval(substr($cmd['params'][1],6,2));
						if ($dp==":" && $pt=="." && 
							$min>=0 && $min<=59 &&
							$sec>=0 && $sec<=59 &&
							$cen>=0 && $cen<=99) {
							$score=(($min*60+$sec)*1000)+($cen*10);
						}
					}
				}
			}
			$coppers = 0;
			if (isset($cmd['params'][0])) {
				$coppers = intval($cmd['params'][0]);
			}

			$position=getposition($login);
			$actuelle = $maxtop + 1;
			if ($position) $actuelle = $position;
			$position=getpositionscore($score);
			$visee = $maxtop + 1;
			if ($position) $visee = $position;

          		if(!$found && ($Coppers>=$copperreserve) && ($sunrise==2) && ($CurrentGameMode == 4) &&
				$coppers>=$coppermin && $coppers<=$coppermax &&
				$score>=$scoremin){

				if (!$client->query("SendBill",purgelogin($login),$coppers,'$0f0'.$txtl['_'.$PlayerLanguage[$login]]['PARI sur'].' '.$score.' '.$txtl['_'.$PlayerLanguage[$login]]['rapport'].' '.$visee.'/'.$actuelle,'')) {
					Error($client->getErrorMessage(), $client->getErrorCode());
	        	    		
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
					ChatSendServerMessageToLogin($msg, $login);
				}else{
					$BillId = $client->getResponse();

					$player = array();
    					foreach($PlayerList as $player){
						if ($player['Login']==$login) {
							$msg = purgeNick($player['NickName']);
							$nick = $player['NickName'];
							break;
						}
				    }
					$msg .= '$z$fff '.txtbal('parie').' $0f0'.$coppers.'$fff coppers '.txtbal('sur').' $0f0'.$score.'$fff '.txtbal('rapport').' '.$visee.'/'.$actuelle;
					
					$Bill['BillMsg'][$BillId] = $msg;
					$Bill['BillType'][$BillId] = 'pari';
					$Bill['Login'][$BillId] = purgelogin($login);
					$Bill['ToLogin'][$BillId] = '';
					$Pari['BillId'][$PariCount] = $BillId;
					$Pari['Coppers'][$PariCount] = $coppers;
					$Pari['Score'][$PariCount] = $score;
					$Pari['Login'][$PariCount] = purgelogin($login);
					$Pari['NickName'][$PariCount] = $nick;
					$Pari['Payed'][$PariCount] = false;
					$Pari['Ok'][$PariCount] = false;
					$Pari['Visee'][$PariCount] = $visee;
					$Pari['Actuelle'][$PariCount] = $actuelle;
					$PariCount++;
					SavePari($PariCount);
				}
			}
          	elseif(!$found && ($Coppers>=$copperreserve) && ($sunrise==2) && ($CurrentGameMode !== 4) &&
				$coppers>=$coppermin && $coppers<=$coppermax &&
				$score<=$scoremin && $score>0){

				if (!$client->query("SendBill",purgelogin($login),$coppers,'$0f0'.$txtl['_'.$PlayerLanguage[$login]]['PARI sur'].' '.MwTimeToString($score).' '.$txtl['_'.$PlayerLanguage[$login]]['rapport'].' '.$visee.'/'.$actuelle,'')) {
					Error($client->getErrorMessage(), $client->getErrorCode());
	        	    		
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC'];
					ChatSendServerMessageToLogin($msg, $login);
				}else{
					$BillId = $client->getResponse();

					$player = array();
    					foreach($PlayerList as $player){
						if ($player['Login']==$login) {
							$msg = purgeNick($player['NickName']);
							$nick = $player['NickName'];
							break;
						}
				    }
					$msg .= '$z$fff '.txtbal('parie').' $0f0'.$coppers.'$fff coppers '.txtbal('sur').' $0f0'.MwTimeToString($score).'$fff '.txtbal('rapport').' '.$visee.'/'.$actuelle;
					
					$Bill['BillMsg'][$BillId] = $msg;
					$Bill['BillType'][$BillId] = 'pari';
					$Bill['Login'][$BillId] = purgelogin($login);
					$Bill['ToLogin'][$BillId] = '';
					$Pari['BillId'][$PariCount] = $BillId;
					$Pari['Coppers'][$PariCount] = $coppers;
					$Pari['Score'][$PariCount] = $score;
					$Pari['Login'][$PariCount] = purgelogin($login);
					$Pari['NickName'][$PariCount] = $nick;
					$Pari['Payed'][$PariCount] = false;
					$Pari['Ok'][$PariCount] = false;
					$Pari['Visee'][$PariCount] = $visee;
					$Pari['Actuelle'][$PariCount] = $actuelle;
					$PariCount++;
					SavePari($PariCount);
	       			}
			}
			else{
				if (!$found) {
					
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['SYNTAXE'].': /pari nbcoppers score ('.$coppermin.'<=nbcoppers<='.$coppermax.' score mini '.MwTimeToString($scoremin).')';
					ChatSendServerMessageToLogin($msg, $login);
				}
			}
		}elseif($cmd['command'] == "srank"){
		
			$msg="";
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=27;
			elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=27; 
			else $max=10;
			if (isset($cmd['params'][0]) && intval($cmd['params'][0])>0) {
				$page = intval($cmd['params'][0]);
				if ($page>=ceil(count($RankServer)/$max)) $page=ceil(count($RankServer)/$max)-1;
				$end = $max * ($page+1);
				$begin = $end - $max;
				$moins = $page - 1;
				$plus = $page + 1;
			}
			else {
				$begin = 0;
				$end = $max;
				$moins = 0;
				$plus =  1;
			}
			reset($RankServer);
			//$msg .= "Rank Map\n\r\n\r";
			if (isset($cmd['params'][0]) && intval($cmd['params'][0])>0) {
//				for ($i=0; $i<$end*($cmd['params'][0]-1);$i++) {
				for ($i=0; $i<($end-$max);$i++) {
					next($RankServer);
				}
			}
			for ($i=$begin; $i<=count($RankServer) && $i<$end;$i++) {
				list($key, $val) = each($RankServer);
				if (!$val) break;
				$LastNick=$key;
				GetLastNickName($key,$LastNick);
				if (!isset($RecordLogin[$key])) { $RecordLogin[$key] = 0; }
				$msg .= '$z' . $colors['interact'] . ($i + 1) . '. $z' . purgeNick($LastNick)  . '$z'. $colors['interact'] . ' ( '. $key  . ' )'  . '$z'. $colors['highlight'] . ' ( ' . $val . ' '.$txtl['_'.$PlayerLanguage[$login]]['pts'].' - ' . $RecordLogin[$key] . ' '.$txtl['_'.$PlayerLanguage[$login]]['record'].' )' ."\n\r" ;
			}              
			$LastNick='????';
			$key=purgelogin($login);
			$i=0;
			reset($RankServer);
			foreach ($RankServer as $key => $val){
				$i++;
				if  ($key == purgelogin($login)){ 
					GetLastNickName($key,$LastNick);
					if (!isset($RecordLogin[$key])) { $RecordLogin[$key] = 0; }
					$msg .= "\n\r";
					$msg .= '$z' . $colors['interact'] . $i . '. $z' . purgeNick($LastNick) . '$z'. $colors['highlight'] . ' ( ' . $val . ' '.$txtl['_'.$PlayerLanguage[$login]]['pts'].' - ' . $RecordLogin[$key] . ' '.$txtl['_'.$PlayerLanguage[$login]]['record'].' )' ;
					break;
				}
			}        

//			SendMsgToLogin2 ($msg, $login);
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 0) {
				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='List'>
						<timeout>0</timeout>
						<type>default</type>
						<frame posn='-40 43 0'>
						<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
						<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
						<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(50001+$moins)."' ><![CDATA[<<]]></label>
						<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
						<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(50001+$plus)."' ><![CDATA[>>]]></label>
						</frame>
						</manialink>";
						
				if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
			}
			else if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) {
				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='List'>
						<timeout>0</timeout>
						<type>default</type>
						<frame posn='-40 43 0'>
						<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
						<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
						<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(50001+$moins)."' ><![CDATA[<<]]></label>
						<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
						<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(50001+$plus)."' ><![CDATA[>>]]></label>
						</frame>
						</manialink>";
						
				if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
			}
			else {
				$msg = $st . '$z$fff'.$txtl['_'.$PlayerLanguage[$login]]['utilisez'].' $0f0/srank num_page $fff'.$txtl['_'.$PlayerLanguage[$login]]['pour la suite'];
			
				ChatSendServerMessageToLogin($msg, $login);
			}

/*					
		}elseif($cmd['command']=='srank'){
			$msg="";
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=27; 
			elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=27; 
			else $max=10;
			reset($RankServer);
			//$msg .= "Rank Server\n\r\n\r";
			for ($i=0; $i<=$maxtop && $i<$max;$i++) {
				list($key, $val) = each($RankServer);
				if (!$val) break;
				$LastNick=$key;
				GetLastNickName($key,$LastNick);
				if (!isset($RecordLogin[$key])) { $RecordLogin[$key] = 0; }
				$msg .= '$z' . $colors['interact'] . ($i + 1) . '. $z' . purgeNick($LastNick)  . '$z'. $colors['interact'] . ' ( '. $key  . ' )'  . '$z'. $colors['highlight'] . ' ( ' . $val . ' '.$txtl['_'.$PlayerLanguage[$login]]['pts'].' - ' . $RecordLogin[$key] . ' '.$txtl['_'.$PlayerLanguage[$login]]['record'].' )' ."\n\r" ;
			}      
			$LastNick='????';
			$key=purgelogin($login);
			$i=0;
			reset($RankServer);
			foreach ($RankServer as $key => $val){
				$i++;
				if  ($key == purgelogin($login)){ 
					GetLastNickName($key,$LastNick);
					if (!isset($RecordLogin[$key])) { $RecordLogin[$key] = 0; }
					$msg .= "\n\r";
					$msg .= '$z' . $colors['interact'] . $i . '. $z' . purgeNick($LastNick) . '$z'. $colors['highlight'] . ' ( ' . $val . ' '.$txtl['_'.$PlayerLanguage[$login]]['pts'].' - ' . $RecordLogin[$key] . ' '.$txtl['_'.$PlayerLanguage[$login]]['record'].' )' ;
					break;
				}
			}        

			SendMsgToLogin2 ($msg, $login);
*/			
/*
		}elseif($cmd['command'] == "mrank"){
		
			$msg="";
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=27; 
			elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=27; 
			else $max=10;
			reset($RankMappeur);
			//$msg .= "Rank Mappeur\n\r\n\r";
			$you=0;
			$i=0;
			foreach ($RankMappeur as $key => $val){
				if ($RankMappeur2[$key] !== 1) {
					$i++;
					$LastNick=$key;
					if ($i < $max) { 
						GetLastNickName($key,$LastNick); 
						$msg .= '$z' . $colors['interact'] . $i . '. $z' . purgeNick($LastNick)  . '$z'. $colors['interact'] . ' ( '. $key  . ' )' . '$z'. $colors['highlight'] . ' ( '. round($val, 1) . $colors['interact'] . '/20 '.$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . $RankMappeur2[$key] . ' maps )' ."\n\r" ;
					}
				}
				if  ($key == purgelogin($login)){ 
					GetLastNickName($key,$LastNick);
					$msg2 = '$z' . $colors['interact'] . $i . '. $z' . purgeNick($LastNick) . '$z'. $colors['highlight'] . ' ( '. round($val, 1) . $colors['interact'] . '/20 '.$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . $RankMappeur2[$key] . ' maps )' ."\n\r" ;
					$you=1;
				}
			}      
			if ($you) $msg .= "\n\r" . $msg2;		
			
			SendMsgToLogin2 ($msg, $login);
*/			
		}elseif($cmd['command'] == "mrank"){
		
			$msg="";
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=27; 
			elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=27; 
			else $max=10;
			$NbMappeur = 0;
			foreach ($RankMappeur as $key => $val) {
				if ($RankMappeur2[$key] !== 1) $NbMappeur++;
			}
			if (isset($cmd['params'][0]) && intval($cmd['params'][0])>0) {
				$page = intval($cmd['params'][0]);
				if ($page>=ceil($NbMappeur/$max)) $page=ceil($NbMappeur/$max)-1;
				$end = $max * ($page+1);
				$moins = $page - 1;
				$plus = $page + 1;
			}
			else {
				$begin = 0;
				$end = $max;
				$moins = 0;
				$plus =  1;
			}
			reset($RankMappeur);
			//$msg .= "Rank Mappeur\n\r\n\r";
			$i=0;
			$you=0;
			if (isset($cmd['params'][0]) && intval($cmd['params'][0])>0) {
				for ($j=0; $i<($end-$max) && $j<count($RankMappeur);$j++) {
					list($key, $val) = each($RankMappeur);
					if ($key != '') { 
						if ($RankMappeur2[$key] !== 1) $i++;
						if  ($key == purgelogin($login)){ 
							GetLastNickName($key,$LastNick);
							$msg2 = '$z' . $colors['interact'] . $i . '. $z' . purgeNick($LastNick) . '$z'. $colors['highlight'] . ' ( '. round($val, 1) . $colors['interact'] . '/20 '.$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . $RankMappeur2[$key] . ' maps )' ."\n\r" ;
							$you=1;
						}
					}
				}
				$begin = $j;
			}
			for ($j=$begin; $j<=count($RankMappeur) && $i<$end;$j++) {
				list($key, $val) = each($RankMappeur);
				if ($key != '') { 
					if ($RankMappeur2[$key] !== 1) {
						$i++;
						$LastNick=$key;
						GetLastNickName($key,$LastNick); 
						$msg .= '$z' . $colors['interact'] . $i . '. $z' . purgeNick($LastNick)  . '$z'. $colors['interact'] . ' ( '. $key  . ' )' . '$z'. $colors['highlight'] . ' ( '. round($val, 1) . $colors['interact'] . '/20 '.$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . $RankMappeur2[$key] . ' maps )' ."\n\r" ;
					}
					if  ($key == purgelogin($login)){ 
						GetLastNickName($key,$LastNick);
						$msg2 = '$z' . $colors['interact'] . $i . '. $z' . purgeNick($LastNick) . '$z'. $colors['highlight'] . ' ( '. round($val, 1) . $colors['interact'] . '/20 '.$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . $RankMappeur2[$key] . ' maps )' ."\n\r" ;
						$you=1;
					}
				}
			}              

			if ($you) $msg .= "\n\r" . $msg2;		
			
//			SendMsgToLogin2 ($msg, $login);
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 0) {
				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='List'>
						<timeout>0</timeout>
						<type>default</type>
						<frame posn='-40 43 0'>
						<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
						<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
						<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(40001+$moins)."' ><![CDATA[<<]]></label>
						<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
						<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(40001+$plus)."' ><![CDATA[>>]]></label>
						</frame>
						</manialink>";
						
				if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
			}
			else if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) {
				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='List'>
						<timeout>0</timeout>
						<type>default</type>
						<frame posn='-40 43 0'>
						<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
						<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
						<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(40001+$moins)."' ><![CDATA[<<]]></label>
						<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
						<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(40001+$plus)."' ><![CDATA[>>]]></label>
						</frame>
						</manialink>";
						
				if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
			}
			else {
				$msg = $st . '$z$fff'.$txtl['_'.$PlayerLanguage[$login]]['utilisez'].' $0f0/mrank num_page $fff'.$txtl['_'.$PlayerLanguage[$login]]['pour la suite'];
			
				ChatSendServerMessageToLogin($msg, $login);
			}
			
		}elseif(($cmd['command'] == "moyenne")||($cmd['command'] == "average")){
		
			$msg = $st . $colors['interact'] . $txtl['_'.$PlayerLanguage[$login]]['Note moyenne des maps du serveur'].' : ' . $colors['highlight'] . round($Moyenne, 1) . $colors['interact'] ."/20";
				
			ChatSendServerMessageToLogin($msg, $login);
			
		}elseif($cmd['command'] == "rankmap"){
		
			$msg="";
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) $max=28;
			elseif ($Server_Status['Name']=='Running - Play' && $sunrise == 0) $max=28; 
			else $max=10;
			if (isset($cmd['params'][0]) && intval($cmd['params'][0])>0) {
				$page = intval($cmd['params'][0]);
				if ($page>=ceil(count($RankMap)/$max)) $page=ceil(count($RankMap)/$max)-1;
				$end = $max * ($page+1);
				$begin = $end - $max;
				$moins = $page - 1;
				$plus = $page + 1;
			}
			else {
				$begin = 0;
				$end = $max;
				$moins = 0;
				$plus =  1;
			}
			reset($RankMap);
			//$msg .= "Rank Map\n\r\n\r";
			if (isset($cmd['params'][0]) && intval($cmd['params'][0])>0) {
//				for ($i=0; $i<$end*($cmd['params'][0]-1);$i++) {
				for ($i=0; $i<($end-$max);$i++) {
					next($RankMap);
				}
			}
			for ($i=$begin; $i<=$CurrentGameInfo['NbChallenge'] && $i<$end;$i++) {
				list($key, $val) = each($RankMap);
				$LastName=$key;
				if ($key != '') { 
					GetMapName($key,$LastName); 
					$msg .= '$z' . $colors['interact'] . ($i + 1) . '. $z' . purgeNick($LastName)  . '$z'. $colors['highlight'] . ' ( '. round($val, 1) . $colors['interact'] . '/20 '.$txtl['_'.$PlayerLanguage[$login]]['en'].' ' . $colors['highlight'] . $RankMap2[$key] . ' '.$txtl['_'.$PlayerLanguage[$login]]['vote(s)'].' )' ."\n\r" ;
				} 
				else { $LastName = 'Empty'; $RankMap2[$key] = 0; }
			}              

//			SendMsgToLogin2 ($msg, $login);
			if ($Server_Status['Name']=='Running - Play' && $sunrise == 0) {
				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='List'>
						<timeout>0</timeout>
						<type>default</type>
						<frame posn='-40 43 0'>
						<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
						<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
						<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(30001+$moins)."' ><![CDATA[<<]]></label>
						<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
						<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(30001+$plus)."' ><![CDATA[>>]]></label>
						</frame>
						</manialink>";
						
				if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
			}
			else if ($Server_Status['Name']=='Running - Play' && $sunrise == 2) {
				$xml = "<?xml version='1.0' encoding='utf-8' ?> 
						<manialink id='List'>
						<timeout>0</timeout>
						<type>default</type>
						<frame posn='-40 43 0'>
						<quad  sizen='82 78'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='BgWindow3' />
						<label sizen='80 3'  posn='0 0 0' halign='left' style='TextStaticSmall'><![CDATA[".$msg."]]></label>
						<label sizen='10 3'  posn='5 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(30001+$moins)."' ><![CDATA[<<]]></label>
						<label sizen='60 3'  posn='40 -75 0' halign='center' valign='center' style='TextValueSmall' action='99' >OK</label>
						<label sizen='10 3'  posn='75 -75 0' halign='center' valign='center' style='TextValueSmall' action='".(30001+$plus)."' ><![CDATA[>>]]></label>
						</frame>
						</manialink>";
						
				if (!$client->query("SendDisplayManialinkPageToLogin", $login, $xml, 0, true)) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
			}
			else {
				$msg = $st . '$z$fff'.$txtl['_'.$PlayerLanguage[$login]]['utilisez'].' $0f0/rankmap num_page $fff'.$txtl['_'.$PlayerLanguage[$login]]['pour la suite'];
			
				ChatSendServerMessageToLogin($msg, $login);
			}

		} elseif($plugins->CallChatCommand($cmd,array($login,$nick)) === true){	//DedDerek
			return;
		
		}else {
			
			$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['COMMANDE INCONNUE'].' !';
			ChatSendServerMessageToLogin($msg, $login);
		}
				
		if($cmd['command']){
       			$param = "";
       			$all_params = "";
       			foreach($cmd['params'] as $param){
               			$all_params .= " - ".$param;
       			}
			console("[".purgelogin($login)."] /".$cmd['command'].$all_params);
		}

	}

}

function purgelogin($login) {
  $tmp1=strrchr($login,"/");
  //echo "tmp1=".$tmp1."\n\r";
  $tmp2=str_replace($tmp1,'',$login);
  //echo "tmp2=".$tmp2."\n\r";
  $tmp=stripColors($tmp2,1);
//  echo "purgelogin=".$tmp."\n\r";
  return strtolower($tmp);
}

function playerConnect($Player) {
//string Login, bool IsSpectator
global $client;
global $welcome_msg;
global $annonce;
global $st;
global $colors;
global $messages;
global $CurrentChallenge;
global $record;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $chat;
global $repplayer;
global $sunrise;
global $Server_Status;
//global $ftpplayer;
global $PlayerList;
global $use_ftp;
global $MaxPlayer;
global $RankServer;
global $txt;
global $lang;
global $PlayerLanguage;
global $txtl;
global $codelang;
global $PlayerAccueil;
global $RoundBegan;
global $PlayerScript;
global $PlayerAccount;

	$login = $Player[0];
	$nick = $Player[0];
	$rank = 0;

	echo "Player ".purgelogin($login)." is connected";
	if ($Player[1] == 1) echo " and he is spectator";

	$script = get_script(purgelogin($login));
	if ($script==='') {
		$PlayerScript[$login] = '1';
	}
	else {
		$PlayerScript[$login] = $script;
	}

	$mylang = get_mylang(purgelogin($login));
	if ($mylang==='') {
		$PlayerLanguage[$login] = $lang;
		$PlayerLang = '';
	}
	else {
		$PlayerLanguage[$login] = $mylang;
		$PlayerLang = '';
	}
	if ($sunrise==2) {	//tmu
		if (!$client->query("GetDetailedPlayerInfo", $login)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
		else {
			$player = $client->getResponse();
			$PlayerAccount[$login]=$player['OnlineRights'];
			echo " Account (0=tmn 3=tmu) : ".$PlayerAccount[$login];
			$PlayerLang=$player['Language'];
			echo " Language : ".$PlayerLang."\n\r";
			if ($mylang==='') {
				if (in_array($PlayerLang,$codelang,true)) {
					$PlayerLanguage[$login]=$PlayerLang;
					$mylang=$PlayerLang;
				}
			}
		}
	}
	else if (!$sunrise) {	//tmn
//		if (!$client->query("GetPlayerInfo", $Player[0])) {
//			Error($client->getErrorMessage(), $client->getErrorCode());
//		}	
//		else {
//			$player = $client->getResponse();
//			$nation=$player['Nation'];
//			if ($nation=="FRA") $PlayerLang='fr';
//			else if ($nation=="BEL") $PlayerLang='nl';
//			else if ($nation=="AUS") $PlayerLang='en';
//			else if ($nation=="CZE") $PlayerLang='cz';
//			else if ($nation=="ESP") $PlayerLang='es';
//			else if ($nation=="GBR") $PlayerLang='en';
//			else if ($nation=="GER") $PlayerLang='de';
//			else if ($nation=="IRL") $PlayerLang='en';
//			else if ($nation=="ITA") $PlayerLang='it';
//			else if ($nation=="MEX") $PlayerLang='es';
//			else if ($nation=="NED") $PlayerLang='nl';
//			else if ($nation=="RUS") $PlayerLang='ru';
//			else if ($nation=="NZL") $PlayerLang='en';
//			else if ($nation=="USA") $PlayerLang='en';
//			else if ($nation=="SVK") $PlayerLang='sk';
//			else if ($nation=="UKR") $PlayerLang='ru';
//			else $PlayerLang = $nation;
//			echo " Language : ".$PlayerLang."\n\r";
//			if ($mylang==='') {
//				if (in_array($PlayerLang,$codelang,true)) {
//					$PlayerLanguage[$Player[0]]=$PlayerLang;
//					$mylang=$PlayerLang;
//				}
//			}
//		}
		if (!$client->query("GetDetailedPlayerInfo", $login)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
		else {
			$player = $client->getResponse();
			$PlayerAccount[$login]=$player['OnlineRights'];
			echo " Account (0=tmn 3=tmu) : ".$PlayerAccount[$login];
			$PlayerLang=$player['Language'];
			echo " Language : ".$PlayerLang."\n\r";
			if ($mylang==='') {
				if (in_array($PlayerLang,$codelang,true)) {
					$PlayerLanguage[$login]=$PlayerLang;
					$mylang=$PlayerLang;
				}
			}
		}
	}
	echo "\n\r";
	
	$found=false;

	$msg1 = $st . $welcome_msg."\n\r";
	if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$PlayerList = $client->getResponse();
		foreach ($PlayerList as $player) {
			if ($login==$player['Login']) {
				$nick=$player['NickName'];
//				$login=$player['Login'];
				$rank=$player['LadderRanking'];
				$msg1 = $st . $welcome_msg .' $z'.$nick."\n\r" ;
				$found=true;
				break;
			}
		}
	}

	if (!$found) {
		if (!$client->query("GetPlayerInfo", $login)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
		else {
			$player = $client->getResponse();
			$nick=$player['NickName'];
//			$login=$player['Login'];
			$rank=$player['LadderRanking'];
			$msg1 = $st . $welcome_msg .' $z'.$nick."\n\r" ;
		}
	}
	
	$msg2 = $st . '$f00$s$w' . '/help '.$txtl['_'.$PlayerLanguage[$login]]['pour les commandes'].'!' . "\n\r" . $st . $annonce ."\n\r";

	if($record['Time']){
		$msg = $st . $colors['track_round'] . '$w' . $txtl['_'.$PlayerLanguage[$login]]['record'].' ' . $colors['highlight'] . '$w' . MwTimeToString($record['Time'])  . $colors['track_round'] . ' '. '$w' .$txtl['_'.$PlayerLanguage[$login]]['le'].' ' . $colors['highlight'] . '$w' . $record['Date'] . $colors['track_round'] . "\n\r" . '$w' . $txtl['_'.$PlayerLanguage[$login]]['par'].' ' . $colors['highlight'] . '$w' . $record['Author']  . $st . $colors['track_round'] . '$w' . ' ( ' . $record['Login'] . ' )';
	}else{
		$msg = $st . $colors['track_round'] . '$w' . $txtl['_'.$PlayerLanguage[$login]]['pas de record sur'].' ' . $colors['highlight'] . '$w' . stripColors($CurrentChallenge['Name'],0);
	}
	$msg3 = $msg;

	$position=getposition($login);
	if ($position > 1) {
		$msg4 = $st . $colors['track_round'] . '$w' . $txtl['_'.$PlayerLanguage[$login]]['votre record'].' ' . $colors['highlight'] . '$w' . MwTimeToString($TopBestTime[$position-1])  . $colors['track_round'] . ' '. '$w' .$txtl['_'.$PlayerLanguage[$login]]['le'].' ' . $colors['highlight'] . '$w' . $TopDateRec[$position-1]   . $colors['track_round'] . '$w' . ' TOP' . $colors['highlight'] . '$w' . $position ;
	}
	else $msg4="";

	$srank=0;
	$srankfound=0;
	$msg5 = "";
	reset($RankServer);
	foreach ($RankServer as $key => $val){
		$srank++;
		if  ($key == purgelogin($login)){ 
			$msg5 = "\n\r";
			$msg5 .= $st . $colors['track_round'] . '$w' . $txtl['_'.$PlayerLanguage[$login]]['votre rang serveur est'].' ' . $colors['highlight'] . '$w' . $srank . $colors['track_round'] . '$w' . '/' . count($RankServer). ' '. '$w' .$txtl['_'.$PlayerLanguage[$login]]['avec'].' ' . $colors['highlight'] . '$w' . $val . $colors['track_round'] . ' '. '$w' .$txtl['_'.$PlayerLanguage[$login]]['pts'] ;
			$srankfound=1;
			break;
		}
	}        

	if ($RoundBegan || ($Server_Status['Name']=='Running - Play')){
		$msg = $msg1.$msg2.$msg3."\n\r\n\r".$msg4.$msg5;
		if ( !$sunrise) {	//si nations
//			if (!$client->query("SendHideServerMessageToLogin", $Player[0])) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}
//			if (!$client->query("SendDisplayServerMessageToLogin", $Player[0], $msg,"","",10000)) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}
//			ChatSendServerMessageToLogin($msg3, $Player[0]);
			SendDisplayManialinkAcceuil ($login, $msg, 0);
			SendManiaBottomVote ($login, true);
		}
		else if ($sunrise == 2) {	//si united
			SendDisplayManialinkAcceuil ($login, $msg, 0);
			SendManiaBottomVote ($login, true);
		}
	}
	else {
		
//		ChatSendServerMessageToLogin($msg1.$msg2.$msg3."\n\r".$msg4.$msg5, $Player[0]);
		$msg = $msg1.$msg2."\n\r\n\r".$msg5;
		$PlayerAccueil[$login] = $msg;
	}

	$msg = purgeNick($nick) . '$z ' . $colors['highlight'] ;
	if ($Player[1] == 1) $msg .= txtbal('est spectateur'); else  $msg .= txtbal('a rejoint');
	if ($PlayerLang!='') $msg .= " "  . $colors['record'] . '(' . $colors['highlight'] . $PlayerLang . $colors['record'] . ")";
	if ($srankfound) $msg .= " "  . $colors['record'] . '(SR:' . $colors['highlight'] . $srank . $colors['record'] . ")";
	if (isadmin($login) || isadmin2($login)) $msg .= " "  . $colors['record'] . '(' . $colors['highlight'] . txtbal('admin') . $colors['record'] . ")";
	ChatSendServerMessage($msg);

	save_player($login,$nick,$rank,$mylang,$PlayerScript[$login]);

	AfficheTop($login, true);	
}

function get_mylang($logname) {
global $repplayer;
global $codelang;

	$chunksize = 8192;
	$buffer = '';
	if (!file_exists($repplayer.$logname)) return '';
	$handle = fopen($repplayer.$logname, 'rb');
	if(!$handle) return '';
	$buffer=fread($handle, $chunksize);
	$stat = fclose($handle); 
	if($stat && $buffer ){
		$tmp=strstr($buffer,'<Language>');
		$tmp=str_replace('<Language>','',$tmp);
		$stop=strpos($tmp,'</');
		$tmp=substr($tmp,0,$stop);
		if ($stop>0 && in_array($tmp,$codelang,true)) {
			return $tmp;
		}
		else {
			return '';
		}
	}
	else {
		return '';
	}
}

function get_script($logname) {
global $repplayer;

	$chunksize = 8192;
	$buffer = '';
	if (!file_exists($repplayer.$logname)) return '';
	$handle = fopen($repplayer.$logname, 'rb');
	if(!$handle) return '';
	$buffer=fread($handle, $chunksize);
	$stat = fclose($handle); 
	if($stat && $buffer ){
		$tmp=strstr($buffer,'<Script>');
		$tmp=str_replace('<Script>','',$tmp);
		$stop=strpos($tmp,'</');
		$tmp=substr($tmp,0,$stop);
		if ($stop>0) {
			return $tmp;
		}
		else {
			return '';
		}
	}
	else {
		return '';
	}
}

function save_player($login,$nick,$rank,$language,$script) {
global $repplayer;
global $ftpplayer;
global $use_ftp;

	$handle = fopen($repplayer.purgelogin($login), 'wb');
	if($handle) {
		fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
		fprintf($handle,"\n");
		fprintf($handle,'<PLAYER>');
		fprintf($handle,"\n");

		fprintf($handle,'<NickName>');
		fprintf($handle,"%s",$nick);
		fprintf($handle,'</NickName>');
		fprintf($handle,"\n");

		fprintf($handle,'<Login>');
		fprintf($handle,"%s",purgelogin($login));
		fprintf($handle,'</Login>');
		fprintf($handle,"\n");

		fprintf($handle,'<Ranking>');
		fprintf($handle,"%s",$rank);
		fprintf($handle,'</Ranking>');
		fprintf($handle,"\n");

		fprintf($handle,'<LastDate>');
		fprintf($handle,"%s",Date("Y-m-d H:i:s"));
		fprintf($handle,'</LastDate>');
		fprintf($handle,"\n");

		fprintf($handle,'<Language>');
		fprintf($handle,"%s",$language);
		fprintf($handle,'</Language>');
		fprintf($handle,"\n");

		fprintf($handle,'<Script>');
		fprintf($handle,"%s",$script);
		fprintf($handle,'</Script>');
		fprintf($handle,"\n");

		fprintf($handle,'</PLAYER>');
		fclose($handle);
		if ($use_ftp==1) save_ftp($ftpplayer.purgelogin($login),$repplayer.purgelogin($login), True); 
	}
}

function playerIncoherence($Player) {
//PlayerUid, PlayerLogin
global $client;
global $PlayerList;
global $MaxPlayer;
global $txt;

echo "Player Uid ".purgelogin($Player[0])." login ".$Player[1]." is in Incoherence";
echo "\n\r";

	
	$msg = '$ff0'.txtbal('Le Serveur a detecte que le joueur avec le login').' '.$Player[1].' '.txtbal('est un tricheur');
	ChatSendServerMessage($msg);

	if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$PlayerList = $client->getResponse();
	}
}

function playerDisconnect($Player) {
//string Login
global $client;
global $PlayerList;
global $MaxPlayer;
global $Duel;
global $messages;
global $DuelCount;
global $Bill;
global $txt;
global $PlayerLanguage;
global $txtl;
global $lang;
global $PlayerScript;
global $colors;
global $PlayerAccount;

$login = $Player[0];

echo "Player ".purgelogin($login)." is disconnected";
echo "\n\r";

	$nick=$login;
	if (GetLastNickName($login,$res)) {
		//echo $login." last nick : ".$res."\n\r";
		$nick=$res;
	}
	$msg = purgeNick($nick) . '$z ' . $colors['highlight'] . txtbal('quitte');
	ChatSendServerMessage($msg);

	if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$PlayerList = $client->getResponse();
	}

	for ($i=0;$i<$DuelCount;$i++) {
		if ($Duel['Login'][$i]==purgelogin($login)) {
			
			$msg = '$ff0'.purgeNick($Duel['NickName'][$i]).'$z$ff0 '.txtbal('quitte le duel').' !';
			ChatSendServerMessage($msg);

			$part=intval($Duel['Coppers'][$i])*intval($Duel['Coef'][$i]);

			if ($Duel['Payed'][$i]) {
				if (!isset($PlayerLanguage[$Duel['Login'][$i]])) $PlayerLanguage[$Duel['Login'][$i]]=$lang;

				if (!$client->query("Pay",$Duel['Login'][$i],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Duel['Login'][$i]]]['Duel annule avec'].' '.$Duel['ToNickName'][$i])) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
				else {
					$BillId = $client->getResponse();
					echo "rendu ".$part." coppers a ".$Duel['Login'][$i]." BillId : " . $BillId . "\n\r";
					$msg = purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('recupere ses').' $0f0'.$part.'$fff coppers';
					$Bill['BillMsg'][$BillId] = $msg;
					$Bill['BillType'][$BillId] = 'don';
					$Bill['Login'][$BillId] = '';
					$Bill['ToLogin'][$BillId] = $Duel['Login'][$i];
				}
			}

			for ($j=0;$j<$DuelCount;$j++) {
				if ($Duel['Login'][$j]==$Duel['ToLogin'][$i]) {
					if ($Duel['Payed'][$j]) {
						if (!isset($PlayerLanguage[$Duel['Login'][$j]])) $PlayerLanguage[$Duel['Login'][$j]]=$lang;

						if (!$client->query("Pay",$Duel['Login'][$j],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Duel['Login'][$j]]]['Duel annule avec'].' '.$Duel['ToNickName'][$j])) {
							Error($client->getErrorMessage(), $client->getErrorCode());
						}	
						else {
							$BillId = $client->getResponse();
							echo "rendu ".$part." coppers a ".$Duel['Login'][$j]." BillId : " . $BillId . "\n\r";
							$msg = purgeNick($Duel['NickName'][$j]).' $z$fff'.txtbal('recupere ses').' $0f0'.$part.'$fff coppers';
							$Bill['BillMsg'][$BillId] = $msg;
							$Bill['BillType'][$BillId] = 'don';
							$Bill['Login'][$BillId] = '';
							$Bill['ToLogin'][$BillId] = $Duel['Login'][$j];
						}
					}
					$Duel['Payed'][$j] = false;
					$Duel['Login'][$j] = '';
					$Duel['ToLogin'][$j] = '';
					$Duel['Score'][$j] = 0;
					SaveDuel($j+1);
					break;
				}
			}
			
			// effacement manialink eventuel de l'autre
			$xml = "<manialink posx='1.0' posy='0.22' id='Duel'></manialink>";
			if (@!$client->query("SendDisplayManialinkPageToLogin", $Duel['ToLogin'][$i], $xml, 0, true)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
			}
			
			$Duel['Payed'][$i] = false;
			$Duel['Login'][$i] = '';
			$Duel['ToLogin'][$i] = '';
			$Duel['Score'][$i] = 0;
			SaveDuel($i+1);
			break;
		}
	}
	if (isset($PlayerLanguage[$login])) unset($PlayerLanguage[$login]);
	if (isset($PlayerScript[$login])) unset($PlayerScript[$login]);
	if (isset($PlayerAccount[$login])) unset($PlayerAccount[$login]);

	foreach ($PlayerList as $player) {
		if ($login==$player['Login']) {
			if (!$client->query("Kick",$login)) {
				Error($client->getErrorMessage(), $client->getErrorCode());
			}
			else echo purgelogin($login)." kicked because bug\n\r";
			if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
				Error($client->getErrorMessage(), $client->getErrorCode());
			}else{
				$PlayerList = $client->getResponse();
			}
			break;
		}
	}
}

function statusChanged($Status) {
//int StatusCode, string StatusName
global $Server_Status;
global $Server_OStatus;
global $client;
global $CurrentGameMode;
global $WarmUp;
global $OWarmUp;
global $RoundBegan;
global $PlayerScript;
global $ToSend;
global $PlayerList;

echo "Status ".$Status[0]." ".$Status[1];
echo "\n\r";

/*
if ($Server_OStatus=='Running - Play' && $Status[1]=='Running - Synchronization') {
	$Server_Status['Name'] = 'Running - Play';
	echo "Status force ".$Server_Status['Name'];
	echo "\n\r";
}
else*/
 if ($Server_OStatus=='Launching' && $Status[1]=='Running - Finish') {
	$Server_Status['Name'] = 'Launching';
	echo "Status force ".$Server_Status['Name'];
	echo "\n\r";
}
else $Server_Status['Name'] = $Status[1];

if ($Status[1]=='Running - Synchronization') {
	if (!$client->query("SendHideManialinkPage")) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}
}
        		        
$Server_Status['Code'] = $Status[0];
$Server_OStatus=$Server_Status['Name'];

//if ($CurrentGameMode==5) { //cup
	if (@!$client->query("GetWarmUp")) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else {
		$OWarmUp = $WarmUp;
		$WarmUp = $client->getResponse();
	//	if ($WarmUp) echo "GetWarmUp : 1\n\r"; else echo "GetWarmUp : 0\n\r";
	}
//}
       		        
$RoundBegan = False;
}

function BillUpdated($BillInfo) {
//TrackMania.BillUpdated(int BillId, int State, string StateName, int TransactionId)

global $client;
global $Bill;
global $Pari;
global $PariCount;
global $CurrentGameMode;
global $Inj;
global $InjureCount;
global $PlayerList;
global $Duel;
global $DuelCount;
global $messages;
global $txt;
global $PlayerLanguage;
global $txtl;
global $lang;

	echo "BillId : " . $BillInfo[0] . "\n\r";
	echo "State : " . $BillInfo[1] . "\n\r";
	echo "StateName : " . $BillInfo[2] . "\n\r";
	echo "TransactionId : " . $BillInfo[3] . "\n\r";

	$BillId = $BillInfo[0];

	if ($BillId < 0) return;

	if (isset($Bill['BillType'][$BillId])) {
		if (($BillInfo[1] == 4) && ($Bill['BillType'][$BillId] == 'don')) {
			
			ChatSendServerMessage($Bill['BillMsg'][$BillId]);
			for ($i=0;$i<$InjureCount;$i++) {
				if (($Inj['Login'][$i]!=='') && ($Inj['Login'][$i]==$Bill['Login'][$BillId]) && ($Bill['ToLogin'][$BillId]=='')) {
					foreach ($PlayerList as $Player) {
						if ($Inj['Login'][$i]==purgelogin($Player['Login'])) {
							if(!$client->query("UnIgnore", $Player['Login'])){
								Error($client->getErrorMessage(), $client->getErrorCode());
					   		}
							break;
						}
					}
					
					$msg = '$ff0'.purgeNick($Inj['NickName'][$i]).'$z$ff0 '.txtbal('n est plus ignore');
					ChatSendServerMessage($msg);
					$Inj['Login'][$i]='';
				}
			}
		}
		if (($BillInfo[1] == 4) && ($Bill['BillType'][$BillId] == 'pari')) {
			for ($i=0;$i<$PariCount;$i++) {
				if ($Pari['BillId'][$i]==$BillId) {
					$Pari['Payed'][$i] = true;
					SavePari($i+1);
				}
			}
			
			ChatSendServerMessage($Bill['BillMsg'][$BillId]);
		}
		if (($BillInfo[1] == 4) && ($Bill['BillType'][$BillId] == 'amende')) {
			
			ChatSendServerMessage($Bill['BillMsg'][$BillId]);
			for ($i=0;$i<$InjureCount;$i++) {
				if ($Inj['BillId'][$i]==$BillId) $Inj['Login'][$i]='';
			}
		}
		if (($BillInfo[1] == 5) && ($Bill['BillType'][$BillId] == 'amende')) {
			for ($i=0;$i<$InjureCount;$i++) {
				if ($Inj['BillId'][$i]==$BillId) {
					foreach ($PlayerList as $Player) {
						if ($Inj['Login'][$i]==purgelogin($Player['Login'])) {
							if(!$client->query("Ignore", $Player['Login'])){
								Error($client->getErrorMessage(), $client->getErrorCode());
					   		}
							else {
								if (!isset($PlayerLanguage[$Player['Login']])) $PlayerLanguage[$Player['Login']]=$lang;
								$msg = '$ff0'.purgeNick($Inj['NickName'][$i]).'$z$ff0 '.txtbal('est ignore pour grossierete').' !';
								ChatSendServerMessage($msg);
								SendMsgToLogin ('$0f0'.$txtl['_'.$PlayerLanguage[$Player['Login']]]['utilisez'].' /don 10 '.$txtl['_'.$PlayerLanguage[$Player['Login']]]['pour reactiver le chat'],$Player['Login']);
					   		}
							break;
						}
					}
				}
			}
		}
		if (($BillInfo[1] == 4) && ($Bill['BillType'][$BillId] == 'duel2')) {
			for ($i=0;$i<$DuelCount;$i++) {
				if ($Duel['BillId'][$i]==$BillId) {
					$Duel['Payed'][$i] = true;
					SaveDuel($i+1);
					break;
				}
			}
			
			ChatSendServerMessage($Bill['BillMsg'][$BillId]);
		}
		if (($BillInfo[1] == 5) && ($Bill['BillType'][$BillId] == 'duel')) {
			for ($i=0;$i<$DuelCount;$i++) {
				if ($Duel['BillId'][$i]==$BillId) {
					$Duel['Payed'][$i] = false;
					$Duel['Login'][$i] = '';
					$Duel['ToLogin'][$i] = '';
					$Duel['Score'][$i] = 0;
					SaveDuel($i+1);
					break;
				}
			}
		}
		if (($BillInfo[1] == 4) && ($Bill['BillType'][$BillId] == 'duel')) {
			for ($i=0;$i<$DuelCount;$i++) {
				if ($Duel['BillId'][$i]==$BillId) {
					$Duel['Payed'][$i] = true;
					$nick = $Duel['NickName'][$i];
					$login = $Duel['Login'][$i];
					$coppers = $Duel['Coppers'][$i];
					$tologin = $Duel['ToLogin'][$i];
					$tonick = $Duel['ToNickName'][$i];
					SaveDuel($i+1);
					break;
				}
			}
			
			ChatSendServerMessage($Bill['BillMsg'][$BillId]);
			if (!isset($PlayerLanguage[$tologin])) $PlayerLanguage[$tologin]=$lang;
			$msg = '$z$fff'.$txtl['_'.$PlayerLanguage[$tologin]]['DUEL CONTRE'].'$z$fff '.$nick.'$z$fff '.$txtl['_'.$PlayerLanguage[$tologin]]['avec'].' '.$coppers.' coppers ?';
			if (!SendManiaDuelOk($tologin, $msg)) {
//			if (!$client->query("SendBill",$tologin,$coppers,'$0f0'.$txtl['_'.$PlayerLanguage[$tologin]]['DUEL CONTRE'].' '.$nick,'')) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
        		        
				if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;
				$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC provocation echouee'];
				ChatSendServerMessageToLogin($msg, $login);
				$part=intval($Duel['Coppers'][$i])*intval($Duel['Coef'][$i]);
				if (!isset($PlayerLanguage[$Duel['Login'][$i]])) $PlayerLanguage[$Duel['Login'][$i]]=$lang;
				if (!$client->query("Pay",$Duel['Login'][$i],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Duel['Login'][$i]]]['Duel annule avec'].' '.$Duel['ToNickName'][$i])) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
				else {
					$BillId = $client->getResponse();
					echo "rendu ".$part." coppers a ".$Duel['Login'][$i]." BillId : " . $BillId . "\n\r";
					$msg = purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('recupere ses').' $0f0'.$part.'$fff coppers';
					$Bill['BillMsg'][$BillId] = $msg;
					$Bill['BillType'][$BillId] = 'don';
					$Bill['Login'][$BillId] = '';
					$Bill['ToLogin'][$BillId] = $Duel['Login'][$i];
				}
				$Duel['Payed'][$i] = false;
				$Duel['Login'][$i] = '';
				$Duel['ToLogin'][$i] = '';
				$Duel['Score'][$i] = 0;
				SaveDuel($i+1);
			}
/*			else{
				$BillId = $client->getResponse();

				$msg = '$m'.purgeNick($tonick).'$z$fff '.txtbal('accepte').' '.purgeNick($nick).'$z$fff '.txtbal('en duel pour').' $0f0'.$coppers.'$fff coppers ';

				$Bill['BillMsg'][$BillId] = $msg;
				$Bill['BillType'][$BillId] = 'duel2';
				$Bill['Login'][$BillId] = $tologin;
				$Bill['ToLogin'][$BillId] = $login;
				$Duel['BillId'][$DuelCount] = $BillId;
				$Duel['Score'][$DuelCount] = 0;
				$Duel['Coppers'][$DuelCount] = $coppers;
				$Duel['Login'][$DuelCount] = $tologin;
				$Duel['NickName'][$DuelCount] = $tonick;
				$Duel['ToLogin'][$DuelCount] = $login;
				$Duel['ToNickName'][$DuelCount] = $nick;
				$Duel['Payed'][$DuelCount] = false;
				$Duel['Ok'][$DuelCount] = true;
				$Duel['Coef'][$DuelCount] = 1;
				$DuelCount++;
				SaveDuel($DuelCount);
       			}
*/
		}
		if (($BillInfo[1] == 5) && ($Bill['BillType'][$BillId] == 'duel2')) {
			for ($i=0;$i<$DuelCount;$i++) {
				if ($Duel['BillId'][$i]==$BillId) {
					
					$msg = '$ff0'.purgeNick($Duel['NickName'][$i]).'$z$ff0 '.txtbal('refuse le duel').' !';
					ChatSendServerMessage($msg);

					$part=intval($Duel['Coppers'][$i])*intval($Duel['Coef'][$i]);

					if (!isset($PlayerLanguage[$Duel['ToLogin'][$i]])) $PlayerLanguage[$Duel['ToLogin'][$i]]=$lang;
					if (!$client->query("Pay",$Duel['ToLogin'][$i],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Duel['ToLogin'][$i]]]['Duel annule avec'].' '.$Duel['NickName'][$i])) {
						Error($client->getErrorMessage(), $client->getErrorCode());
					}	
					else {
						$BillId = $client->getResponse();
						echo "rendu ".$part." coppers a ".$Duel['ToLogin'][$i]." BillId : " . $BillId . "\n\r";
						$msg = purgeNick($Duel['ToNickName'][$i]).' $z$fff'.txtbal('recupere ses').' $0f0'.$part.'$fff coppers';
						$Bill['BillMsg'][$BillId] = $msg;
						$Bill['BillType'][$BillId] = 'don';
						$Bill['Login'][$BillId] = '';
						$Bill['ToLogin'][$BillId] = $Duel['ToLogin'][$i];
					}
					for ($j=0;$j<$DuelCount;$j++) {
						if ($Duel['Login'][$j]==$Duel['ToLogin'][$i]) {
							$Duel['Payed'][$j] = false;
							$Duel['Login'][$j] = '';
							$Duel['ToLogin'][$j] = '';
							$Duel['Score'][$j] = 0;
							SaveDuel($j+1);
							break;
						}
					}
					$Duel['Payed'][$i] = false;
					$Duel['Login'][$i] = '';
					$Duel['ToLogin'][$i] = '';
					$Duel['Score'][$i] = 0;
					SaveDuel($i+1);
					break;
				}
			}
		}
	}
	else {
		if ($BillInfo[1] == 4) {
			$Bill['BillType'][$BillId] = 'unknown';
			echo "autre type de bill payee !\n\r";
		}
	}
}


function SaveRec() {
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $CurrentChallenge;
global $reprecord;
global $maxtop;
global $ftprecord;
global $use_ftp;
global $Note;
global $NbVote;
global $norecord;
global $NbLaps;

	if ($norecord) return;

	$fichier = $reprecord.$CurrentChallenge['UId'];
	if ($NbLaps > 1) $fichier .= ".".$NbLaps;
	
	$handle = fopen($fichier, 'wb');
	if($handle) {
		fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
		fprintf($handle,"\n");
		fprintf($handle,'<RECORD>');
		fprintf($handle,"\n");

		fprintf($handle,'<NickName>');
		fprintf($handle,"%s",$NickName);
		fprintf($handle,'</NickName>');
		fprintf($handle,"\n");
		fprintf($handle,'<Login>');
		fprintf($handle,"%s",purgelogin($Login));
		fprintf($handle,'</Login>');
		fprintf($handle,"\n");
		fprintf($handle,'<BestTime>');
		fprintf($handle,"%s",$BestTime);
		fprintf($handle,'</BestTime>');
		fprintf($handle,"\n");
		fprintf($handle,'<DateRec>');
		fprintf($handle,"%s",$DateRec);
		fprintf($handle,'</DateRec>');
		fprintf($handle,"\n");

		for ($i=2; $i<=$maxtop; $i++) {
			fprintf($handle,'<Top'.$i.'NickName>');
			fprintf($handle,"%s",$TopNickName[$i-1]);
			fprintf($handle,'</Top'.$i.'NickName>');
			fprintf($handle,"\n");
			fprintf($handle,'<Top'.$i.'Login>');
			fprintf($handle,"%s",purgelogin($TopLogin[$i-1]));
			fprintf($handle,'</Top'.$i.'Login>');
			fprintf($handle,"\n");
			fprintf($handle,'<Top'.$i.'BestTime>');
			fprintf($handle,"%s",$TopBestTime[$i-1]);
			fprintf($handle,'</Top'.$i.'BestTime>');
			fprintf($handle,"\n");
			fprintf($handle,'<Top'.$i.'DateRec>');
			fprintf($handle,"%s",$TopDateRec[$i-1]);
			fprintf($handle,'</Top'.$i.'DateRec>');
			fprintf($handle,"\n");
		}

		fprintf($handle,'<TrackName>');
		fprintf($handle,"%s",$CurrentChallenge['Name']);
		fprintf($handle,'</TrackName>');
		fprintf($handle,"\n");

		fprintf($handle,'<UId>');
		fprintf($handle,"%s",$CurrentChallenge['UId']);
		fprintf($handle,'</UId>');
		fprintf($handle,"\n");

		fprintf($handle,'<Author>');
		fprintf($handle,"%s",$CurrentChallenge['Author']);
		fprintf($handle,'</Author>');
		fprintf($handle,"\n");

		fprintf($handle,'<Note>');
		fprintf($handle,"%s",$Note);
		fprintf($handle,'</Note>');
		fprintf($handle,"\n");

		fprintf($handle,'<NbVote>');
		fprintf($handle,"%s",$NbVote);
		fprintf($handle,'</NbVote>');
		fprintf($handle,"\n");

		fprintf($handle,'<NbLaps>');
		fprintf($handle,"%s",$NbLaps);
		fprintf($handle,'</NbLaps>');
		fprintf($handle,"\n");

		fprintf($handle,'</RECORD>');
		fclose($handle); 
		$ftpfichier = $ftprecord.$CurrentChallenge['UId'];
		if ($NbLaps > 1) $ftpfichier .= ".".$NbLaps;
		if ($use_ftp==1) save_ftp($ftpfichier,$fichier, True);
	}
}

function DelRec($position) {
global $record;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $maxtop;

	if (($position<1) || ($position>$maxtop)) return;

	for ($j=$position-1;$j<$maxtop-1;$j++) {
		$TopNickName[$j]=$TopNickName[$j+1];
		$TopLogin[$j]=$TopLogin[$j+1];
		$TopBestTime[$j]=$TopBestTime[$j+1];
		$TopDateRec[$j]=$TopDateRec[$j+1];
	}

	$TopNickName[$maxtop-1] = ' ';
	$TopLogin[$maxtop-1] = ' ';
	$TopBestTime[$maxtop-1] = 0;
	$TopDateRec[$maxtop-1] = '?';

	// save record
	$record['Author'] = $TopNickName[0];
	$record['Login'] = $TopLogin[0];
	$record['Time'] = $TopBestTime[0];
	$record['Date'] = $TopDateRec[0];

	$NickName = $TopNickName[0];
	$Login = $TopLogin[0];
	$BestTime = $TopBestTime[0];
	$DateRec = $TopDateRec[0];

	SaveRec();			

	echo "TOP".$position." detruit\n\r";
}


function playerFinish($Player) {
//int PlayerUid, string Login, int TimeOrScore
global $client;
global $st;
global $colors;
global $messages;
global $CurrentChallenge;
global $record;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $maxtop;
global $CurrentGameMode;
global $CurrentGameInfo;
global $cadeau;
global $PlayerList;
global $spscoresTA;
global $spscoresST;
global $txt;
global $auto_savereplay;
global $sunrise;
global $Server_Status;

	if ($Player[0] == 0) return;
	if ($Server_Status['Name']!=='Running - Play') 	return;
	if ($Player[2] == 0) {
		$xml = "<?xml version='1.0' encoding='utf-8' ?><manialink id='List'></manialink>";//effacer la fenetre de commande
		if (!$client->query("SendDisplayManialinkPageToLogin", $Player[1], $xml, 0, false)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
		return;
	}

	$Player1Login = $Player[1];
	$Player1BestTime = $Player[2];
	$Player1Score = $Player[2];
	$Player1DateRec = Date("Y-m-d H:i:s");

	$found=false;
	foreach ($PlayerList as $player) {
		if ($Player1Login==$player['Login']) {
			$Player1NickName=$player['NickName'];
			$found=true;
			break;
		}
	}

	if (!$found) {
		if (!$client->query("GetPlayerInfo", $Player1Login)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
			$Player1NickName = $Player1Login;
		}	
		else {
			$player = $client->getResponse();
			$Player1NickName = $player["NickName"];
			$found=true;
		}
	}

	echo "Player ".purgelogin($Player1Login)." Uid " . $Player[0]." finish : ".MwTimeToString($Player1BestTime)." Nick : ".stripColors($Player1NickName,1);
	echo "\n\r";

	if ($CurrentGameMode == -1) {
		$CurrentGameMode = 1;
		if (!@$client->query('GetCurrentGameInfo')) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else
		{
			$CurrentGameInfo = $client->getResponse();
			$CurrentGameMode = $CurrentGameInfo['GameMode'];
		}
	}

	if ($CurrentGameMode !== 4) {//TimeAttack

		if ($Player1BestTime >0 ){
			foreach ($spscoresTA as $spscore) if (MwTimeToString($Player1BestTime)==$spscore) RecompenseBonus(purgelogin($Player1Login),$Player1NickName,intval($cadeau/3),$Player1BestTime);

			PariValidation (purgelogin($Player1Login), $Player1BestTime);

			DuelValidation (purgelogin($Player1Login), $Player1BestTime);

			SendManiaTOP10 ($Player1Login);
		}

		if(($Player1BestTime < $record['Time'] || $record['Time']==0) && $Player1BestTime >0 ){
			

			for ($i=1; $i<$maxtop; $i++) {
				if ($TopLogin[$i]==purgelogin($Player1Login)) {
					for ($j=$i;$j<$maxtop-1;$j++) {
						$TopNickName[$j]=$TopNickName[$j+1];
						$TopLogin[$j]=$TopLogin[$j+1];
						$TopBestTime[$j]=$TopBestTime[$j+1];
						$TopDateRec[$j]=$TopDateRec[$j+1];
					}
					$TopNickName[$maxtop-1]=' ';
					$TopLogin[$maxtop-1]=' ';
					$TopBestTime[$maxtop-1]=0;
					$TopDateRec[$maxtop-1]='?';
				}
			}
			if ($record['Login'] != purgelogin($Player1Login)) {
				for ($j=$maxtop-2;$j>0;$j--) {
					$TopNickName[$j+1]=$TopNickName[$j];
					$TopLogin[$j+1]=$TopLogin[$j];
					$TopBestTime[$j+1]=$TopBestTime[$j];
					$TopDateRec[$j+1]=$TopDateRec[$j];
				}

				$TopNickName[1]=$record['Author'];
				$TopLogin[1]=$record['Login'];
				$TopBestTime[1]=$record['Time'];
				$TopDateRec[1]=$record['Date'];
			}
			

			// save record
			$record['Author'] = $Player1NickName;
			$record['Login'] = purgelogin($Player1Login);
			$record['Time'] = $Player1BestTime;
			$record['Date'] = $Player1DateRec;

			$NickName = $Player1NickName;
			$Login = purgelogin($Player1Login);
			$BestTime = $Player1BestTime;
			$DateRec = $Player1DateRec;
		
			$TopNickName[0] = $Player1NickName;
			$TopLogin[0] = purgelogin($Player1Login);
			$TopBestTime[0] = $Player1BestTime;
			$TopDateRec[0] = $Player1DateRec;

			console(stripColors($Player1NickName,1)." set up a new record: ".MwTimeToString($Player1BestTime)." the ". $Player1DateRec);
			

			$msg = $st .  $colors['highlight'] . stripColors(purgeNick($Player1NickName),0) . '$z' . $colors['record'] . ' '.txtbal('nouveau record').' (' . $colors['highlight'] . MwTimeToString($Player1BestTime) . $colors['record'].') '.txtbal('sur').' ' . $colors['highlight'] . stripColors(purgeNick($CurrentChallenge["Name"]),0);
			
			ChatSendServerMessage($msg);
			
			SaveRec();
			if ($Player1BestTime < $CurrentChallenge['GoldTime']) Recompense(purgelogin($Player1Login),$Player1NickName,$cadeau);
			
			// save replay
			if ($auto_savereplay && ($sunrise==2)) { // TMU 
				$titre = stripColors($CurrentChallenge['Name'],1)." (".purgelogin($Player1Login)." - ".MwTimeToString($Player1BestTime).")";
				if(!$client->query("SaveCurrentReplay", $titre)){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
			}
			elseif ($auto_savereplay && ($sunrise==0)) { // TMN 
				$titre = stripColors($CurrentChallenge['Name'],1)." (".purgelogin($Player1Login)." - ".MwTimeToString($Player1BestTime).")";
				if(!$client->query("SaveCurrentReplay", $titre)){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
			}
			
			Affiche_tops();
		}
		else {
		$stop=0;
		$find=0;
		$meilleur=0;
		if ($record['Login'] != purgelogin($Player1Login)) {
		for ($k=1;$k<$maxtop && !$stop;$k++){
			if(($Player1BestTime < $TopBestTime[$k] || $TopBestTime[$k]==0) && $Player1BestTime >0 ){
				for ($i=1; $i<$maxtop; $i++) {
					if ($TopLogin[$i]==purgelogin($Player1Login)) {
						$find=1;
						if ( $Player1BestTime < $TopBestTime[$i]) {
							$meilleur=1;
							for ($j=$i;$j<$maxtop-1;$j++) {
								$TopNickName[$j]=$TopNickName[$j+1];
								$TopLogin[$j]=$TopLogin[$j+1];
								$TopBestTime[$j]=$TopBestTime[$j+1];
								$TopDateRec[$j]=$TopDateRec[$j+1];
							}
						}
					}
				}
				if (($find && $meilleur) || !$find ) {
					for ($j=$maxtop-2;$j>=$k;$j--) {
						$TopNickName[$j+1]=$TopNickName[$j];
						$TopLogin[$j+1]=$TopLogin[$j];
						$TopBestTime[$j+1]=$TopBestTime[$j];
						$TopDateRec[$j+1]=$TopDateRec[$j];
					}
					$TopNickName[$k]=$Player1NickName;
					$TopLogin[$k]=purgelogin($Player1Login);
					$TopBestTime[$k]=$Player1BestTime;
					$TopDateRec[$k]=$Player1DateRec;

					$msg = $st . $colors['highlight'] . stripColors(purgeNick($Player1NickName),0) . '$z' . $colors['record'] . ' '.txtbal('prend la place').' '. $colors['highlight'] . ($k+1) . $colors['record'] . ' '.txtbal('avec').' ' . $colors['highlight'] . MwTimeToString($Player1BestTime);
			
					if (($k+1)<=5) ChatSendServerMessage($msg);
					else ChatSendServerMessageToLogin($msg, $Player1Login);

					SaveRec();
			
					AfficheTop($Player1Login, true);

					if (($k<=2)&&($Player1BestTime < $CurrentChallenge['GoldTime'])) Recompense(purgelogin($Player1Login),$Player1NickName,intval(($cadeau/3)*(3-$k)));
				}
				$stop=1;
			}
		}
		}
		}
	}

	if ($CurrentGameMode == 4) {//Stunt

		if ($Player1Score >0 ){
			foreach ($spscoresST as $spscore) if ($Player1Score == $spscore) RecompenseBonus(purgelogin($Player1Login),$Player1NickName,intval($cadeau/3),$Player1Score);

			PariValidation (purgelogin($Player1Login), $Player1Score);

			DuelValidation (purgelogin($Player1Login), $Player1Score);

			SendManiaTOP10 ($Player1Login);
			
//			if ($CurrentChallenge['Name']=='lulucastagnette') {
//				$titre = stripColors($CurrentChallenge['Name'],1)." (".purgelogin($Player1Login)." - ".MwTimeToString($Player1Score).")";
//				if(!$client->query("SaveBestGhostsReplay", $Player1Login, $titre)){
//					Error($client->getErrorMessage(), $client->getErrorCode());
//				}
//			}
		}

		if(($Player1Score > $record['Time'] || $record['Time']==0) && $Player1Score >0 ){
			
			for ($i=1; $i<$maxtop; $i++) {
				if ($TopLogin[$i]==purgelogin($Player1Login)) {
					for ($j=$i;$j<$maxtop-1;$j++) {
						$TopNickName[$j]=$TopNickName[$j+1];
						$TopLogin[$j]=$TopLogin[$j+1];
						$TopBestTime[$j]=$TopBestTime[$j+1];
						$TopDateRec[$j]=$TopDateRec[$j+1];
					}
					$TopNickName[$maxtop-1]=' ';
					$TopLogin[$maxtop-1]=' ';
					$TopBestTime[$maxtop-1]=0;
					$TopDateRec[$maxtop-1]='?';
				}
			}
			if ($record['Login'] != purgelogin($Player1Login)) {
				for ($j=$maxtop-2;$j>0;$j--) {
					$TopNickName[$j+1]=$TopNickName[$j];
					$TopLogin[$j+1]=$TopLogin[$j];
					$TopBestTime[$j+1]=$TopBestTime[$j];
					$TopDateRec[$j+1]=$TopDateRec[$j];
				}

				$TopNickName[1]=$record['Author'];
				$TopLogin[1]=$record['Login'];
				$TopBestTime[1]=$record['Time'];
				$TopDateRec[1]=$record['Date'];
			}
			

			// save record
			$record['Author'] = $Player1NickName;
			$record['Login'] = purgelogin($Player1Login);
			$record['Time'] = $Player1Score;
			$record['Date'] = $Player1DateRec;

			$NickName = $Player1NickName;
			$Login = purgelogin($Player1Login);
			$BestTime = $Player1Score;
			$DateRec = $Player1DateRec;
			
			$TopNickName[0] = $Player1NickName;
			$TopLogin[0] = purgelogin($Player1Login);
			$TopBestTime[0] = $Player1BestTime;
			$TopDateRec[0] = $Player1DateRec;

			console(stripColors($Player1NickName,1)." set up a new record: ".$Player1Score." the ". $Player1DateRec);
			

			$msg = $st .  $colors['highlight'] . stripColors(purgeNick($Player1NickName),0) . '$z' . $colors['record'] . ' '.txtbal('nouveau record').' (' . $colors['highlight'] . MwTimeToString($Player1Score) . $colors['record'].') '.txtbal('sur').' ' . $colors['highlight'] . stripColors(purgeNick($CurrentChallenge["Name"]),0);
			
			ChatSendServerMessage($msg);
			
			SaveRec();
			if ($Player1Score > $CurrentChallenge['GoldTime']) Recompense(purgelogin($Player1Login),$Player1NickName,$cadeau);
			
			// save replay
			if ($auto_savereplay && ($sunrise==2)) { // TMU
				$titre = stripColors($CurrentChallenge['Name'],1)." (".purgelogin($Player1Login)." - ".MwTimeToString($Player1Score).")";
				if(!$client->query("SaveCurrentReplay", $titre)){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
			}
			elseif ($auto_savereplay && ($sunrise==0)) { // TMN
				$titre = stripColors($CurrentChallenge['Name'],1)." (".purgelogin($Player1Login)." - ".MwTimeToString($Player1Score).")";
				if(!$client->query("SaveCurrentReplay", $titre)){
					Error($client->getErrorMessage(), $client->getErrorCode());
				}
			}
			
			Affiche_tops();
		}
		else {
		$stop=0;
		$find=0;
		$meilleur=0;
		if ($record['Login'] != purgelogin($Player1Login)) {
		for ($k=1;$k<$maxtop && !$stop;$k++){
			if(($Player1Score > $TopBestTime[$k] || $TopBestTime[$k]==0) && $Player1Score >0 ){
				for ($i=1; $i<$maxtop; $i++) {
					if ($TopLogin[$i]==purgelogin($Player1Login)) {
						$find=1;
						if ( $Player1Score > $TopBestTime[$i]) {
							$meilleur=1;
							for ($j=$i;$j<$maxtop-1;$j++) {
								$TopNickName[$j]=$TopNickName[$j+1];
								$TopLogin[$j]=$TopLogin[$j+1];
								$TopBestTime[$j]=$TopBestTime[$j+1];
								$TopDateRec[$j]=$TopDateRec[$j+1];
							}
						 } 
					}
				}
				if (($find && $meilleur) || !$find) {
					for ($j=$maxtop-2;$j>=$k;$j--) {
						$TopNickName[$j+1]=$TopNickName[$j];
						$TopLogin[$j+1]=$TopLogin[$j];
						$TopBestTime[$j+1]=$TopBestTime[$j];
						$TopDateRec[$j+1]=$TopDateRec[$j];
					}
					$TopNickName[$k]=$Player1NickName;
					$TopLogin[$k]=purgelogin($Player1Login);
					$TopBestTime[$k]=$Player1Score;
					$TopDateRec[$k]=$Player1DateRec;

					$msg = $st .  $colors['highlight'] . stripColors(purgeNick($Player1NickName),0) . '$z' . $colors['record'] . ' '.txtbal('prend la place').' ' . $colors['highlight'] . ($k+1) . $colors['record'] . ' '. txtbal('avec').' ' . $colors['highlight'] . MwTimeToString($Player1Score);
			
					if (($k+1)<=5) ChatSendServerMessage($msg);
					else ChatSendServerMessageToLogin($msg, $Player1Login);

					SaveRec();

					AfficheTop($Player1Login, true);

					if (($k<=2)&&($Player1Score > $CurrentChallenge['GoldTime'])) Recompense(purgelogin($Player1Login),$Player1NickName,intval(($cadeau/3)*(3-$k)));
				}
				$stop=1;
			}
		}
		}
		}

	}
	
}



function endRace($Datas)
//SPlayerRanking Rankings[], SChallengeInfo Challenge
 {
//SChallengeInfo Challenge
//	struct SChallengeInfo
//	{
//		string Name;
//		string UId;
//		string FileName;
//		string Author;
//		string Environnement;
//		string Mood;
//		int BronzeTime;
//		int SilverTime;
//		int GoldTime;
//		int AuthorTime;
//		int CopperPrice;
//		bool LapRace;
//	}
//	struct SPlayerRanking {
//		string Login;
//		string NickName;
//		int PlayerId
//
//		int Rank;
//		int BestTime;
//		int[] BestCheckpoints;
//		int Score;
//		int NbrLapsFinished;
//		double LadderScore;
global $client;
global $NextChallengeInfo;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $CurrentChallenge;
global $st;
global $colors;
global $record;
global $sunrise;
global $NbVote;
global $messages;
global $NextChallengeType;
global $txt;
global $PlayerList;
global $PlayerLanguage;
global $lang;
global $txtl;
global $CurrentGameMode;
global $WarmUp;
global $OWarmUp;

	$SPlayerRanking=$Datas[0];
	SendManiaPodium ($SPlayerRanking);
	
	$ModeText = getNextChallenge(false);

//	if ($NbVote==0) {
//		$msgvote = '$z$0f0'.$txt['Votez svp'] ;
//	}
//	else 		$msgvote = '' ;

					
	if ($sunrise==2) {
		if ($CurrentGameMode==5) {	//mode cup
			$msg = '$f00$sTOP 5' . "\n\r";
			$msg .= '$z' . $colors['interact'] . '1. ' . $colors['highlight'] . MwTimeToString($record['Time'])  . ' $z'. purgeNick($record['Author']) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '2. ' . $colors['highlight'] . MwTimeToString($TopBestTime[1])  . ' $z'. purgeNick($TopNickName[1]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '3. ' . $colors['highlight'] . MwTimeToString($TopBestTime[2])  . ' $z'. purgeNick($TopNickName[2]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '4. ' . $colors['highlight'] . MwTimeToString($TopBestTime[3])  . ' $z'. purgeNick($TopNickName[3]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '5. ' . $colors['highlight'] . MwTimeToString($TopBestTime[4])  . ' $z'. purgeNick($TopNickName[4]) ;
		}
		else {
			$msg = '$f00$sTOP 20' . "\n\r";
			$msg .= '$z' . $colors['interact'] . '1. ' . $colors['highlight'] . MwTimeToString($record['Time'])  . ' $z'. purgeNick($record['Author']) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '2. ' . $colors['highlight'] . MwTimeToString($TopBestTime[1])  . ' $z'. purgeNick($TopNickName[1]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '3. ' . $colors['highlight'] . MwTimeToString($TopBestTime[2])  . ' $z'. purgeNick($TopNickName[2]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '4. ' . $colors['highlight'] . MwTimeToString($TopBestTime[3])  . ' $z'. purgeNick($TopNickName[3]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '5. ' . $colors['highlight'] . MwTimeToString($TopBestTime[4])  . ' $z'. purgeNick($TopNickName[4]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '6. ' . $colors['highlight'] . MwTimeToString($TopBestTime[5])  . ' $z'. purgeNick($TopNickName[5]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '7. ' . $colors['highlight'] . MwTimeToString($TopBestTime[6])  . ' $z'. purgeNick($TopNickName[6]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '8. ' . $colors['highlight'] . MwTimeToString($TopBestTime[7])  . ' $z'. purgeNick($TopNickName[7]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '9. ' . $colors['highlight'] . MwTimeToString($TopBestTime[8])  . ' $z'. purgeNick($TopNickName[8]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '10.' . $colors['highlight'] . MwTimeToString($TopBestTime[9])  . ' $z'. purgeNick($TopNickName[9]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '11.' . $colors['highlight'] . MwTimeToString($TopBestTime[10])  . ' $z'. purgeNick($TopNickName[10]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '12.' . $colors['highlight'] . MwTimeToString($TopBestTime[11])  . ' $z'. purgeNick($TopNickName[11]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '13.' . $colors['highlight'] . MwTimeToString($TopBestTime[12])  . ' $z'. purgeNick($TopNickName[12]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '14.' . $colors['highlight'] . MwTimeToString($TopBestTime[13])  . ' $z'. purgeNick($TopNickName[13]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '15.' . $colors['highlight'] . MwTimeToString($TopBestTime[14])  . ' $z'. purgeNick($TopNickName[14]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '16.' . $colors['highlight'] . MwTimeToString($TopBestTime[15])  . ' $z'. purgeNick($TopNickName[15]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '17.' . $colors['highlight'] . MwTimeToString($TopBestTime[16])  . ' $z'. purgeNick($TopNickName[16]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '18.' . $colors['highlight'] . MwTimeToString($TopBestTime[17])  . ' $z'. purgeNick($TopNickName[17]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '19.' . $colors['highlight'] . MwTimeToString($TopBestTime[18])  . ' $z'. purgeNick($TopNickName[18]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '20.' . $colors['highlight'] . MwTimeToString($TopBestTime[19])  . ' $z'. purgeNick($TopNickName[19]) ;
		}

		$msgnext  = '$z' . $colors['interact'] . 'Next           '  . $colors['highlight'] . purgeNick($NextChallengeInfo['Name']) . "\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Author        '  . $colors['highlight'] . $NextChallengeInfo['Author'] . "\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Type            '  . $colors['highlight'] . $NextChallengeType . "\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Environ        '  . $colors['highlight'] . $NextChallengeInfo['Environnement']."\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Mood           '  . $colors['highlight'] . $NextChallengeInfo['Mood']."\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'CopperPrice '  . $colors['highlight'] . $NextChallengeInfo['CopperPrice'];

//		SendManiaBottomNext ($msg."\n\r".$msgvote, $msgnext);
		if (!$WarmUp && !$OWarmUp) {
			if ($CurrentGameMode==5) {	//mode cup
				SendManiaTopNext ($msg, $msgnext);
			}
			else SendManiaBottomNext ($msg, $msgnext);
		}

		PariGain();
		DuelGain();
	}
	elseif ($sunrise==0) {
		if ($CurrentGameMode==5) {	//mode cup
			$msg = '$f00$sTOP 5' . "\n\r";
			$msg .= '$z' . $colors['interact'] . '1. ' . $colors['highlight'] . MwTimeToString($record['Time'])  . ' $z'. purgeNick($record['Author']) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '2. ' . $colors['highlight'] . MwTimeToString($TopBestTime[1])  . ' $z'. purgeNick($TopNickName[1]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '3. ' . $colors['highlight'] . MwTimeToString($TopBestTime[2])  . ' $z'. purgeNick($TopNickName[2]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '4. ' . $colors['highlight'] . MwTimeToString($TopBestTime[3])  . ' $z'. purgeNick($TopNickName[3]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '5. ' . $colors['highlight'] . MwTimeToString($TopBestTime[4])  . ' $z'. purgeNick($TopNickName[4]) ;
		}
		else {
			$msg = '$f00$sTOP 20' . "\n\r";
			$msg .= '$z' . $colors['interact'] . '1. ' . $colors['highlight'] . MwTimeToString($record['Time'])  . ' $z'. purgeNick($record['Author']) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '2. ' . $colors['highlight'] . MwTimeToString($TopBestTime[1])  . ' $z'. purgeNick($TopNickName[1]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '3. ' . $colors['highlight'] . MwTimeToString($TopBestTime[2])  . ' $z'. purgeNick($TopNickName[2]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '4. ' . $colors['highlight'] . MwTimeToString($TopBestTime[3])  . ' $z'. purgeNick($TopNickName[3]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '5. ' . $colors['highlight'] . MwTimeToString($TopBestTime[4])  . ' $z'. purgeNick($TopNickName[4]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '6. ' . $colors['highlight'] . MwTimeToString($TopBestTime[5])  . ' $z'. purgeNick($TopNickName[5]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '7. ' . $colors['highlight'] . MwTimeToString($TopBestTime[6])  . ' $z'. purgeNick($TopNickName[6]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '8. ' . $colors['highlight'] . MwTimeToString($TopBestTime[7])  . ' $z'. purgeNick($TopNickName[7]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '9. ' . $colors['highlight'] . MwTimeToString($TopBestTime[8])  . ' $z'. purgeNick($TopNickName[8]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '10.' . $colors['highlight'] . MwTimeToString($TopBestTime[9])  . ' $z'. purgeNick($TopNickName[9]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '11.' . $colors['highlight'] . MwTimeToString($TopBestTime[10])  . ' $z'. purgeNick($TopNickName[10]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '12.' . $colors['highlight'] . MwTimeToString($TopBestTime[11])  . ' $z'. purgeNick($TopNickName[11]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '13.' . $colors['highlight'] . MwTimeToString($TopBestTime[12])  . ' $z'. purgeNick($TopNickName[12]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '14.' . $colors['highlight'] . MwTimeToString($TopBestTime[13])  . ' $z'. purgeNick($TopNickName[13]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '15.' . $colors['highlight'] . MwTimeToString($TopBestTime[14])  . ' $z'. purgeNick($TopNickName[14]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '16.' . $colors['highlight'] . MwTimeToString($TopBestTime[15])  . ' $z'. purgeNick($TopNickName[15]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '17.' . $colors['highlight'] . MwTimeToString($TopBestTime[16])  . ' $z'. purgeNick($TopNickName[16]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '18.' . $colors['highlight'] . MwTimeToString($TopBestTime[17])  . ' $z'. purgeNick($TopNickName[17]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '19.' . $colors['highlight'] . MwTimeToString($TopBestTime[18])  . ' $z'. purgeNick($TopNickName[18]) . '$z'. "\n\r" ;
			$msg .= '$z' . $colors['interact'] . '20.' . $colors['highlight'] . MwTimeToString($TopBestTime[19])  . ' $z'. purgeNick($TopNickName[19]) ;
		}

		$msgnext  = '$z' . $colors['interact'] . 'Next           '  . $colors['highlight'] . purgeNick($NextChallengeInfo['Name']) . "\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Author        '  . $colors['highlight'] . $NextChallengeInfo['Author'] . "\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Type            '  . $colors['highlight'] . $NextChallengeType . "\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Environ        '  . $colors['highlight'] . $NextChallengeInfo['Environnement']."\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'Mood           '  . $colors['highlight'] . $NextChallengeInfo['Mood']."\n\r";
		$msgnext .= '$z' . $colors['interact'] . 'CopperPrice '  . $colors['highlight'] . $NextChallengeInfo['CopperPrice'];

//		SendManiaBottomNext ($msg."\n\r".$msgvote, $msgnext);
		if (!$WarmUp && !$OWarmUp) {
			if ($CurrentGameMode==5) {	//mode cup
				SendManiaTopNext ($msg, $msgnext);
			}
			else SendManiaBottomNext ($msg, $msgnext);
		}
	}
	else {
		$msg  = '$z' . $colors['interact'] . '1. ' . $colors['highlight'] . MwTimeToString($record['Time'])  . ' $z'. purgeNick($record['Author']) . '$z' . $colors['interact'] . ' ( ' . $record['Login'] . ' )'. '$z'."\n\r" ;
		$msg .= '$z' . $colors['interact'] . '2. ' . $colors['highlight'] . MwTimeToString($TopBestTime[1])  . ' $z'. purgeNick($TopNickName[1]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[1] . ') '. '$z'."\n\r" ;
		$msg .= '$z' . $colors['interact'] . '3. ' . $colors['highlight'] . MwTimeToString($TopBestTime[2])  . ' $z'. purgeNick($TopNickName[2]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[2] . ') '. '$z'."\n\r" ;
		$msg .= '$z' . $colors['interact'] . '4. ' . $colors['highlight'] . MwTimeToString($TopBestTime[3])  . ' $z'. purgeNick($TopNickName[3]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[3] . ') '. '$z'."\n\r" ;
		$msg .= '$z' . $colors['interact'] . '5. ' . $colors['highlight'] . MwTimeToString($TopBestTime[4])  . ' $z'. purgeNick($TopNickName[4]) . '$z' . $colors['interact'] . ' ( ' . $TopLogin[4] . ') ';
		foreach ($PlayerList as $Player) {
			$msgnext = '$fffNext'.$ModeText.$NextChallengeInfo['Name']. '$z$fff - ' . $NextChallengeInfo['Author'];
			$msg2 = $msg . "\n\r";
			if ($NbVote==0) {
				if (!isset($PlayerLanguage[$Player['Login']])) $PlayerLanguage[$Player['Login']] = $lang;
				$msgvote = '$z$0f0'.$txtl['_'.$PlayerLanguage[$Player['Login']]]['Votez svp'] ;
			}
			else 		$msgvote = '' ;
			if ($msgvote != '') $msg2 .= $msgvote . "     ";
			$msg2 .= $msgnext;
			addCall("ChatSendServerMessageToLogin",$msg2,$Player['Login']);
//			ChatSendServerMessageToLogin($msg2,$Player['Login']);
		}
		multiquery();
//		if ($sunrise==0) { //nations
//			if (!$client->query("SendHideServerMessage")) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}
//		}
	}

}

function ReadRec() {
global $client;
global $st;
global $colors;
global $messages;
global $CurrentChallenge;
global $record;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $reprecord;
global $maxtop;
global $PlayerList;
global $Note;
global $NbVote;
global $RankServer;
global $max_exec_time;
global $Server_Status;
global $txt;
global $PlayerLanguage;
global $lang;
global $txtl;
global $CurrentGameInfo;
global $first;
global $PlayerScript;
global $ToSend;
global $NbLaps;
global $CurrentGameMode;
global $norecord;

echo "Current Challenge ".stripColors($CurrentChallenge['Name'],1)."\n\r";
echo "              UId ".$CurrentChallenge['UId']."\n\r";
echo "           Author ".$CurrentChallenge['Author']."\n\r";
if ($CurrentChallenge['LapRace']) echo "          LapRace\n\r";

$NbLaps = 1;
if (($CurrentGameMode == 0) || ($CurrentGameMode == 5)) { //round or cups
	if ($CurrentChallenge['LapRace']) {
		echo "RoundsForcedLaps : ".$CurrentGameInfo['RoundsForcedLaps']."\n\r";
		if ($CurrentGameInfo['RoundsForcedLaps'] == 0) {
			$getlaps=getnblaps($CurrentChallenge['FileName']);
			echo "getnblaps : ".$getlaps."\n\r";
			if (intval($getlaps > 0)) $NbLaps = intval($getlaps);
		}
		else {
			$NbLaps = $CurrentGameInfo['RoundsForcedLaps'];
		}
	}
}
elseif ($CurrentGameMode == 3) { //laps
	echo "LapsNbLaps : ".$CurrentGameInfo['LapsNbLaps']."\n\r";
	$NbLaps = $CurrentGameInfo['LapsNbLaps'];
}
echo "NbLaps : ".$NbLaps."\n\r";

$fichier = $reprecord.$CurrentChallenge['UId'];
if ($NbLaps > 1) $fichier .= ".".$NbLaps;
echo "fichier : ".$fichier."\n\r";
	
if(LireFichier($fichier,$result)) {
	//echo "ReadRec : ".$result;
	$tmp=strstr($result,'<NickName>');
	$tmp=str_replace('<NickName>','',$tmp);
	$stop=strpos($tmp,'</');
	if ($stop > 0) $NickName = substr($tmp,0,$stop); else $NickName = ' ';
	$TopNickName[0]=$NickName;
	$tmp=strstr($result,'<Login>');
	$tmp=str_replace('<Login>','',$tmp);
	$stop=strpos($tmp,'</');
	if ($stop > 0) $Login = substr($tmp,0,$stop); else $Login = ' ';
	$TopLogin[0]=$Login;
	$tmp=strstr($result,'<BestTime>');
	$tmp=str_replace('<BestTime>','',$tmp);
	$stop=strpos($tmp,'</');
	if ($stop > 0) $BestTime = substr($tmp,0,$stop); else $BestTime = 0;
	$TopBestTime[0]=$BestTime;
	$tmp=strstr($result,'<DateRec>');
	$tmp=str_replace('<DateRec>','',$tmp);
	$stop=strpos($tmp,'</');
	if ($stop > 0) $DateRec = substr($tmp,0,$stop); else $DateRec = '?';
	$TopDateRec[0]=$DateRec;

	for ($i=2;$i<=$maxtop;$i++) {
		$tmp=strstr($result,'<Top'.$i.'NickName>');
		$tmp=str_replace('<Top'.$i.'NickName>','',$tmp);
		$stop=strpos($tmp,'</');
		if ($stop > 0) $TopNickName[$i-1] = substr($tmp,0,$stop); else $TopNickName[$i-1] = ' ';
		$tmp=strstr($result,'<Top'.$i.'Login>');
		$tmp=str_replace('<Top'.$i.'Login>','',$tmp);
		$stop=strpos($tmp,'</');
		if ($stop > 0) $TopLogin[$i-1] = substr($tmp,0,$stop); else $TopLogin[$i-1] = ' ';
		$tmp=strstr($result,'<Top'.$i.'BestTime>');
		$tmp=str_replace('<Top'.$i.'BestTime>','',$tmp);
		$stop=strpos($tmp,'</');
		if ($stop > 0) $TopBestTime[$i-1] = substr($tmp,0,$stop); else $TopBestTime[$i-1] = 0;
		$tmp=strstr($result,'<Top'.$i.'DateRec>');
		$tmp=str_replace('<Top'.$i.'DateRec>','',$tmp);
		$stop=strpos($tmp,'</');
		if ($stop > 0) $TopDateRec[$i-1] = substr($tmp,0,$stop); else $TopDateRec[$i-1] = '?';
	}

	$tmp=strstr($result,'<Note>');
	$tmp=str_replace('<Note>','',$tmp);
	$stop=strpos($tmp,'</');
	if ($stop > 0) $Note = substr($tmp,0,$stop); else $Note=-1;

	$tmp=strstr($result,'<NbVote>');
	$tmp=str_replace('<NbVote>','',$tmp);
	$stop=strpos($tmp,'</');
	if ($stop > 0) {$NbVote = substr($tmp,0,$stop);} else {$NbVote=0; SaveRec();}

	$Change_Nick = False;

	if (($BestTime==0)||($Login=="")||($NickName=="")) {
		$NickName=' ';
		$Login=' ';
		$BestTime=0;
		$DateRec='?';
	}
	else {
		if (GetLastNickName($Login,$res)) {
			//echo $Login." last nick : ".$res."\n\r";
			if ($NickName !== $res) $Change_Nick = True;
			$NickName=$res;
		}
	}
	

	for ($i=1; $i<$maxtop; $i++) {
		if (($TopBestTime[$i]==0)||($TopLogin[$i]=="")||($TopNickName[$i]=="")) {
	 		$TopNickName[$i]=' ';
	 		$TopLogin[$i]=' ';
		 	$TopBestTime[$i]=0;
		 	$TopDateRec[$i]='?';
		}
		else {
			if (GetLastNickName($TopLogin[$i],$res)) {
				//echo $TopLogin[$i]." last nick : ".$res."\n\r";
				if ($TopNickName[$i] !== $res) $Change_Nick = True;
				$TopNickName[$i]=$res;
			}
		}
	}
	if ($Change_Nick) SaveRec();
}
else {
	$NickName=' ';
	$Login=' ';
	$BestTime=0;
	$DateRec='?';
	$Note=-1;
	$NbVote=0;

	for ($i=0; $i<$maxtop; $i++) {
	 	$TopNickName[$i]=' ';
	 	$TopLogin[$i]=' ';
	 	$TopBestTime[$i]=0;
	 	$TopDateRec[$i]='?';
	}
}

$record['Author'] = $NickName;
$record['Login'] = $Login;
$record['Time'] = $BestTime;
$record['Date'] = $DateRec;

$ToSend = array();

if($record['Time'] != ""){
	$i=0;
	foreach ($PlayerList as $Player) {
		if (!isset($PlayerLanguage[$Player['Login']])) $PlayerLanguage[$Player['Login']] = $lang;	
		if($record['Time'] == 0){
			$msg = $st .  $colors['track_round'] . $txtl['_'.$PlayerLanguage[$Player['Login']]]['pas de record sur'].' ' . $colors['highlight'] . stripColors($CurrentChallenge['Name'],0) . $colors['track_round'] . ' go go...';

			$ToSend[$Player['Login']] = $msg;
//			addCall("ChatSendServerMessageToLogin",$msg,$Player['Login']);
//			ChatSendServerMessageToLogin($msg,$Player['Login']);
				
			if (!$i) {
				console("No record on ".stripColors($CurrentChallenge['Name'],1)." available at the moment!");
				$i=1;
			}
		}else{
			$msg = $st .  $colors['track_round'] . $txtl['_'.$PlayerLanguage[$Player['Login']]]['record'] .' ' . $colors['highlight'] . MwTimeToString($record['Time'])  . $colors['track_round'] . ' '.$txtl['_'.$PlayerLanguage[$Player['Login']]]['le'].' ' . $colors['highlight'] . $record['Date'] . $colors['track_round'] 
				. "\n\r" . $txtl['_'.$PlayerLanguage[$Player['Login']]]['par'] .' ' . $colors['highlight'] . $record['Author']  . $st . $colors['track_round'] . ' ( ' . $record['Login'] . ' )';
				
			$ToSend[$Player['Login']] = $msg;
//			addCall("ChatSendServerMessageToLogin",$msg,$Player['Login']);
//			ChatSendServerMessageToLogin($msg,$Player['Login']);
				
			if (!$i) {
				console("Current record on ".stripColors($CurrentChallenge['Name'],1).": ".MwTimeToString($record['Time'])."\n\r" . "by " . stripColors($record['Author'],1)."-" . $record['Login']."\n\r" . "the " . $record['Date']);
				$i=1;
			}
		}
	}
//	multiquery();

}else{
	$handle=0;
	if (!$norecord)	$handle = fopen($fichier, 'wb');
	if($handle) {
		fprintf($handle,'<?xml version="1.0" encoding="utf-8" ?>');
		fprintf($handle,"\n");
		fprintf($handle,'<RECORD>');
		fprintf($handle,"\n");

		fprintf($handle,'<NickName>');
		fprintf($handle,"%s",$NickName);
		fprintf($handle,'</NickName>');
		fprintf($handle,"\n");
		fprintf($handle,'<Login>');
		fprintf($handle,"%s",$Login);
		fprintf($handle,'</Login>');
		fprintf($handle,"\n");
		fprintf($handle,'<BestTime>');
		fprintf($handle,"%s",$BestTime);
		fprintf($handle,'</BestTime>');
		fprintf($handle,"\n");
		fprintf($handle,'<DateRec>');
		fprintf($handle,"%s",$DateRec);
		fprintf($handle,'</DateRec>');
		fprintf($handle,"\n");

		for ($i=2;$i<=$maxtop;$i++) {
			fprintf($handle,'<Top'.$i.'NickName>');
			fprintf($handle,"%s",$TopNickName[$i-1]);
			fprintf($handle,'</Top'.$i.'NickName>');
			fprintf($handle,"\n");
			fprintf($handle,'<Top'.$i.'Login>');
			fprintf($handle,"%s",$TopLogin[$i-1]);
			fprintf($handle,'</Top'.$i.'Login>');
			fprintf($handle,"\n");
			fprintf($handle,'<Top'.$i.'BestTime>');
			fprintf($handle,"%s",$TopBestTime[$i-1]);
			fprintf($handle,'</Top'.$i.'BestTime>');
			fprintf($handle,"\n");
			fprintf($handle,'<Top'.$i.'DateRec>');
			fprintf($handle,"%s",$TopDateRec[$i-1]);
			fprintf($handle,'</Top'.$i.'DateRec>');
			fprintf($handle,"\n");
		}

		fprintf($handle,'<TrackName>');
		fprintf($handle,"%s",$CurrentChallenge['Name']);
		fprintf($handle,'</TrackName>');
		fprintf($handle,"\n");

		fprintf($handle,'<UId>');
		fprintf($handle,"%s",$CurrentChallenge['UId']);
		fprintf($handle,'</UId>');
		fprintf($handle,"\n");

		fprintf($handle,'<Author>');
		fprintf($handle,"%s",$CurrentChallenge['Author']);
		fprintf($handle,'</Author>');
		fprintf($handle,"\n");

		fprintf($handle,'<Note>');
		fprintf($handle,"%s",$Note);
		fprintf($handle,'</Note>');
		fprintf($handle,"\n");

		fprintf($handle,'<NbVote>');
		fprintf($handle,"%s",$NbVote);
		fprintf($handle,'</NbVote>');
		fprintf($handle,"\n");

		fprintf($handle,'<NbLaps>');
		fprintf($handle,"%s",$NbLaps);
		fprintf($handle,'</NbLaps>');
		fprintf($handle,"\n");

		fprintf($handle,'</RECORD>');
		fclose($handle); 
	}
			
	foreach ($PlayerList as $Player) {
		if (!isset($PlayerLanguage[$Player['Login']])) $PlayerLanguage[$Player['Login']] = $lang;	
		$msg = $st .  $colors['track_round'] . $txtl['_'.$PlayerLanguage[$Player['Login']]]['1ere fois sur'].': ' . $colors['highlight'] . stripColors($CurrentChallenge['Name'],0);
				
		$ToSend[$Player['Login']] = $msg;
//		addCall("ChatSendServerMessageToLogin",$msg,$Player['Login']);
//		ChatSendServerMessageToLogin($msg,$Player['Login']);
	}
//	multiquery();
			
	console("+ created row for map: " . stripColors($CurrentChallenge['Name'],1));
}

$NbChallenge = $CurrentGameInfo['NbChallenge'];
if ($NbChallenge > 0) {
	if (!@$client->query('GetChallengeList',$NbChallenge , 0)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else {
	
		$ChallengeList = $client->getResponse();

		set_time_limit ($max_exec_time);
		$t1=microtime(true);
		server_ranking($ChallengeList);
		echo "time : ".(microtime(true)-$t1)."\n\r";
		set_time_limit ($max_exec_time);
		$t1=microtime(true);
		map_ranking($ChallengeList);
		echo "time : ".(microtime(true)-$t1)."\n\r";
		$t1=microtime(true);
		mappeur_ranking($ChallengeList);
		echo "time : ".(microtime(true)-$t1)."\n\r";
	}
}

foreach ($PlayerList as $Player) {
	$position=getposition($Player['Login']);
	if ($position > 1) {
		if (!isset($PlayerLanguage[$Player['Login']])) $PlayerLanguage[$Player['Login']] = $lang;
		$msg = $st . $colors['track_round'] . $txtl['_'.$PlayerLanguage[$Player['Login']]]['votre record'].' ' . $colors['highlight'] . MwTimeToString($TopBestTime[$position-1])  . $colors['track_round'] . ' '. $txtl['_'.$PlayerLanguage[$Player['Login']]]['le'].' ' . $colors['highlight'] . $TopDateRec[$position-1]   . $colors['track_round'] . ' TOP' . $colors['highlight'] . $position ;
		
		$ToSend[$Player['Login']] .= "\n\r".$msg;
//		addCall("ChatSendServerMessageToLogin",$msg, $Player['Login']);
//		ChatSendServerMessageToLogin($msg, $Player['Login']);
	}

	$i=0;
	reset($RankServer);
	foreach ($RankServer as $key => $val){
		$i++;
		if  ($key == purgelogin($Player['Login'])){ 
			if (!isset($PlayerLanguage[$Player['Login']])) $PlayerLanguage[$Player['Login']] = $lang;
			$msg = $st . $colors['track_round'] . $txtl['_'.$PlayerLanguage[$Player['Login']]]['votre rang serveur est'].' ' . $colors['highlight'] . $i . $colors['track_round'] . '/' . count($RankServer) . ' '. $txtl['_'.$PlayerLanguage[$Player['Login']]]['avec'].' ' . $colors['highlight'] . $val . $colors['track_round'] . ' '. $txtl['_'.$PlayerLanguage[$Player['Login']]]['pts'] ;
			$ToSend[$Player['Login']] .= "\n\r".$msg;
//			addCall("ChatSendServerMessageToLogin",$msg, $Player['Login']);
//			ChatSendServerMessageToLogin($msg, $Player['Login']);
			break;
		}
	}        
	if ($NbVote>0) {
		if (!isset($PlayerLanguage[$Player['Login']])) $PlayerLanguage[$Player['Login']] = $lang;
		$msg = $st .  $colors['track_round'] . $txtl['_'.$PlayerLanguage[$Player['Login']]]['Note actuelle'].': ' . $colors['highlight'] . round($Note, 1)  . $colors['track_round'] . '/20 '. $txtl['_'.$PlayerLanguage[$Player['Login']]]['en'].' ' . $colors['highlight'] . $NbVote .  $colors['track_round'] . ' '. $txtl['_'.$PlayerLanguage[$Player['Login']]]['vote(s)'];
		$ToSend[$Player['Login']] .= "\n\r".$msg;
//		addCall("ChatSendServerMessageToLogin",$msg, $Player['Login']);
//		ChatSendServerMessageToLogin($msg, $Player['Login']);
	}
}

if (!$first) {
	foreach ($PlayerList as $Player) {
		if ($PlayerScript[$Player['Login']] !== '1') {
			addCall("ChatSendServerMessageToLogin",$ToSend[$Player['Login']], $Player['Login']);	
		}
	}
	multiquery();
}
//if ($NbVote>0) {
//	$msg = $st .  $colors['track_round'] . $txt['Note actuelle'].': ' . $colors['highlight'] . round($Note, 1)  . $colors['track_round'] . '/20 '. $txt['en'].' ' . $colors['highlight'] . $NbVote .  $colors['track_round'] . ' vote(s)';
//	ChatSendServerMessage($msg);
//}

$first = false;
}

function AfficheTop($PlayerLogin, $solo) {
global $client;
global $TopBestTime;
global $Note;
global $NbVote;
global $RankServer;
global $record;
global $sunrise;
global $PlayerScript;

if (($sunrise != 0) && ($sunrise != 2)) return;

$position=getposition($PlayerLogin);
if (!$position) {
	$pbest = 'none';
} else {
	$pbest = MwTimeToString($TopBestTime[$position-1]);
}

$i=0;
$srank='none/'.count($RankServer);
reset($RankServer);
foreach ($RankServer as $key => $val){
	$i++;
	if  ($key == purgelogin($PlayerLogin)){ 
		break;
	}
}        
if ($i) $srank=$i.'/'.count($RankServer);

/*$xml = "<?xml version='1.0' encoding='utf-8' ?> 
		<manialink posx='1.0' posy='0.44'> 
		<type>default</type> 
		<format textsize='2'/> 
		<background bgcolor='1114' bgborderx='0.00' bgbordery='0.00'/>
		<line height='.038'>
		<cell width='.06'><text halign='right' textcolor='fff'>Rec :</text></cell>
		<cell width='.12'><text textcolor='fff'> ". MwTimeToString($record['Time']) . "</text></cell></line>
		<line height='.038'>
		<cell width='.06'><text halign='right' textcolor='fff'>PB :</text></cell>
		<cell width='.12'><text textcolor='fff'> ". $pbest . "</text></cell></line>
		<line height='.038'>
		<cell width='.06'><text halign='right' textcolor='fff'>SR :</text></cell>
		<cell width='.12'><text textcolor='fff'> ". $srank . "</text></cell></line>
		</manialink>";
*/

if ($PlayerScript[$PlayerLogin] == '1') {
//fenetre en haut a gauche avec 3 textes : LR(local record) , PR(personal record) et SR(rang serveur)
$xml = "<?xml version='1.0' encoding='utf-8'?>
<manialink id='Best'>
<timeout>0</timeout>
<type>default</type>
  <frame posn='-65.5 45.3 0'>
	<quad  sizen='14.5 9'  posn='-1 1 0' halign='top'  valign='left'   style='Bgs1InRace' substyle='NavButton'  action='96'/>
	<label sizen='12 20'  posn='2 0 0' halign='left' style='TextStaticSmall'>LR : ". MwTimeToString($record['Time']) . "\nPR : ". $pbest . "\nSR : ". $srank . "</label>
</frame>
</manialink>";
//fenetre en haut vers la gauche avec texte Help pour ouvrir une fenetre avec des actions de commandes rapides 
		$xml .= "<manialink posx='0.922' posy='0.75' id='Help'> 
  <type>default</type> 
  <format textsize='1'/> 
  <background bgcolor='0000' bgborderx='0.0' bgbordery='0.0'/> 
  <line>
<cell height='0.02' width='0.08'><text halign='center' action='95' textcolor='0F0F'>Help</text></cell>
</line>
</manialink>";
}
else {
$xml = "<?xml version='1.0' encoding='utf-8'?>
<manialink id='Best'></manialink>
<manialink id='Next'></manialink>
<manialink id='Top10'></manialink>
<manialink id='Help'></manialink>";
}

if ($solo) {
	if (!$client->query("SendDisplayManialinkPageToLogin", $PlayerLogin, $xml, 0, false)) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}
}
else {
	addCall("SendDisplayManialinkPageToLogin", $PlayerLogin, $xml, 0, false);
}

}

function Affiche_tops() {
global $sunrise;
global $PlayerList;

if (($sunrise != 0) && ($sunrise != 2)) return;

foreach ($PlayerList as $Player) {
	AfficheTop($Player['Login'], false);
}
multiquery();
}

function PlayerManialinkPageAnswer($Player) {
//int PlayerUid, string Login, int Answer
global $Server_Status;
global $CurrentGameInfo;
global $now;
global $PlayerLanguage;
global $txtl;
global $VoteNextMap;
global $VoteNextMapName;
global $VoteNext;
global $client;
global $PlayerScript;
global $st;
global $TMGeryVersion;
global $VoteNextMapName;
global $PlayerList;
global $VoteNextOk;
global $VoteNextSeuil;
global $VoteNextMap;
global $VoteNext;
global $VoteNextLogin;
global $maxtop;
global $DuelCount;
global $Duel;
global $Bill;

	$PlayerUid=$Player[0];
	$PlayerLogin=$Player[1];
	$PlayerAnswer=$Player[2];
	
	$player = array();
	$player[0] = $PlayerUid;
	$player[1] = $PlayerLogin;
	$player[3] = true;

	$NbChallenge = $CurrentGameInfo['NbChallenge'];

	if ($PlayerAnswer == 99) ;//AfficheTop($PlayerLogin, true); //click sur ok d une fenetre info
	elseif ($PlayerAnswer == 98) {//click sur TMGery
		if ($PlayerScript[$PlayerLogin] == '1') $PlayerScript[$PlayerLogin] = '0'; else $PlayerScript[$PlayerLogin] = '1';
		if (!$client->query("GetPlayerInfo", $PlayerLogin)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}	
		else {
			$player = $client->getResponse();
			$mylang = get_mylang(purgelogin($PlayerLogin));
			save_player($PlayerLogin,$player['NickName'],$player['LadderRanking'],$mylang,$PlayerScript[$PlayerLogin]);
		}
		AfficheTop($PlayerLogin, true);
		SendManiaBottomVote ($PlayerLogin, true);
		$msg = $st . '$eee' . "Script is: ". base64_decode($TMGeryVersion);
		ChatSendServerMessageToLogin($msg, $PlayerLogin);
	}
	elseif ($PlayerAnswer == 97) {//click sur ok pour changer la map suivante
		$player[2] = '/ok';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 96) {//click sur > dans fenetre LR PR SR
		getrec ($PlayerLogin);
	}
	elseif ($PlayerAnswer == 95) {//click sur Help en haut de l ecran
		afficheAide ($PlayerLogin);
	}
	elseif ($PlayerAnswer == 94) {//click sur oui pour accepter un duel
		for ($i=0;$i<$DuelCount;$i++) {
			if ($Duel['ToLogin'][$i]==purgelogin($PlayerLogin)) {
				$tologin = $Duel['ToLogin'][$i];
				$tonick = $Duel['ToNickName'][$i];
				$login = $Duel['Login'][$i];
				$nick = $Duel['NickName'][$i];
				$coppers = $Duel['Coppers'][$i];

				if (!isset($PlayerLanguage[$tologin])) $PlayerLanguage[$tologin]=$lang;
				if (!$client->query("SendBill",$tologin,$coppers,'$0f0'.$txtl['_'.$PlayerLanguage[$tologin]]['DUEL CONTRE'].' '.$nick,'')) {
					Error($client->getErrorMessage(), $client->getErrorCode());
	        		        
					if (!isset($PlayerLanguage[$login])) $PlayerLanguage[$login]=$lang;
					$msg = '$f00 '.$txtl['_'.$PlayerLanguage[$login]]['ECHEC provocation echouee'];
					ChatSendServerMessageToLogin($msg, $login);
					$part=intval($Duel['Coppers'][$i])*intval($Duel['Coef'][$i]);
					if (!isset($PlayerLanguage[$Duel['Login'][$i]])) $PlayerLanguage[$Duel['Login'][$i]]=$lang;
					if (!$client->query("Pay",$Duel['Login'][$i],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Duel['Login'][$i]]]['Duel annule avec'].' '.$Duel['ToNickName'][$i])) {
						Error($client->getErrorMessage(), $client->getErrorCode());
					}	
					else {
						$BillId = $client->getResponse();
						echo "rendu ".$part." coppers a ".$Duel['Login'][$i]." BillId : " . $BillId . "\n\r";
						$msg = purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('recupere ses').' $0f0'.$part.'$fff coppers';
						$Bill['BillMsg'][$BillId] = $msg;
						$Bill['BillType'][$BillId] = 'don';
						$Bill['Login'][$BillId] = '';
						$Bill['ToLogin'][$BillId] = $Duel['Login'][$i];
					}
					$Duel['Payed'][$i] = false;
					$Duel['Login'][$i] = '';
					$Duel['ToLogin'][$i] = '';
					$Duel['Score'][$i] = 0;
					SaveDuel($i+1);
				}else{
					$BillId = $client->getResponse();
	
					$msg = '$m'.purgeNick($tonick).'$z$fff '.txtbal('accepte').' '.purgeNick($nick).'$z$fff '.txtbal('en duel pour').' $0f0'.$coppers.'$fff coppers ';
	
					$Bill['BillMsg'][$BillId] = $msg;
					$Bill['BillType'][$BillId] = 'duel2';
					$Bill['Login'][$BillId] = $tologin;
					$Bill['ToLogin'][$BillId] = $login;
					$Duel['BillId'][$DuelCount] = $BillId;
					$Duel['Score'][$DuelCount] = 0;
					$Duel['Coppers'][$DuelCount] = $coppers;
					$Duel['Login'][$DuelCount] = $tologin;
					$Duel['NickName'][$DuelCount] = $tonick;
					$Duel['ToLogin'][$DuelCount] = $login;
					$Duel['ToNickName'][$DuelCount] = $nick;
					$Duel['Payed'][$DuelCount] = false;
					$Duel['Ok'][$DuelCount] = true;
					$Duel['Coef'][$DuelCount] = 1;
					$DuelCount++;
					SaveDuel($DuelCount);
	       			}
				break;
			}
		}
	}
	elseif ($PlayerAnswer == 93) {//click sur non pour refuser un duel
		for ($i=0;$i<$DuelCount;$i++) {
			if ($Duel['ToLogin'][$i]==purgelogin($PlayerLogin)) {
			
				$msg = '$ff0'.purgeNick($Duel['ToNickName'][$i]).'$z$ff0 '.txtbal('refuse le duel').' !';
				ChatSendServerMessage($msg);

				$part=intval($Duel['Coppers'][$i])*intval($Duel['Coef'][$i]);

				if ($Duel['Payed'][$i]) {
					if (!isset($PlayerLanguage[$Duel['Login'][$i]])) $PlayerLanguage[$Duel['Login'][$i]]=$lang;

					if (!$client->query("Pay",$Duel['Login'][$i],$part,'$0f0'.$txtl['_'.$PlayerLanguage[$Duel['Login'][$i]]]['Duel annule avec'].' '.$Duel['ToNickName'][$i])) {
						Error($client->getErrorMessage(), $client->getErrorCode());
					}	
					else {
						$BillId = $client->getResponse();
						echo "rendu ".$part." coppers a ".$Duel['Login'][$i]." BillId : " . $BillId . "\n\r";
						$msg = purgeNick($Duel['NickName'][$i]).' $z$fff'.txtbal('recupere ses').' $0f0'.$part.'$fff coppers';
						$Bill['BillMsg'][$BillId] = $msg;
						$Bill['BillType'][$BillId] = 'don';
						$Bill['Login'][$BillId] = '';
						$Bill['ToLogin'][$BillId] = $Duel['Login'][$i];
					}
				}

				$Duel['Payed'][$i] = false;
				$Duel['Login'][$i] = '';
				$Duel['ToLogin'][$i] = '';
				$Duel['Score'][$i] = 0;
				SaveDuel($i+1);
				break;
			}
		}
	}
	elseif ($PlayerAnswer == 60) {//click sur help dans fenetre  aide
		$player[2] = '/help';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 61) {//click sur time dans fenetre  aide
		$player[2] = '/time';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 62) {//click sur list dans fenetre  aide
		$player[2] = '/list';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 63) {//click sur record dans fenetre  aide
		$player[2] = '/record';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 64) {//click sur top dans fenetre  aide
		$player[2] = '/top 1';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 65) {//click sur srank dans fenetre  aide
		$player[2] = '/srank';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 66) {//click sur mrank dans fenetre  aide
		$player[2] = '/mrank';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 67) {//click sur rankmap dans fenetre  aide
		$player[2] = '/rankmap';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 68) {//click sur moyenne dans fenetre  aide
		$player[2] = '/moyenne';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 69) {//click sur playerlist dans fenetre  aide
		$player[2] = '/playerlist';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 70) {//click sur next dans fenetre  aide
		$player[2] = '/next';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 71) {//click sur don 100 dans fenetre  aide
		$player[2] = '/don 100';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 72) {//click sur don 200 dans fenetre  aide
		$player[2] = '/don 200';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 73) {//click sur don 500 dans fenetre  aide
		$player[2] = '/don 500';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 74) {//click sur don 1000 dans fenetre  aide
		$player[2] = '/don 1000';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 75) {//click sur don 2000 dans fenetre  aide
		$player[2] = '/don 2000';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 30) {//click sur gonext dans fenetre  aide
		$player[2] = '/gonext';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 31) {//click sur restart dans fenetre  aide
		$player[2] = '/restart';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 32) {//click sur cancel dans fenetre  aide
		$player[2] = '/cancel';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 33) {//click sur end dans fenetre  aide
		$player[2] = '/end';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 34) {//click sur time attack dans fenetre  aide
		$player[2] = '/ta';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 35) {//click sur round dans fenetre  aide
		$player[2] = '/round';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 36) {//click sur laps dans fenetre  aide
		$player[2] = '/laps';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 37) {//click sur stunts dans fenetre  aide
		$player[2] = '/stunts';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 38) {//click sur team dans fenetre  aide
		$player[2] = '/team';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 39) {//click sur cup dans fenetre  aide
		$player[2] = '/cup';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 40) {//click sur die dans fenetre  aide
		$player[2] = '/die';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 41) {//click sur shutdown dans fenetre  aide
		$player[2] = '/shutdown';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 42) {//click sur varlist dans fenetre  aide
		$player[2] = '/varlist';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 43) {//click sur pub dans fenetre  aide
		$player[2] = '/pub';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 44) {//click sur version dans fenetre  aide
		$player[2] = '/version';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 45) {//click sur coppers dans fenetre  aide
		$player[2] = '/coppers';
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 46) {//click sur ListMatchSettings dans fenetre  aide
		$player[2] = '/ListMatchSettings';
	
		playerChat($player);
	}
	elseif (($PlayerAnswer >= 10000) && ($PlayerAnswer < 20001)) {//click sur << ou >> dans la fenetre /list
		getListChallenge2($PlayerAnswer-10001, $PlayerLogin);
	}
	elseif (($PlayerAnswer >= 20001) && ($PlayerAnswer <= (20001+$maxtop))) {//click sur << ou >> dans la fenetre /top
		$player[2] = '/top '.($PlayerAnswer-20001);
	
		playerChat($player);
	}
	elseif (($PlayerAnswer >= 30001) && ($PlayerAnswer <= 39999)) {//click sur << ou >> dans la fenetre /rankmap
		$player[2] = '/rankmap '.($PlayerAnswer-30001);
	
		playerChat($player);
	}
	elseif (($PlayerAnswer >= 40001) && ($PlayerAnswer <= 49999)) {//click sur << ou >> dans la fenetre /mrank
		$player[2] = '/mrank '.($PlayerAnswer-40001);
	
		playerChat($player);
	}
	elseif (($PlayerAnswer >= 50001) && ($PlayerAnswer <= 59999)) {//click sur << ou >> dans la fenetre /srank
		$player[2] = '/srank '.($PlayerAnswer-50001);
	
		playerChat($player);
	}
	elseif ($PlayerAnswer == 60000) {//click sur vox dans fenetre  aide
		$player[2] = '/vox';
	
		playerChat($player);
	}
	elseif (($PlayerAnswer >= 100) && ($PlayerAnswer <= 100+$NbChallenge-1)) {//click sur une map dans la fenetre /list
		$NextIndex = $PlayerAnswer - 100;
		$smap=0;
		if (!@$client->query('GetChallengeList',1 , $NextIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else {
			$ChallengeList = $client->getResponse();
			$NextChallengeName = $ChallengeList[0]['Name'];
			$smap=1;
		}
		if(!$smap){
			$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['ECHEC'].')';
			ChatSendServerMessageToLogin($msg, $PlayerLogin);
		}
		else {
			$player[2] = '/choosenext ' . stripColors($NextChallengeName, 1);
	
			playerChat($player);
		}
	}
	elseif (($PlayerAnswer >= 100+$NbChallenge) && ($PlayerAnswer <= 100+(2*$NbChallenge)-1)) {//click sur un auteur dans la fenetre /list
		$NextIndex = $PlayerAnswer - 100 - $NbChallenge;
		$smap=0;
		if (!@$client->query('GetChallengeList',1 , $NextIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else {
			$ChallengeList = $client->getResponse();
			$NextChallengeAuthor = $ChallengeList[0]['Author'];
			$smap=1;
		}
		if(!$smap){
			$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['ECHEC'].')';
			ChatSendServerMessageToLogin($msg, $PlayerLogin);
		}
		else {
			$player[2] = '/listlogin ' . $NextChallengeAuthor;
	
			playerChat($player);
		}
	}
	elseif (($PlayerAnswer >= 100+2*$NbChallenge) && ($PlayerAnswer <= 100+(3*$NbChallenge)-1)) {//click sur un environnement dans la fenetre /list
		$NextIndex = $PlayerAnswer - 100 - 2*$NbChallenge;
		$smap=0;
		if (!@$client->query('GetChallengeList',1 , $NextIndex)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else {
			$ChallengeList = $client->getResponse();
			$NextChallengeEnv = $ChallengeList[0]['Environnement'];
			$smap=1;
		}
		if(!$smap){
			$msg = '$f00 ('.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['ECHEC'].')';
			ChatSendServerMessageToLogin($msg, $PlayerLogin);
		}
		else {
			$player[2] = '/list ' . $NextChallengeEnv;
	
			playerChat($player);
		}
	}
	elseif (($Server_Status['Name']=='Running - Play') || ($Server_Status['Name']=='Running - Finish')) {
		if (($PlayerAnswer >= 0) && ($PlayerAnswer <= 20))	{
			$player[2] = '/vote ' . $PlayerAnswer;
	
			playerChat($player);
//			Voter($PlayerLogin, $PlayerAnswer, 1);
		}
	}
}

function beginRace($Challenge) {
//SChallengeInfo Challenge
//	struct SChallengeInfo
//	{
//		string Name;
//		string UId;
//		string FileName;
//		string Author;
//		string Environnement;
//		string Mood;
//		int BronzeTime;
//		int SilverTime;
//		int GoldTime;
//		int AuthorTime;
//		int CopperPrice;
//		bool LapRace;
//	}
global $client;
global $welcome_msg;
global $annonce;
global $st;
global $colors;
global $messages;
global $CurrentChallenge;
global $record;
global $NickName;
global $Login;
global $BestTime;
global $DateRec;
global $TopNickName;
global $TopLogin;
global $TopBestTime;
global $TopDateRec;
global $chat;
global $PlayerList;
global $PariCount;
global $CurrentGameInfo;
global $CurrentGameMode;
global $VoteCount;
global $VoteNext;
global $VoteNextOk;
global $now;
global $MaxPlayer;
global $DuelCount;

/*
	if(!@$client->query("GetMaxPlayers")){
		$MaxPlayer=250;
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$MaxPlayers = $client->getResponse();
		$MaxPlayer = 2*intval($MaxPlayers['CurrentValue']);
		if ($MaxPlayer>250) $MaxPlayer=250;
	}
//	echo "MaxPlayer : ".$MaxPlayer."\n\r>";
*/

	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$CurrentGameMode = $CurrentGameInfo['GameMode'];
	}

	$CurrentChallenge = $Challenge[0];

	ReadRec();

	$PariCount=0;
	SavePari($PariCount);

	$DuelCount=0;
	SaveDuel($DuelCount);

	$VoteCount=0;

	$VoteNext=false;
	$VoteNextOk=0;

//	$now=time();

}

function PlayerCheckpoint($PlayerCheckpoint) {
//int PlayerUid, string Login, int TimeOrScore, int CurLap, int CheckpointIndex

print_r($PlayerCheckpoint);
$PlayerUid=$PlayerCheckpoint[0];
$Login=$PlayerCheckpoint[1];
$MwTime=MwTimeToString($PlayerCheckpoint[2]);
$CurLap=$PlayerCheckpoint[3];
$CheckpointIndex=$PlayerCheckpoint[4];
echo "PlayerCheckpoint PlayerUid $PlayerUid login ".purgelogin($Login)." Time or Score ".$MwTime." CurLap $CurLap CheckpointIndex $CheckpointIndex\n\r";
}

function Voter($PlayerLogin, $PlayerVote, $trace) {
global $VoteCount;
global $Vote;
global $CurrentChallenge;
global $NbVote;
global $Note;
global $txt;
global $PlayerLanguage;
global $lang;
global $txtl;

	$found=false;	
	for ($i=0;$i<$VoteCount;$i++) {
		if ($Vote['Login'][$i]==purgelogin($PlayerLogin)){
 			if (!isset($PlayerLanguage[$PlayerLogin])) $PlayerLanguage[$PlayerLogin] = $lang;
      	        	
			$msg = '$0f0 '.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['ECHEC vous avez deja vote'];
			if ($trace) ChatSendServerMessageToLogin($msg, $PlayerLogin);
			$found=true;
			break;
		}
	}
	if (!$found) {
		if (strtolower($CurrentChallenge['Author'])==purgelogin($PlayerLogin)){
  			if (!isset($PlayerLanguage[$PlayerLogin])) $PlayerLanguage[$PlayerLogin] = $lang;
      	        	
			$msg = '$0f0 '.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['ECHEC vous ne pouvez voter pour vous'].' !';
			if ($trace) ChatSendServerMessageToLogin($msg, $PlayerLogin);
			$found=true;
		}
	}
	if (!$found) {
		if ($NbVote>0) {
			$Note = ($Note*$NbVote + $PlayerVote)/($NbVote+1);
		}
		else $Note = $PlayerVote;
		$NbVote++;
		SaveRec();
		
  		if (!isset($PlayerLanguage[$PlayerLogin])) $PlayerLanguage[$PlayerLogin] = $lang;
					
		$msg = '$fff '.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['Nouvelle note'].': $0f0'.round($Note, 1).'$fff/20 '.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['en'].' '.$NbVote.' '.$txtl['_'.$PlayerLanguage[$PlayerLogin]]['vote(s)'];
		if ($trace) ChatSendServerMessageToLogin($msg, $PlayerLogin);
		$Vote['Login'][$VoteCount]=purgelogin($PlayerLogin);
		$VoteCount++;
		echo purgelogin($PlayerLogin) . " vote $PlayerVote\n\r";
	}

}

function MsgAcceuil () {
global $sunrise;
global $PlayerAccueil;
global $client;

	foreach ($PlayerAccueil as $login=>$msg) {
		if ( !$sunrise) {	//si nations
//			if (!$client->query("SendHideServerMessageToLogin", $login)) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}
//			if (!$client->query("SendDisplayServerMessageToLogin", $login, $msg,"","",10000)) {
//				Error($client->getErrorMessage(), $client->getErrorCode());
//			}
			SendDisplayManialinkAcceuil ($login, $msg, 0);
		}
		else if ($sunrise == 2) {	//si united
			SendDisplayManialinkAcceuil ($login, $msg, 0);
		}				
		unset ($PlayerAccueil[$login]);
	}
}

function PlayerInfoChanged($PlayerInfo) {
//string Login, string NickName, int PlayerId, int TeamId, int SpectatorStatus, int LadderRanking, int Flags

global $PlayerLanguage;
global $PlayerScript;

$Player=$PlayerInfo[0];
if ($Player['LadderRanking'] > 0) {
//	echo $Player['Login']."\n\r";
//	echo $Player['NickName']."\n\r";
//	echo $Player['PlayerId']."\n\r";
//	echo $Player['TeamId']."\n\r";
//	echo $Player['SpectatorStatus']."\n\r";
//	echo $Player['LadderRanking']."\n\r";
//	echo $Player['Flags']."\n\r";

	$mylang = get_mylang(purgelogin($Player['Login']));
//	echo $mylang."\n\r";
//	$script = get_script(purgelogin($Player['Login']));
	save_player($Player['Login'],$Player['NickName'],$Player['LadderRanking'],$mylang,$PlayerScript[$Player['Login']]);
}

//$bar = each($PlayerInfo);
//print_r($bar);
}

function ChallengeListModified($ChallengeInfo) {
//int CurChallengeIndex, int NextChallengeIndex, bool IsListModified

echo "CurChallengeIndex:".$ChallengeInfo[0]."\n\r";
echo "NextChallengeIndex:".$ChallengeInfo[1]."\n\r";
echo "IsListModified:".$ChallengeInfo[2]."\n\r";

//$bar = each($ChallengeInfo);
//print_r($bar);
}


$Server_Status['Name'] = "";

function Error($errstr, $errcode){
global $ServerStop;

	if($errcode != -1000){
		echo("Error: $errstr [$errcode]\n\r");
	}
	if($errcode <= -32000) if ($ServerStop) die(2); else die(0);
}

echo "\n\r".stripColors(base64_decode($TMGeryVersion),1)."\n\r";

if ($maxtop<5) $maxtop=5;

$now=time();

//cree les repertoires necessaires
@!mkdir($reprecord);
@!mkdir($repplayer);
//if ($ftp_ext) {
	@!mkdir($repftptmp);
	@!mkdir($repftptmp.$reprecord);
	@!mkdir($repftptmp.$repplayer);
//}

information ($infos);

//--------------------------------------------------------------
// Connect to server and login
//--------------------------------------------------------------

$ServerStop = true;

if($ip && $port && $login && $password){

	$islogedin = true;
	
	$client = new IXR_Client_Gbx;
	if (!$client->InitWithIp($ip, $port)) {
		echo "\n\rerreur de connexion a ".$ip.":".$port."\n\r";
		Error($client->getErrorMessage(), $client->getErrorCode());
		//$islogedin = false;
		die(2);
	}

	if (!$client->query("Authenticate", $login, $password)) {
		echo "\n\rerreur de connexion avec ".$login.":".$password."\n\r";
		Error($client->getErrorMessage(), $client->getErrorCode());
		//$islogedin = false;
		die(2);
	}	
}
else {
	echo "Mauvaise configuration ip, port, login, password\n\r";
	die(2);
}

//if($islogedin){
	if (!$client->query("GetVersion")) {
		Error($client->getErrorMessage(), $client->getErrorCode());
		// 3=auto 2=tmu 1=sunrise ou original 0=nations
		if ($sunrise == 3) $sunrise = 1; // si pas detecté forcer chat uniquement
	}	
	else {
		$NameVersion = $client->getResponse(); 
		echo "\n\rserver : " . $NameVersion['Name'] . " " . $NameVersion['Version'] ."\n\r";
		if ($sunrise == 3) {
			$sunrise = 1;
			if ($NameVersion['Name'] == 'TmForever') {
				$sunrise = 2;
				echo $NameVersion['Name'] . " detection\n\r";
			}
			if (($NameVersion['Name'] == 'TmUnited.') || ($NameVersion['Name'] == 'TmUnited')) {
				$sunrise = 2;
				echo $NameVersion['Name'] . " detection\n\r";
			}
			if ($NameVersion['Name'] == 'TmSunrise') {
				$sunrise = 1;
				echo $NameVersion['Name'] . " detection\n\r";
			}
			if ($NameVersion['Name'] == 'TmOriginal') {
				$sunrise = 1;
				echo $NameVersion['Name'] . " detection\n\r";
			}
			if ($NameVersion['Name'] == 'TmNationsESWC') {
				$sunrise = 0;
				echo $NameVersion['Name'] . " detection\n\r";
			}
		}
	}
	echo "##############################################\n\r";
	echo "running on $ip : $port \n\r";
	echo "##############################################\n\r";

	//load DedDerek's pluginmanager
	$plugins->initpluginmanager();

	while ($ServerStop) {
		if(!@$client->query("GetStatus")){
			echo "\n\rerreur de connexion a ".$ip.":".$port."\n\r";
			Error($client->getErrorMessage(), $client->getErrorCode());
			die(2);
		}
		$Server_Status = $client->getResponse();
		if ($Server_Status['Name'] != "Waiting") $ServerStop = false;
		sleep(1);
	}
	echo "ca roule";
	echo "\n\r\n\r";
	flush();

if (($sunrise!=0) && ($sunrise!=2)) {
	@$client->query('CleanChatCommand');
	@$client->query('AddChatCommand', 'time');
	@$client->query('AddChatCommand', 'record');
	@$client->query('AddChatCommand', 'rec');
	@$client->query('AddChatCommand', 'bye');
	@$client->query('AddChatCommand', 'hi');
	@$client->query('AddChatCommand', 'lu');
	@$client->query('AddChatCommand', 'lol');
	@$client->query('AddChatCommand', 'help');
	@$client->query('AddChatCommand', 'gg');
	@$client->query('AddChatCommand', 'cu');
	@$client->query('AddChatCommand', 'afk');
	@$client->query('AddChatCommand', 'playerlist');
	@$client->query('AddChatCommand', 'msg');
	@$client->query('AddChatCommand', 'restart');
	@$client->query('AddChatCommand', 'next');
	@$client->query('AddChatCommand', 'list');
	@$client->query('AddChatCommand', 'listlogin');
	@$client->query('AddChatCommand', 'gonext');
	@$client->query('AddChatCommand', 'cancel');
	@$client->query('AddChatCommand', 'end');
	@$client->query('AddChatCommand', 'ta');
	@$client->query('AddChatCommand', 'round');
	@$client->query('AddChatCommand', 'laps');
	@$client->query('AddChatCommand', 'stunts');
	@$client->query('AddChatCommand', 'team');
	@$client->query('AddChatCommand', 'top');
	@$client->query('AddChatCommand', 'top5');
	@$client->query('AddChatCommand', 'Kick');
	@$client->query('AddChatCommand', 'Ban');
	@$client->query('AddChatCommand', 'UnBan');
	@$client->query('AddChatCommand', 'BlackList');
	@$client->query('AddChatCommand', 'UnBlackList');
	@$client->query('AddChatCommand', 'AddGuest');
	@$client->query('AddChatCommand', 'RemoveGuest');
	@$client->query('AddChatCommand', 'choosenext');
	@$client->query('AddChatCommand', 'vote');
	@$client->query('AddChatCommand', 'delrec');
	@$client->query('AddChatCommand', 'ok');
	@$client->query('AddChatCommand', 'varlist');
	@$client->query('AddChatCommand', 'get');
	@$client->query('AddChatCommand', 'set');
	@$client->query('AddChatCommand', 'exchange');
	@$client->query('AddChatCommand', 'srank');
	@$client->query('AddChatCommand', 'mrank');
	@$client->query('AddChatCommand', 'rankmap');
	@$client->query('AddChatCommand', 'moyenne');
	@$client->query('AddChatCommand', 'average');
	@$client->query('AddChatCommand', 'pub');
	@$client->query('AddChatCommand', 'die');
	@$client->query('AddChatCommand', 'lang');
	@$client->query('AddChatCommand', 'shutdown');
	@$client->query('AddChatCommand', 'mylang');
	@$client->query('AddChatCommand', 'delmap');
}
	//------------------------------------------
	// Read pieces of information
	//------------------------------------------
	
	if (!@$client->query('GetTracksDirectory')) {
		Error($client->getErrorMessage(), $client->getErrorCode());
		$TracksDirectory = "";
	}
	else $TracksDirectory = $client->getResponse();

/*
	if(!@$client->query("GetMaxPlayers")){
		$MaxPlayer=250;
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$MaxPlayers = $client->getResponse();
		$MaxPlayer = 2*intval($MaxPlayers['CurrentValue']);
		if ($MaxPlayer>250) $MaxPlayer=250;
	}
//	echo "MaxPlayer : ".$MaxPlayer."\n\r>";
*/

	if(!@$client->query("GetPlayerList", $MaxPlayer, 0)){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$PlayerList = $client->getResponse();
		foreach ($PlayerList as $Player) {
			$script = get_script(purgelogin($Player['Login']));
			if ($script==='') {
				$PlayerScript[$Player['Login']] = '1';
			}
			else {
				$PlayerScript[$Player['Login']] = $script;
			}
			$mylang = get_mylang(purgelogin($Player['Login']));
			if ($mylang==='') {
				$PlayerLanguage[$Player['Login']] = $lang;
			}
			else {
				$PlayerLanguage[$Player['Login']] = $mylang;
			}
			if ($sunrise==2) {	//tmu
				if (!$client->query("GetDetailedPlayerInfo", $Player['Login'])) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
				else {
					$PlayerInfo = $client->getResponse();
					$PlayerAccount[$Player['Login']]=$PlayerInfo['OnlineRights'];
					if ($mylang==='') {
						if (in_array($PlayerInfo['Language'],$codelang,true)) $PlayerLanguage[$Player['Login']]=$PlayerInfo['Language'];
					}
				}
			}
			if ($sunrise==0) {	//tmn
				if (!$client->query("GetDetailedPlayerInfo", $Player['Login'])) {
					Error($client->getErrorMessage(), $client->getErrorCode());
				}	
				else {
					$PlayerInfo = $client->getResponse();
					$PlayerAccount[$Player['Login']]=$PlayerInfo['OnlineRights'];
					if ($mylang==='') {
						if (in_array($PlayerInfo['Language'],$codelang,true)) $PlayerLanguage[$Player['Login']]=$PlayerInfo['Language'];
					}
				}
			}
		}
	}

	if ($sunrise==2) {	//tmu
		if(!@$client->query("GetIgnoreList", $MaxPlayer, 0)){
			Error($client->getErrorMessage(), $client->getErrorCode());
		}else{
			$IgnoreList = $client->getResponse();
			foreach ($IgnoreList as $player) {
				$Inj['Login'][$InjureCount]=purgelogin($player['Login']);
				$Inj['BillId'][$InjureCount] = -1;
				foreach ($PlayerList as $player2) {
					if (purgelogin($player2['Login'])==$Inj['Login'][$InjureCount]) $Inj['NickName'][$InjureCount] = $player2['NickName'];
				}
				$InjureCount++;
			}
		}
	}

	$ModeText = getNextChallenge(true);

	if(!@$client->query("GetCurrentChallengeInfo")){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}else{
		$CurrentChallenge = $client->getResponse();
	}

	if (!@$client->query('GetCurrentGameInfo')) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	else
	{
		$CurrentGameInfo = $client->getResponse();
		$CurrentGameMode = $CurrentGameInfo['GameMode'];
	}

//	if ($CurrentGameMode==5) { //cup
		if (@!$client->query("GetWarmUp")) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}
		else {
			$WarmUp = $client->getResponse();
			if (!$WarmUp) $OWarmUp = False; else  $OWarmUp = True;
		}
//	}

	if ($RoundCustomPoints && ($CurrentGameMode==0)) { // mode round et points personnalises
		if (@!$client->query("SetRoundCustomPoints", $CustomPoints)) {
			Error($client->getErrorMessage(), $client->getErrorCode());
		}
	}
	
	ReadRec();

	ReadPari();

	ReadDuel();

//////////////////////
	if(!@$client->query("GetStatus")){
		Error($client->getErrorMessage(), $client->getErrorCode());
	}
	$Verify_Status = $client->getResponse();
	if ($Server_Status['Name'] != $Verify_Status['Name']) {
		echo "restart pour eviter incoherence\n\r";
		die(0);											//restart TMGery si le status serveur change pendant les initialisations
	}
	if ($Server_Status['Name'] == 'Running - Play') {	//reaffiche LR PB SR et les votes si status play
		Affiche_tops();
		SendManiaBottomVote('',false);
	}
//////////////////////

	echo "callbacks:\n\r>";
	if (!$client->query('EnableCallbacks', false)) {
		   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	flush();
	if (!$client->query('EnableCallbacks', true)) {
	   Error($client->getErrorMessage(), $client->getErrorCode());
	}
	flush();
//}

$start_time=0;
$start_pub=0;

$plugins->CallEvent('onStartup','');	//DedDerek


//while($Server_Status['Name'] != "stopped" && $islogedin){
while(true){

	$client->readCB(1*1000*1000);
	if ($client->IsError()) {
		Error($client->getErrorMessage(), $client->getErrorCode());
	}

	$plugins->CallEvent('onMainLoop','');	//DedDerek

	$calls = $client->getCBResponses();
//	if (!empty($calls)) {
		foreach ($calls as $call) {
//		while ($call = array_shift($calls)) {
//			echo $call[0]."\n\r";


		        switch ($call[0]) {
          
		        case "TrackMania.PlayerConnect":
		          playerConnect($call[1]);
				  $plugins->CallEvent('PlayerConnect',$call[1]);	//DedDerek
		          break;
				  
		        case "TrackMania.PlayerDisconnect":
		          playerDisconnect($call[1]);
				  $plugins->CallEvent('PlayerDisconnect',$call[1]);	//DedDerek
		          break;
		          
		        case "TrackMania.StatusChanged":
		          statusChanged($call[1]);
				  $plugins->CallEvent('StatusChanged',$call[1]);	//DedDerek
		          break;
		          
		        case "TrackMania.PlayerFinish":
		          playerFinish($call[1]);
  				  $plugins->CallEvent('PlayerFinish',$call[1]);		//DedDerek
		          break;
		          
		        case "TrackMania.BeginRace":
		          beginRace($call[1]);
  				  $plugins->CallEvent('BeginRace',$call[1]);	//DedDerek
		          break;
		          
		        case "TrackMania.BeginRound":
					echo "BeginRound\n\r";
					$RoundBegan = True;
					Affiche_tops();
					AfficheRec();
					MsgAcceuil();
					SendManiaBottomVote('',false);
					$plugins->CallEvent('BeginRound',$call[1]);		//DedDerek
					$now=time();
		          break;
		          
		        case "TrackMania.ServerStart":
		          echo "ServerStart\n\r";
				  $ServerStop = false;
		          break;

		        case "TrackMania.ServerStop":
		          echo "ServerStop\n\r";
				  $ServerStop = true;
		          break;

		        case "TrackMania.PlayerChat":
		          playerChat($call[1]);
				  $plugins->CallEvent('PlayerChat',$call[1]);	//DedDerek
		          break;

		        case "TrackMania.EndRace":
		          endRace($call[1]);
				  $plugins->CallEvent('EndRace',$call[1]);	//DedDerek
		          break;
		          
		        case "TrackMania.BillUpdated":
		          BillUpdated($call[1]);
				  $plugins->CallEvent('BillUpdated',$call[1]);	//DedDerek+gery
		          break;
 
		        case "TrackMania.PlayerIncoherence":
		          playerIncoherence($call[1]);
		          break;

		        case "TrackMania.PlayerManialinkPageAnswer":
		          PlayerManialinkPageAnswer($call[1]);
				  $plugins->CallEvent('PlayerManialinkPageAnswer',$call[1]);	//DedDerek
		          break;

				case "TrackMania.PlayerCheckpoint":
//				  PlayerCheckpoint($call[1]); 
				  $plugins->CallEvent('PlayerCheckpoint',$call[1]);	//DedDerek
				  break;
				  
		        case "TrackMania.PlayerInfoChanged":
					$plugins->CallEvent('PlayerInfoChanged',$call[1]);	//DedDerek
		         	PlayerInfoChanged ($call[1]);
		          break;

		        case "TrackMania.ChallengeListModified":
//		         	ChallengeListModified ($call[1]);
		          break;

		        default:
		          // do nothing ...
		        }
		
	
	
		}		
//	}
	flush();
if (!$ServerStop) {
	$end_time = time();
	if (($end_time-$start_time) >= $ftp_t_status) {
		$start_time=$end_time;
		if ($Server_Status['Name']=='Running - Play') Etat_Serveur();
	}
	if ( ($pub) || ((($end_time-$start_pub) >= 60)&&(time()-$now) >= 30) ) {
		$start_pub=$end_time;
		$tirage=rand(0,$wgfreq);
		if (($pub||($tirage!==1)) && ($Server_Status['Name']=='Running - Play')){
			$tirage = rand(0,(count($infos)/2)-1);
			if (($sunrise==2) && (($CurrentGameMode!=5) || ($WarmUp && $CurrentGameMode==5))) {	//si united pub+info
				$msg='$0f0$s/help$fff ' . txtbal('pour les commandes') . '.' . "\n\r".$infos[$tirage*2+1]. "\n\r" . $pubtext;
				if (time() < ($now+($CurrentGameInfo['TimeAttackLimit']/1000)-20)) {
					SendDisplayManiaLinkInfo($msg, 10000);
				}
/*
				foreach ($PlayerList as $Player) {
					for ($i=0;$i<2;$i++) {
//						addCall("SendNoticeToLogin", $Player['Login'], translate($msg,$PlayerLanguage[$Player['Login']]), $avatar);
//						if(!$client->query("SendNoticeToLogin", $Player['Login'], translate($msg,$PlayerLanguage[$Player['Login']]), $avatar)){
//							Error($client->getErrorMessage(), $client->getErrorCode());
//						}
					}
//					usleep(1);
				}
				multiquery();
*/
			}
			elseif (($sunrise==0) && (($CurrentGameMode!=5) || ($WarmUp && $CurrentGameMode==5))) {	//si nations pub+info
				if ($infos[$tirage*2]=='0') {
					$msg='$0f0$s/help$fff ' . txtbal('pour les commandes') . '.' . "\n\r" . $pubtext."\n\r".$infos[$tirage*2+1];
				}
				else {
					$msg='$0f0$s/help$fff ' . txtbal('pour les commandes') . '.' . "\n\r" . $pubtext;
				}
				if (time() < ($now+($CurrentGameInfo['TimeAttackLimit']/1000)-20)) {
					SendDisplayManiaLinkInfo($msg, 10000);
				}
/*
				foreach ($PlayerList as $Player) {
					for ($i=0;$i<2;$i++) {
						addCall("SendNoticeToLogin", $Player['Login'], translate($msg,$PlayerLanguage[$Player['Login']]), $avatar);
//						if(!$client->query("SendNoticeToLogin", $Player['Login'], translate($msg,$PlayerLanguage[$Player['Login']]), $avatar)){
//							Error($client->getErrorMessage(), $client->getErrorCode());
//						}
					}
//					usleep(1);
				}
				multiquery();
*/
			}
			else {			//si pas info seulement
				if ($infos[$tirage*2]=='0') {
					$msg=$infos[$tirage*2+1];
					ChatSendServerMessage($msg);
				}
			}
			echo("envoi info\n\r");
		}
		else if ($tirage==1 && count($PlayerList)>=$wgplayer && $Server_Status['Name']=='Running - Play' && $sunrise == 2) {
			$wgprice=rand($wgminprice,$wgmaxprice);
			$Coppers=0;
			if (!$client->query("GetServerCoppers")) {
				Error($client->getErrorMessage(), $client->getErrorCode());
			}	
			else {
				$Coppers = $client->getResponse();
				echo "Coppers restants: " . $Coppers . "\n\r";
			}
			if ($Coppers > ($copperreserve + $wgprice)) {
				$wg=true;
				$wgtime = time();
				$wgindex = rand(0,count($wgmot)-1);
				foreach ($PlayerList as $Player) {
//					addCall("SendNoticeToLogin", $Player['Login'], '$w$0f0'.$txtl['_'.$PlayerLanguage[$Player['Login']]]['JEU DU MOT'], $avatar);
//					if(!$client->query("SendNoticeToLogin", $Player['Login'], '$w$0f0'.$txtl['_'.$PlayerLanguage[$Player['Login']]]['JEU DU MOT'], $avatar)){
//						Error($client->getErrorMessage(), $client->getErrorCode());
//					}
					$msg = $messages['pref'].  '$z$0f0/'.$wgmot[$wgindex].' $fff'.$txtl['_'.$PlayerLanguage[$Player['Login']]]['pour gagner'].' $0f0'.$wgprice.'$fff coppers';
					addCall("ChatSendServerMessageToLogin",$msg,$Player['Login']);
//					ChatSendServerMessageToLogin($msg,$Player['Login']);
				}
				multiquery();
			}
			else	echo "pas assez de coppers pour le jeu de mot\n\r";
		}
		$pub=0;
	}
}
	usleep(1);
	set_time_limit ($max_exec_time);
}


$client->Terminate();

?>
