<?php
// load laguare resurce

if(!(is_readable(realpath(dirname(__FILE__)).'/settings.inc'))) {
	logmessage('Error - Could not open or read file include/settings.inc');
	StopPortalOnError();
	header("Location: ".getCurPageURLWO()."/stopbs.php");
	ob_end_flush();
	exit;		
} else {
    include_once(realpath(dirname(__FILE__)).'/settings.inc');
}

function getLanguageListFromBrowser($languageList = null) {
    if (is_null($languageList)) {
        if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            return array();
        }
        $languageList = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
    }
    $languages = array();
    $languageRanges = explode(',', trim($languageList));
    foreach ($languageRanges as $languageRange) {
        if (preg_match('/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/', trim($languageRange), $match)) {
            if (!isset($match[2])) {
                $match[2] = '1.0';
            } else {
                $match[2] = (string) floatval($match[2]);
            }
            if (!isset($languages[$match[2]])) {
                $languages[$match[2]] = array();
            }
            $languages[$match[2]][] = strtolower($match[1]);
        }
    }
    krsort($languages);
    return $languages;
}
function getLangFromBrowser(){
		$lngList = getLanguageListFromBrowser();
		foreach ($lngList as $k => $v) {
			if (is_readable(realpath(dirname(__FILE__).'/../').'/resources/'.$lngList[ $k ][ 0 ].'.ini')){
				return $lngList[ $k ][ 0 ];
			}
		}
		return getSetting('portal','defaultLanguage','en');
}

// проверка что заданы языки
function checkLanguagesSettings($cn) {
	$res = db_checkLanguagesSettings($cn);
	$_SESSION['allowLanguages'] = mb_strtolower(getSetting('portal','allowLanguages',''));
	$res = $res && (mb_strlen($_SESSION['allowLanguages']) > 1);
	if (!$res){
		StopPortalOnError();
		if (basename($_SERVER['SCRIPT_NAME'], ".php") != "stop") {
			header("Location:  ".getCurPageURLWO()."/stop.php");
			ob_end_flush();
			exit;
		}
	}
	if ( getSetting('portal','useRights',0) == 1) { 
		if (IsUserLogin()) {
			db_getUserLangsByID($cn, getUserMainID());
		} else {
			$langFromBrowser = getLangFromBrowser();
			$_SESSION['user_idlanguageinterface'] = db_checkInterfaceLangByID($cn, db_getLanguageID($cn,strtolower($langFromBrowser),-1));
			$_SESSION['user_idlanguagecontent'] = db_getDefaultLangID($cn);
		}
	} else {
		$langFromBrowser = getLangFromBrowser();
		if (!isset($_SESSION['user_idlanguageinterface'])){
			$_SESSION['user_idlanguageinterface'] = db_checkInterfaceLangByID($cn, db_getLanguageID($cn,strtolower($langFromBrowser),-1));
		}
		$_SESSION['user_idlanguagecontent'] = db_getDefaultLangID($cn);
	}
	return $res;
}	 

function checkLanguage()
{
	$cn = db_connect();
	if (!checkLanguagesSettings($cn)){
		if (basename($_SERVER['SCRIPT_NAME'], ".php") != 'stop') {
			header("Location: ".getCurPageURLWO()."/stop.php");
			ob_end_flush();
			exit;
		}
	}
	
	if (isset($_REQUEST['lang'])){
		$validPages = array("searchservice", "treestructservice", "report", "reportnotexist", "businessmodel", "download", "downloadreportfile", "img", "adminstatistic");
		if ( !in_array(mb_strtolower(basename($_SERVER['SCRIPT_NAME'], ".php")), $validPages) ) {
			$url = urlReplaceParam(getCurPageURL() ,'lang');
			header("Location: ".$url);
			ob_end_flush();
			if ($cn) {db_disconnect($cn);}
			exit;
		} 
	}
	
	if ($cn) {db_disconnect($cn);}

	if ( getSetting('portal','start',0) != 1 ) {
		if (basename($_SERVER['SCRIPT_NAME'], ".php") != 'stop') {
			header("Location: ".getCurPageURLWO()."/stop.php");
			ob_end_flush();
			exit;
		}
	}	
}


