<?php

##############################################################################
# mailing.php3                                                               #
#                                                                            #
# Copyright ViralGames SARL 2000                                             #
##############################################################################

include("../config.php3");
include($BIB."bib_generic.php3");

include($BIB."bib_mailing.php3");

$fic = "../Public/mailing.log"; #fichier appartenant a viralgame et accessible par nobody uniquement en ecriture
$MAILING = $ADMIN_URL."mailing_special_template.php3"; 

####################
# Administration script defaults
####################
# pas de timeout possible qql soit l'action effectuée
set_time_limit($TIME_LIMIT);

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

?>
<html>
<head></head>
<link rel="stylesheet" href="admin.css">
<body rightmargin=0>
<div align=center class=trTitle>Mailing spécial avec templates</div>
<br>
<?php

############################
# fonction qui ajoute le tag de désinscription
# unregisterTag(Id du membre,message)
############################
function pseudoTag($pseudo,$msg)
{
	echo "on remplace le pseudo par ".$pseudo."<br>";
	return ereg_replace("__PSEUDO__",$pseudo,$msg);
}

function pwdTag($pwd,$msg)
{
	return ereg_replace("__PWD__",$pwd,$msg);
}
function mailTag($mail,$msg)
{
	return ereg_replace("__EMAIL__",$mail,$msg);
}

//SELECT Members.Id AS Id,Email,NickName,Password,Players.Id AS PId FROM Members WHERE IsOff='0' AND (YEAR(BirthDate) <= 1984 OR Age>=3) AND Origin='0'



