<?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
session_start();

$nextpage="member.php";
$nextval="Member Page";
$backtostr="";
$backtoonload="";
$dbname="users";
$utable="musers";
$ucolumn="username";
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'];
}

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 {
   $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><html><body onload="document.getElementById(' . "'" . 'username' . "'" . ').focus();"><div align="center">
   <form 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><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></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[$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 ($_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='submit' id='subm' name='subm' value='<?php echo $nextval; ?>'></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>
