<?php
$rijnKey = str2hex("d4HdKTEtMcDzcyBXCCvwQRrvBHcLtQcz");
$rijnIV = "\x31\x55\x94\x69\x59\x66\x87\x48\x52\x36\x96\x52\x96\x98\x75\x42";
$__TOKEN = "hardcodeshitbykernstudios";
require_once('_init.php');

if(isset($_GET['func'])){
	if($_GET['func'] == 'login'){
		if(isset($_GET['platform'])){
			if($_GET['platform'] == 'Noctis'){
				if(empty($_GET['username']) || empty($_GET['password'])){
					exit();
				}
				$conn = sqlsrv_connect($__CONFIG['SQLHost'], array('UID' => $__CONFIG['SQLUID'], 'PWD' => $__CONFIG['SQLPWD'], 'Database' => $__CONFIG['SQLDB']));
				if(!$conn){
					echo print_r(sqlsrv_errors(), true);
					exit();
				}
				$username = mssql_escape_string($_GET['username']);
				$password = mssql_escape_string($_GET['password']);
				$content = get_data("http://forums.noctis-gaming.com/_IPBAPI.php?tkn=somerandometoken&platform=pureAPI&func=1&mail=".urlencode($username));
				$json = json_decode($content, true);
				if($json['status'] == 'success'){
					if($json['members_pass_hash'] == md5(md5($json['members_pass_salt']).$password)){
						$checkAccount = sqlsrv_query($conn, "SELECT * FROM tAccounts WHERE nEMID = ?;", array($json['member_id']), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
						if(sqlsrv_num_rows($checkAccount) == 0){
							$insert = sqlsrv_query($conn, "INSERT INTO tAccounts (nEMID, sUsername, sUserPass, sUserPassSalt, sEmail, sIP, nAuthID) VALUES (?, ?, ?, ?, ?, ?, ?);", array($json['member_id'], $username, 'CheckForum', 'Forum', 'CheckForum', getRemoteIP(), 1));
							if(!$insert){
								echo json_encode(array('status' => 'error', 'message' => 'Pure Games API Error! Sync mistake #1!'.print_r(sqlsrv_errors(), true)));
								exit();
							}
						}
						$checkUsername = sqlsrv_query($conn, "SELECT * FROM tAccounts WHERE nEMID = ? AND sUsername = ?;", array($json['member_id'], $json['name']), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
						if(sqlsrv_num_rows($checkUsername) == 0){
							$update = sqlsrv_query($conn, "UPDATE tAccounts SET sUsername = ? WHERE nEMID = ?;", array($json['name'], $json['member_id']));
							if(!$update){
								echo json_encode(array('status' => 'error', 'message' => 'Pure Games API Error! Sync mistake #2!'));
								exit();
							}
						}
						$selectLoginQU = sqlsrv_query($conn, "SELECT nLoginable FROM tLogin WHERE nID = '1';");
						$selectLoginFT = sqlsrv_fetch_array($selectLoginQU);
						
						$selectAuthIDQU = sqlsrv_query($conn, "SELECT nAuthID FROM tAccounts WHERE nEMID = ?;", array($json['member_id']));
						$selectAuthIDFT = sqlsrv_fetch_array($selectAuthIDQU);
						
						$selectAuthQU = sqlsrv_query($conn, "SELECT nLoginable FROM tAuth WHERE nAuthID = (SELECT nAuthID FROM tAccounts WHERE nEMID = ?);", array($json['member_id']));
						$selectAuthFT = sqlsrv_fetch_array($selectAuthQU);
						
						if($selectLoginFT['nLoginable'] >= 1 OR $selectAuthIDFT['nAuthID'] == 9){
						if($selectAuthFT['nLoginable'] >= 1){
							$Token = generateRandomString(50);
							$tokens = sqlsrv_query($conn, "SELECT * FROM tTokens  WHERE nEMID = ?;", array($json['member_id']), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
							if(sqlsrv_num_rows($tokens) >= 1){
								$delete = sqlsrv_query($conn, "DELETE FROM tTokens WHERE nEMID = ?;", array($json['member_id']));
								$insertToken = sqlsrv_query($conn, "INSERT INTO tTokens (nEMID, sToken) VALUES (?, ?);", array($json['member_id'], $Token));
								$insertLog = sqlsrv_query($conn, "INSERT INTO AccountLog..tAccountLoginLog (nEMID, sIP) VALUES (?, ?);", array($json['member_id'], getRemoteIP()));
								if($delete && $insertToken && $insertLog){
									echo json_encode(array('status' => 'success', 'token' => encrypt($Token)));
								}else{
									echo json_encode(array('status' => 'error', 'message' => 'Token unsuccessfully added'));
								}
							}else{
								$insertToken = sqlsrv_query($conn, "INSERT INTO tTokens (nEMID, sToken) VALUES (?, ?);", array($json['member_id'], $Token));
								$insertLog = sqlsrv_query($conn, "INSERT INTO AccountLog..tAccountLoginLog (nEMID, sIP) VALUES (?, ?);", array($json['member_id'], getRemoteIP()));
								if($insertToken && $insertLog){
									echo json_encode(array('status' => 'success', 'token' => encrypt($Token)));
								}else{
									echo json_encode(array('status' => 'error', 'message' => 'Token unsuccessfully added'));
								}
							}
						}else{
							echo json_encode(array('status' => 'error', 'message' => 'Server is currently in Maintenance mode!'));
						}
						
						}else{
							echo json_encode(array('status' => 'error', 'message' => 'Server is currently in Maintenance mode!'));
						}
					}else{
						echo json_encode(array('status' => 'error', 'message' => 'Please check your Password.'));
					}
				}else{
					echo json_encode(array('status' => 'error', 'message' => $json['status']));
				}
			}
		}
	}
}

function Encrypt($s){
	global $rijnKey, $rijnIV;

	// Have to pad if it is too small
	$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
	$pad = $block - (strlen($s) % $block);
	$s .= str_repeat(chr($pad), $pad);

	$s = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $rijnKey, $s, MCRYPT_MODE_CBC, $rijnIV);
	$s = base64_encode($s);
	$s = str_replace("+", "BIN00101011BIN", $s);
	return $s;
}

function str2hex($str){
	return preg_replace("#(\\\x[0-9A-F]{2})#e", "chr(hexdec('\\1'))", $str);
}
?>