<?php
mb_internal_encoding('UTF-8');

function renderMainMenu($scriptName = NULL, $renderCloseSectionTag = TRUE){
	if(!(is_readable(realpath(dirname(__FILE__).'/../').'/templates/mainmenu.template'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/templates/mainmenu.template');
	} else {
		include_once(realpath(dirname(__FILE__).'/../').'/templates/mainmenu.template');
		echoMainMenu($cn, $usr_arr, $scriptName, $renderCloseSectionTag);
	}
}

function renderLoginBlock(){
	if(!(is_readable(realpath(dirname(__FILE__).'/../').'/templates/header.template'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/templates/header.template');
	} else {
		include_once(realpath(dirname(__FILE__).'/../').'/templates/header.template');
	}
}

function renderFooterTemplate()
{
	if(!(is_readable(realpath(dirname(__FILE__).'/../')."/templates/footer.template"))) {
		die("Error - Could not open or read file ".realpath(dirname(__FILE__).'/../')."/include/footer.template");
	} else {
		include_once(realpath(dirname(__FILE__).'/../')."/templates/footer.template");
	}
}

function getReportVotingFooter()
{
	if(!(is_readable(realpath(dirname(__FILE__).'/../')."/templates/votingfooter.template"))) {
		die("Error - Could not open or read file ".realpath(dirname(__FILE__).'/../')."/include/votingfooter.template");
	} else {
		include_once(realpath(dirname(__FILE__).'/../')."/templates/votingfooter.template");
	}
}

function getReportVotingFooterJS()
{
	if(!(is_readable(realpath(dirname(__FILE__).'/../')."/templates/votingfooter.js.template"))) {
		die("Error - Could not open or read file ".realpath(dirname(__FILE__).'/../')."/include/votingfooter.js.template");
	} else {
		include_once(realpath(dirname(__FILE__).'/../')."/templates/votingfooter.js.template");
	}
}

function getCurPageWithEncodeParams($url = '') {
	if ($url == '') {
		return str_replace('&', '_@nd_', $_SERVER["REQUEST_URI"]);
	} else {
		return str_replace('&', '_@nd_', $url);
	}
}

function getPageDencodeParams($url) {
	return str_replace('_@nd_', '&', $url);
}

function getCurPageURL($exclude = "") {
	$pageURL = 'http';
	if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
		$pageURL .= "s";
	}
	$pageURL .= "://";
	if (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	if (strlen($exclude) > 0) {
		$pageURL = str_ireplace($exclude, "", $pageURL);
	}
	return $pageURL;
	echo $pageURL;
}

function getCurPageURLWO($exclude = "") {
	$pageURL = 'http';
	if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
		$pageURL .= "s";
	}
	$pageURL .= "://";
	if (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"];
	}

	$ret = $pageURL.getCurPageSubFolders();
	if (is_array($exclude)) {
		foreach ($exclude as $ex) { 
			$ret = str_ireplace($ex, "", $ret);
			return $ret;
		}
	} else {
		return (strlen($exclude) > 0 ? str_ireplace($exclude, "", $ret) : $ret);
	}
}

function getCurPageSubFolders(){
	$folders = '';
	$subfld = $_SERVER['PHP_SELF'];
	$fld = explode("/", $subfld);
	$size = sizeof($fld);
	if ($size > 0) {
		unset($fld[$size-1]);
		$folders = implode("/", $fld);
	}
	return $folders;
}

function urlReplaceParam(
		$url,
		$varname,
		$value = NULL, // если NULL - убираем переменную совсем
		$clean = TRUE // превращать ли ?one=&two=
) {              // в ?one&two (так адрес красивее)
	// Версия функции "substitue get parameter" без регулярных выражений
 	if (is_array($varname)) {
		foreach ($varname as $i => $n) {
			$v = (is_array($value))
			? ( isset($value[$i]) ? $value[$i] : NULL )
			: $value;
			$url = urlReplaceParam($url, $n, $v, $clean);
		}
		return $url;
	}

	$urlinfo = parse_url($url);

	$get = (isset($urlinfo['query']))
	? ($urlinfo['query'])
	: '';

	parse_str($get, $vars);

	if (!is_null($value))        // одновременно переписываем переменную
		$vars[$varname] = $value; // либо добавляем новую
	else
		unset($vars[$varname]); // убираем переменную совсем

	$new_get = str_replace('%5C%5C','%5C',http_build_query($vars));

	if ($clean) {
		$new_get = preg_replace( // str_replace() выигрывает
				'/=(?=&|\z)/',     // в данном случае
				'',                // всего на 20%
				$new_get
		);
	}

	$result_url =   (isset($urlinfo['scheme']) ? "$urlinfo[scheme]://" : '')
	. (isset($urlinfo['host']) ? "$urlinfo[host]" : '')
	. (isset($urlinfo['port']) ? ":$urlinfo[port]" : '')
	. (isset($urlinfo['path']) ? "$urlinfo[path]" : '')
	. ( ($new_get) ? "?$new_get" : '')
	. (isset($urlinfo['fragment']) ? "#$urlinfo[fragment]" : '')
	;
	return $result_url;
}

function getTitleForSettings(){
	$pm = htmlentities(getSetting('panel','title','Business Studio Portal'),ENT_QUOTES, "UTF-8"); //STU: вынес в настройки
	return $pm;
}

function renderTitle($objectName="", $repotrName=""){
	$pm = getTitleForSettings();
	if (strlen(trim($objectName))){
		$pm .= " ".$objectName;
	}
	if (strlen(trim($objectName))>0 && strlen(trim($repotrName))>0){
        $pm .= " (".$repotrName.")";
	}
	return $pm."";
}


function renderHeader(){
	//js disable warning
	echo '<noscript><div class="fullscreenDiv"><div style="position: absolute;    width: 300px;    height: 250px;    top: 50%;    left: 45%;    margin-left: -50px;    margin-top: -25px;"><p style="color:red">'; 
	getResource("message.javascriptdisable");
	echo '</p></div></div>​</noscript>';

	$pm = html_entity_decode(getSetting('company','portalname','',1));
	$pm = strlen($pm) > 0 ? " - ".$pm : $pm;
	$pm = htmlentities(getSetting('panel','title','Business Studio Portal'),ENT_QUOTES, "UTF-8").html_entity_decode($pm); //STU: вынес в настройки

	if (getSetting('portal','useRights',0) == 1){
		echo "<div id=\"header-h2\"><span><span><table><tr><td style=\"	background-image: url( ./img/portal_minilogo.png );background-position: left top;	background-repeat: no-repeat; padding:1px 0px 0px 18px;\">".$pm."</td></tr></table></span></span></div>";
	}
	else {
		echo "<div id=\"header-h2\"><span><span><table><tr><td style=\"padding:1px 0px 10px 4px;\">".$pm."</td></tr></table></span></span></div>";
	}

	$pm = getSetting('company','logo','');
	if (strlen($pm) > 0 ){
    echo "<div id=\"header-h1\" style=\"background-image: url('".$pm."')\"></div>";
	} else {
		$tl = html_entity_decode(getSetting('company','name','',1));
		echo "<div id=\"header-h1\" style=\"display:table;\"><div id=\"table-sell\"><h2 style=\"text-align: left;\">".$tl."</h2></div></div>";
	}
}

function getDataByUrl($url)
{
	$curl = curl_init($url);
	echo $url;
	curl_setopt($curl, CURLOPT_URL, $url );
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($curl);
	curl_close($curl);
	return $result;
}

function getDataByUrlPost($url)
{
	$chp=curl_init($url);
	curl_exec($chp);
	curl_close($chp);
}

function renderCommonCSS()
{
	if(!(is_readable(realpath(dirname(__FILE__).'/../')."/templates/commoncss.template"))) {
		die("Error - Could not open or read file ".realpath(dirname(__FILE__).'/../')."/include/commoncss.template");
	} else {
		include_once(realpath(dirname(__FILE__).'/../')."/templates/commoncss.template");
	}
}

function renderCommonMeta($description="")
{
	echo '<meta name="description" content="'.(empty($description) ? 'Business Studio Portal' : $description).'"/>';
	if(!(is_readable(realpath(dirname(__FILE__).'/../')."/templates/commonmeta.template"))) {
		die("Error - Could not open or read file ".realpath(dirname(__FILE__).'/../')."/include/commonmeta.template");
	} else {
		include_once(realpath(dirname(__FILE__).'/../')."/templates/commonmeta.template");
	}	
}

function buildSortColumnTitle( $name, $is_active, $order_column, $order_val, $exclude = "" ) {
	global $default_order_val;
	$new_order_val = ( $order_val == 'asc' ) ? 'desc' : 'asc';
	$link = ( !$is_active ) ? "" : "<nobr><a href=".buildTableTitleURL( $order_column, $new_order_val, $exclude )." class='btn-sort discussion-sort-label ".( ( $order_val == 'asc' ) ? 'btn-sort-asc' : 'btn-sort-desc' )."' title='".( ( $order_val == 'asc' ) ? '&uarr;' : '&darr;' )."'>".( ( $order_val == 'asc' ) ? '&uarr;' : '&darr;' )."</a>";
	$link .= "<a class='discussion-sort-label' href=".buildTableTitleURL( $order_column, ( $is_active ?  $new_order_val : $default_order_val ), $exclude ).">".$name."</a></nobr>";
	return $link;
}

function buildTableTitleURL( $order_column, $order_val, $exclude = "") {
	$url = getCurPageURL($exclude);
	$url = urlReplaceParam($url,'order_column', $order_column);
	$url = urlReplaceParam($url,'order_val', $order_val);
	return  $url;
}

function nameReportWithBranchAndLanguage($flroot, $oguid, $rguid, $lang_short, $idbranch, $end='.htm'){
	$guid = $oguid.($rguid==null?'':'_'.$rguid);
	if (getSetting('portal','useRights', 0)==1){
		return $flroot.'/'.$idbranch.'/'.($lang_short == null ? '' : $lang_short.'/').$guid.$end;
	}else{
		return $flroot.'/'.$guid.$end;
	}
}

function renderModalHourGlassDiv()
{
	if(!(is_readable(realpath(dirname(__FILE__).'/../')."/templates/modalhourglass.template"))) {
		die("Error - Could not open or read file ".realpath(dirname(__FILE__).'/../')."/include/modalhourglass.template");
	} else {
		include_once(realpath(dirname(__FILE__).'/../')."/templates/modalhourglass.template");
	}
}

function linkTextReplacer($buff){
    //59703
    $rpos = 0;
    $i = 0;
	$lpos = strpos($buff, '<a ', $rpos);
	while($lpos !== FALSE && $i < 5){
                $i++;
                $rpos = strpos($buff, '</a>', $lpos + 3); 
		$linksource = substr($buff, $lpos, $rpos - $lpos + 4);
		$link = str_replace('&', '&amp;', $linksource);
		$xmlstr = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'.$link;
                $xml = simplexml_load_string($xmlstr);
                $title = mb_strtolower($xml,"UTF-8");
		$elem = $xml->xpath('//a');
		$href = "" ;
		if (isset($elem[0]["href"])) {
                        $href = mb_strtolower($elem[0]["href"],"UTF-8");
                        if ($href == $title && strpos($href, 'businessmodel') !== FALSE){
                                $buff = str_replace($linksource, $elem[0]["href"], $buff);
                                $rpos = 0;
                        } else {
                                $rpos = $rpos + 4;
                        }
                }
                $lpos = strpos($buff, '<a ', $rpos);
	}
	return $buff;        
}


function renderModalDialogWithIframeDiv()
{
	if(!(is_readable(realpath(dirname(__FILE__).'/../')."/templates/modaldialogwithiframe.template"))) {
		die("Error - Could not open or read file ".realpath(dirname(__FILE__).'/../')."/include/modaldialogwithiframe.template");
	} else {
		include_once(realpath(dirname(__FILE__).'/../')."/templates/modaldialogwithiframe.template");
	}
}


function getImgIcon($db_value){
	return 'img/'.$db_value;
	//return 'img/objects/'.$db_value.'.png';
}
?>