<?php
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');

// error_reporting(E_ALL);
// ini_set('display_errors', 1);

$root = $_SERVER['DOCUMENT_ROOT'];
if (empty($root))
{
	$root = (__DIR__);									  
}
$dir = (dirname(__FILE__));
$parentDir = dirname($dir);
$baseDir = dirname($parentDir);

include_once $parentDir.'/rdtvims/rdtphp/connect.php';
$conn = dbConnection();
$mConnection = $conn['connection'];

function initSalt()
{
    $options = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./';
    $salt = '';
    for ($i = 0; $i <= 21; $i ++)
    {
      $options = str_shuffle ( $options );
      $salt .= $options [rand ( 0, 63 )];
    }
    return $salt;
}

function userLogin($mUser, $mPassword)
{
	global $conn;
	
	session_start();
    
    $error = "FAIL-Wrong Username or Password";
    
// Test for existing User Session   
    if(isset($_SESSION['userData']))
    {
// Check entered User against Stored-Session User
        if ($mUser == $_SESSION['userData']['user_id'])
        {
            $mUserPassword = ($_SESSION['userData']['password']);
            if ($mPassword != $mUserPassword)
            {
                if (crypt($mPassword, $mUserPassword) != $mUserPassword)
                {
                    $error = "FAIL-Wrong Username or Password";
                }
                else
                    $error = "";
            }
            else
                $error = "";
// Input User matches Session User - Return Stored Allowed Menu Codes      
            if ($error == "")
            {
                $_SESSION['userData']['timestamp'] = time();
                $mAllowedMenuCodes = $_SESSION['userData']['allowed_menu_codes'];
                $mAllowedMenuCodes = str_replace(",",";",$mAllowedMenuCodes);
                $mBlockedMenuCodes = $_SESSION['userData']['blocked_menu_codes'];
				$mUser = $_SESSION['userData']['user_id'];
//                return ("OKUS-".json_encode("user:".$mUser.",allowedMenuCodes:".$mAllowedMenuCodes.",blockedMenuCodes:".$mBlockedMenuCodes));
// Return the values
				$output = array(
				'type'				=>	"USER",
				'status'			=>	"OK  -",
				'user'				=>	$mUser,
				'level'				=>	$mLevel,
				'allowedmenus'		=>	$mAllowedMenuCodes,
				'blockedmenus'		=> 	$mBlockedMenuCodes
				);
				return "OKUS-".json_encode($output);
//				header("Location: login.php?success=true");
//				exit();
            }
        }
    }
// GBet user Settings
	$mUserId = $mUser;
	$mStatus = "";
	$mPath = ROOT_PATH;
	$mMenu = "";
	$mSystem = SERVER_DOMAIN;
	$mCompany = "";
	$mDbHost = DB_HOST;
	$mDbUser = DB_USERNAME;
	$mDbPwd = DB_PASSWORD;
	$mDbase = DB_NAME;
	$mMqServer = ""; 
	$mConnection = $conn['connection'];

// Get input User & Password    
//  $mPassword = strtolower($mPassword);

//Anti-Injection
//  $mUser = mysqli_real_escape_string($mUser);
//  $mPassword = mysqli_real_escape_string($mPassword);

// Release Session
    if(isset($_SESSION['userData']))
        unset($_SESSION['userData']);
    
// Get User Settings from Database
//  $mResult="SELECT * FROM user WHERE lower(user_id)='".strtolower($mUser)."' AND active=1 LIMIT 1";
    $mResult="SELECT username AS user_id,password AS password, enabled AS active, user_level_id AS user_level_id, '' AS allowed_menu_codes FROM user WHERE lower(username)='".strtolower($mUser)."' LIMIT 1";
    $mData = mysqli_query($mConnection,$mResult);
    $mUserPassword = "";
    $mAllowedMenuCodes = "";
    $mUserLevelId = 3;
    $i = 0;
    while($mRow = mysqli_fetch_assoc($mData)) 
    {
// Store User Settings in Session
        $_SESSION['userData'] = array_merge(array('timestamp'=>time()),$mRow);
        
        $mUserPassword = ($mRow['password']);
        $mUserLevelId = ($mRow['user_level_id']);
//      $mAllowedMenuCodes = ($mRow['allowed_menu_codes']);
        $i++;
    }
    if ($i == 0)
    {
        $error = "FAIL-Wrong Username or Password";
    }
    
// Encrypt Input Password
    elseif ($mPassword != $mUserPassword)
    {
        if (crypt($mPassword, $mUserPassword) != $mUserPassword)
        {
            if(isset($_SESSION['userData']))
                unset($_SESSION['userData']);
            $error = "FAIL-Wrong Username or Password";
        }
        else
            $error = "";
    }
    else
        $error = "";

// Allowed Screen Access
    if ($error == "")
    {
        $mAllowedMenuCodes = "";
        $mBlockedMenuCodes = "";
        $mResult = "SELECT * FROM user_level WHERE id=".$mUserLevelId." LIMIT 1";
        if (!mysqli_query($mConnection,$mResult))
            return "FAIL-".mysqli_error($mConnection)."-".$mResult;
        $mData = mysqli_query($mConnection,$mResult);
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            foreach($mRow as $k1=>$v1)
            {
                if((substr($k1,0,3) == "rdt") || (substr($k1,0,2) == "fs"))
                    if ($k1 == "rdt_pi")
                        $k1 = "rdt_PI";
                    if ($v1 == "1")
                        $mAllowedMenuCodes .= $k1;
            }
        }
// Get Additional Entries from Menu_detail
        $mResult = "SELECT action AS k1 FROM menu_detail WHERE menu_code IS NOT null and menu_code <> '' AND active = '0' AND menu_code=".$mUserLevelId;
        if (!mysqli_query($mConnection,$mResult))
            return "FAIL-".mysqli_error($mConnection)."-".$mResult;
        $mData = mysqli_query($mConnection,$mResult);
        if (mysqli_num_rows($mData) == 0)
        {
            $mResult = "SELECT action AS k1 FROM menu_detail WHERE description IS NOT null and description <> '' AND active = '0' AND description LIKE('%".$mUserLevelId."%')";
            if (!mysqli_query($mConnection,$mResult))
                return "FAIL-".mysqli_error($mConnection)."-".$mResult;
            $mData = mysqli_query($mConnection,$mResult);
        }
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mAllowedMenuCodes .= $mRow['k1'];
        }
        $mResult = "SELECT action AS k1 FROM menu_detail WHERE description IS NOT null and description <> '' AND active = '0' AND description NOT LIKE('%".$mUserLevelId."%')";
        if (!mysqli_query($mConnection,$mResult))
            return "FAIL-".mysqli_error($mConnection)."-".$mResult;
        $mData = mysqli_query($mConnection,$mResult);
        while($mRow = mysqli_fetch_assoc($mData)) 
        {
            $mBlockedMenuCodes .= $mRow['k1'];
        }

    }   
    mysqli_close($mConnection);
    
    if ($error == "")
    {
        $mAllowedMenuCodes = str_replace(",",";",$mAllowedMenuCodes);
        $_SESSION['userData']['allowed_menu_codes'] = $mAllowedMenuCodes;
        $_SESSION['userData']['blocked_menu_codes'] = $mBlockedMenuCodes;
//        exit("OKUS-user:".$mUser.",allowedMenuCodes:".$mAllowedMenuCodes.",blockedMenuCodes:".$mBlockedMenuCodes.",userLevel:".$mUserLevelId);
		
// Return the values
		$output = array(
		'type'				=>	"USER",
		'status'			=>	"OK  -",
		'user'				=>	$mUser,
		'level'				=>	$mLevel,
		'allowedmenus'		=>	$mAllowedMenuCodes,
		'blockedmenus'		=> 	$mBlockedMenuCodes
		);
	
//		header("Location: login.php?success=true");
		return "OKUS-".json_encode($output);		
    }
    else
        exit($error);   
}
 
