<?php

$ruri = $_SERVER['REQUEST_URI'];
$ln = strlen($ruri);
$lsl = strrpos($ruri,'/');

if ($_SERVER['HTTP_HOST']!="nwi-tours.ru" && $_SERVER['HTTP_HOST']!="www.nwi-tours.ru") {
	$newurl = "http://nwi-tours.ru/";
	header('HTTP/1.1 301 Moved Permanently');
	header("Location: $newurl");
	exit();	
}

/*
//$f = fopen($_SERVER['DOCUMENT_ROOT']."/debug_log","a");
//fwrite($f, $ruri."\r\n");
//fclose($f);

if (strpos($ruri,"?")  && strpos(" ".$ruri,"/admin/")!=1 && strpos(" ".$ruri,"/personalnyj_razdel/")!=1 ) {
	$newurl = "http://".$_SERVER['HTTP_HOST'].str_replace("?","",$ruri);
	header('HTTP/1.1 301 Moved Permanently');
	header("Location: $newurl");
	exit();	
}

if ($lsl!=$ln-1 && strpos(" ".$ruri,"/admin/")!=1 && strpos(" ".$ruri,"/personalnyj_razdel/")!=1 ) {
	$newurl = "http://".$_SERVER['HTTP_HOST'].substr($ruri,0,$lsl+1);
	header('HTTP/1.1 301 Moved Permanently');
	header("Location: $newurl");
	exit();	
}

*/

	ini_set('include_path', str_replace("\\", "/", dirname(__FILE__)) . '/');
	ini_set('session.use_only_cookies', '1');
	@set_time_limit(300);
	setlocale(LC_ALL, 'ru_RU.utf-8');
	error_reporting(E_ALL);
	
	header("Cache-Control: no-store, no-cache, must-revalidate");	// HTTP/1.1
	header("Cache-Control: post-check=0, pre-check=0", false);	// HTTP/1.1
	header("Pragma: no-cache");	// HTTP/1.0
	header("Date: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("X-XSS-Protection: 0"); //Disable new IE8 XSS filter

	if(!isset($_REQUEST['path'])) {
		$_REQUEST['path'] = "/";
	}
	
	if(!isset($_ENV['OS']) || strtolower(substr($_ENV['OS'], 0, 3)) != "win") {
		setlocale(LC_NUMERIC, 'en_US.utf8');
	}
	
	if(function_exists("mb_internal_encoding")) {
		mb_internal_encoding('UTF-8');
	}	

	function set_timebreak($time_end = false) {
		global $time_start;
		
		if($time_end == false) {
			$time_end = microtime(true);
		}
		$time = $time_end - $time_start;
		echo "\r\n", '<!-- This page generated in ', $time, ' secs -->', "\r\n";
		exit();
	}
    

	if (!defined("UMI_SESSION_LIVETIME")) {
		define ("UMI_SESSION_LIVETIME", 60); //minutes
	}
	ini_set("session.gc_maxlifetime", (string) UMI_SESSION_LIVETIME*60);
	ini_set("session.cookie_lifetime", "0");
	ini_set("session.use_cookies", "1");
	ini_set("session.use_only_cookies", "1");

	if(file_exists("./cacheControl.php")) {
		include "./cacheControl.php";
	}
	
	if(file_exists("./sessions_memcached.php")) {
		include "./sessions_memcached.php";
	}


	$request_uri = trim($_SERVER['REQUEST_URI'], "/");
	if(!trim($request_uri, "/")) $request_uri = "__splash";

	$path_c = '';
	$is_admin =  (substr($request_uri, 0, strlen("admin")) == "admin") ? true : 
				((substr($request_uri, 3, strlen("admin")) == "admin") ? true : false );

	if(function_exists("prepareCacheFile") && $is_admin == false && !strpos($_SERVER['REQUEST_URI'],"user/") && !strpos($_SERVER['REQUEST_URI'],"users/") && $_SERVER['REQUEST_METHOD']!="POST") {
		if(file_exists("./cache.config")) {
			session_start();
			$path_c = prepareCacheFile($request_uri);
		}
	} else {
		//session_start();
	}
	$is_cached = false;

	$time_start = microtime(true);
	tryGetCache($path_c, $is_admin);

	include 'config.php';
	
	enableOutputCompression();

	// try preauthorize :
	if (file_exists("./classes/permissionsModel/iUmiAuth.php") && file_exists("./classes/permissionsModel/umiAuth.php")) {
		$i_preauth = umiAuth::getInstance()->tryPreAuth();
	}

	// start session if not started during pre-authorization :
	if (!session_id()) session_start();
	check_session();
	
	if(file_exists("./umaps/sitemap.xml")) {
		$matches = new matches("sitemap.xml");
		$matches->setCurrentURI(getRequest('path'));
		
		try {
			$matches->execute();
		} catch (Exception $e) {
			traceException($e);
		}

		unset($matches);
	}


	if(defined("CLUSTER_CACHE_CORRECTION")) {
		cacheFrontend::getInstance();
		clusterCacheSync::getInstance();
	}
	
	domainsCollection::getInstance();
	langsCollection::getInstance();
	regedit::getInstance();
	
	$cmsControllerInstance = cmsController::getInstance();
	$regedit = regedit::getInstance();
	
	if($regedit->getVal("//settings/allow_alt_name_with_module_collision")) {
	    if(!defined("IGNORE_MODULE_NAMES_OVERRITE")) {
	        define("IGNORE_MODULE_NAMES_OVERRITE", "1");
	    }
	}
	
	$cmsControllerInstance->nav_arr = Array();

	$regedit->getList('//modules');
	$regedit->getList('//settings');

	$cmsControllerInstance->analyzePath();	

	$mode   = $cmsControllerInstance->getCurrentMode();
	$module = getRequest('module');
	$method = getRequest('method');
	
	system_runSession();
	
	$xsltTemplater = xslTemplater::getInstance();
    if(getRequest("xmlMode") == "force" && $mode != "admin") {
		header("Content-type: text/html; charset=utf-8");
        $xsltTemplater->init();
        $xsltTemplater = xslTemplater::getInstance();
        $xsltTemplater->flushXml();
	}
	

	$parser = templater::getInstance();

	if($cmsControllerInstance->getCurrentMode() == "admin") {
		system_returnSkinPath();
	}

	$primary_module = $cmsControllerInstance->getCurrentModule();
	
	try {
		$cmsControllerInstance = cmsController::getInstance();
		if($cmsControllerInstance->getCurrentMode() == "admin") {
			xslTemplater::getInstance()->init();
		}
	} catch (Exception $e) {
		traceException($e);
	}

	if($cmsControllerInstance->getCurrentMode() == "admin") {
		$tpl_skinned = system_returnSkinPath();
	}

	try {
		if($cmsControllerInstance->getCurrentMode() == "admin") {
			header('Content-Type: text/xml; charset=utf-8');
			try {
				$cmsControllerInstance->parsedContent = macros_content();
			} catch(requireAdminPermissionsException $e) {}

			$xsltTemplater = xslAdminTemplater::getInstance();
			$xsltTemplater->init("./main.xsl");
					
			if(getRequest("xmlMode") == "force") {
				$xsltTemplater->flushXml();
			} else {
				header("Content-type: text/html; charset=utf-8");
				$res = $xsltTemplater->parseResult();
				
				if(is_null(getRequest('showStreamsCalls')) == false) {
					umiBaseStream::getCalledStreams();
					exit();
				}
				
				echo $res;
			}
			set_timebreak();
		} else {
			header('Content-Type: text/html; charset=utf-8');
			if($primary_module_inst = $cmsControllerInstance->getModule($primary_module)) {
				$tpl_id = $primary_module_inst->get_tpl_id();
			} else {
				$tpl_id = def_module::get_tpl_id();
			}
			
			$tpl_path = system_get_tpl($tpl_id);
			
            if(substr($tpl_path, strlen($tpl_path) - 4, 4) == ".xsl") {
				header("Content-type: text/html; charset=utf-8");
				
				define("XSLT_TPL_MODE", "1");
	
	            $xsltTemplater->init($tpl_path);
	            
	            try {
					$cmsControllerInstance->parsedContent = macros_content();
				} catch(requireAdminPermissionsException $e) {}
				
	            $xsltTemplater = xslTemplater::getInstance();
	            $res = $xsltTemplater->parseResult();
            } else {
				define("XSLT_TPL_MODE", "");
				
				try {
					$cmsControllerInstance->parsedContent = macros_content();
				} catch(requireAdminPermissionsException $e) {}

				if(!$tpl_path) {
					$tpl_path = 'index.tpl';
				}
                
                $tpl_path = getPrintableTpl($tpl_path);
				
				if(!file_exists("tpls/content/".$tpl_path)) {
					$lang_filepath = substr($tpl_path, 0, strlen($tpl_path) - 3) .
									 cmsController::getInstance()->getCurrentLang()->getPrefix() .
									 ".tpl";
					$lang_filepath = getPrintableTpl($lang_filepath);
					$tpl_path      = $lang_filepath;
				}
			
				if(!file_exists("tpls/content/" . $tpl_path)) {
					include "./errors/no_design_template.html";
					exit();
				}

				if(!XSLT_TPL_MODE) {
					$resourse = file_get_contents('tpls/content/' . $tpl_path, 1);
				}
			}
		}
		
		if(!defined("XSLT_TPL_MODE") || !XSLT_TPL_MODE || $cmsControllerInstance->getCurrentMode() == "admin") {
			$parser->init($resourse);
		}
	} catch (Exception $e) {
		traceException($e);
	}

	if(!($regedit->getVal('//settings/chache_browser'))) {
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Pragma: no-cache");
	}

	if(!defined("XSLT_TPL_MODE") || !XSLT_TPL_MODE || $cmsControllerInstance->getCurrentMode() == "admin") {
		$res = $parser->putLangs($parser->output);

		if($cmsControllerInstance->getCurrentMode() == '') {
			$res = str_replace("&#037;", "%", $res);
		}	

		$res = str_replace("%pid%", $cmsControllerInstance->getCurrentElementId(), $res);
		$res = $parser->parseInput($res);
		$res = str_replace("%catched_errors%", macros_catched_errors(), $res);
		$res = $parser->cleanUpResult($res);

	}

	if((defined("DB_DRIVER") && DB_DRIVER != "xml")||(!defined("DB_DRIVER")))
    if($stat_module = $cmsControllerInstance->getModule('stat')) {
		$stat_module->pushStat();
	}
	
	if($cmsControllerInstance->getCurrentMode() == "") {
		if($regedit->getVal("//settings/chache_browser")) {
			if($update_time = umiHierarchy::getInstance()->getElementsLastUpdateTime()) {
				header("Last-Modified: " . gmdate("D, d M Y H:i:s", $update_time) . " GMT");
				header("Expires: " . gmdate("D, d M Y H:i:s", $update_time + 3600) . " GMT");
			}
		}
		$parser->prepareQuickEdit();
	}

	$mt = microtime(true);
	
	if(is_null(getRequest('showStreamsCalls')) == false) {
		umiBaseStream::getCalledStreams();
		exit();
	}
	
	header("ETag: \"" . sha1($res) . "\"");
	echo $res;

	if($is_cached == false && !$is_admin) {
		if(function_exists("trySaveCache")) {
			if(file_exists("./cache.config") && isset($path_c)) {
				trySaveCache($path_c, $res);
			}
		}
	}

	set_timebreak($mt);
?>