<?php
// login.php
// RJM Programming
// May, 2015
// Thanks to PHP and MySql Web Development by Luke Welling, Laura Thomson
// Thanks to Professional PHP Programming by Jesus Castagnetto, Haeish Rawat, Sascha Schumann, Chris Scollo, Deepak Veliath ... chapter 20
include "db_connect.php";

$ut="registered";
$msg="";
$captcha_bit="
<p><img src='captcha.php' width='120' height='30' border='1' alt='CAPTCHA'></p>
<p><input type='text' size='6' maxlength='5' name='captcha' value=''><br>
<small>copy the digits from the image into this box</small></p>
";
$more="";
$nextpage="member.php";
$nextval="Member Page";
$backtostr="";
$backtoonload="";
$dbname="users";
$utable="rusers"; //"musers";
$ucolumn="username";


function get_random_word($min_length, $max_length) {
// grab a random word from dictionary between the two lengths
// and return it

   // generate a random word
  $word = '';
  // remember to change this path to suit your system
  $dictionary = '/usr/share/dict/words';  // the ispell dictionary
  $fp = @fopen($dictionary, 'r');
  if(!$fp) {
    if ($_SERVER['SERVER_PORT'] == "youllneverfindthis8888") {
    return "pork";
    } else {
    return false;
    }
  }
  $size = filesize($dictionary);

  // go to a random location in dictionary
  $rand_location = rand(0, $size);
  fseek($fp, $rand_location);

  // get the next whole word of the right length in the file
  while ((strlen($word) < $min_length) || (strlen($word)>$max_length) || (strstr($word, "'"))) {
     if (feof($fp)) {
        fseek($fp, 0);        // if at end, go to start
     }
     $word = fgets($fp, 80);  // skip first word as it could be partial
     $word = fgets($fp, 80);  // the potential password
  }
  $word = trim($word); // trim the trailing \n from fgets
  return $word;
}