function addUser($mUser, $mPassword, $mLevel=null, $mFirstName=null, $mLastName=null, $mForceReset=null, $mDbHost=null, $mDbUser=null, $mDbPwd=null, $mDbName=null)
{
    $mErrMsg = "";
    if ($mUser == "")
    {
        $mErrMsg = "FAIL-Enter User Id";
    }
    if ($mErrMsg == "")
    {
// mysql connection
        if (($mDbHost == null) || ($mDbHost == ""))
            $mConnection = defaultDbConnection();
        else
            $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
                exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Test for Existing User       
        $mDataQuery = "SELECT id AS id, first_name AS name FROM user WHERE username = '".$mUser."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection));
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
/*
        while($mRow = mysqli_fetch_assoc($mData)) 
        {   
            $mErrMsg = "FAIL-User Already Exists - ".$mUser." - ".($mRow['name']);
            $i++;
        }
*/
    }
    if ($mErrMsg == "")
    {
        if (!mysqli_query($mConnection,"DELETE FROM user WHERE username = '".$mUser."' LIMIT 1"))
            exit("FAIL-".mysqli_error($mConnection));
        if (($mName == "") || ($mName == null))
            $mName = $mUser;
// Encrypt Password
        $salt = initSalt();
        $blowfish = '$2a$10$';
        $mHashedPassword = crypt($mPassword, $blowfish . $salt);
// Force Password Reset
        if (($mForceReset) && (strtolower($mForceReset) == "y"))
            $mResetPassword = $mHashedPassword;
        else
            $mResetPassword = "";
// set default level
        if (($mLevel == null) || ($mLevel==""))
            $mLevel = "3";
//      $mHashedPassword = crypt(trim($mPassword));
//      $mDataQuery = "INSERT INTO user (id, user_id, name, email, password, password_reset_code, active, company_id) VALUES(DEFAULT,'".$mUser."','".$mName."','','".$mHashedPassword."','".$mResetPassword."',1,1)";
        $mDataQuery = "INSERT INTO user (id, version, account_expired, account_locked, enabled, password, password_expired,username, first_name,last_name,user_level_id) VALUES(DEFAULT,0,0,0,1,'".$mHashedPassword."',0,'".$mUser."','".$mFirstName."','".$mLastName."','".$mLevel."')";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection)."-".$mDataQuery);
        else
            $mErrMsg = "OK  -User ".$mUser." Added";
    }

    mysqli_close($mConnection);
    return $mErrMsg;
}
    
