<?php

##############################################################################
# registration.php3                                                          #
#                                                                            #
# Copyright ViralGames SARL 2000                                             #
##############################################################################

include("config.php3");
include($BIB."bib_generic.php3");
include($BIB."bib_check_members.php3");
include($BIB."bib_mailing.php3");
include($BIB."bib_all_country.php3");
include($BIB.$ORIGINE."_bib_check_members_vip.php3");

/*------------ TAG HEADER ----*/
$header_title = "Jeu de pronostics gratuits sur le football, inscription";
$header_description = "Vous inscrire au jeu Kestufoot vous permettra de pronostiquer gratuitement sur tous les matchs (Ligue 1, ligue 2, coupes de France, coupes de la ligue, championnats étrangers…) et de remporter de nombreux cadeaux!";
$header_keywords = "Inscrivez-vous, identifiants, coordonnées, gagner des cadeaux, ligue 1, ligue 2, coupe de France, coupe de la ligue, coupe des champions, coupe de l’UEFA, ligue des champions, équipe de France, championnats étrangers.";
/*------------ /TAG HEADER ----*/
/*
function updateFathers($fatherplayer,$NickName,$rootpid)
{
    global $NB_PTS_PAR_FILLEUL,$NB_PTS_PAR_P_FILLEUL,$NB_PTS_PAR_AP_FILLEUL;

      # If no father, the root player id is set to himself
      if ($rootpid == -1) {
	$rowplayer = main_db_query("SELECT * FROM Players WHERE NickName='$NickName'");
	$player = db_fetch_array($rowplayer);
	main_db_query("UPDATE Players SET RootPId='$player[Id]' WHERE NickName='$NickName'");
      }

      # Update fathers up to the root
      # Direct father
      if (!empty($fatherplayer)) {
	# Increment number of offsprings
	$update = "UPDATE Players SET Offsprings = $fatherplayer[Offsprings] + 1 , Score = $fatherplayer[Score]+$NB_PTS_PAR_FILLEUL, Sons = Sons+1 WHERE Id = $fatherplayer[Id]";
	main_db_query($update);
	$prerowfather = "SELECT * FROM Players WHERE Id=$fatherplayer[FatherPId]";
	$rowfather = main_db_query($prerowfather);
	$fatherplayer = db_fetch_array($rowfather);
	
      }
      # Grand father
      if (!empty($fatherplayer)) {
	# Increment number of offsprings
	$update = "UPDATE Players SET Offsprings = $fatherplayer[Offsprings] + 1 , Score = $fatherplayer[Score]+$NB_PTS_PAR_P_FILLEUL, GrandSons = GrandSons+1 WHERE Id = $fatherplayer[Id]";
	main_db_query($update);
	$prerowfather = "SELECT * FROM Players WHERE Id=$fatherplayer[FatherPId]";
	$rowfather = main_db_query($prerowfather);
	$fatherplayer = db_fetch_array($rowfather);
      }
      # Grand Grand father
      if (!empty($fatherplayer)) {
	# Increment number of offsprings
	$update = "UPDATE Players SET Offsprings = $fatherplayer[Offsprings] + 1 , Score = $fatherplayer[Score]+$NB_PTS_PAR_AP_FILLEUL, GrandGrandSons = GrandGrandSons+1 WHERE Id = $fatherplayer[Id]";
	main_db_query($update);
	$prerowfather = "SELECT * FROM Players WHERE Id=$fatherplayer[FatherPId]";
	$rowfather = main_db_query($prerowfather);
	$fatherplayer = db_fetch_array($rowfather);
      }
      
      # Other fathers
      while (!empty($fatherplayer)) {
	# Increment number of offsprings
	$update = "UPDATE Players SET Offsprings = $fatherplayer[Offsprings] + 1 WHERE Id = $fatherplayer[Id]";
	main_db_query($update);
	$prerowfather = "SELECT * FROM Players WHERE Id=$fatherplayer[FatherPId]";
	$rowfather = main_db_query($prerowfather);
	$fatherplayer = db_fetch_array($rowfather);
      }
}*/


