<?php
include("config.php3");
include($BIB."bib_generic.php3");
include($BIB."bib_mailing.php3");
include($BIB."bib_tables.php3");
include($BIB_GLOBAL."ContactImporter/Bib_PHPContactImporter.php");


$sess = open_page($sessid,1);
if ($sess->memberid == -1) $sess->redirect($DECONNECTED_PAGE,"");

$checkboxes = "";
$error = "";

$message = "";

$member = getmember($sess->memberid);
$player = getplayer($sess->memberid);




switch(trim($typecompte))
{
	case "MSN" : 
		$ProviderName = "Hotmail";
		$Picto = "parrainage_btn_hotmail.png";
		$ID_TRACKING=68;
	break;
	case "Hotmail" : 
		$ProviderName = "Hotmail";
		$Picto = "parrainage_btn_hotmail.png";
		$ID_TRACKING=68;
	break;
	case "Gmail" : 
		$ProviderName = "Gmail";
		$Picto = "parrainage_btn_gmail.png";
		$ID_TRACKING=69;
	break;
	case "Yahoo" : 
		$ProviderName = "Yahoo";
		$Picto = "parrainage_btn_yahoo.png";
		$ID_TRACKING=70;
	break;
	default :  $sess->redirect($ADD_FRIENDS_PAGE,"");
}


############## LES FONCTIONS DE PARRAINAGE
function preparemail($guestemail,$guestname, $guestid, $fatheremail, $fathernick,$fathername, $message, $template, $isnew = true)
{
	global $tabMailsToSend;
	
	$tabMail = array();
	$tabMail['guestemail'] = $guestemail;
	$tabMail['guestname'] = $guestname;
	$tabMail['guestid'] = $guestid;
	$tabMail['fatheremail'] = $fatheremail;
	$tabMail['fathernick'] = $fathernick;
	$tabMail['fathername'] = $fathername;
	$tabMail['message'] = $message;
	$tabMail['template'] = $template;
	$tabMail['isnew'] = $isnew;
	$tabMailsToSend[] = $tabMail;
}

function sendmail($guestemail,$guestname, $guestid, $fatheremail, $fathernick,$fathername, $message, $template)
{
	global $IMAGES_DIR,$GAME_NAME, $GAME_DIR, $SITES_ORIGINES, $ORIGINE, $LOGIN_PAGE, $SERVER_URL, $REGISTRATION_PAGE,$perso,$FROM_FIELD,$REPLY_TO_FIELD;
	global $TRCK_CLICK_PAGE,$TRCK_CARNET_CLIC_ID,$TRCK_OPENINGIMAGE_PAGE,$TRCK_CARNET_OPENING_ID;
	
	
	$subject= $GAME_NAME." ?! ".$fathernick." vous invite ...";
	
	$guestUrl = $REGISTRATION_PAGE."?id=".$guestid;
	$style = "<font face=verdana size=2 color=black>";
	
	$msg = loadTemplate($GAME_DIR."Mailing/".$template);
	
	$msg = replaceTag("__FONT__", $style, $msg);
	$msg = replaceTag("__FATHEREMAIL__", $fatheremail, $msg);
	$msg = replaceTag("__MSG__", $message, $msg);
	$msg = replaceTag("__FULLNAME__", $fathernick, $msg);
	$msg = replaceTag("__URL__", $guestUrl, $msg);
	$msg = replaceTag("__SERVEUR_URL__", $SERVER_URL, $msg);

/*		
	$msg = replaceTag("__PERSOID__", $perso, $msg);
	$msg = replaceTag("__FIRSTNAME__", $fathernick, $msg);
	$msg = replaceTag("__NAME__", $fathername, $msg);
	$msg = replaceTag("__FATHEREMAIL__", $fatheremail, $msg);
	$msg = replaceTag("__FULLNAME__", $fathernick, $msg);
	$msg = replaceTag("__MSG__", htmlentities(stripslashes(nl2br($message))), $msg);
	$msg = replaceTag("__IMAGESURL__", $IMAGES_DIR, $msg);
	//URL DE CLIC ET D'OUVERTURE TRACKER (CONSTANTES EN CONFIG.PHP3)
	$msg = replaceTag("__OPENING__", "<img src='".$TRCK_OPENINGIMAGE_PAGE."?code=".$TRCK_CARNET_OPENING_ID."&email=".$guestemail."'>", $msg);
	$msg = replaceTag("__URL__", $TRCK_CLICK_PAGE."?code=".$TRCK_CARNET_CLIC_ID."&email=".$guestemail."&url=".$LOGIN_PAGE."&GuestId=".$guestid, $msg);
*/
	generic_mail($guestemail, $subject, $msg,
		     "From: ".$fathernick."<".$FROM_FIELD.">\n" . 
		     "Reply-To: ".$REPLY_TO_FIELD." \n" . 
		     "X-Mailer: PHP/" . phpversion()."\n".
		     "MIME-Version: 1.0\n".
		     "Content-Type: text/html; charset=iso-8859-1"."\n"
		     );
}
###############

