<?php

function str_startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}
function str_endsWith($haystack, $needle)
{
    return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}



function initDB()
{
	global $CONFIG;
	$CONFIG['db_conn'] = sqlsrv_connect($CONFIG['db_host'], array('Database'=>$CONFIG['db_accountDB'], 'UID'=>$CONFIG['db_user'], 'PWD'=>$CONFIG['db_pass']));
	return $CONFIG['db_conn'];
}

function closeDB()
{
	global $CONFIG;
	sqlsrv_close($CONFIG['db_conn']);
}

function sqlsrv_escape_string($data)
{
	if ( !isset($data) or $data == null ) return '';
	if ( is_numeric($data) ) return $data;

	$non_displayables = array(
		'/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
		'/%1[0-9a-f]/',             // url encoded 16-31
		'/[\x00-\x08]/',            // 00-08
		'/\x0b/',                   // 11
		'/\x0c/',                   // 12
		'/[\x0e-\x1f]/'             // 14-31
	);
	foreach ( $non_displayables as $regex )
		$data = preg_replace( $regex, '', $data );
	$data = str_replace("'", "''", $data );
	return $data;
}

function loadTpl($template)
{
	global $CONFIG, $ERRORS, $USER;
	//$noInc = array('footer','header','account_menu');
	if(file_exists('templates/'.$CONFIG['template'].'/'.$template.'.tpl.php'))
		return 'templates/'.$CONFIG['template'].'/'.$template.'.tpl.php';
	elseif(str_startsWith(strtolower($template), 'store'))
		return 'templates/'.$CONFIG['template'].'/store.tpl.php';
	else
		return loadTpl('index');
}

function initUSER()
{
	global $CONFIG, $_SESSION, $USER, $_POST;
	if((empty($_SESSION) || $_SESSION['USER']['loggedIn'] !== true || ($_SESSION['lastActive'] + $CONFIG['inactiveTimeBeforeLogout']) < time()) && $_POST['postType'] != 'login' && $_POST['postType'] != 'register')
	{//not logged in or inactive for 12 hours
		//clean UserData and Session
		cleanLogin();
		return;
	}
	elseif($_POST['postType'] == 'login')
	{//logging in
		//clean UserData and Session
		cleanLogin();
		
		//try to log in
		$loginInfo = login();
		if(isset($loginInfo['wrongPW']))
		{//failed
			return;
		}
	}
	elseif($_POST['postType'] == 'register')
	{//registering
		//clean UserData and Session
		cleanLogin();
		register();
		
	}
	
	
	if(!empty($_SESSION))
	{//logged in
		$_SESSION['lastActive'] = time();
		sqlChooseDB($CONFIG['db_accountDB']);
		$rs = sqlsrv_query($CONFIG['db_conn'], 'SELECT * FROM tAccounts WHERE nEMID = \''.$_SESSION['tAccounts']['nEMID'].'\'');
		if(sqlsrv_has_rows($rs))
		{
			$rs = sqlsrv_fetch_array($rs, SQLSRV_FETCH_ASSOC);
			$USER = array();
			foreach($rs as $key => $value)
			{
				$USER[$key] = $value;
			}
			/*
			'nEMID' => $_SESSION['nEMID'],
			'sUsername' => $rs['sUsername'],
			'sEmail' => $rs['sEmail'],
			'nAuthID' => $rs['nAuthID'],
			'nPoints' => $rs['nPoints'],
			'sReferCode' => $rs['sReferCode']
			);*/
		}
		else
		{
			//Failed to get account data, so clean everything and pretend they weren't logged in :)
			cleanLogin();
		}
	}
}

function login()
{
	global $_SESSION, $_POST, $ERRORS, $CONFIG;
	if(preg_match('/^[\w]$/', $_POST['username']))$ERRORS['login'][] = '<b>Username</b> contains invalid symbols.';
	//if(INSERT TOO.MANY.TRIES-CONDITION HERE)$ERRORS['login'][] = 'Please try again in '.(($x >= 60)? ($x/60).' minutes.' : $x.' seconds.');
	
	$username = $_POST['username'];
	$password = sha1($_POST['password']);
	
	if(count($ERRORS['login']) == 0)
	{
		sqlChooseDB($CONFIG['db_accountDB']);
		$rs = sqlsrv_query($CONFIG['db_conn'], 'SELECT nEMID FROM tAccounts WHERE sUsername = \''.$username.'\' AND sUserPassSalt = \''.$password.'\'');
		if(sqlsrv_has_rows($rs))
		{
			$rs = sqlsrv_fetch_array($rs);
			$_SESSION['tAccounts']['nEMID'] = $rs['nEMID'];
			$_SESSION['USER']['loggedIn'] = true;
		}
		else
		{
			//INSERT TOO.MANY.TRIES-CODE
			$ERRORS['login']['wrongPW'] = '<b>Username</b> or <b>Password</b> is incorrect.';
			// '<b>'.$x.'</b> tries left.' OR 'Please try again in '.(($x >= 60)? ($x/60).' minutes.' : $x.' seconds.';
		}
	}
	return $ERRORS['login'];
}