function trans($s)
{
	return strtr($s, "µ€ñãåäâáàÅÃÁàÄÂéèêëéÈËÊîïìíÎÌÍÏôöóòõÖÒÓÕÔØùûüúÜÛÙÚÿýÝçÇÐÑÞþßƒ", "UEnaaaaaaAAAAAAeeeeeEEEiiiiIIIIoooooOOOOOOuuuuUUUUyyYcCDNBBBF");
}


# le script continue une fois qu'il est lancé qql soit l'état de la connection après
ignore_user_abort(true); 


$sess = open_page($sessid);

//if ($sess->memberid != -1 and !isset($oncemid))
//	$sess->redirect($MEMBER_PAGE, "");

	
	
if ($sess->memberid != -1)
{
	$player = getplayer($sess->memberid);
	$NickName = $player['NickName'];
	$onceMId = true;
}
else
	$onceMId = false;

$error = ""; 

# si la personne a été parrainée, on prend en compte le guestid
if (strlen($sess->guestid) > 1)
	$id = $sess->guestid;

#######################################
# CAS D'UNE PERSONNE INVITEE
#######################################
if ( isset($id) && !empty($id) ) 
{
	# recupere les infos sur le Guest
  	$rowguest = main_db_query("SELECT * FROM Guests WHERE GuestId='".$id."'");
  	$guest = db_fetch_array($rowguest);
	# si on ne retrouve pas l'enregistrement du Guest
  	if (db_num_rows($rowguest)<1)
    	$error = "L'URL utilisée est invalide<br>";	
	else
	{
		# s'il s'est déjà inscrit, son champs member indique son memberId
	    if ($guest[Member] != 0)
      		$error = "Vous avez déjà rempli le formulaire d'inscription !<br><a class=whiteLink href=".$LOGIN_PAGE.">Retour à la page d'accueil du ".$GAME_NAME."</a>";
		else
		{
			# il a été invité, son enregistrement d'invité a été trouvé
			# il n'est pas encore inscrit car il n'a pas de memberId
			
			# récup des infos sur le parrain
			$fatherpid = $guest[FatherPId];
			$fatherplayer = getplayer2($guest[FatherPId]);
/*			
			echo "fatherplayer : ".$fatherplayer['NickName']."<br>";
			if ($fatherplayer['Sons'] < $MAX_SONS_IN_TEAM)
			{
*/
				$fathermember = getmember2($guest[FatherPId]);
				
				# on affecte les infos sur le player :
				# rank : sa profondeur dans la dynastie
				# root : le fondateur de la dynastie
				$rank = $fatherplayer[Rank] + 1;
				$rootpid = $fatherplayer[RootPId];
				$root = getplayer2($rootpid);
				
				# on affecte le guestId de la session. Si le type sort de la page
				# et y revient, il est reconnu
				$sess->guestid = $id;
				$sess->save();
				
				# l'invité n'a pas besoin de taper son email, il est déjà connu
				$Email = $guest[Email];
			  
				# on va checker pour voir si le mail existe déjà dans une des bases
				# auquel cas, on récupère les infos
			  	$onceId = checkEmailInBases($Email);
			  
			  	# s'il est dans $DATABASE c'est qu'il est déjà inscrit à ce jeu !
			  	if ($onceId[base]==1)
			  		$error = $error . "Vous êtes déjà inscrit!<br>";
/*
			echo "fatherplayer : ".$fatherplayer['NickName']."<br>";

			}
			else
			{
				unset($fatherpid);
				unset($fatherplayer);
			}
*/    	
    	}
  	}
}
# il n'est pas parrainé
if (!isset($fatherpid))
{
	$fatherpid = 0;
	$rank = 0;
	$rootpid = -1;
}

# on "clean" le $Email
$Email = trim($Email);
$NickName = trans($NickName);
$Login = strtr(trim($NickName), "<>", "__");
$Origine=$ORIGINE;

if( $REGISTRATION_ROBOT == true )
{
	# Clé de cryptage pour le code de confirmation
	$rand = genRandomPassword();
}

