Registration system for phpfreechat


Hola a todos,

Como phpfreechat es un chat bastante usado en la web, i que además es fácil de instalar y usar ayudándote como webmaster a tener un chat rápido y sin ninguna complicación, solo lo subes en un folder como quieras llamarle y le das permisos 777 a el folder ./DATA y echo te vas a tu explorador y lo abres y ya estas chateando..
Lo desafortunado de el script esque no tiene una sistema de registracion , pues bueno me decidí a crear una y tengo como resultado un sistema completo de registracion que evita que otros usuarios que entren al chat, utilicen el nombre o nick de otro usuario registrado..
El script permite que entren como anónimos al chat pero chequea que el nombre no este registrado con eso te da un completo manejo del chat no mas personas que personifiquen a otra o el moderador.. que dolor…
Requerimientos mínimos:
Los privilegios mínimos del usuario de mysql son:

* SELECT, CREATE, INSERT, UPDATE,DELETE,FILE.

Lo que hace el script:

1. Registra el nombre y lo salva en una base de datos de mysql.
2. Usuario anónimo , deja entrar al chat anónimamente pero si el nombre escogido como anónimo no esta registrado.
3. La posibilidad de desactivar la opción de usuario anónimo.
4. La registracion de un nombre pero si no usa el mismo correo electrónico , no permite registrar si el correo existe en la base de datos.
5. Restringe el acceso al chat si no esta autorizado a entrar, eliminas la posibilidad de que entren si no an iniciado la sesión que indica o que son anónimos o si están registrados..
6. Ninguna clave de usuario es colocada en la sesión php , en cambio el nombre es encriptado y agregado una sal que es salvada en la base de datos lo cual la clave nunca esta en-riesgo.
7. Cantidad mínimas de caracteres para el nombre que se quiere registrar, así también cantidad máxima.
8. Cantidad mínima de caracteres para la clave , entre mas larga sea la clave mas difícil de dar con ella si quieren usar fuerza bruta y diccionarios .

Prosigamos a la instalación :

1. Descarga el login.rar.
2. Descomprime lo y los subes al folder donde esta tu chat, ejemplo ./chat , entonces se vera ./chat/login .
3. Crea una base de datos de mysql y asegura que el usuario que se conecta a esa base de datos tenga los permisos siguientes: SELECT, CREATE,INSERT,UPDATE,DELETE,FILE.
4. Ahora abre el documento php localizado en ./login/settings.php ,edita los siguientes parámetros: $hostServer=”localhost”; // la direccion del servidor mysql.
$MysqlUser=”phpfreechat”; // el nombre del usuario de mysql.
$MysqlPass=”somepass”; // la clave de usuario del msql.
$DataBaseName=”MiBaseDeDatos”; // cambia a la base de datos que creaste en el paso 3.
5. Una ves tienes todo creado, base de datos y sabes que el usuario con el cual te conectaras a la base de datos tiene suficiente permisos, seguimos.
6. Dirígete a tu website y instala las tablas en la base de datos yendo a ejemplo: http://miwebsite.com/chat/login/install.php .
7. Si todo salio bien este habrá instalado las tablas automáticamente y te habrá dicho esto, además te mostrara el enlace a el login.php , si te da algún error entonces revisa todo los pasos otra vez.
8. ahora en el folder ./login se encuentra un documento llamado index.phpfreechat, re/nombralo a index.php y sube lo o arrástralo a la raíz de tu chat reescribiendo en antiguo por la versión nueva , este paso es muy importante porque se hace pruebas de validación a el usuario.
9. Echo todo lo anterior y con un nombre ya registrado , identificate si todo coincide el chat te dirigirá al chat con tu nick. ahora solo abre settings.php y edita el administrado el lenguaje y otros parámetros .

Todo esta completado, si quieres probar el chat y el sistema de registracion; sigue este enlace a el chat que esta instalado en este sitio.. dale clic al enlace DEMO CHAT usuario anónimo esta habilitado.