function reset_password($username) {
  global $utable, $msg;
// set password for username to a random value
// return the new password or false on failure
  // get a random dictionary word b/w 6 and 13 chars in length
  $new_password = get_random_word(6, 13);

  if($new_password == false) {
    $msg='Could not generate new password.';
    throw new Exception('Could not generate new password.');
  }

  // add a number  between 0 and 999 to it
  // to make it a slightly better password
  $rand_number = rand(0, 999);
  $new_password .= $rand_number;

  // set user's password to this in database or return false
  $conn = db_connect();
  $result = mysql_query("update " . $utable . " 
                          set password = sha1('".$new_password."')
                          where username = '".$username."'");
  if (!$result) {
    $msg='Could not change password.';
    throw new Exception('Could not change password.');  // not changed
  } else {
    return $new_password;  // changed successfully
  }
}



function notify_password($username, $password) {
// notify the user that their password has been changed
    global $utable, $msg;

    $conn = db_connect();
    $result = mysql_query("select * from " . $utable . " 
                            where username='".$username."'");
    if (!$result) {
      $msg='Could not find email address.';
      throw new Exception('Could not find email address.');
    } else if (mysql_num_rows($result) == 0) {
      $msg='Could not find email address.';
      throw new Exception('Could not find email address.');
      // username not in db
    } else {
      $row = mysql_fetch_row($result, MYSQL_NUM);
      $email = $row[2];
      $from = "From: rmetcalfe@rjmprogramming.com.au \r\n";
      $mesg = "Your Things That We Have in Common password has been changed to ".$password."\r\n";
              

      if (mail($email, 'Things That We Have in Common login information', $mesg, $from)) {
        return true;
      } else {
        $msg='Could not send email.';
        throw new Exception('Could not send email.');
      }
    }
}

if (isset($_POST['username']) || isset($_POST['rusername']) || isset($_POST['fusername'])) {
  session_start();
  if ($_POST['captcha'] != $_SESSION['digit']) {
   $msg="Sorry, the CAPTCHA code entered was incorrect!";
  } else if (isset($_POST['rusername'])) {
   insertuser();
  } else if (isset($_POST['fusername'])) {
   $nextpage="login.php";
   $nextval="Login Page";
   $fusername = $_POST['fusername'];
   try {
    $fpassword = reset_password($fusername);
    try {
     notify_password($fusername, $fpassword);
     $msg="Your new password has been emailed to you.";
    } catch (Exception $ee1) {
     $msg="Your password could not be notified - please try again later.";
    }
   } catch (Exception $ee2) {
    $msg="Your password could not be notified - please try again later.";
   }
  }
  session_destroy();
} 
session_start();


if( isset( $_GET['utable'] ) ) {
  $utable=$_GET['utable'];
}
if( isset( $_POST['utable'] ) ) {
  $utable=$_POST['utable'];
}
if( isset( $_GET['dbname'] ) ) {
  $dbname=$_GET['dbname'];
}
if( isset( $_POST['dbname'] ) ) {
  $dbname=$_POST['dbname'];
}
if( isset( $_GET['ucolumn'] ) ) {
  $ucolumn=$_GET['ucolumn'];
}
if( isset( $_POST['ucolumn'] ) ) {
  $ucolumn=$_POST['ucolumn'];
}

function insertuser() {
  global $dbname, $link, $utable;
  $pusername="";
  if ( isset( $_POST['rusername'] ) ) {
    $pusername=urldecode($_POST['rusername']);
  }
  $ppassword="";
  if ( isset( $_POST['rpassword'] ) ) {
    $ppassword=urldecode($_POST['rpassword']);
  }
  $remail="";
  if ( isset( $_POST['email'] ) ) {
    $remail=urldecode($_POST['email']);
  }
  $pstatus="registered";
  if ( isset( $_POST['usertype'] ) ) {
    $pstatus=urldecode($_POST['usertype']);
  }
  try {
    if (!$link) $link = db_connect(); 
    if (!$link) {
       die('Could not connect: ' . mysql_error());
    }
    mysql_select_db($dbname);
    $result = mysql_query("insert into " . $utable . " values ('".$pusername."', '".$ppassword."', '".$remail."', '".$pstatus."')");
  } catch (Exception $e) {
    die('Could not connect: ' . mysql_error());
  }
}

if (!isset($_SERVER["PHP_AUTH_USER"]) && !isset($_GET['use401']) && !isset($_GET['donotuse401']) && !isset($_POST['donotuse401'])) {
    if (isset($_GET["backto"])) {
      echo "<!doctype html><html><body onload=\" document.getElementById('subm').click(); \"><form action='" . $_SERVER['PHP_SELF'] . "' method='post'><input type='hidden' name='backto' value='" . $_GET["backto"] . "'></input><input type='hidden' name='donotuse401' value='y'></input><input type='submit' id='subm' name='subm' value='Submit' style='display:none;'></input></form></body></html>";
    } else {
      echo "<!doctype html><html><body onload=\" document.getElementById('subm').click(); \"><form action='" . $_SERVER['PHP_SELF'] . "' method='post'><input type='hidden' name='donotuse401' value='y'></input><input type='submit' id='subm' name='subm' value='Submit' style='display:none;'></input></form></body></html>";
    }
    exit;
}

if( isset( $_GET['logout'] ) ) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF'] . '?' . urldecode($_GET['logout']));
    exit;
}

if( !isset( $_SESSION['login'] ) || isset($_GET['donotuse401']) || isset($_POST['donotuse401'])) { 
 if ((!isset($_SERVER["PHP_AUTH_USER"]) || isset($_GET['donotuse401']) || isset($_POST['donotuse401'])) && ($_GET['donotuse401'] != "form" && $_POST['donotuse401'] != "form")) { 

  if (isset($_GET['use401'])) {
   header("WWW-authenticate: basic realm=\"authorized usage\"");
   header("HTTP/1.0 401 Unauthorized");
   echo "Your username/password is incorrect ...";
   exit;
  } else {
   if ($msg == "") $msg="Please log in here:";
   if ($_GET['donotuse401'] == "Error") $msg="Cannot reach database.  Please log in here:";
   if ($_GET['donotuse401'] == "error") $msg="Wrong username/password.  Please log in here:";
   if ($_POST['donotuse401'] == "Error") $msg="Cannot reach database.  Please log in here:";
   if ($_POST['donotuse401'] == "error") $msg="Wrong username/password.  Please log in here:";
   if (isset($_GET["backto"])) {
    $backtostr='<input type="hidden" name="backto" value="' . $_GET["backto"] . '"></input>';
   } else if (isset($_POST["backto"])) {
    $backtostr='<input type="hidden" name="backto" value="' . $_POST["backto"] . '"></input>';
   }
   echo '<!doctype html><head><title>Registration or login</title><script type="text/javascript"> var alogin=null; var drego=null; var dlogin=null; var dforgot=null; var way="block"; var noway="none"; function atstart() { alogin=document.getElementById("alogin"); dforgot=document.getElementById("dforgot"); drego=document.getElementById("dregistration"); dlogin=document.getElementById("dlogin"); if (document.URL.indexOf("register=") != -1) { andthen();  } } 
   
 function andthen() {
      document.getElementById("aregistration").click();
 }  

 function checkForm(form) {
    if (!form.captcha.value.match(/^\d{5}$/)) {
      alert("Please enter the CAPTCHA digits in the box provided");
      form.captcha.focus();
      return false;
    }
    return true;
 }
   
 function checkForgot(form) {
    if (eval(form.fusername.value.length) < 6) {
      alert("Please enter valid username of at least 6 characters.");
      form.fusername.focus();
      return false;
    }
    if (!form.captcha.value.match(/^\d{5}$/)) {
      alert("Please enter the CAPTCHA digits in the box provided");
      form.captcha.focus();
      return false;
    }
    return true;
 }
   
 function checkRego(form) {
    if (eval(form.rusername.value.length) < 6) {
      alert("Please enter valid username of at least 6 characters.");
      form.rusername.focus();
      return false;
    }
    if (form.rpassword.value != form.spassword.value || eval(form.rpassword.value.length) < 6) {
      alert("Please have a password with at least 6 characters and repeat the password in the form.");
      form.rpassword.focus();
      return false;
    }
    if (form.email.value.indexOf("@") == -1 || form.email.value.indexOf(" ") != -1 || eval(form.email.value.length) == 0) {
      alert("Please enter valid email.");
      form.email.focus();
      return false;
    }
    if (form.usertype.value.indexOf("admin") != -1) {
      alert("Please choose a user type.");
      form.usertype.focus();
      return false;
    }
    if (!form.captcha.value.match(/^\d{5}$/)) {
      alert("Please enter the CAPTCHA digits in the box provided");
      form.captcha.focus();
      return false;
    }
    return true;
 }

   
   </script></head><body onload="document.getElementById(' . "'" . 'username' . "'" . ').focus(); atstart(); "><div id="dlogin" align="center">
   <form onsubmit="return checkForm(this);" action="' . $_SERVER['PHP_SELF'] . '" method="post">
   <input type="hidden" name="donotuse401" value="form"></input>' . $backtostr . '
   <table cellpadding="6" bgcolor="#cccccc" style="border:5px solid purple;">
   <tbody><tr>
     <td colspan="2">' . $msg . '</td>
   </tr><tr>
     <td>Username:</td>
     <td><input type="text" id="username" name="username"></td></tr>
   <tr>
     <td>Password:</td>
     <td><input type="password" name="password"></td></tr>
   <tr>
     <td align="center" colspan="2">
     <div data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-icon="null" data-iconpos="null" data-theme="c" aria-disabled="false"><span><span></span></span>' . $captcha_bit . '<input type="submit" value="Log in" aria-disabled="false"></div></td></tr>
   <!--tr>
   <td colspan="2"><a href="forgot.php" style="text-decoration:none;" class="ui-link"><figure style="TEXT-DECORATION:none;"><figcaption style="TEXT-DECORATION:none;">Forgot your password or other enquiry?</figcaption></figure></a></td>
   </tr-->
   </tbody></table></form><br><a id="aregistration" href="#dregistration" onclick=" drego.style.display=way; dlogin.style.display=noway; alogin.style.display=way; ">Register</a><br></div>
   <div align="center" id="dregistration" style="display:none;">
   <form id="fregistration" onsubmit="return checkRego(this);" action="' . $_SERVER['PHP_SELF'] . '" method="post">
   <input type="hidden" name="donotuse401" value="form"></input>' . $backtostr . '
   <table cellpadding="6" bgcolor="#cccccc" style="border:5px solid purple;">
   <tbody><tr>
     <td colspan="2">Please register here:</td>
   </tr><tr>
     <td>Username:</td>
     <td><input type="text" id="rusername" name="rusername"></td></tr>
   <tr>
     <td>Password:</td>
     <td><input type="password" name="rpassword" id="rpassword"></td></tr>
   <tr>
     <td>Password Again:</td>
     <td><input type="password" name="spassword" id="spassword"></td></tr>
   <tr>
     <td>Email:</td>
     <td><input type="email" name="email" id="email"></td></tr>
   <tr>
     <td>User Type:</td>
     <td><select name="usertype" id="usertype"><option value="admin">Please choose user type below ...</option><option value="registered">Registered</option><option value="subscriber">Subscriber</option></select></td></tr>
   <tr>
     <td align="center" colspan="2">
     <div data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-icon="null" data-iconpos="null" data-theme="c" aria-disabled="false"><span><span></span></span>' . $captcha_bit . '<input type="submit" value="Register" aria-disabled="false"></div></td></tr>
   </tbody></table></form></div>   
   <div align="center"><br><a id="aforgot" href="#dforgot" onclick=" dforgot.style.display=way; dlogin.style.display=noway; this.style.display=noway;  alogin.style.display=way; ">Forgot password?</a><br></div>
   <div align="center" id="dforgot" style="display:none;">
   <form id="fforgot" onsubmit="return checkForgot(this);" action="' . $_SERVER['PHP_SELF'] . '" method="post">
   <input type="hidden" name="donotuse401" value="form"></input>' . $backtostr . '
   <table bgcolor="#cccccc" style="border:5px solid purple;">
   <tr><td>Enter your username</td>
       <td><input type="text" name="fusername" size="16" maxlength="16" /></td>
   </tr>
   <tr><td colspan=2 align="center">
       ' . $captcha_bit . '<input type="submit" value="Change password" />
   </td></tr>
   </table></form></div>
   <div align="center"><br><a style="display:none;" id="alogin" href="' . $_SERVER['PHP_SELF'] . '">Login</a><br></div>
   </body></html>';
   exit;
   }
} else {  // check out the MySql database
  //include "db_connect.php";
  try {
    $link = db_connect(); 
    if (!$link) {
      if (isset($_GET['donotuse401']) || isset($_POST['donotuse401']) || !isset($_SERVER["PHP_AUTH_USER"])) {
       echo "<!doctype html><html><body onload=\" document.getElementById('subm').click(); \"><form action='" . $_SERVER['PHP_SELF'] . "' method='post'><input type='hidden' name='donotuse401' value='Error'></input><input type='submit' id='subm' name='subm' value='Submit' style='display:none;'></input></form></body></html>";
       exit;
      } else {
       die('Could not connect: ' . mysql_error());
      }
    }
    mysql_select_db($dbname);
  } catch (Exception $e) {
    if (isset($_GET['donotuse401']) || isset($_POST['donotuse401']) || !isset($_SERVER["PHP_AUTH_USER"])) {
     echo "<!doctype html><html><body onload=\" document.getElementById('subm').click(); \"><form action='" . $_SERVER['PHP_SELF'] . "' method='post'><input type='hidden' name='donotuse401' value='Error'></input><input type='submit' id='subm' name='subm' value='Submit' style='display:none;'></input></form></body></html>";
     exit;
    } else {
     die('Could not connect: ' . mysql_error());
    }
  }
  if (isset($_POST['username'])) {
   $username=strtolower(urldecode($_POST['username']));
  } else {
   $username=strtolower($_SERVER["PHP_AUTH_USER"]);
  }
  $result=mysql_query("SELECT * FROM " . $utable . " WHERE " . $ucolumn . "='" . $username . "'");
  $row=mysql_fetch_array($result, MYSQL_NUM);
  if (isset($_POST['username'])) {
   $ip=0;
   if ($row) {
     while ($row[$ip] != $username) {
      $ip++;
     }
    $ip++;
   }
   if (urldecode($_POST['password']) != $row[1]) { //$ip]) {
    echo "<!doctype html><html><body onload=\" document.getElementById('subm').click(); \"><form action='" . $_SERVER['PHP_SELF'] . "' method='post'><input type='hidden' name='donotuse401' value='error'></input><input type='submit' id='subm' name='subm' value='Submit' style='display:none;'></input></form></body></html>";
    exit;
   } else if ($row[3] == "registered") {
    $ut="registered";
    $_SESSION['usertype']="registered";
    $nextpage="registered.php";
    $nextval="Registered User Page";
   } else if ($row[3] == "subscriber") {
    $ut="subscriber";
    $_SESSION['usertype']="subscriber";
    $nextpage="subscriber.php";
    $nextval="Subscriber Page";
   } else {
    $ut="admin";
    $_SESSION['usertype']="admin";
   }
  } else {
   if ($_SERVER["PHP_AUTH_PW"] != $row[$ip]) {
    header("WWW-authenticate: basic realm=\"authorized usage\"");
    header("HTTP/1.0 401 Unauthorized");
    echo "Your username/password is wrong ...";
    exit;
   }
  }
  $_SESSION['login']=true;
 }
}

if (!isset($_SERVER["PHP_AUTH_USER"]) && isset($_GET['use401'])) {
   header("WWW-authenticate: basic realm=\"authorized usage\"");
   header("HTTP/1.0 401 Unauthorized");
   echo "Your username/password is incorrect ...";
   exit;
}

if (isset($_GET["backto"])) {
   $nextpage=$_GET["backto"];
   $nextvals=explode("/", $nextpage);
   $nextval= strtoupper(substr($nextvals[sizeof($nextvals) - 1],0,1)) . str_replace(".php", " Page", substr($nextvals[sizeof($nextvals) - 1],1));
   $backtoonload=' onload=" document.getElementById(' . "'" . 'subm' . "'" . ').click(); "';
} else if (isset($_POST["backto"])) {
   $nextpage=$_POST["backto"];
   $nextvals=explode("/", $nextpage);
   $nextval= strtoupper(substr($nextvals[sizeof($nextvals) - 1],0,1)) . str_replace(".php", " Page", substr($nextvals[sizeof($nextvals) - 1],1));
   $backtoonload=' onload=" document.getElementById(' . "'" . 'subm' . "'" . ').click(); "';
} 

if (!file_exists("loginpage.name")) {
   file_put_contents("loginpage.name", $_SERVER['PHP_SELF']);
}

?>
<!doctype html><html><body<?php echo $backtoonload; ?>><div align="center">
<form action='<?php echo $nextpage; ?>' method='post'><input type='hidden' name='login' value='true'></input><input type='hidden' name='usertype' value='<?php echo $ut; ?>'></input><input type='submit' id='subm' name='subm' value='<?php echo $nextval . $more; ?>'></input></form>
<br><br>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?logout=<?php echo urlencode(str_replace('=form','=y', $_SERVER['QUERY_STRING'])); ?>" title="Logout">Logout</a>
</div>
</body></html>