function clearResource(){
	unset($_SESSION['lang']);
	unset($_SESSION['resources']);
	unset($_SESSION['user_idlanguageinterface']);
	unset($_SESSION['user_idlanguagecontent']);
}

function loadResource(){
    $langf  = getLanguage();
    if( ($langf != '') and is_readable(realpath(dirname(__FILE__).'/../').'/resources/'.$langf.'.ini')) {
        $_SESSION['resources'] = parse_ini_file(realpath(dirname(__FILE__).'/../').'/resources/'.$langf.'.ini', true);
        $_SESSION['lang'] = $langf;
    } else {
        clearResource();
		logmessage("Main resources file is lost!".$langf);
		StopPortalOnError();
		header("Location: ".getCurPageURLWO()."/stopbs.php");
		ob_end_flush();
		exit;		
	}
}

function getLanguage(){
	$cn = db_connect();
	$lang = !empty( $_SESSION['user_idlanguageinterface'] ) ? db_getLanguageShortByID($cn,$_SESSION['user_idlanguageinterface'], true) : getDefaultInterfaceLangShortName($cn);
	if ($cn) {db_disconnect($cn);}
	return $lang;
}

function getResource($resource)
{
	echo returnResource($resource);
}

function returnResource($resource)
{
	$lang = getLanguage();
    if (!isset($_SESSION['resources']) || !isset($_SESSION['lang']) || (sizeof($_SESSION['resources']) == 0) ||  ($_SESSION['lang']) != $lang || !array_key_exists($resource, $_SESSION['resources'])) {
		loadResource();
    }
    if ( array_key_exists($resource, $_SESSION['resources'] )) {
        return urldecode($_SESSION['resources'][$resource]);
    } else {
        return returnResourceDefault($resource);
    }
}

function getResourceDefault($resource)
{
	echo returnResourceDefault($resource);
}

function returnResourceDefault($resource)
{
	$cn = db_connect();
	$langf = getDefaultInterfaceLangShortName($cn);
	if( ($langf != '') and is_readable(realpath(dirname(__FILE__).'/../').'/resources/'.$langf.'.ini')) {
		$_SESSION['resourcesdefault'] = parse_ini_file(realpath(dirname(__FILE__).'/../').'/resources/'.$langf.'.ini', true);
    } else {
		logmessage("Main resources file is lost! ".$defln);
		StopPortalOnError();
		header("Location: ".getCurPageURLWO()."/stopbs.php");
		ob_end_flush();
		exit;		
	}
    if ($cn) {db_disconnect($cn);}
	
    if ( array_key_exists($resource, $_SESSION['resourcesdefault'] )) {
        return urldecode($_SESSION['resources'][$resource]);
    } else {
        return "WARNING: resources ".$resource." not found!";
    }
}

function getIniFileFromLanguage($langfile)
{
	$adress = realpath(dirname(__FILE__).'/../').'/resources/'.$langfile.'.ini';
	if (!is_readable($adress))
		return false;
	return parse_ini_file($adress);
}

function getDefaultInterfaceLangShortName($cn){
// STU 54368.3 отключили взятие языка интерфейса на основном языке данных
//	$langf = db_getDefaultLangShortName($cn);
//	$adress = realpath(dirname(__FILE__).'/../').'/resources/'.$langf.'.ini';
//	if (is_readable($adress))
//		return $langf;
	return getSetting('portal', 'defaultLanguage', 'en');
}

function getResourceByLang($resource, $lang = null )
{
	if($lang == null ){
		// return current local
		return returnResource($resource);
	} else {
		if (!$res = getIniFileFromLanguage($lang)){
			$cn = db_connect();
			$langf = getDefaultInterfaceLangShortName($cn);
			if ($cn) {db_disconnect($cn);}
			if (!$res = getIniFileFromLanguage($langf)){
				$res = array($resource=>$lang);	//Было так в этом случае: $result =$lang;
			}
		}
		return urldecode($res[$resource]);
	}
}

function echoSetLangauge(){
	echo getCurPageURLWO()."/service/setlanguage.php?&returl=".getCurPageWithEncodeParams();
}

?>