Sugerencias o problemas con el script por favor házmelo saber.. gracias

Si quieren chequear el code:

<?php
/**
* Created by Neu Valle Aka UTAN, RE*S.T.A.R.S.*2 emails:vcomputadoras@yahoo.com, utan@radioscatrachas.info.
* features are: checks username is in use, email in use
* checks username minimun characters, checks password minimun length,
* checks maximun username characters, guest login.
* Password and usernames are encrypted with sha1 one way hashing and salted.
* Created specially for phpfreechat, forviden the use in other project without explicit permition.
* If you like the script, I only ask to put a link back to my sites radioscatrachas.info, vcomputadoras.com
*/
require_once('settings.php');

if(!isset($_SESSION)){
session_start();}

function IsAuthorized(){
// N_V- lets call the database.
global $connect,$DataBaseName;
// N_V- lets check if at least we got some session to play with.
if(isset($_SESSION['loggeduser']))
{
// N_V- we set the username from session loggeduser to check in mysql
$username=$_SESSION['loggeduser'];
// N_V- check if connected.
if($connect)
{
// N_V- We dont know if someone can inject something in the session, so lets clean for Mysql injection
$username=mysql_real_escape_string(stripslashes($username));
mysql_select_db($DataBaseName, $connect);
$query = "SELECT salted FROM $DataBaseName WHERE username='$username'";
$result= mysql_query($query);
while($row=mysql_fetch_array($result)){
$salted=$row['salted'];
}
// N_V- Since we made the firsts test with loggeduser session and we have got here
// N_V- we check if username that session holds is the same one we used
// N_V- in LoggedInUser function and we do so checking against the hashed name and the salt we saved in MSQL ..
if(sha1(sha1($username).$salted) == $_SESSION['hashedname'])
{
return $username;
mysql_close($connect);
}
}
}else
{
// N_V- check guestlogin session, not really important in security.
if(isset($_SESSION['guestlogin']))
{
$GuestUsernick=$_SESSION['guestlogin'];
return $GuestUsernick;
}else
{
// N_V- none of them exist, then lets return false
return false;
}
}
}