function register()
{
	global $_SESSION, $_POST, $ERRORS, $CONFIG;
	
	if(!$CONFIG['registerEnabled'])
	{
		$ERRORS['register'][] = 'The register form has been deactivated for maintenance. Please try again later.';
		return $ERRORS['register'];
	}
	
	$username = $_POST['inputUsername'];
	$password = $_POST['inputPassword'];
	$conpassword = $_POST['inputConPassword'];
	$email = $_POST['inputEmail'];
	
	//Username
	if(strlen($username) < 5)	$ERRORS['register'][] = '<b>Username</b> must be at least 5 characters long.';
	if(strlen($username) > 32)	$ERRORS['register'][] = '<b>Username</b> must be less than 32 characters long.';
	if(preg_match('/^[\w]$/', $username))$ERRORS['register'][] = '<b>Username</b> must not contain symbols.';
	//Password
	//if(strlen($password) < 8)		$ERRORS['register'][] = '<b>Password</b> must be at least 8 characters long.';
	//if(strlen($password) > 32)	$ERRORS['register'][] = '<b>Password</b> must be less than 32 characters long.';
	if(!preg_match('#[0-9]#',$password) || !preg_match('#[a-zA-Z]#',$password))$ERRORS['register'][] = '<b>Password</b> must contain at least <b>1 letter</b> and <b>1 number</b>.';
	if($password != $conpassword) $ERRORS['register'][] = '<b>Passwords</b> don\'t match.';
	//Email
	if(!filter_var($email, FILTER_VALIDATE_EMAIL))$ERRORS['register'][] = '<b>Email</b> not valid.';
	//Captcha
	if(!checkCaptcha())$ERRORS['register'][] = '<b>Captcha</b> was wrong.';
	
	if(count($ERRORS['register']) == 0)
	{
		sqlChooseDB($CONFIG['db_accountDB']);
		
		//Does username or email already exist?
		$email = sqlsrv_escape_string($email);
		$rs = sqlsrv_query($CONFIG['db_conn'], 'SELECT sUsername, sEmail FROM tAccounts WHERE sUsername = \''.$username.'\' OR sEmail = \''.$email.'\'');
		if(sqlsrv_has_rows($rs))
		{
			$rs = sqlsrv_fetch_array($rs);
			if(strtolower($rs['sUsername']) == strtolower($username)) $ERRORS['register'][] = '<b>Username</b> already taken.';
			if(strtolower($rs['sEmail']) == strtolower($email)) $ERRORS['register'][] = '<b>Email</b> already in use.';
		}
		else
		{
			$nReferedByEMID = 'NULL';
			if(isset($_SESSION['USER']['RaF'])) //already validated in index.php
			{
				$rs = sqlsrv_query($CONFIG['db_conn'], 'SELECT nEMID FROM tAccounts WHERE sReferCode = \''.$_SESSION['USER']['RaF'].'\'');
				if(sqlsrv_has_rows($rs))
				{
					$rs = sqlsrv_fetch_array($rs);
					$nReferedByEMID = $rs['nEMID'];
				}
			}
		
			$rs = sqlsrv_query($CONFIG['db_conn'], 'INSERT INTO tAccounts (sUsername, sUserPass, sUserPassSalt, sEmail, sIP, nReferedByEMID) VALUES (\''.$username.'\',\''.sqlsrv_escape_string($password).'\',\''.sha1($password).'\',\''.$email.'\',\''.$_SERVER['REMOTE_ADDR'].'\', '. $nReferedByEMID .'); SELECT SCOPE_IDENTITY() AS IDENTITY_COLUMN_NAME');
			if($rs !== false)
			{
				sqlsrv_next_result($rs);
				sqlsrv_fetch($rs);
				$nEMID = sqlsrv_get_field($rs, 0);
				if(strlen($nEMID)>0)	$_SESSION['tAccounts']['nEMID'] = $nEMID;
			}
		}
	}
	return $ERRORS['register'];
}

function validInc()
{
	return true;
}

function loggedIn()
{
	global $USER;
	if(!$USER)
		return false;
	else
		return true;
}

