<?php
/*************************************************************************
*                                                                        *
* This script pre-registers and confirms an user by e-mail.              *
* It features an anti-spam protection by enabling the owner of the mail  *
* account to blacklist his/her e-mail address. IPs are logged.           *
*                                                                        *
* Copyright (C) 2004 RedFo1 <http://www.mpam2.fr.st>                     *
*                                 Version 1.0                            *
*                                                                        *
* This program is free software; you can redistribute it and/or modify   *
* it under the terms of the GNU General Public License as published by   *
* the Free Software Foundation; either version 2, or (at your option)    *
* any later version.                                                     *
*                                                                        *
* This program is distributed in the hope that it will be useful,        *
* but WITHOUT ANY WARRANTY; without even the implied warranty of         *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
* GNU General Public License for more details.                           *
*                                                                        *
* You should have received a copy of the GNU General Public License      *
* along with this program; if not, write to the Free Software            *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.              *
* You can also provide yourself with an online copy of the text:         *
* <http://www.gnu.org/copyleft/gpl.html>                                 *
* <http://www.gnu.org/copyleft/gpl.txt>                                  *
*                                                                        *
*************************************************************************/
$serveur="http://mpam2.free.fr";	// Racine du serveur
$validité=3600*24*7;			// Durée de validité du code de confirmation en secondes (3600 secondes par heure, 24 h par jour, donc là ça fait 7 j lol)
$db_host="127.0.0.1";			// Paramètres de la DB
$db_user="root";
$db_pass="password";
$database="database";

//************ Fin des paramètres


if (isset($_POST["email"]))		// Si le formulaire a été rempli (sans '), on le traite...
{
mysql_connect($db_host,$db_user,$db_pass) or die("Unable to connect to database");
mysql_select_db($database) or die("Unable to select database");

$page=$serveur.$_SERVER["PHP_SELF"];
$nom=$_POST["nom"];
$pass=$_POST["pass"];
$pass2=$_POST["pass2"];
$email=$_POST["email"];
$IP=$_SERVER['REMOTE_ADDR'];
$heure=time();

do					// Le code doit être unique... mais on doit pas en parler à l'utilisateur ;)
{
$session=md5(time());
$resultat = db_mysql_Query("SELECT * FROM membres WHERE session ='$session'");
}
while(false!=($ligne = mysql_fetch_array ($resultat)));

if($nom=="" || $pass=="" || $pass2=="" || $email==""){show_error('One or more fields are missing.');show_form($nom,$pass,$pass2,$email);die();}		// Merci de tout remplir monsieur :)
if($pass!=$pass2){show_error('Password and confirmation didn\'t match.');show_form($nom,$pass,$pass2,$email);die();}					// Faut que les 2 mots de passe soient pareils
if(!(!strrpos($_POST["nom"], "'") && !strrpos($_POST["pass"], "'") && !strrpos($_POST["email"], "'"))){show_error('You used a forbidden character.');show_form($nom,$pass,$pass2,$email);die();}	// Pas de SQL insertion SVP
$resultat = db_mysql_Query("SELECT * FROM members WHERE nom ='$nom'"); 
if(false!=($ligne = mysql_fetch_array ($resultat))){show_error('This username ('.$nom.') is already taken.');show_form($nom,$pass,$pass2,$email);die();}	// Si le login est déjà pris (confirmé)
$resultat = db_mysql_Query("SELECT * FROM membres WHERE nom ='$nom'"); 
if(false!=($ligne = mysql_fetch_array ($resultat))){show_error('This username ('.$nom.') is already taken.');show_form($nom,$pass,$pass2,$email);die();}	// Si le login est déjà pris (en attente)
$resultat = db_mysql_Query("SELECT * FROM blackl WHERE email ='$email'"); 
if(false!=($ligne = mysql_fetch_array ($resultat))){show_error('This e-mail ('.$email.') is blacklisted. You can\'t use it to sign up here.');show_form($nom,$pass,$pass2,$email);die();}	// Si l'e-mail est dans la blacklist

//********* L'e-mail qu'on va envoyer (je vous conseille de le modifier parce que là avec tous les "registration" et "sign up" qu'il contient, il ne passe pas les filtres anti-spam...) :
/* subject */
$subject = "Please confirm your registration";

/* message */
$message = '
<html>
<head>
 <title>Please confirm your registration</title>
</head>
<body>
Hello '.$nom.',<br/><br/>

You are receiving this e-mail because you or someone else used your address to sign up on our site.<br/>
Please complete your registration by clicking <a href="'.$page.'?code='.$session.'">here</a>.<br/><br/>

If you didn\'t register on our site, just ignore this message and please accept our apologies.<br/>
You can also choose to blacklist your e-mail so you won\'t hear from us anymore by clicking <a href="'.$page.'?code='.$session.'&BL=1">here</a>.<br/>
Your e-mail was submitted from IP '.$IP.'.<br/><br/>

Best regards,<br/>
Site Admin
</body>
</html>
';

/* To send HTML mail, you can set the Content-type header. */
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

/* additional headers */
$headers .= "To: ".$nom." <".$email.">\r\n";
$headers .= "From: Site <do_not_reply@free.fr>\r\n";

/* and now mail it */
if(mail($email, $subject, $message, $headers))
	{
	$query = "INSERT INTO membres VALUES('','$nom','$pass','$email','$heure','$session','$IP','".date("Y-m-d")."','".date("H:i:s")."')";		// On met les données dans la table d'attente
	db_mysql_Query($query);
	mysql_close();

	echo 'Thank you.<br/>An e-mail was sent to '.$email.'. Please check your e-mail and confirm your membership within 7 days.';
	}
else {show_error('We weren\'t able to send you the confirmation e-mail. Please contact the webmaster.');show_form($nom,$pass,$pass2,$email);}
}



