<?php
require_once ('./config.php');

if (!isset($_GET['Username'])) //USERNAMESTRING
    $user = mssql_escape_string($_GET['']);
else
    $user = sql_clean($_GET['Username']);

if (!isset($_GET['Password'])) //PASSWORDSTRING
    $passhash = mssql_escape_string($_GET['']);
else
    $passhash = sql_clean($_GET['Password']);
 
 
$con = odbc_connect($conf['db_name'], $conf['db_user'], $conf['db_pass']) or die('ODBC Connection connect Fail.');
 
$exec = odbc_exec($con, "SELECT nEMID, sUserPass, nAuthID FROM tAccounts where sUsername = '$user'");
 
if($exec)
{
    if(odbc_num_rows($exec) != 1)
    {
        die('Account Not Found.');
    }
    $AccountData = odbc_fetch_object($exec);
    $PlaintxtPass = $AccountData->sUserPass;
    $PlaintxtnEMID = $AccountData->nEMID;
	$Auth = $AccountData->nAuthID;
	
	$fetch_Status = odbc_exec($con, "SELECT nLoginable FROM tAuth where nAuthID = '$Auth'");
	$get_Status = odbc_fetch_object($fetch_Status);
	$Status = $get_Status->nLoginable;
	
    if ($conf['Wartung'] == '1' and ($Status == '0')){

        die('Maintenance');


}
	if ($Auth == 3 OR $Auth == 9 OR $Auth == 2)
	{
	if (MD5($PlaintxtPass) == MD5($passhash))
    {
        $Token = RandomToken(50);
 
        $setToken = null;
 
        if (odbc_num_rows(odbc_exec($con, "SELECT * FROM tTokens WHERE nEMID = '".$PlaintxtnEMID."'")) >= 1)
        {
            odbc_exec($con, "DELETE FROM tTokens WHERE nEMID = '".$PlaintxtnEMID."'");
            $setToken = odbc_exec($con, "INSERT INTO tTokens (nEMID, sToken) VALUES('".$PlaintxtnEMID."', '".$Token."')");
        }
        else
            $setToken = odbc_exec($con, "INSERT INTO tTokens (nEMID, sToken) VALUES('".$PlaintxtnEMID."', '".$Token."')");
 
        if ($setToken)
            die('OK#'.$Token);
        else
            die('SetToken Error');
    }
    else
    {
        die('Wrong Password.');
    }

	}
	elseif ($Auth == 2)
    {
        die('Maintenance');
    }
	elseif ($Auth == -1)
	{
        die('Account banned');
	}

	
	
	}
else
{
    die('Query Failed');
}






odbc_close();
 
function sql_clean($str)
{
    $search  = array('^', '°', '!', '"', '²', '§', '³', '$', '%', '&', '/', '{', '(', '[', ')', ']', '=', '}', '?', '\'', '´', '`', '€', '*', '+', '~', '#', "'", '<', '>', '|', 'µ', ';' , 'UPDATE' , 'RESTORE' , 'UNION' , 'SELECT' , '*' , ' FROM' , 'DATABASE' , 'DROP' , '\0' , '\\' , '\n' , '\r');
    $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;
}
?>