function invite($guestemail,$guestname, &$player, &$member, &$message, $checkGuestAlreadyInvited = true)
{
	global $GAME_NAME;

	$result = "";
	$error = "";
		
	if (checkemail($guestemail, 1))
	{
	    # Checking membership
	   	$rowmember = main_db_query("SELECT * FROM Members WHERE Email = '$guestemail'");
			
	    if ($guestmember = db_fetch_array($rowmember))
		{
			# Already a member
			$error = $guestemail . " est déjà inscrit. - ";
      	}
		else
		{
			$rowguest = db_fetch_array(main_db_query("SELECT * FROM Guests WHERE Email = '$guestemail' AND FatherPId = '".$player[Id]."'"));
			
			if ($rowguest['Id'] > 0)
			{
				//$checkGuestAlreadyInvited permet d'indiquer si oui ou non on vérifie que le mail a déjà été parrainé par le joueur. Par défaut à "true" car on n'autorise pas le joueur à parrainer plusieurs fois la même personne (même si elle ne s'est pas inscrit. On le met à false dans le cas des "relances" de filleuls qui ne se sont pas encore inscrit.
				if ($checkGuestAlreadyInvited)
					# Already a member
					$error = "Vous avez déjà invité ".$guestemail . " ! - ";
				else
				{
					# dans le cas présent on autorise un joueur à parrainer un filleul qu'il a déjà parrainé. C'est le cas des "relances".
				  	preparemail($guestemail,$guestname, $rowguest['GuestId'], $member[Email], $member[FirstName], $member[Name], $message, "template_invitation.html", false);
					$result = "le message pour ".$guestemail." a bien été envoyé ! - ";
				}
			}
			else
			{
				# Sending invitation message
			  	preparemail($guestemail,$guestname, $id, $member[Email], $member[FirstName],$member[Name], $message, "template_invitation.html", true);
				//$result .= "Un email d'invitation a été envoyé à $guestemail<br>";
				$result = "le message pour ".$guestemail." a bien été envoyé ! - ";
			}
		}
	}
	else
	{
    	$error= $guestemail." n'est pas une adresse valide - ";
    }	
	return array($error, $result);
}
############## LES FONCTIONS DE PARRAINAGE




//CAS ENVOI MAIL
if($listEmail)
{

	$error = "";
	if (empty($error))
	{
		$tabMailsToSend = array();
		$nbMailsEnvoyes = 0;
		
		for($i=1;$i <= $nbemail; $i++)
		{
			$guestemail = $_POST["email".$i];
			if($guestemail && $guestemail != $defautemail)
			{
				$guestemail = trim($guestemail);
				list($error_mail, $result) = invite($guestemail,$$guestname, $player, $member, $message);
				
				if ($error_mail != "")
				{
					$error .= $error_mail;
				}
				else
				{
					//on détruit pour que ce mail ne soit plus selectionné si il reste des erreurs
					unset($_POST["email".$i]);
					$nbMailsEnvoyes++;
				}
				$result_mail .= $result;
			}	
		}		
	}
	if($nbMailsEnvoyes==0 && $error == "")
	{
		$error = "Veuillez indiquer au moins un email";	
	}
	else if ($error=="")
	{
		//
		
	}
	


	if(!$error)	
	{
		# on envoie les mails
		for($r=0;$r < $nbMailsEnvoyes; $r++)
		{
			if ($tabMailsToSend[$r]['isnew'])
			{
				# New guest
				# ajout du guest dans la table Guests
				main_db_query("INSERT INTO Guests (Email,Name, FatherPId, GuestId) VALUES ('".$tabMailsToSend[$r]['guestemail']."','".$tabMailsToSend[$r]['guestname']."', '".$player['Id']."', '')");
				
				# recup de l'id inséré dans la table Guest
				$newGuest = db_fetch_array(main_db_query("SELECT Id FROM Guests WHERE Email = '".$tabMailsToSend[$r]['guestemail']."' ORDER BY Id DESC LIMIT 0,1"));
				
				# on construit le GuestId
				# $newGuest[Id] est unique, md5(uniqid(rand())) est une chaine sur 32 char, on a donc un
				# id unique (grace à newGuestId et imprédictible grace au md5(...)
				$id = $newGuest['Id'].md5(uniqid(rand()));
				
				# on update le guest Id ainsi composé
				main_db_query("UPDATE Guests SET GuestId='".$id."' WHERE Id='".$newGuest['Id']."'");
				
				$tabMailsToSend[$r]['guestid'] = $id;
			}
			
			sendmail(
				$tabMailsToSend[$r]['guestemail'],
				$tabMailsToSend[$r]['guestname'],
				$tabMailsToSend[$r]['guestid'],
				$tabMailsToSend[$r]['fatheremail'],
				$tabMailsToSend[$r]['fathernick'],
				$tabMailsToSend[$r]['fathername'],
				$tabMailsToSend[$r]['message'],
				$tabMailsToSend[$r]['template']
				);
		}
	
	}	

}
//si l'envoi s'est bien déoulé
if(isset($listEmail) && $error == "" )
{
	unset($email);
}

//CAS CONNEXION A UN CARNET @
if(isset($email) )
{
	
		//if (!function_exists ('curl_version'))
			//throw new Exception ("Curl n'est pas install");
	
		//On include la librairie correspondant au provider
		include($importerinfo[$ProviderName]);
		
		
		$email = trim($email);
		$password = trim($pwd);	
		
		
		$i = 1;
		$contactemails = import_contacts($email,$password);
		
		if(is_array($contactemails))
		{
			
			foreach($contactemails AS $contact)
			{
				if(strlen(trim($contact[1]))>1)
				{
					$checked = "";
					if(isset($_POST["email".$i]))
						$checked = "checked";
					
					$checkboxes .= "<div style='float:left;width:240px;'><input type='checkbox' name='email".$i."' id='email".$i."' value='".trim($contact[1])."' ".$checked."><label for='email".$i."'>".trim($contact[1])."</label></div>\n";
					$i++;
				}		
			}
			$checkboxes .= "<input type='hidden' name='nbemail'  value='".$i."'>";
		}
		else
			$error = "Identifiants incorrects";
			
		
		
		
		
		
		
	
}

$page_courante = "Carnet d'adresse";

if($sess->memberid != -1)
{
	$sub_header='subh_connecte.inc';
}
else
{
	$sub_header='subh_deconnecte.inc';
} 
 
 

include("header.inc");
include("carnet-adresse.inc");
include("footer.inc");

?>