function LoggedInUser($username,$password,$guestlogin,$remember){
global $MinUserlength,$MaxUserlength,$MinPasslength,$connect,$DataBaseName;
// N_V- check if connected.
if($connect)
{
// N_V- check if user is a guest to the system, if not ticked the box then he has a password
if($guestlogin != TRUE)
{
if(!empty($password))
{
/*If magic_quotes_gpc is enabled (good Idea, php.ini), first apply stripslashes() to the data.
Using this function on data which has already been escaped will escape the data twice. */
$username=mysql_real_escape_string(stripslashes($username));
$password=mysql_real_escape_string(stripslashes($password));// N_V- not needed we only checking $username var
$remember=mysql_real_escape_string(stripslashes($remember));// N_V- not needed
mysql_select_db($DataBaseName, $connect);
$query = "SELECT * FROM $DataBaseName WHERE username='$username'";
$result= mysql_query($query);
// N_V- check is a username exist in database, if not give then an error
// N_V- otherwise he wouldnt get any response from script, because the username doesnt exist..
if(mysql_num_rows($result) < 1)
{
// N_V- lets give it a simple error if no username exist, no more info to them.
echo '<p id="error">Sorry username and or password are incorrept.</p>';
}
// N_V- lets iterate tru users table and return it into array.
while($row=mysql_fetch_array($result)){
// N_V- lets put the array results in variables for easy understanding, I like simple stuff
$sqlUsername=$row['username'];
$sqlhashedname=$row['hashedname'];
$sqlEncryptedPass=$row['password'];
$sqluserID=$row['ID'];
// N_V- lets compare the password we got from form, double hash it and salt it..
$password=sha1(sha1($password).$row['salted']);
// N_V- then compare the one we got when we registered..
if($password == $sqlEncryptedPass)
{
// N_V- check if remember box is ticked and put it then in cookies
// N_V- I have problems with cookie errors, can write cookie because header is already sent..
// N_V- in the meantime, phpfreechat dont like other thing but session cookies, so wont do.
/*if($remember == TRUE){
$time=time()+3600000*24;
$username=$sqlUsername;
$hasedname=$sqlhashedname;
setcookie("userlogged",$username,$time);
setcookie("hashed",$hasedname,$time);
}else{*/
// N_V- here we put it in the session
$_SESSION['loggeduser']=$sqlUsername;
$_SESSION['hashedname']=$sqlhashedname;
$_SESSION['ID']=$sqluserID;
mysql_close($connect);
echo "<script>location.href='../'</script>";
//echo "<p id=\"okgo\">Corrept you are logged_in now <span class=\"highlight\">$sqlUsername</span>.</p>";
// N_V- bracket part of the $remember if}
}else{
// N_V- error the pass doesnt match really..
echo '<p id="error">Sorry username and or password are incorrept.</p>';
mysql_close($connect);
}
}
}else{
echo'<p id="error">Please fill up the password field.</p>';
}
}else{
// N_V- if he thicked he is trying to be guest, lets check username is registered already.
if(!IfUserExist($username)){
if(strlen($username) >= $MinUserlength){
if(strlen($username) <= $MaxUserlength){
$username=htmlentities(stripslashes($username));
// N_V- we dont want this again rigth even if he is a guest.
$NotwantedStrings=array(
',','`','|','~','!','#','$','%','^','&','*','(',')','-','+','{','}','[',']','?','@','.','<','>','='
);
$ReplacewithString='_';
$username=filter_var(str_replace($NotwantedStrings,$ReplacewithString,$username),FILTER_SANITIZE_STRING);
$_SESSION['guestlogin']="[$username]";// N_V- [] prefix so we identify this guest..
$guestlogin=$_SESSION['guestlogin'];
echo "<script>location.href='../'</script>";
// echo "<p id=\"okgo\">Corrept you are logged_in now <span class=\"highlight\">$guestlogin</span>.</p>";
}else{
echo "<p id=\"error\">Guest login nikname is too long, please choose a shorter one less than $MaxUserlength words..</p>";
}
}else{
echo "<p id=\"error\">Guest login nikname is too short, please choose one of at least $MinUserlength words..</p>";
}
}else{
echo '<p id="error">Sorry cant use that nickname.</p>';
}
}
}else
{
// N_V- connection problem we die and then tell the user.
die('<p id="error">Error: </p>' . mysql_error());
}
}

function IfUserExist($username){
// N_V- lets call the database.
global $connect,$DataBaseName;
// N_V- check if connected.
if($connect)
{
$username=mysql_real_escape_string(stripslashes($username));
mysql_select_db($DataBaseName, $connect);
$query = "SELECT username FROM $DataBaseName WHERE username='$username'";
$result= mysql_query($query);
if(mysql_num_rows($result) > 0)
{
return true;
mysql_close($connect);
}else{
return false;
}
}else{
die('<p id="error">Error: </p>' . mysql_error());
}
}

function IfEmailExist($email){
// N_V- lets call the database.
global $connect,$DataBaseName;
// N_V- check if connected.
if($connect)
{
$email=mysql_real_escape_string(stripslashes($email));
mysql_select_db($DataBaseName, $connect);
$query = "SELECT email FROM $DataBaseName WHERE email='$email'";
$result= mysql_query($query);
if(mysql_num_rows($result) > 0)
{
return true;
mysql_close($connect);
}else{
return false;
}
}else{
die('<p id="error">Error: </p>' . mysql_error());
}
}

