<?php
/*
	DevSaver Web Framework
	Copyright (c) 2013-2016 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com		
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CModules extends CModulesBackend{
	
	var $tplvars; 

	function __construct() {
		//$this->CPlugin($db, $tables , $templates);
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;

		parent::DoEvents();
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __preinit() {
		global $_LANG_ID , $_SESS , $_TSM , $base , $_LANG , $_CONF;

		if ($this->__preinited) {
			return "";
		}

		if (is_array($_SESS["minibase"]["raw"])) {
			$cond = " AND mod_status in (1,2) ";
		} else {
			$cond = " AND mod_status = 1 ";
		}

		//device detection
		if ($base->isTablet) {
				$cond .= " AND find_in_set(2,mod_device) ";
		} elseif ($base->isMobile) {
				//phone
				$cond .= " AND find_in_set(3,mod_device) ";
			} else {
				//desktop
				$cond .= " AND find_in_set(1,mod_device) ";
			}

		//read modules without language
		$modules = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:modules']},
					{$this->tables['core:user_modules']}
				WHERE 
					module_installed = 2 AND 
					mod_module=module_id 
					{$cond}
				ORDER BY 
					mod_parent ASC,
					mod_order ASC"
		);

		if (is_array($modules)) {
			foreach ($modules as $key => $val) {
				$_modules[$val["mod_id"]] = $val;
			}			

			$modules = $_modules;


			$modules_lang = $this->db->QFetchRowArray("
				SELECT * FROM 
					{$this->tables['core:user_modules_lang']}
				WHERE 
					lang_id = {$_LANG_ID} AND 
					mod_id in (" . implode("," , array_keys($modules)) .")"				
			);

			if (is_array($modules_lang)) {
				foreach ($modules_lang as $key => $val) {
					$modules[$val["mod_id"]] = array_merge(
						$modules[$val["mod_id"]] , 
						$val
					);
				}				
			}
					
						
			//process modules to remove the ones without lang and keep only the one that are links to global modules
			foreach ($modules as $key => $val) {
				if (!$val["lang_id"] && ($val["module_id"] != 999)) {
					unset($modules[$key]);
				}				
			}			
		}
		
		$cond = array();

		if (is_array($modules) && count($modules)) {
			foreach ($modules as $key => $val) {
				$ids2[] = $val["mod_id"];
				$val["link"] = $this->ModuleLink($val);

				if (!$val["lang_id"]) {
					$val["lang_id"] = $_LANG_ID;
				}				

				$this->modules[$val["mod_id"]] = $val;

				$this->instancemodules[$val["mod_id"]] = &$this->modules[$val["mod_id"]];

			}			

			$cond[] = "(module in (" . implode("," , $ids2) . ") AND type=2 AND (lang_id=0 OR lang_id={$_LANG_ID}))";
		}

	
		$core = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:modules']} as m
			WHERE 
				module_installed = 2 AND 
				module_type=2 AND 			
				module_status=1
				{$mcond}
			"
		);

		if (is_array($core)) {
			foreach ($core as $key => $val) {
				$ids[] = $val["module_code"];
				$ids3[] = $val["module_id"];
				$_core[$val["module_code"]] = $val;
			}

			$core = $_core;

			$core_lang = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:modules']} as m,
					{$this->tables['core:modules_lang']} as l
				WHERE 
					m.module_installed = 2 AND 
					m.module_id = l.module_id AND 
					l.lang_id = {$_LANG_ID} AND 
					m.module_id in (" . implode("," , $ids3) . ")
				"
			);

			//read the language specific fields where applies

			if (is_array($core_lang)) {
				foreach ($core_lang as $key => $val) {
					$core[$val["module_code"]] = array_merge(
						$val , 
						$core[$val["module_code"]]
					);
				}				
			}		

			foreach ($core as $key => $val) {

				if ($val["module_url"]) {
					$_TSM[strtoupper($val["module_code"] . "_LINK")] = $val["link"] = $this->ModuleLink(array("mod_url" => $val["module_url"]));
				}


				if (!$val["lang_id"]) {
					$val["lang_id"] = $_LANG_ID;
				}

				$this->modules[$val["module_code"]] = $val;

				$this->globalmodules[$val["module_id"]] = &$this->modules[$val["module_code"]];
			}	

			$cond[] = "(module in ('" . implode("','" , $ids) . "') AND type=2 AND (lang_id=0 OR lang_id={$_LANG_ID}))";
			
		}



		if (is_array($cond) && count($cond)) {
			$settings = $this->db->QFetchRowArray("
				SELECT * FROM 
					{$this->tables['core:modules_settings']} 
				
				WHERE " . implode(" OR " , $cond)
			);

			if (is_array($settings)) {
				foreach ($settings as $key => $val) {

					if ($this->modules[$val["module"]]) {
						$this->modules[$val["module"]]["settings"][$val["setting"]] = $val["value"] ? $val["value"] : $val["default"];
					}					
				}
				
			}		
		}

		$this->__preinited = true;

		//check if i have user protection
		if (is_object($this->plugins["users"])) {
			foreach ($this->modules as $key => $val) {
				$this->modules[$key]["deny"] = $this->plugins["users"]->isProtected($val);
			}			
		}
		

		if (is_array($this->modules)) {

			//check if we have a custom homepage
			if ($base->isTablet) {
					$home = $this->vars->data["set_homepage_tablet"];
			} elseif ($base->isMobile) {
					$home = $this->vars->data["set_homepage_phone"];
				} else {
					$home = $this->vars->data["set_homepage"];
				}
			
	
			//if found return the module
			if ($home && $this->modules[$home]) {
				$this->modules[$home]["home"] = true;
				$_TSM["PUB:HOME_LINK"] = $this->modules[$home]["home_link"] =  ($this->plugins["languages"]->languages_count > 1 && $this->vars->data["set_multilanguage"]) ? $_CONF["url"] . $_LANG . "/" : $_CONF["url"];
			} else {
				//detect the first content module that is not a category
				reset($this->modules);
				foreach ($this->modules as $key => $module) {					
					if ($module["mod_id"] && ($module["mod_module_code"] != "category")) {
						$this->modules[$key]["home"] = true;
						$_TSM["PUB:HOME_LINK"] = $this->modules[$key]["home_link"] =  ($this->plugins["languages"]->languages_count > 1 && $this->vars->data["set_multilanguage"]) ? $_CONF["url"] . $_LANG . "/" : $_CONF["url"];

						break;
					}					
				}
			}
		}
			
	}
	

	function __init() {
		global $_CONF;

		if ($this->__inited) {
			return "";
		}

		$this->__inited = true;
		
		$path = $this->tpl_path;

		$templates = array(
			"shortcodes"				=> "shortcodes.htm",
		);

		foreach ($templates as $key => $val) {
			$this->private->templates[$key] = new CTemplateDynamic(
				$path . $val 
			);
		}
	} 


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ModuleLink($module) {
		return $this->PrepareLink($module["mod_url"] . "/") ;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ScriptLink($script , $params = array()) {
		global $_CONF ,$_LANG;

		if ($this->vars->data["set_multilanguage"]) {

			$params["_LANG"] = $_LANG;
		}

		return $_CONF["url"] . $script . (is_Array($params) ? "?" . http_build_query($params) : "");
		
	}
	
	
	
	function LoadModuleInfo() {
		global $_LANG_ID;

		$this->__preinit();

		if ($this->modules[$_GET["module_id"]]) {
			return $this->modules[$_GET["module_id"]];
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function isLoaded($mod_code) {
		return $this->IsCoreModuleEnabled($mod_code);	
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function IsCoreModuleEnabled($mod_code) {


		if ($this->modules[$mod_code]) {
			return true;
		} else {
			return false;
		}		
	}
	

	function LoadDefaultModule($mod , $force = false , $type = "code") {
		global $_LANG_ID;

		$this->__preinit();

		if ($type == "id") {
			if (is_array($this->modules)) {
				foreach ($this->modules as $key => $val) {
					if ($val["module_id"] == $mod) {
						return $val;
					}					
				}				
			}
			
		}
		

		if ($this->modules[$mod] && !$force) {
			return $this->modules[$mod];
		}

		if ($force) {

			$module = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['core:modules']} as m,
					{$this->tables['core:modules_lang']} as l
				WHERE 
					module_installed = 2 AND 
					m.module_id = l.module_id AND 
					l.lang_id = {$_LANG_ID} AND 
					module_type=2 AND 			
					module_status=1 AND
					module_code LIKE '{$mod}'
				"
			);

			if (is_array($module)) {

				$module["settings"] = $this->LoadDefaultModuleSettings($module);
				$module["link"] = $this->ModuleLink(array("mod_url" => $module["module_url"]));


				return $module;
			} else {
				//do another try for the users who didnt configure the multilanguage for module propertly

				$module = $this->db->QFetchArray(
					"SELECT * FROM 
						{$this->tables['core:modules']}
					WHERE 
						module_installed = 2 AND 
						module_type=2 AND 			
						module_status=1 AND
						module_code LIKE '{$mod}'
					"
				);

				if (is_array($module)) {
					// no language so no need to bother trying to load it 
					$module["lang_id"] = $_LANG_ID;

					//load settings
					$module["settings"] = $this->LoadDefaultModuleSettings($module);

					return $module;
				}
				

			}

		}
		
	}

	function LoadDefaultModuleSettings($module) {
		$settings = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module[module_code]}' AND type=2");


		if (is_array($settings)) {
			foreach ($settings as $key => $val) {
				if ($val["array"]) {
					$module["settings"][$val["setting"]] = unserialize($val["value"]);
				} else {
					$module["settings"][$val["setting"]] = ($val["value"]);
				}					
			}				
		} 
		if (!is_array($module["settings"])) {
			$module["settings"] = unserialize($module["module_settings"]);
		}
		

		return $module["settings"];
	}
	


	function GetDefaultModuleByUrl($mod) {

		if (is_array($this->modules)) {

			foreach ($this->modules as $key => $val) {

				if (($val["module_status"] == "1") && ($val["module_url"] == $mod)) {
					return $val;					
				}				
			}			
		}
	}



	function GetFirstModule() {
		global $_LANG_ID;

		global $base;

		$this->__preInit();

		if (is_array($this->modules)) {								
			foreach ($this->modules as $key => $module) {
				if ($module["home"]) {
					return $module;				
				}

			}
						
			//return $module;
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetModulesByParent($parent) {

		$this->__preInit();

		if (is_array($this->modules)) {
			foreach ($this->modules as $key => $val) {

				if ($val["mod_parent"] == $parent) {
					$mods[$val["mod_id"]] = $val;					
				}
				
			}			
		}

		return $mods;

	}
	

	function GetModuleByCode($module) {
		global $_LANG , $_LANG_ID;

		$this->__preInit();

		if (is_array($this->modules)) {
			foreach ($this->modules as $key => $val) {
				if ($val["mod_url"] == $module) {
					return $val;					
				}				
			}			
		}
	}

	function GetModuleByID($module) {

		$this->__preInit();

		return $this->modules[$module];
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetGlobalModuleById($id) {
		$this->__preInit();

		if (is_array($this->modules)) {
			foreach ($this->modules as $key => $val) {

				if ($val["module_id"] && !$val["mod_id"] && ($val["module_id"] == $id)) {
					return $val;
				}
			}			
		}
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetIdFromLink($link) {
		$tmp = explode("-" , $link);

		return trim($tmp[count($tmp)-1]);
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function RedirectToModule($id , $link = false) {

		//check the url based on module type

		if (is_array($this->modules[$id])) {
			if ($link) {
				return $this->modules[$id]["link"];
			}
			
			urlredirect($this->modules[$id]["link"]);
		}
		

	}

	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/

	
	function Redirect404() {
		global $_CONF;

		$module = $this->GetModuleById($this->vars->data["set_404"]);
		header("HTTP/1.1 404 Not Found");
		header("Location: " . $this->PrepareLink($module["mod_url"] . "/"));
		exit();
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function BuildLink($data) {

		switch ($data["type"]) {
			case "0":
				$link = "";
			break;

			case "1":
				$link = $data["link"];
			break;

			case "2":
				if (is_array($this->plugins["modules"]->modules[$data["module"]])) {
					$link = $this->plugins["modules"]->modules[$data["module"]]["link"];
				}						
			break;

			case "3":
				$mod = $this->plugins["modules"]->LoadDefaultModule($data["global"] , false , "id");
				if (is_array($mod)) {
					return $mod["link"];
				}				
			break;
		}

		return $link;

	}
	

	function onGlobalHooksExecute($module) {
		global $_LANG_ID , $_TSM , $base;


		//shortcodes
		$this->plugins["shortcodes"]->dynamic[] = array(
			"code"	=> 'moduleurl',
			"method"	=> array(&$this, "shortcode")
		);

		//shortcodes
		$this->plugins["shortcodes"]->dynamic[] = array(
			"code"	=> 'modulelink',
			"method"	=> array(&$this, "shortcode")
		);

	}

		
	function ShortCode($matches) {

		switch ($matches["shortcode"]) {
			case "moduleurl":
				return $this->modules[$matches["vars"]["attr"]]["link"];
			break;

			case "modulelink":

				$mod = $this->modules[$matches["vars"]["attr"]];

				if ($mod["mod_id"]) {
					$link = $mod["link"];
					$title = $mod["mod_name"];
				} elseif ($mod["module_id"]) {
					$link = $mod["link"];
					$title = $mod["module_name"];
				}				

				return $this->_t("shortcodes")->blockREplace(
					"modulelink",
					array(
						"title"		=> $title , 
						"link"		=> $link , 
						"target"	=> $matches["vars"]["target"] ? $matches["vars"]["target"] : "",
						"content"	=> $matches["vars"]["content"]
					)
				);
			break;
		}
	}

}

?>