function changePassword($mUser, $mOldPassword, $mNewPassword1, $mNewPassword2=null, $mDbHost=null, $mDbUser=null, $mDbPwd=null, $mDbName=null)
{
    $mErrMsg = "";
//  if ($mDbUser == "")
//      $mDbUser = "root";
//  $mErrMsg = "FAIL-".$mDbHost.":".$mDbUser.":".$mDbPwd.":".$mDbName;
    if(isset($_SESSION['userData']))
        unset($_SESSION['userData']);
    
    if (($mNewPassword2) && ($mNewPassword1 != $mNewPassword2))
    {
        $mErrMsg = "FALO-New Passwords Don't Match";
    }
    if ($mErrMsg == "")
    {
// mysql connection
    if (($mDbHost == null) || ($mDbHost == ""))
        $mConnection = defaultDbConnection();
    else
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error().":".$mDbHost);
// Test for Existing User       
        $mDataQuery = "SELECT id AS id, username AS name, password AS password FROM user WHERE username = '".$mUser."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-Database Error-".mysqli_error($mConnection));
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = mysqli_num_rows($mData);
        if ($i = 0)
        {
            $mErrMsg = "FALO-Wrong Username or Password".$mUser;
        }
    }
// Check Password
    if ($mErrMsg == "")
    {
        $i = 0;
        $mPassword = "";
        $mResetPassword = "";
        while($mRow = mysqli_fetch_assoc($mData)) 
        {   
            $mPassword = $mRow['password'];
//          $mResetPassword['password_reset_code'];
            $i++;
        }
// convert passwords to lower-case
//          $mOldPassword = strtolower($mOldPassword);
//          $mNewPassword1 = strtolower($mNewPassword1);
// check against encrypted password
            if ((crypt($mOldPassword, $mPassword) != $mPassword) && ($mOldPassword != $mPassword))
            {
                $mErrMsg = "FALO-Wrong Username or Password";
            }
    }
    if ($mErrMsg == "")
    {
// Encrypt Password
        $salt = initSalt();
        $blowfish = '$2a$10$';
        $mHashedPassword = crypt($mNewPassword1, $blowfish . $salt);
// Force Password Reset
        $mResetPassword = "";
        
//      $mDataQuery = "UPDATE user SET password = '".$mHashedPassword."',password_reset_code='', last_updated_date=now(), last_updated_by='".$mUser."' WHERE user_id = '".$mUser."' LIMIT 1";
        $mDataQuery = "UPDATE user SET password = '".$mHashedPassword."' WHERE username = '".$mUser."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection));
        else
            $mErrMsg = "OKMS-User ".$mUser." Updated";
            userLogin ($mUser,$mNewPassword1);
    }

    mysqli_close($mConnection);