function RegisterUser($username, $password, $email){
global $MinUserlength,$MaxUserlength,$MinPasslength,$connect,$DataBaseName;;
$salted=saltedPass();

// N_V- check if connected.
if($connect)
{
// N_V- minimun username length is checked here
if(strlen($username) >= $MinUserlength)
{
if(strlen($username) <= $MaxUserlength)
{
// N_V- minimun password length is checked here
if(strlen($password) >= $MinPasslength)
{
// N_V- check if email exist here
if(!IfEmailExist($email))
{
// N_V- check if username exist here
if(!IfUserExist($username))
{
// N_V- lets clean up a litle bit,check for hacking attempts and mysql injection on username,password and email.
$username =mysql_real_escape_string(stripslashes($username));
$password=mysql_real_escape_string(stripslashes($password));
// N_V- We dont want this string in the usernick rigth?
$NotwantedStrings=array(
',','`','|','~','!','#','$','%','^','&','*','(',')','-','+','{','}','[',']','?','@','.','<','>','='
);
$ReplacewithString='_';
$username=filter_var(str_replace($NotwantedStrings,$ReplacewithString,$username),FILTER_SANITIZE_STRING);
$hashedname=sha1($username);
$email=mysql_real_escape_string(stripslashes($email));
// N_V-lets encrypt form input password and username
$hashedname=sha1(sha1($username).$salted);
$password= sha1(sha1($password).$salted);

// N_V- once cleaned lets insert it into database
mysql_select_db($DataBaseName, $connect);
$SqlWrite=mysql_query("INSERT INTO $DataBaseName(username,hashedname,password,salted,email)
VALUES('$username','$hashedname','$password','$salted','$email')");
if (!$SqlWrite)
{
die('<p id="error">Error: </p>' . mysql_error());
}
mysql_close($connect);
// N_V- once register is susscess send them to the login page.
echo "<script>location.href='./login.php'</script>";
echo "<p id=\"okgo\">You have been registered sussefuly <span class=\"highlight\">$username</span>.</p>";
}else{
echo "<p id=\"error\">Sorry <span class=\"highlight\">$username</span> is registered already..</p>";
}
}else{
echo "<p id=\"error\">Sorry the email: <span class=\"highlight\">$email</span> is already in use..</p>";
}
}else{
echo "<p id=\"error\">Choose a password at least <span class=\"highlight\">$MinPasslength</span> word long please!..</p>";
}
}else{
echo "<p id=\"error\">Your username cannot be more that <span class=\"highlight\">$MaxUserlength</span> characters!</p>";
}
}else{
echo "<p id=\"error\">Choose a username at least <span class=\"highlight\">$MinUserlength</span> word long please!..</p>";
}
}else
{
die('<p id="error">Error: </p>' . mysql_error());
}
}

function saltedPass(){
$salted = '';
// N_V-lets create our 3 words salt.
for ($i = 0; $i < 3; $i++)
{
$salted .= chr(rand(35, 126));
}
return $salted;
}
?>

register.php

<?php
require_once('functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $rftitle; ?></title>
<link rel="stylesheet" href="login.css" type="text/css" />
</head>
<body>
<div id="register_form">
<form class="register_form" action="register.php" method="post">
<h5 class="welcome"><?php echo $rfH5title; ?></h5>
<span class="rform"><?php echo $rfnick; ?></span> <input type="text" name="username" />
<br />
<span class="rform"><?php echo $rfpass; ?><span> <input type="password"  name="password" />
<br />
<span class="rform"><?php echo $rfrpass; ?><span> <input type="password" name="repassword" />
<br />
<span class="rform"><?php echo $rfmail; ?></span> <input type="text" name="email" />
<br />
<?php echo $rfrfield; ?>
<input type="submit" value="Submit" />
<input type="hidden" name="submitted" value="true" />
<?php echo $rfp; ?>
<?php
// N_V- lets put all Post array in variables for easy understanding
$username=trim($_POST['username']);
$password=trim($_POST['password']);
$repassword=trim($_POST['repassword']);
$email=trim($_POST['email']);
if($_POST['submitted'] == "true")
{
if(empty($username))
{
echo '<p id="error">Please fill up the username field.</p>';
}elseif(empty($password)){
echo'<p id="error">Please fill up the password field.</p>';
}elseif(empty($repassword)){
echo'<p id="error">Please fill up the repassword field.</p>';
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo '<p id="error">E-mail, is invalid.</p>';
}
// N_V- check if password match, could also been done in the RegisterUser function
elseif($password != $repassword){
echo '<p id="error">The password doesnt match, please retype it again!!</p>';
}else{
RegisterUser($username, $password, $email);
}
}
?>
<?php echo $phpfreechatlogo; ?>
</form>
</div>
</body>
</html>

login.php

<?php
require_once('functions.php');
if(isset($_SESSION['loggeduser']) OR ($_SESSION['guestlogin'])){setcookie(session_name(), '', time()-42000, '/');}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $lftitle; ?></title>
<link rel="stylesheet" href="login.css" type="text/css" />
</head>
<body>
<div id="login_form">
<form class="login_form" action="<?php $PHP_SELF; ?>" method="post">
<h5 class="welcome"><?php echo $lfH5title; ?></h5>
<span class="lform"><?php echo $lfnick ;?></span> <input type="text" name="username" />
<br />
<span class="lform"><?php echo $lfpass; ?></span> <input type="password" name="password" />
<br />
<?php if($guestlogin){
echo "<span class=\"lform\">$lfguest</span><input type=\"checkbox\" name=\"guestlogin\" value=\"$guestlogin\" /><br />";
$guestlogin=trim($_POST['guestlogin']);
} ?>
<input type="hidden" name="submitted" value="true" />
<input type="submit" value="Submit" />
<?php echo $lfp; ?>

<?php
$username=trim($_POST['username']);
$password=trim($_POST['password']);
$remember=trim($_POST['remember']);

if($_POST['submitted'] == "true")
{
if(empty($username)){
echo'<p id="error">Please fill up the username field.</p>';
}else{
LoggedInUser($username, $password,$guestlogin,$remember);
}
}
?>
<?php echo $phpfreechatlogo; ?>
<form>
</div>
</body>
</html>

login.css

/*
*Created by Neu Valle Aka utan, re*s.t.a.r.s.*2
*This is the css for the login and registration form
*/
#error{
color:red;
}
#okgo{
color:#666699;
}
.w-h{
color:#CCFF99;
font-size:13px;
}
.w-p{
color:#FFFF66;
font-size:12px;
}
.highlight{
color:blue;
font-size:14px;
}
.rform{
color:#9966FF;
font-size:13px;
}
.lform{
color:#9966FF;
font-size:13px;
}
body{
background-color:#330000;
background-image:url('./img/dgren002.jpg');
padding:0;
margin:0;
}
.welcome{
text-align:center;
color:#666699;
}
/*style for Registration form*/