function setSESSIONifnotyet()
{
	global $_SESSION;
	if(empty($_SESSION))$_SESSION = array('USER' => array('loggedIn' => false),'tAccounts' => array(), 'tCharacter' => array());
}

function cleanLogin()
{
	global $USER, $_SESSION;
	$USER = false;
	
	if(!empty($_SESSION))//Wenn nicht leer, alles leeren bis auf USER
	{
		foreach($_SESSION as $key => $value)
		{
			if($key != 'USER')$_SESSION[$key]=array();
		}
		$_SESSION['USER']['loggedIn'] = false;
	}
	else				 //Ansonsten neu anlegen
	{
		setSESSIONifnotyet();
	}
}


function sqlChooseDB($dbname)
{
	global $CONFIG;
	if($dbname == $CONFIG['db_inUse'] || ($dbname == $CONFIG['db_accountDB'] && !isset($CONFIG['db_inUse'])))return;
	sqlsrv_query($CONFIG['db_conn'], 'USE '. $dbname);
}
function sqlGetTableColumns($table, $columns='*',$condition=null)
{
	global $_CONFIG;
	$rs = sqlsrv_query($_CONFIG['db_conn'], 'SELECT '.$columns.' FROM '.$table.(($condition!=null)?'WHERE '.$condition : ''));
	return sqlsrv_fetch_array($rs);
}

function getLink($page = '')
{
	global $CONFIG;
	if($page=='') return $CONFIG['webAddress'];
	$base = substr($CONFIG['webAddress'],strpos(strtolower($CONFIG['webAddress']),strtolower($_SERVER['SERVER_NAME']))+ strlen($_SERVER['SERVER_NAME']));
	$suffix = substr($_SERVER['REQUEST_URI'],strpos(strtolower($_SERVER['REQUEST_URI']),strtolower($base))+strlen($base));
	$basecount = substr_count($suffix, '/');
	
	$tmpstr = '';
	for($i=0; $i<$basecount; $i++)
	{
		$tmpstr .= '../';
	}
	return $tmpstr . $page;
}
function linkActive($page = '')
{
	global $CONFIG;
		
	$base = substr($CONFIG['webAddress'],strpos(strtolower($CONFIG['webAddress']),strtolower($_SERVER['SERVER_NAME']))+ strlen($_SERVER['SERVER_NAME']));
	$suffix = substr($_SERVER['REQUEST_URI'],strpos(strtolower($_SERVER['REQUEST_URI']),strtolower($base))+strlen($base));
	
	if(strtolower(((substr($suffix,0,1)=='/')?substr($suffix,1):$suffix)) == strtolower($page))return true;
	else return false;
}
function linkActive_forSwitch($page = '', $case = true)
{
	global $CONFIG;
		
	$base = substr($CONFIG['webAddress'],strpos(strtolower($CONFIG['webAddress']),strtolower($_SERVER['SERVER_NAME']))+ strlen($_SERVER['SERVER_NAME']));
	$suffix = substr($_SERVER['REQUEST_URI'],strpos(strtolower($_SERVER['REQUEST_URI']),strtolower($base))+strlen($base));
	
	if($case)return strtolower(((substr($suffix,0,1)=='/')?substr($suffix,1):$suffix));
	else return ((substr($suffix,0,1)=='/')?substr($suffix,1):$suffix);
}

function hideMail($mail)
{
	$mailArr = explode('@',$mail);
	return substr($mailArr[0],0,((strlen($mailArr[0])>4)?4 : strlen($mailArr[0])-1)) . '...@' . $mailArr[1];
}
function cryptMail($email)
{ $character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  $key = str_shuffle($character_set); $cipher_text = ''; $id = 'e'.rand(1,999999999);
  for ($i=0;$i<strlen($email);$i+=1) $cipher_text.= $key[strpos($character_set,$email[$i])];
  $script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";';
  $script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
  $script.= 'document.getElementById("'.$id.'").innerHTML=d';
  $script = "eval(\"".str_replace(array("\\",'"'),array("\\\\",'\"'), $script)."\")"; 
  $script = '<script type="text/javascript">/*<![CDATA[*/'.$script.'/*]]>*/</script>';
  return '<span id="'.$id.'"></span>'.$script;
}

function checkCaptcha()
{
	global $CONFIG, $_SERVER, $_POST;
	require_once('recaptchalib.php');
	$resp = recaptcha_check_answer ($CONFIG['reCAPTCHA_privateKey'],
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

	if (!$resp->is_valid) {
		return false;
	} else {
		return true;
	}
}

/*function getPage()
{
	global $_GET, $CONFIG;
}*/
?>