else if(isset($_GET["code"]))					// Si un code est entré
{
mysql_connect($db_host,$db_user,$db_pass) or die("Unable to connect to database");
@mysql_select_db($database) or die("Unable to select database");

$heure=time();
$heure2=$heure-$validité;					// On supprime les codes périmés
db_mysql_Query("DELETE FROM membres WHERE heure<$heure2");

$session=$_GET["code"];
$sql = "SELECT * FROM membres WHERE session ='$session'";
$resultat = db_mysql_Query($sql);

if(false==($ligne = mysql_fetch_array ($resultat))){mysql_close();die('This code is wrong or has expired, please fill in the form again <a href="'.$_SERVER["PHP_SELF"].'">here</a>.');}

if(!isset($_GET["BL"]))						// Si l'utilisateur vient vraiment pour confirmer, on le mets dans la table des membres enregistrés et on l'enlève de la table d'attente
{
$nom=$ligne['nom'];
$query = "INSERT INTO members VALUES('','".$ligne['nom']."','".$ligne['pass']."','".$ligne['email']."','".$ligne['IP']."','".$ligne['date']."','".$ligne['heure2']."')";
db_mysql_Query($query);
db_mysql_Query("DELETE FROM membres WHERE session='$session'");

echo 'Thank you for confirming your inscription '.$nom.'. You are now a member of the site.';
}

else if($_GET["BL"]==1)						// Si l'utilisateur vient pour être dans la liste noire, on demande confirmation
{
echo 'Click <a href="'.$_SERVER["PHP_SELF"].'?code='.$_GET["code"].'&BL=2">here</a> to blacklist your e-mail. This CANNOT be undone.';
}

else								// Si l'utilisateur a confirmé qu'il veut être dans la liste noire, on l'y met et on l'enlève de la table d'attente
{
$email=$ligne['email'];
$query = "INSERT INTO blackl VALUES('','$email','".$ligne['IP']."','".$ligne['date']."','".$ligne['heure2']."')";
db_mysql_Query($query);
db_mysql_Query("DELETE FROM membres WHERE session='$session'");

echo 'Your e-mail '.$email.' has been blacklisted. You won\'t receive anymore e-mails from us.';
}

mysql_close();
}



else{show_form();}		// S'il n'y a ni formulaire rempli, ni code, on affiche le formulaire

//************ Quelques fonctions
function show_form($nom="",$pass="",$pass2="",$email="")
{
echo 'Please fill in the sign up form (do not use any \') :<br/>
<form action="'.$_SERVER["PHP_SELF"].'" method="post">
<table>
<tr>
<td>Desired login&nbsp;:</td><td><input type="text" name="nom" size="50" maxlength="20" value="'.$nom.'" /></td>
</tr>

<tr>
<td>Password&nbsp;:</td><td><input type="password" name="pass" size="50" maxlength="20" value="'.$pass.'" /></td>
</tr>

<tr>
<td>Confirm password&nbsp;:</td><td><input type="password" name="pass2" size="50" maxlength="20" value="'.$pass2.'" /></td>
</tr>

<tr>
<td>E-mail&nbsp;:</td><td><input type="text" name="email" size="50" maxlength="100" value="'.$email.'" /></td>
</tr>
</table>

<input type="submit" value=" Sign Up " />
</form>';
}

function show_error($text)
{
echo '<div style="color:#ff0000;font-weight:bold;">'.$text.'<br/></div>';
}
?>