<?php // Config - Start
$conf['db_host'] = ".\SQLEXPRESS";
$conf['db_user'] = "sa";
$conf['db_pass'] = "Z85A8j4tCXGdPpbEcRrxTeMg";
$conf['db_name'] = "Accounts";
// Config - End


$user = sql_clean($_GET['Username']);
$passhash = sql_clean($_GET['Password']);


$connectionInfo = array( "Database"=>$conf['db_name'], "UID"=>$conf['db_user'], "PWD"=>$conf['db_pass']);
$conn = sqlsrv_connect( $conf['db_host'], $connectionInfo);

$exec = sqlsrv_query($conn, "SELECT nEMID, sUserPass FROM tAccounts where sUsername = ?", array($user), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));

if($exec)
{
    if(sqlsrv_num_rows($exec) != 1)
    {
        die('Account Not Found.');
    }
    $AccountData = sqlsrv_fetch_array($exec);
    $PlaintxtPass = $AccountData['sUserPass'];
    $PlaintxtnEMID = $AccountData['nEMID'];
    if (MD5($PlaintxtPass) == $passhash)
    {
        $Token = RandomToken(50);

        $setToken = null;

        if (sqlsrv_num_rows(sqlsrv_query($conn, "SELECT * FROM tTokens WHERE nEMID = ?;", array($PlaintxtnEMID), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ))) >= 1)
        {
            sqlsrv_query($conn, "DELETE FROM tTokens WHERE nEMID = '".$PlaintxtnEMID."'");
            $setToken = sqlsrv_query($conn, "INSERT INTO tTokens (nEMID, sToken) VALUES(?, ?)", array($PlaintxtnEMID, $Token));
        }
        else
		{
            $setToken = sqlsrv_query($conn, "INSERT INTO tTokens (nEMID, sToken) VALUES(?, ?)", array($PlaintxtnEMID, $Token));
		}

        if ($setToken)
            die('OK#'.$Token);
        else
            die('SetToken Error');
    }
    else
    {
        die('Wrong Password.');
    }
}
else
{
    die('Query Failed');
}

function sql_clean($str)
{
    $search  = array("\\", "\0", "\n", "\r", "\x1a", "'", '"');
    $replace = array("", "", "", "", "", "", "");
    return str_replace($search, $replace, $str);
}

function RandomToken( $length )
{
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	$str = "";
	$size = strlen( $chars );
	for( $i = 0; $i < $length; $i++ ) {
			$str .= $chars[ rand( 0, $size - 1 ) ];
	}

	return $str;
}
?>