if (empty($error))
{
	# après le 1er passage
	if (isset($modif))
	{
	    if ( ( $Password && $Password != $Password2 ) || ( $Password1 && $Password1 != $Password2 ) )
	      $error = $error . C_ERREURPWD."<br>";

		  if (empty($Zip))
			$error = $error.C_ERREURCPOSTAL."<br>";

		if (empty($Gender))
			$error = $error.C_ERREURSEXE."<br>";

		if (empty($NickName))
			$error = $error.C_ERREURPSEUDO."<br>";

	    ##############################################
		if (!$onceMId)
		{
			if (empty($NickName))
				$error = $error."Vous devez saisir votre pseudo<br>";

			$onceId = isLoginExists($NickName,$ORIGINE);
		
			if ($onceId[0]>0)
				$error = $error . "Le pseudo ".$NickName." est déjà utilisé par un joueur !<br>";
	
			if (strlen($Password) < 6)
				$error = $error . "Votre mot de passe doit faire au moins 6 caractères<br>";
	
			if ($Accepte != 1)
				$error .= "Vous devez accepter le règlement pour valider votre inscription<br>";
		}
	    ##############################################

		if (empty($Name))
			$error .= "Vous devez saisir votre nom<br>";
		if (empty($FirstName))
			$error .= "Vous devez saisir votre prénom<br>";
		if (empty($Address))
			$error .= "Vous devez saisir votre adresse<br>";
		if (empty($Town))
			$error .= "Vous devez saisir votre ville<br>";
		if (empty($Country))
			$error .= "Vous devez saisir votre pays<br>";
		/*if (empty($Telephone))
			$error .= "Vous devez saisir votre Telephone<br>";
*/
		if (empty($Email))
		{
			$error = $error."Vous devez saisir un email.<br>";		
		}
		else
		{
			if (checkemail($Email)==false)
				$error = $error."Votre adresse email est incorrecte.<br>";
			else
			{
				$onceId = isEmailExists($Email,$ORIGINE);	
				if ( $onceId[0]>0 && $onceId[0] != $sess->memberid )
					$error = $error . "Cet email est déjà inscrit !<br>";
			}
		}
		
		if ($jj < 1 or $jj > 31 or $mm < 1 or $mm > 12 or $yyyy < 1900 or $yyyy > 1999 or ($jj == 31 and ($mm == 2 or $mm == 4 or $mm == 6 or $mm == 9 or $mm == 11)) or ($jj == 30 and $mm == 2))
			$error .= "Votre date de naissance est incorrecte<br>";
		else
			$Birthdate = intval($yyyy)."-".intval($mm)."-".intval($jj);


		# vérifie que le code de confirmation dans le cas d'une inscription avec anti-robot		
		if( $REGISTRATION_ROBOT == true && !$onceMId)
		{
			if( strtoupper(substr(md5($REGISTRATION_CONFIRMATION_KEY.$conf_hash),10,6)) != $conf_code )
			{
				$error = $error."Le code de confirmation saisi est erroné.<br>";
			}
		}

	    if (empty($error))
		{
			# There was no error
			# A new member is created if the total number of members does not exceed MAX_NBMEMBERS
			$date = date("Y-m-d H:i:s", my_local_time());
		  
			if ( $onceMId )
			{

				if( $Password1 )
					$updPassword = "Password='".encryptePassword($Password1)."',";
				else
					$updPassword = "";

				# ici on est en modification de profil ou inscription après
				# avoir été inscrit par audiotel
				main_db_query("UPDATE Members SET ".
			  	$updPassword." Email = '$Email', IP = '$REMOTE_ADDR', Host = '$REMOTE_HOST', Browser = '$HTTP_USER_AGENT', IsOff = '0', IsSuspect = '$IsSuspect',".
				"Gender = '$Gender', Name = '$Name', FirstName = '$FirstName', Zip = '$Zip', Town = '$Town', Country='$Country', Birthdate = '$Birthdate',".
				"Address = '$Address', Mobile = '$Mobile', ".
				"Telephone = '$Telephone'".
				",acceptNews = '$acceptNews', acceptPartenaires = '$acceptPartenaires'".
				" WHERE Id = '".$sess->memberid."'");
				
				$player = getplayer($sess->memberid);
				//main_db_query("UPDATE Players SET NickName = '$NickName' WHERE Id='".$player['Id']."'");
				$member = getmember($sess->memberid);
								
			}
			else
			{
				# met la langue par défaut
				if (($LgMail!="fr") &&($LgMail!="uk") &&($LgMail!="esp") &&($LgMail!="aucun"))
			  		$LgMail = "fr";
			
				$retour_creation = user_create( $Login, $Password, $Email );
				switch ($retour_creation)
				{
					case "ok_create_user":
					{
						# There was no error
						$date = date("Y-m-d H:i:s", my_local_time());				
	
						# on génère un id unique pour le joueur
						$Vip = getUVip( $Login , $Origine);
						
						$NickName=$Login;
										
						include("login_box.core.php3");
						
						break;
					}

					case "user_already_exists":
					{
						$error .= "Cet identifiant est déjà utilisé... Merci d'en saisir un autre !<br>";
						break;
					}
					case "email_already_exists":
					{
						$error .= "Cet email est déjà utilisé.<br>";
						break;
					}
					default:
					{
						debug("erreur de création de compte ".$ORIGINE." : ".$retour_creation);
						$error .= "Erreur de transmission des données.<br>";
						break;
					}
				}
				
			}
			include("config.php3");
			# Update session
			$sess->memberid = $member[Id];
			$sess->save_member_cookies($NickName, $Password);
			$sess->save(); 
			
			//updateFathers($fatherplayer,$NickName,$rootpid);				
		}
	}
}  

