<?php
if(!(is_readable(realpath(dirname(__FILE__)).'/settings.inc'))) {
    die('Error - Could not open or read file include/settings.inc');
} else {
    include_once(realpath(dirname(__FILE__)).'/settings.inc');
}

// параметр фасад передается как часть пути
if(!(is_readable(realpath(dirname(__FILE__))."/db/mysqlroutines.common.inc"))) {
	die("Error - Could not open or read file ".realpath(dirname(__FILE__))."/db/mysqlroutines.common.inc");
} else {
	include_once(realpath(dirname(__FILE__))."/db/mysqlroutines.common.inc");
}
function mb_substr_replace($original, $replacement, $position, $length)
{
    $startString = mb_substr($original, 0, $position, "UTF-8");
    $endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8");
    $out = $startString . $replacement . $endString;
    return $out;
}

if (getSetting('portal','useLocalSession','0') == 1) {
	$localPath = mb_substr(__DIR__,0,-8).'/'.'sessions';
	if (!file_exists($localPath)) {
		mkdir($localPath, 0777, true);
	}
	session_save_path($localPath);
	session_name(md5($localPath));
} 
session_write_close();
session_start();

if (!isset($_SESSION['SERVER_GENERATED_SID'])) {
    session_destroy(); 
	session_start();
	session_regenerate_id(); 
	$_SESSION['SERVER_GENERATED_SID'] = true;
}

function bsService_UserLogin($user_login, $user_Password)
{
	return $user_login == $user_Password;
}

define('AES_256_CBC', 'aes-256-cbc');

function encrypt($string = "")
{
    $key = base64_decode(getSetting('service','key','')."=");
    $iv = base64_decode(getSetting('service','iv','')."=");
	return openssl_encrypt($string, AES_256_CBC, $key, 0, $iv);
}

function decrypt($string = "")
{
    $key = base64_decode(getSetting('service','key','')."=");
	$iv = base64_decode(getSetting('service','iv','')."=");
	$ret = openssl_decrypt($string, AES_256_CBC, $key, 0, $iv);
	return $ret;
}

function setAuthTicket($ticket){
	setcookie('authticket', $ticket, time() + (86400 * 365));
}

function getAuthTicket(){
	return (isset($_COOKIE['authticket']) && strlen($_COOKIE['authticket']) > 0 ? $_COOKIE['authticket'] : '');
}

function setCookieHash($hash){
	setcookie('uhash', $hash, time() + (86400 * 365));
}

function isUserLogin()
{
	$cn = db_connect();
	$skey = db_getPortalSessionKey($cn);
	db_disconnect($cn);
	unset($cn);
	if (getSetting('portal','useRights',0) != 1 )
		logOut();
	return ( isset($_SESSION['user_login']) && ($_SESSION['user_login']) == true && isset($_SESSION['portal_sessionkey']) && ($_SESSION['portal_sessionkey'] == $skey )) ;
}

function isUserAdmin()
{
	if (getSetting('portal','useRights',0) != 1 ) {
		logOut();
		return false;
	} else {
		$cn = db_connect();
		return ( isUserLogin() && db_isUserAdmin($cn, $_SESSION['user_ids'][0]));
	}
}

function getUserLogin()
{
	if (getSetting('portal','useRights',0) != 1 )
		logOut();
	return isset($_SESSION['user_login']) ? $_SESSION['user_login'] : null;
}

function getUserIDs()
{
	if (getSetting('portal','useRights',0) != 1 ) {
		logOut();
	}
	return isset($_SESSION['user_ids']) ? $_SESSION['user_ids'] : array(0);
}

function getUserMainID()
{
	return getUserIDs()[0];
}

function getUserFullName()
{
	if (getSetting('portal','useRights',0) != 1 ) {
		logOut();
	} else {
		$cn = db_connect();
		echo db_getUserNameByID($cn, $_SESSION['user_ids'][0], $_SESSION['user_idlanguagecontent']);
		unset($cn);
	}
}

function logIn($user_ids, $user_isadmin, $user_idlanguageinterface, $user_idlanguagecontent, $uhashfake = "", $bsuhash = "", $user_name = "")
{
	$_SESSION['user_ids'] = $user_ids;
	$_SESSION['user_isadmin'] = $user_isadmin;
	$_SESSION['user_login'] = true;
	$_SESSION['sspi_key'] = createGuid();
	$_SESSION['sspi_user'] = $user_name;
	$_SESSION['user_idlanguageinterface'] = $user_idlanguageinterface;
	$_SESSION['user_idlanguagecontent'] = $user_idlanguagecontent;
	$cn = db_connect();
	$skey = db_getPortalSessionKey($cn);
	db_disconnect($cn);
	unset($cn);
	$_SESSION['portal_sessionkey'] = $skey;
	$_SESSION['user_uhashfake'] = $uhashfake;
	$_SESSION['user_bsuhash'] = $bsuhash;
	$_SESSION['ss_key'] = createGuid();
}

function logOut()
{
	unset($_SESSION['user_ids']);
	unset($_SESSION['user_login']);
	unset($_SESSION['user_isadmin']);
	unset($_SESSION['portal_sessionkey']);
	unset($_SESSION['user_uhashfake']);
	unset($_SESSION['user_bsuhash']);
	unset($_SESSION['sspi_key']);
	unset($_SESSION['sspi_user']);
	unset($_SESSION['ss_key']);
}

function createGuid($delimeter = true)
{
    static $guid = '';
     $uid = uniqid("", true);
     $data = "portal";
     $data .= $_SERVER['REQUEST_TIME'];
     $data .= $_SERVER['HTTP_USER_AGENT'];
     $data .= $_SERVER['PHP_SELF'];
     $data .= $_SERVER['REMOTE_ADDR'];
     $data .= $_SERVER['REMOTE_PORT'];
	 $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
	 if ($delimeter) {
		$guid = substr($hash,  0,  8).
		'-'.substr($hash,  8,  4).
		'-'.substr($hash, 12,  4).
		'-'.substr($hash, 16,  4).
		'-'.substr($hash, 20, 12);
	 } else {
		$guid = substr($hash,  0,  8).
		substr($hash,  8,  4).
		substr($hash, 12,  4).
		substr($hash, 16,  4).
		substr($hash, 20, 12);
	 }
     return $guid;
}

function getSessionSSKEY()
{
	return (ISSET($_SESSION['ss_key']) ? $_SESSION['ss_key'] : '');
}
?>