if (($fichier!="")&&($subject!="")){
	echo "</td></tr></table>";
    $fd = fopen($fic,'w');
    fwrite($fd,"######### mailing.log ########\n\n");
    fwrite($fd,"MemberId | NickName | Email | localtime\n\n");

    #envoie a tous les membres du Kestufoot non desinscrits
    if (strcmp($cible,"tous")==0 or strcmp($cible,"actifs")==0 or strcmp($cible,"inactifs")==0)
    {
		# pour les membres de sport24
		if ($brand==$ORIGINE_KTF or $brand==$ORIGINE_M6)
		{
			# on récupère la liste des participants
			$row_personne = main_db_query("SELECT Members.Id AS Id,Email,NickName,Password,Players.Id AS PId FROM Members ".
				"LEFT JOIN Players ON Members.Id=Players.MemberId WHERE IsOff='0' AND ".
//				"(YEAR(BirthDate) <= 1984 OR Age>=3) AND ".
				"Origine='".$brand."'");
		}
		# pour les membres de wanadoo
		elseif ($brand==$ORIGINE_LYCOS)
		{
			# on récupère la liste des participants
			$row_personne = main_db_query("SELECT Members.Id AS Id, Email2 AS Email, NickName, Password,Players.Id AS PId  FROM Members ".
				"LEFT JOIN Players ON Members.Id=Players.MemberId WHERE IsOff='0' AND ".
				"Origine='".$ORIGINE_LYCOS."'");
		}
	}

    #envoie a une plage de membres du Kestufoot non desinscrits
    elseif (strcmp($cible,"plage")==0)
	$row_personne = main_db_query("SELECT Members.Id AS Id,Email,NickName, Password FROM Members LEFT JOIN Players ON Members.Id=Players.MemberId WHERE Members.Id>=$min AND Members.Id<=$max AND IsOff=0 ");

    #envoie a une ou plusieurs adresses 
    elseif (strcmp($cible,"particulier")==0){
		$guestemail = "";
		$emails = extractemail($adresse);
		for ($i = 0; $i < count($emails); $i++) 
			$guestemail .= "'".trim($emails[$i])."',";
		
		# on retire la dernière virgule		
		$guestemail = substr($guestemail, 0, -1);
		
	//echo "Requ : "."SELECT Members.Id AS Id,Email,NickName, Password FROM Members LEFT JOIN Players ON Members.Id=Players.MemberId WHERE Email IN ($guestemail) AND IsOff=0 <br>";
	$row_personne = main_db_query("SELECT Members.Id AS Id,Email,NickName, Password FROM Members LEFT JOIN Players ON Members.Id=Players.MemberId WHERE Email IN ($guestemail) AND IsOff=0");
	
	//echo "SELECT Members.Id AS Id,Email,NickName, Password FROM Members LEFT JOIN Players ON Members.Id=Players.MemberId WHERE Email IN ($guestemail) AND IsOff=0";
	//echo "nb1:".db_num_rows($row_personne);
	//$xxxx = db_fetch_array(main_db_query("SELECT count(*) as total FROM Members WHERE Email IN ($guestemail)"));
	//echo "xxx:".$xxxx['total'];
	
	
    }

    #envoie aux membres selectionnes par une requete entree par le root
    elseif (strcmp($cible,"req_member")==0)
	$row_personne = main_db_query("SELECT Members.Id AS Id,Email,NickName, Password FROM Members LEFT JOIN Players ON Members.Id=Players.MemberId WHERE $where_member AND IsOff=0");
    
    #envoie a tous les invites non membres
    elseif (strcmp($cible,"guests_not_member")==0)
	$row_personne = main_db_query("SELECT Guests.Email AS Gemail, Members.Email AS Femail, NickName, GuestId FROM Guests LEFT JOIN Players ON Guests.FatherPId=Players.Id LEFT JOIN Members ON Players.MemberId=Members.Id WHERE Member=0 ");

    else $error = $error . "Problème de radio button<br>";

    if ($error==""){
	#on recupere le fichier a envoyer en le mettant dans une string
	$html = file($fichier);
	for($k=0;$k<sizeof($html);$k++)
	    $msg = $msg.$html[$k];
	
	#cas du mailing aux invites non membres
	if (strcmp($cible,"guests_not_member")==0){
	    while ($personne = db_fetch_array($row_personne)) {
#		echo "<br>### pere : $personne[NickName] $personne[Femail] | $personne[Gemail] $personne[GuestId]";
		$from = $personne[Femail];
		$subj = ereg_replace("FATHER_NICKNAME",$personne[NickName],$subject);
		$ms = ereg_replace("ID_REGISTRATION",$personne[GuestId],$msg);

		waitMail($personne[Gemail]);

		generic_mail($personne[Gemail], $subj, $ms,
			 "From: $from\n" . 
			 "Reply-To: $from\n" . 
			 "X-Mailer: PHP/" . phpversion()."\n".
			 "MIME-Version: 1.0\n".
			 "Content-Type: text/html; charset=iso-8859-1"."\n"
			 );
		fwrite($fd,$personne[Gemail]." ".my_local_time()."\n");
	    }
	}

	else
	{ 
		$ii = 0;
		$xx = 0;
		#cas general
		echo "nb:".db_num_rows($row_personne);
		
		
	    while ($personne = db_fetch_array($row_personne))
	    {	
			if ($cible == "actifs" or $cible == "inactifs")
			{
				# est-ce un actif ?
				$bet = db_fetch_array(main_db_query("SELECT MatchId FROM Paris WHERE PlayerId='".$personne['PId']."' AND Date > '".$dateRelance."' LIMIT 0,1"));
				
				# on a trouvé un match après la date indiquée
				if (($cible == "inactifs" and $bet) or ($cible == "actifs" and !$bet))
				{
					continue;
				}
			}

			if ($DEBUG!=1)
			{

				if ($personne['NickName'])
				# on inclue la lien pour la désinscription
				$newMsg = unregisterTag($personne[Id],$msg);
				$newMsg2 = pseudoTag($personne['NickName'],$newMsg);
				$newMsg3 = pwdTag($personne['Password'],$newMsg2);
				$newMsg4 = mailTag($personne['Email'],$newMsg3);
		
				waitMail($personne[Email]);
		
				
				generic_mail($personne[Email], $subject, $newMsg4,
					     "From: $GAME_NAME <".$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"
					     );
				
				fwrite($fd,"$personne[Id]; $personne[NickName]; $personne[Email]; ".my_local_time()."\n");

			$xx++;
			}
			else
			{
				echo $personne['PId']." - ".$ii."<br>";
			}
			
			$ii++;
	    }
	}
    }
    fclose($fd);
    echo "<b>Nb Mails envoyés : ".$ii."</b><br>".$xx;
}