// ici on retire les slashes mis en place par le magic_quote_gpc
// au cas où on retourne en erreur ou en suspicion_check
if($HTTP_POST_VARS)
{
	foreach($HTTP_POST_VARS as $key => $val)
			$$key = stripslashes($val);
}   	
if(!isset($modif) or !empty($error))
{
	# If first visit or an error occured
	# the Gender is set by default to Homme
	$title= C_INSCRIPTION;
	$page_courante='inscription';
	$NO_SKY=1;
	
	if ( $onceMId )
		$sub_header='subh_connecte.inc';
	else
		$sub_header='subh_howtowin.inc';

	include("header.inc");
	
	$title_image = "Titres/Titre-Formulaire.gif";
	$nolinks = "no";

	$form_action = $sess->action($REGISTRATION_PAGE);
	$form_name = "modif";
  
	if ( $onceMId and empty($error))
	{
		# on récupère les params
		$member = getmember($sess->memberid);
		$player = getplayer($sess->memberid);
		
		$Email = $member['Email'];
		$Gender = $member['Gender'];
		$Name = $member['Name'];
		$FirstName = $member['FirstName'];
		$Zip = $member['Zip'];
		$Town = $member['Town'];
		$Country = $member['Country'];
		$Mobile = $member['Mobile'];
		$Ages = explode("-",$member['Birthdate']);
		$jj = $Ages[2];
		$mm = $Ages[1];
		$yyyy = $Ages[0];
		$Address = $member['Address'];
		$Telephone = $member['Telephone'];
		$InfoOpe = $member['InfoOpe'];
		$Password = $Password2 = $member['Password'];
		$NickName = $player['NickName'];
		$acceptNews = $member['acceptNews'];
		$acceptPartenaires = $member['acceptPartenaires'];
	
		$Password = "";
		$Password1 = "";
		$Password2 = "";
	}
	else
	{
		$Gender="M";
		$acceptNews = 1;
		$acceptPartenaires = 1;
	}
	/*
	if (!isset($Accepte))
		$Accepte = 1;
  	*/
	include("inscrivez-vous.inc");
	include("form_footer.inc");
	include("footer.inc");
}
else
{
	$sess->redirect($MEMBER_PAGE, "plog=".$plog);
}

close_page($sess);
?> 