#register_form{
background-color:#330000;
background-image:url('./img/dgren007.jpg');
position:absolute;
*height:400px;
top:50px;
left:430px;

}
.register_form{
border: 1px solid #666699;
padding: 5px;
*height:390px;
width:150px;
}
.register_form input{
}
.register_form p{
font-size:12.5px;
color:#666699;
}
.register_form a{
text-decoration:none;
font-size:12px;
color:#666699;
}
.register_form a:hover{
color:#FF6666;
text-decoration:underline;
}
.phpfreechatlogo{
background-image:url('./img/logo2_80x15.png');
margin-left:70px;

}
/*style for login form*/
#login_form{
background-color:#330000;
background-image:url('./img/dgren007.jpg');
position:absolute;
top:50px;
left:430px;
}
.login_form{
border: 1px solid #666699;
padding: 5px;
width:150px;
}
.login_form input{
}
.login_form p{
font-size:12.5px;
color:#666699;
}
.login_form a{
text-decoration:none;
font-size:12px;
color:#666699;
}
.login_form a:hover{
color:#FF6666;
text-decoration:underline;
}

index.phpfreechat to be renamed for index.php and placed in /chat

<?php
require_once('./login/functions.php');
require_once dirname(__FILE__)."/src/phpfreechat.class.php";
// we get from function IsAuthorized() the nick that the session holds
// dont discriminate between both guest and registered.
if(IsAuthorized()){$phpfreechatnick=IsAuthorized();}else{header('Location:./login/login.php');}
$params = array();
$params["title"] =$ChatTitle;
$params['channels']=$ChatChannel;
$params["nick"] =$phpfreechatnick;  // setup the intitial nickname
if(!isset($_SESSION['guestlogin']) && ($phpfreechatnick == $administrator)){$params["isadmin"] = TRUE;}
$params["height"] = "$ChatHeight.px";
$params["frozen_nick"] =$frozen_nick;
$params["max_nick_len"] = $maxnicklen;
$params["max_msg"] = $maxmessage;
$params["max_displayed_lines"] = $maxdisplaylines;
$params["short_url"] = $shorturl;
$params["short_url_width"] = $shorturlwidth;
$params['clock'] = $showclock;
$params['theme']= $ChatTheme;
$params['firstisadmin'] =FALSE;
//$params["isadmin"] = true; // makes everybody admin: do not use it on production servers ;)
$params["serverid"] = md5(__FILE__); // calculate a unique id for this chat
$params["debug"] = false;
$chat = new phpFreeChat( $params );

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo $params["title"]; ?></title>
<link rel="stylesheet" title="classic" type="text/css" href="style/generic.css" />
<link rel="stylesheet" title="classic" type="text/css" href="style/header.css" />
<link rel="stylesheet" title="classic" type="text/css" href="style/footer.css" />
<link rel="stylesheet" title="classic" type="text/css" href="style/menu.css" />
<link rel="stylesheet" title="classic" type="text/css" href="style/content.css" />
<link rel="stylesheet" title="classic" type="text/css" href="./login/login.css" />
</head>
<body>