//  session_start;
//  if(isset($_SESSION['userData']))
//      ($_SESSION['userData']['password']) = $mHashedPassword;
    return $mErrMsg;
//  exit ($mErrMsg.$mDataQuery);
}

function testPassword($mUser, $mTestPassword=null, $mDbHost=null, $mDbUser=null, $mDbPwd=null, $mDbName=null)
{
    if ($mTestPassword)
    {
        $mErrMsg = "";
// mysql connection
    if (($mDbHost == null) || ($mDbHost == ""))
        $mConnection = defaultDbConnection();
    else
        $mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
            exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// Test for Existing User       
//      $mDataQuery = "SELECT id AS id, name AS name, password AS password FROM user WHERE user_id = '".$mUser."' AND active = 1 LIMIT 1";
        $mDataQuery = "SELECT id AS id, name AS name, password AS password FROM user WHERE username = '".$mUser."' LIMIT 1";
        if (!mysqli_query($mConnection,$mDataQuery))
            exit("FAIL-".mysqli_error($mConnection));
        $mData = mysqli_query($mConnection,$mDataQuery);
        $i = 0;
        while($mRow = mysqli_fetch_assoc($mData)) 
        {   
            $mErrMsg = "FAIL-Test Password - ".$mUser." - ".($mRow['password'])." : ".crypt($mTestPassword,($mRow['password']));
            $i++;
        }
        mysqli_close($mConnection);
        return $mErrMsg.$mDataQuery;
    }
}

// Test for Session Time-out
function sessionTimeout($mTimeout=15)
{
    $mErrMsg = "";
// convert Time-out to seconds
    if ($mTimeout < 1)
        $mTimeout = 15;
    $mTimeout = $mTimeout * 60;
// subtract Start Session Time from Now     
    session_start();
    if(time() - $_SESSION['userData']['timestamp'] > $mTimeout)  
    {
// - "FA"=Failed, "LO"-Log-Out      
        $mErrMsg = "FALO-Session Timed-out";
        unset($_SESSION['userData']);
        exit;
    } 
    else 
    {
        $_SESSION['userData']['timestamp'] = time(); //set new timestamp
        $mErrMsg = "OK  -";
    }
    if ($mErrMsg == "")
        $mErrMsg = "OK  -";
    return $mErrMsg;
}

// Main Process

function mainUserProcess($mDbHost=null, $mDbUser=null, $mDbPwd=null, $mDbName=null, $mUser, $mPassword, $mName=null, $mForceReset=null, $mTestPassword=null)
{
// date / time
    $date = date('d/m/Y h:i:s a', time());

// Add User
    if ($mUser != "")
    {
//      $mErrMsg = addUser($mDbHost, $mDbUser, $mDbPwd, $mDbName, $mUser, $mPassword, $mName, $mForceReset);
//      $mErrMsg = testPassword($mDbHost, $mDbUser, $mDbPwd, $mDbName, $mUser, $mTestPassword);
    }
    if ($mErrMsg == "")
        $mErrMsg = "FAIL-Unexpected Result";
        
    exit($mErrMsg);
}

