<?php
/* phpemailuser by georgfly
* Desc: Main application script for the User Login
* application. It provides two options: (1) login
* using an existing User Name and (2) register
* a new user name. User Names and passwords are
* stored in a MySQL database.
*/
session_start();
include("config.inc.php");
include("login_reg_functions.php");
/* debug */
/*
echo "<pre>";
print_r(@$_POST);
echo "</pre>";
*/
switch (@$_POST['resendlink']) {
case "resendpass":
$resendpass = true;
include("login_reg_form.inc.php");
exit;
break;
case "resendact":
$resendact = true;
include("login_reg_form.inc.php");
exit;
break;
}
switch (@$_POST['Button']) {
case "Login":
$fuseremail = $_POST['fuseremail'];
$fpassword = $_POST['fpassword'];
// check if valid email address
if(!preg_match($fieldnames['user_email'][3],$fuseremail) || !isValidEmail($fuseremail)) {
// admin? only numbers and letters allowed
if (preg_match("/^[0-9A-Za-z]{1,50}$/",$fuseremail)) {
// check db if this is a valid admin
$fuseremail = strip_tags(trim($fuseremail));
$cxn = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$mysqldb)
or die("Query died: connect");
$sql = "SELECT * FROM useradmin
WHERE adname='".mysqli_real_escape_string($cxn,$fuseremail)."'
AND password=md5('$fpassword')";
$result = mysqli_query($cxn,$sql)
or die("Query died: admin");
$num = mysqli_num_rows($result);
if ($num==1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['auth']="yes";
$_SESSION['uaid']=$row['uaid'];
$_SESSION['logadminname'] = $fuseremail;
header("Location: login_reg_admin.php");
}
else {
$message_1 = "Bad Email address.";
include("login_reg_form.inc.php");
}
}
else {
$message_1 = "Bad Email address.";
include("login_reg_form.inc.php");
}
}
else {
$fuseremail = strip_tags(trim($fuseremail));
$cxn = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$mysqldb)
or die("Query died: connect");
$sql = "SELECT uid, user_email, loginattempts, lastlogin_date FROM user
WHERE user_email='".mysqli_real_escape_string($cxn,$fuseremail)."'";
$result = mysqli_query($cxn,$sql)
or die("Query died: email");
$num = mysqli_num_rows($result);
if($num > 0) {
// find out if we are within a login-failure timout & allowedattempts is reached; if yes => kick user out with message
$row = mysqli_fetch_assoc($result);
$uid = $row['uid'];
$lastlogin_date = strtotime($row['lastlogin_date']);
$loginattempts = $row['loginattempts'];
$timediff = (time() - $lastlogin_date)/60;
if ($timediff <= $loginfailtimeout && $loginattempts >= $allowedattempts && $enableattemptlimit){
$message_1 = "You exceeded the number of allowed failed login attempts. Please wait ".ceil($loginfailtimeout-$timediff)." minutes before trying again.";
session_destroy();
include("login_reg_form.inc.php");
}
else {
// check if password is ok
$sql = "SELECT activated, blocked FROM user
WHERE uid=$uid AND password=md5('$fpassword')";
$result2 = mysqli_query($cxn,$sql)
or die("Query died: fpassword");
$num2 = mysqli_num_rows($result2);
$row2 = mysqli_fetch_assoc($result2);
if($num2 > 0) //password matches
{
if ($row2['activated'] != 1)
{
$message_1="Your account is not yet activated!";
session_destroy();
include("login_reg_form.inc.php");
}
elseif ($row2['blocked'] == 1)
{
$message_1 = $blockedwarning;
session_destroy();
include("login_reg_form.inc.php");
}
else // everything is ok
{
// set loginattempts to zero
$sql = "update user set loginattempts=0 where uid=$uid";
$result3 = mysqli_query($cxn,$sql)
or die ("Query died: reset loginattempts");
$_SESSION['auth']="yes";
$_SESSION['uid']=$uid;
$_SESSION['logname'] = $fuseremail;
header("Location: $startpage");
}
}
// password does not match and we have attemptlimit enabled
elseif ($enableattemptlimit) {
// find out if we are within a timeout period
// if yes and we have already had attempts ($loginattempts > 0) => count up attempts
// else (either not in timeout period, or this is our first new attempt ($loginattempt = 0) => start counting from one again, update last login attempt to current timestamp
// in any case: message
if ($timediff <= $loginfailtimeout && $loginattempts > 0){
$loginattempts++;
$sql = "update user set loginattempts=$loginattempts where uid=$uid";
$result3 = mysqli_query($cxn,$sql)
or die ("Query died: count up loginattempts");
} else {
$loginattempts = 1;
$today = date("Y-m-d H:i:s");
$sql = "update user set loginattempts=$loginattempts, lastlogin_date='$today' where uid=$uid";
$result3 = mysqli_query($cxn,$sql)
or die ("Query died: restart loginattempts");
}
if ($loginattempts >= $allowedattempts) {
$message_1="Wrong password! You had $loginattempts failed login attempts. Your account will be accessible again in ".ceil($loginfailtimeout-$timediff)." minutes.";
} else {
$message_1="Wrong password! The total number of allowed failed login attempts is $allowedattempts. After that, your account will be blocked for ".$loginfailtimeout." minutes.";
}
include("login_reg_form.inc.php");
// password does not match and we have attemptlimit disabled
} else {
$message_1="Wrong password!";
include("login_reg_form.inc.php");
}
}
} // end if $num > 0
elseif($num == 0) // login name not found
{
$message_1 = "The Email address you entered does not
exist!";
include("login_reg_form.inc.php");
}
}
break;
//---------------------------------------------------------
case "Register":
/* Check for blanks */
foreach($_POST as $field => $value)
{
// check if this is one of our specified fields (excludes buttons, passwordrep)
if (isset($fieldnames[$field]))
{
if ($field != 'password')
$strippedpost[$field] = strip_tags(trim($value));
else $strippedpost[$field] = trim($value);
if ($fieldnames[$field][2] == "yes")
{
if (empty($value))
{
$blanks[] = $fieldnames[$field][0];
}
else
{
$good_data[$field] = $strippedpost[$field];
}
}
}
} // end foreach POST
if(isset($blanks))
{
$message_2 = "The following fields are blank.
Please enter the required information: ";
foreach($blanks as $value)
{
$message_2 .="$value, ";
}
$message_2 = trim ($message_2, ', ');
//extract($good_data);
include("login_reg_form.inc.php");
exit();
} // end if blanks found
// check captcha
if ($inclmathcaptcha){
if (empty($_POST['nobots']) || empty($_POST['nobotsresult']) || md5(trim($_POST['nobots'])) != $_POST['nobotsresult']){
$message_2 = "Error. Please enter the correct result for the maths question (last field, enter as number, not letters).";
include("login_reg_form.inc.php");
exit();
}
}
/* validate data = sanitize with preg_match */
foreach($strippedpost as $field => $value){
if(!empty($value)){
if (!preg_match($fieldnames[$field][3], $value)){
$errors[] = "$value is not a valid entry for ".$fieldnames[$field][0];
}
elseif ($field == "user_email"){
if (!isValidEmail($value)){
$errors[] = "$value is not a valid entry for ".$fieldnames[$field][0];
}
}
} // end if not empty
} // end foreach POST
if(@is_array($errors))
{
$message_2 = "";
foreach($errors as $value)
{
$message_2 .= $value."<br>";
}
include("login_reg_form.inc.php");
exit();
} // end if errors are found
/* check to see if user name already exists */
$cxn = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$mysqldb)
or die("Couldn't connect to server");
$sql = "SELECT user_email FROM user
WHERE user_email='".mysqli_real_escape_string($cxn,$strippedpost['user_email'])."'";
$result = mysqli_query($cxn,$sql)
or die("Query died: user_email.");
$num = mysqli_num_rows($result);
if($num > 0) {
$message_2 = "$strippedpost[user_email] is already registered";
include("login_reg_form.inc.php");
exit();
} // end if user email already exists
/* check if password == passwordrep */
if ($strippedpost['password'] != @$_POST['passwordrep']) {
$message_2 = "Passwords don't match.";
include("login_reg_form.inc.php");
exit();
}
// check password length
elseif (strlen($strippedpost['password']) < $minpasslen){
$message_2 = "The password has to be at least $minpasslen characters long.";
include("login_reg_form.inc.php");
exit();
}
else
{
// insert data in database
// first into db user
$today = date("Y-m-d H:i:s");
$actkey = md5(randomword(10) . time());
$activated = abs($needactivation-1);
$tablecols = mysqli_get_colnames($cxn,'user');
$sql1 = "";
$sql2 = "";
foreach($strippedpost as $field => $value){
foreach($tablecols as $col){
if ($field == $col){
$sql1 .= "$field,";
if ($field == "password"){
$sql2 .= "md5('$value'),";
} else {
$sql2 .= "'".mysqli_real_escape_string($cxn,$value)."',";
}
break;
}
}
}
$sql = "INSERT INTO user (".$sql1."create_date,activated,actkey,actkey_date,userlevel,blocked,loginattempts,lastlogin_date)
VALUES (".$sql2."'$today',$activated,'$actkey','$today',1,0,0,'$today')";
$result = mysqli_query($cxn,$sql)
or die ("Query died: insert data.");
$uid = mysqli_insert_id($cxn);
// and now insert data into db userdata
$tablecols2 = mysqli_get_colnames($cxn,'userdata');
$sql1 = "";
$sql2 = "";
foreach($strippedpost as $field => $value){
foreach($tablecols2 as $col){
if ($field == $col){
$sql1 .= "$field,";
if ($field == "password"){
$sql2 .= "md5('$value'),";
} else {
$sql2 .= "'".mysqli_real_escape_string($cxn,$value)."',";
}
break;
}
}
}
$sql = "INSERT INTO userdata (".$sql1."uid)
VALUES (".$sql2.$uid.")";
$result = mysqli_query($cxn,$sql)
or die ("Query died: insert data.");
/* send email to new user */
$emess = "You have successfully registered at $sitename.<br>\n";
if ($needactivation)
{
$emess .= "You still need to activate your account:
<a href=\"$dirurl/login_reg_act.php?ak=$actkey&ud=$uid\">CLICK THIS LINK</a><br>\n";
$emess .= "or paste this link into your browser's address bar:<br>$dirurl/login_reg_act.php?ak=$actkey&ud=$uid<br>\n";
$emess .= "This link expires after $activationkeyexpire hours.<br><br>\n\n";
}
//$emess .= "Your password is:<br>\n";
//$emess .= "$strippedpost[password]<br><br>\n\n";
$emess .= "We appreciate your interest.";
$subj = "Your registration at $sitename";
$headers = "From: $sitename <$sendfromemail>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
mail($strippedpost['user_email'], $subj, $emess, $headers);
if (!$needactivation)
{
$_SESSION['auth']="yes";
$_SESSION['uid']=$uid;
$_SESSION['logname'] = $strippedpost['user_email'];
header("Location: $startpage");
}
else
{
$message_1 = "We have sent you an email containing a link to activate your accout.<br>The link expires after $activationkeyexpire hours.";
$unsetfields = true;
include("login_reg_form.inc.php");
exit();
}
} // end else no errors found
break;
case ("Send me a new password" || "Send me a new activation link"):
$fuseremail = $_POST['fuseremail'];
// check captcha
if ($inclmathcaptcha && md5(trim($_POST['nobots'])) != $_POST['nobotsresult']){
$message_1 = "Error. Please enter the correct result for the maths question (as number, not letters).";
$resendpass = true;
}
elseif(!preg_match($fieldnames['user_email'][3],$fuseremail) || !isValidEmail($fuseremail))
{
$resendpass = true;
$message_1 = "Bad Email address.";
}
else
{
$fuseremail = strip_tags(trim($fuseremail));
$cxn = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$mysqldb)
or die("Query died: connect");
$sql = "SELECT uid, user_email, activated, blocked FROM user
WHERE user_email='".mysqli_real_escape_string($cxn,$fuseremail)."'";
$result = mysqli_query($cxn,$sql)
or die("Query died: email");
$num = mysqli_num_rows($result);
if($num > 0)
{
$row = mysqli_fetch_assoc($result);
$uid = $row['uid'];
if ($row['blocked'] == 1)
{
$message_1 = $blockedwarning;
}
elseif ($_POST['Button'] == "Send me a new activation link")
{
if ($row['activated'] == 1)
{
$message_1 = "Your account is already activated.";
}
else
{
$actkey = md5(randomword(1) . time());
$today = date("Y-m-d H:i:s");
$sql = "UPDATE user SET actkey='$actkey',actkey_date='$today' WHERE user_email='".mysqli_real_escape_string($cxn,$fuseremail)."'";
$update = mysqli_query($cxn,$sql)
or die("Query died: email");
$emess = "You requested a new activation link.<br><br>";
$emess .= "<a href=\"$dirurl/login_reg_act.php?ak=$actkey&ud=$uid\">CLICK THIS LINK</a><br>\n";
$emess .= "or paste this link into your browser's address bar:<br>$dirurl/login_reg_act.php?ak=$actkey&ud=$uid<br>\n";
$emess .= "This link expires after $activationkeyexpire hours.";
$subj = "Your new activation link for $sitename";
$headers = "From: $sitename <$sendfromemail>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
mail($fuseremail, $subj, $emess, $headers);
$message_1 = "We have sent you an email containing a link to activate your accout.<br>The link expires after $activationkeyexpire hours.";
}
}
else //resend password
{
// change password, send new password
$newpass = randomword(8);
$sql = "UPDATE user SET password = md5('$newpass') WHERE user_email='".mysqli_real_escape_string($cxn,$fuseremail)."'";
$update = mysqli_query($cxn,$sql)
or die("Query died: email");
$emess = "You requested a new password.<br><br>";
$emess .= "Your new password is:<br>\n";
$emess .= "$newpass<br><br>\n\n";
$emess .= "You can change this password after you log in.";
$subj = "Your new password for $sitename";
$headers = "From: $sitename <$sendfromemail>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
mail($fuseremail, $subj, $emess, $headers);
$message_1 = "We have sent you a new passord. You can change this password after you log in.";
}
} // end if $num > 0
elseif($num == 0) // login name not found
{
$resendpass = true;
$message_1 = "The Email address you entered does not
exist!";
}
}
include("login_reg_form.inc.php");
break;
default:
include("login_reg_form.inc.php");
} // end switch
?>