if (($fichier=="")||($subject=="")||($error!=""))
{
    echo $error;
    $form_action = $MAILING;
    $form_name = "mailing";
?>
Envoyer à :<br>
<form method="post" ENCTYPE="multipart/form-data" action="<?php echo $form_action ?>" name="main">
<input type="hidden" name="<?php echo $form_name ?>" value="x">
Les membres de
<?php
$nbP = main_db_query("SELECT COUNT(*) AS tot, Origine FROM Members WHERE IsOff='0' GROUP BY Origine ORDER BY Origine ASC");
while($row = db_fetch_array($nbP))
{
	if ($row['Origine'] == $ORIGINE_KTF)
		$nbKTF = $row;
	elseif ($row['Origine'] == $ORIGINE_M6)
		$nbM6 = $row;
	elseif ($row['Origine'] == $ORIGINE_LYCOS)
		$nbLycos = $row;
}
/*
$nbKTF = db_fetch_array($nbP);
$nbLycos = db_fetch_array($nbP);
$nbM6 = db_fetch_array($nbP);
*/
?>
<select name="brand">
	<option value="<?php echo $ORIGINE_KTF ?>">Kestufoot (<?php echo $nbKTF['tot'] ?>)</option>
	<option value="<?php echo $ORIGINE_LYCOS ?>">Lycos Foot (<?php echo $nbLycos['tot'] ?>)</option>
	<option value="<?php echo $ORIGINE_M6 ?>">M6 (<?php echo $nbM6['tot'] ?>)</option>
</select>
<br>

<input type="radio" name="cible" value="tous"> Tous les membres (
<?php
$allMembers = main_db_query("SELECT COUNT(*) AS tot, IsOff FROM Members GROUP BY IsOff");
$allMembersOn = db_fetch_array($allMembers);
$allMembersOff = db_fetch_array($allMembers);
echo $allMembersOn['tot']." sur ".($allMembersOff['tot']+$allMembersOn['tot']);
?>
 ) --> poste à tous les membres d'une brand donnée<br>
<table border=1>
	<tr>
		<td>
<input type="radio" name="cible" value="actifs"> Tous les membres actifs depuis...<br>
<input type="radio" name="cible" value="inactifs"> Tous les membres n'ayant pas joué depuis...
		</td>
		<td>
	...le <input type="text" name="dateRelance" value="<?php echo $dateRelance ?>"><br>
		</td>
	</tr>
</table>

	<!--<input type="radio" name="cible" value="plage"> Les membres d'Id compris entre <input type="text" name="min" value="1"> et <input type="text" name="max" value="<?php $nb = db_fetch_array(main_db_query('SELECT count(*) AS NB FROM Members')); echo $nb[NB]; ?>" > inclus<br>-->
<input type="radio" name="cible" value="particulier" checked> Les membres d'adresses suivantes<br><textarea name="adresse" rows=10 cols=50></textarea><br>
<!--<input type="radio" name="cible" value="req_member"> Les membres dont la clause SQL WHERE suivante est vérifiée (réservé aux experts, attention a la jointure et aux caractères spéciaux comme les cotes): <input type="text" size="50" name="where_member">
<br>
<input type="radio" name="cible" value="guests_not_member"> Les invités non membres (à ne pas utiliser dans le cas général pour ne pas les embeter)-->
<br>
Sélectionnez le nom du fichier de mailing <input type="file" name="fichier" size="50"><br>
<br>Entrez le Sujet du message<br><input size=45 type="text" name="subject"><br><br>
<input type=checkbox name=DEBUG value=1> DEBUG MODE
<br><br>
<input type="submit">
</form>
<?php
}
?>
</body>
</html>