$function = $_GET['function'];
// exit ("FAIL-TEST1-".$function);
// if (strpos($function,"userlogin"))
if ($function == "userlogin")
{
// Initialises variables
	$username = ''; 
	$password = '';

// Get Input Parameters from POST or GET
	if (!empty($_POST))
	{
		exit("FAIL-TEST1");
		if (!empty($_POST['data']))
		{
			$jsonString = $_POST['data'];
			$data = json_decode($jsonString, true);
		}
		if (!empty($_POST['username']))
		{
			$username = $_POST['username'];
		}
		if (!empty($_POST['password']))
		{
			$password = $_POST['password'];
		}
	}
	else
	{
		$params = file_get_contents("php://input");
		try
		{
			if (strpos($params,'data:') !== false)
			{
				$s = strpos($params,'data:')+5;
			}
			else
			{
				$s = 0;
			}
			$jsonString = substr($params,$s);
//			exit("FAIL-TEST1-".$s." ".var_dump($jsonString));
			try
			{
				$data = json_decode($jsonString, true);
			}
			catch (Exception $e)
			{
				exit("FAIL-Incorrect parameters");
			}
		}
		catch (Exception $e)
		{
		}
	}
	if (!empty($data))
	{
		foreach($data as $k2=>$v2)
		{
			if ($k2 == "username")
				$username = trim($v2);
			elseif ($k2 == "password")
				$password = trim($v2);
		}
	}
// Checks if username is empty
	if (empty($username))
	{
		$value = ['username' => 'Please complete all fields'];
		echo "FAIL-Invalid User";
//		header('Location: login.php');
		exit;
	}

// Check is password is empty
	if (empty($password)) 
	{
		$value = ['password' => 'Please complete all fields'];
//		header('Location: login.php');
		echo "FAIL-invalid Password";
		exit;
	}	
    echo userLogin($username, $password);
}

if (strpos($mFilter,"adduser"))
{
    $mFilter = str_replace("filter:","",$mFilter);
    $mFilter = str_replace("=",":",$mFilter);
    $mFilter = str_replace("|AND|",",",$mFilter);
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "function")
            $mFunction = $v2;
        elseif ($k2 == "userid")
            $mUser = strtolower($v2);
        elseif ($k2 == "password")
            $mPassword = strtolower($v2);
        elseif ($k2 == "level")
            $mLevel = $v2;
        elseif ($k2 == "firstname")
        {
            $mFirstName = strtolower($v2);
            $mFirstName = ucfirst($mFirstName);
        }
        elseif ($k2 == "lastname")
        {
            $mLastName = strtolower($v2);
            $mLastName = ucfirst($mLastName);
        }
    }
//  echo "FAIL-TEST1".$mArray1[7]."-".$mUser;
    echo addUser($mUser,$mPassword,$mLevel,$mFirstName,$mLastName);
}

if (strpos($mFilter,"changepassword"))
{
    $mDbHost = null;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
//      print_r("FAIL-TEST".$k1.":".$v1);
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "function")
            $mFunction = $v2;
        elseif ($k2 == "userid")
            $mUser = $v2;
        elseif ($k2 == "password")
            $mOldPassword = strtolower($v2);
        elseif ($k2 == "password1")
            $mNewPassword1 = strtolower($v2);
        elseif ($k2 == "password2")
            $mNewPassword2 = strtolower($v2);
        elseif ($k2 == "currentUser")
            $mCurrentUser = $v2;
    }
    echo changePassword($mUser, $mOldPassword, $mNewPassword1, $mNewPassword2,$mDbHost, $mDbUser, $mDbPwd, $mDbName);
}

if (strpos($mFilter,"sessiontimeout"))
{
// Default Settion Tiimeout to 15 minutes
    $mTimeout=15;
// Explode Input String Into Array - Separated by ,
    $mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
    foreach($mArray1 as $k1=>$v1)
    {
        list($k2, $v2) = explode(":",$mArray1[$k1]);
        if ($k2 == "function")
            $mFunction = $v2;
        elseif ($k2 == "timeout")
            $mTimeout = $v2;
    }   
    echo sessionTimeout($mTimeout);
}
?>