<?php

class cApp {

	public $cfg, $path, $action;
	public $oDb, $oDbS, $oUrl, $oFunctions, $oSession, $oMenu;
	public $rights, $cookies, $lang, $mutilangKeys;
	private $config;
	
	function __construct() {
		global $_cfg, $_path;
		$this->cfg = $_cfg;
		$this->path = $_path;
		$this->rights = Array();
		$this->config = Array();
		$this->cookies = array_key_exists("cookies", $this->cfg) && $this->cfg['cookies'];
		$this->lang = array_key_exists("lang", $_GET) ? $_GET['lang'] : "";
		$this->mutilangKeys = Array();
	}
	
	public final function run() {
		$this->useCookies();
		if ($this->cfg['db_engine'] == "MySQL") {
			$this->oDb = new cDb($this->cfg['db_host'], $this->cfg['db_user'],
				$this->cfg['db_pass'], $this->cfg['db_dbse']);
			$this->oDbS[] = clone $this->oDb;
			/*if ($this->aKe($this->cfg,"db_host2"))
				$this->oDbS[] = new cDb($this->cfg['db_host2'], $this->cfg['db_user2'],
					$this->cfg['db_pass2'], $this->cfg['db_dbse2']);
			if ($this->aKe($this->cfg,"db_host3"))
				$this->oDbS[] = new cDb($this->cfg['db_host3'], $this->cfg['db_user3'],
					$this->cfg['db_pass3'], $this->cfg['db_dbse3']);*/
		} else
			showErrorTemplate("dbext",$this->cfg['db_engine']);
		if ($this->langActive())
			$this->checkLang();
		$this->oSession = new cSession($this->oDbS[0]);
		
		// Actions
		if (array_key_exists("Insert",$_POST))
			$this->action = "Insert";
		elseif (array_key_exists("Save",$_POST))
			$this->action = "Save";
		elseif (array_key_exists("Back",$_POST))
			$this->action = "Back";
		elseif (array_key_exists("submit",$_POST))
			$this->action = $_POST['submit'];
		else
			$this->action = "";
			
		$redirectAfterLogin = FALSE;
		
		// Login + Search
		if (array_key_exists("login",$_POST))
			if ($this->oSession->login())
				$redirectAfterLogin = TRUE;
		if (array_key_exists($this->cfg['session_name'],$_GET)
			|| $this->cookies && array_key_exists($this->cfg['session_name'],$_COOKIE))
				$this->oSession->restore();
		if (array_key_exists("logout",$_POST))
			if ($this->oSession->logout())
				$redirectAfterLogin = TRUE;
		if ($this->aKe($_POST,"search_string")) {
			$this->oSession->start();
			$_SESSION['search_string'] = $_POST['search_string'];
		}
			
		$this->oUrl = new cUrl($this->oSession, $this->getGeneralConfig("main_page"));
		$this->oMenu = new cMenu($this->oDbS[0], $this->oUrl);
		$this->oFunctions = new cFunctions($this->oDbS[0], $this->oUrl, $this->oSession, new cForm);
		if ($redirectAfterLogin)
			$this->_home($this->oUrl->href());
			
		$coreFile = $this->path['core'] . "_core.php";
		try {
			if (file_exists($coreFile))
				return include $coreFile;
			else
				throw new Exception($exceptionMsg);
		} catch (Exception $e) {
			showErrorTemplate($e->getMessage());
		}
		$this->oDb->disconnect();
	}
	
	public final function loginForm() {
		return include $this->path['core_tmpl'] . "_login.tmpl.php";
	}
	
	public final function langSelectionTool() {
		return include $this->path['core_tmpl'] . "_langs.tmpl.php";
	}
	
	public final function _HTML($nadpis, $content) {
		$_path = $this->path;
		$_cfg = $this->cfg;
		ob_start();
		include $this->path['core_tmpl'] . "head.tmpl.php";
		$this->_BODY($nadpis, $content);
		include $this->path['core_tmpl'] . "foot.tmpl.php";
		$str = ob_get_contents();
		ob_end_clean();
		return $str;
	}
	
	public final function _BODY($nadpis, $content) {
		try {
			$homeFile = $this->path['html'] . "home.tmpl.php";
			if ($this->oSession->logged()) {
				$pageFile = $this->path['html'] . "pageIn.tmpl.php";
			}
			else
			$pageFile = $this->path['html'] . "page.tmpl.php";
			if (file_exists($homeFile) && $this->oUrl->page == "home" ||
				$this->oUrl->page == $this->getGeneralConfig("main_page"))
				include $homeFile;
			elseif (file_exists($pageFile) && !empty($this->oUrl->page))
				include $pageFile;
			else
				throw new Exception("corefile");
		} catch (Exception $e) {
			showErrorTemplate($e->getMessage());
		}
	}
	
	public function hasRights($what, $idMenu=-1, $act=-1) {
		if ($idMenu == -1)
			$idMenu = $this->oMenu->getID($this->oUrl->page);
		if ($act == -1)
			$act = $this->oUrl->action;
		return $this->checkRights($idMenu,$act,$what,FALSE);
	}
	
	public function checkRights($idMenu, $act, $what, $redirect=TRUE) {
		//echo 'chyba tu'.$this->rights[$idMenu][$act][$what];
		if (@!$this->rights[$idMenu][$act][$what]) {
			if ($redirect)
				// $this->oSession->_home();
				showErrorTemplate("rights");
			else
				return FALSE;
		}
		return TRUE;
	}
	
	public final function getGeneralConfig($var) {
		if (!$this->aKe($this->config, $var)) {
			$gR = $this->oDb->obtain("SELECT `value` FROM settings WHERE `variable` = '".$var."'");
			$this->config[$var] = $gR['value'];
		}
		return $this->config[$var]; 
	}
	
	public final function aKe($var, $key) {
		if (is_array($var) && array_key_exists($key, $var))
			return TRUE;
		return FALSE; 
	}
	
	public function _home($other_addr="") {
		if ($other_addr) $address = $other_addr;
		else $address = $this->path['url'];
		ob_start();
		@ob_clean();
		Header("Location: ".str_replace("&amp;","&",$address));
		die($address);
	}
	
	static final function curDate() {
		return date("Y-m-d H:i:s");
	}
	
	private function useCookies() {
		/*
		// Nepouzite este... Dedenie je cudne
		if ($this->cookies) {
			$cName = "cmsv2_test";
			SetCookie($cName, $cName, time()+90);
			if (!array_key_exists($cName,$_COOKIE))
				$this->cookies = FALSE;
			unset($_COOKIE[$cName]);
		}
		*/
	}
	
	protected function langActive() {
		return strlen($this->lang) > 0;
	}
	
	protected function multilangKeysGet() {
		if (count($this->mutilangKeys) == 0) {
			// :) Aby sa funkcia nevolala znova
			$this->mutilangKeys["-1"]["-1"] = "-2";
			$q = $this->oDb->query("SELECT * FROM lang_keys");
			while ($res = $this->oDb->get($q))
				$this->mutilangKeys[$res['tabname']][$res['keyname']] = TRUE;
		}
		return $this->mutilangKeys;
	}
	
	private function checkLang() {
		if ($this->oDb->dbnumrows("SELECT id_langs FROM langs WHERE lang = '{$this->lang}'") < 1)
			$this->_home();
	}

}

?>