<div class="header">
<img alt="phpFreeChat" src="style/logo.gif" class="logo2" />
</div>

<div class="menu">
<div style="background-color:#669933;">
<p class="sub title"><?php echo $phpfreechatnick; ?></p>
<?php if(!isset($_SESSION['loggeduser'])){
echo "<h4 class=\"w-h\">Welcome $phpfreechatnick</h4>";
echo '<p class="w-p">You are in the chat as guest.</p>';
echo '<p class="w-p">Please <a href="./login/login.php" onclick="pfc.connect_disconnect()">Login</a></p>';
}else{
echo "<h4 class=\"w-h\">Welcome $phpfreechatnick</h4>";
echo '<p class="w-p">Thank you enjoy the chat.. <a href="./login/login.php" onclick="pfc.connect_disconnect()" >Logout</a></p>';
}
?>
</div>
<ul>
<li class="sub title">General</li>
<li>
<ul class="sub">
<li class="item">
<a href="">Demos</a>
</li>
<?php if (file_exists(dirname(__FILE__)."/checkmd5.php")) { ?>
<li>
<a href="">Check md5</a>
</li>
<?php } ?>
<!--
<li class="item">
<a href="admin/">Administration</a>
</li>
-->
</ul>
</li>
<li class="sub title">Documentation</li>
<li>
<ul>
<li class="item">
<a href="">Overview</a>
</li>
<li class="item">
<a href="">Quickstart</a>
</li>
<li class="item">
<a href="">Parameters list</a>
</li>
<li class="item">
<a href="">FAQ</a>
</li>
<li class="item">
<a href="">Advanced configuration</a>
</li>
<li class="item">
<a href="">Customize</a>
</li>
</ul>
</li>
</ul>
<p class="partner">
<a href="http://www.phpfreechat.net"><img alt="phpfreechat.net" src="style/logo_88x31.gif" /></a><br/>
</p>
</div>

<div class="content">
<?php $chat->printChat(); ?>
</div>

<div class="footer">
<span class="partners">phpFreeChat partners:</span>
<a href="">jeux gratuits</a> |
<a href="">jeux flash</a> |
<a href="">pronofun</a> |
<a href="">areno</a> |
<a href="">micropolia</a> |
<a href="">zeitoun</a> |
<a href="">federation</a>
</div>

</body></html>