<?php
/*
	Stempora Web Framework
	Copyright (c) 2002-2014 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com		
*/

// dependencies

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

	function CModules() {
		//$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 "";
		}

		
		//nneed to rewrite this. REad all modules and then protect the ones that ai'm not supposed to access;
/*
		if (is_array($_SESS["client"]) && is_array($_SESS["client"]["groups"])) {

			foreach ($_SESS["client"]["groups"] as $key => $val) {
				$c1[] = " find_in_set({$val} , module_groups) ";
				$c2[] = " find_in_set({$val} , mod_groups) ";
			}
			
			$cond_1 = "  
				(
					module_protected=0 OR 
					( module_protected=1 AND 
						( 
							(" . implode(" AND " , $c1) .") OR 
							module_groups='' OR 
							find_in_set({$_SESS[client][user_id]} , module_users) )
						) 
					)";
			$cond_2 = " AND (mod_protected=0 OR ( mod_protected=1 AND ((" . implode(" AND " , $c2) .") OR mod_groups='' OR find_in_set({$_SESS[client][user_id]} , mod_users ) ) )) ";

			
		} else {
			$cond_1 = "  (module_protected=0 OR module_code LIKE 'users' )";
			$cond_2 = " AND mod_protected=0 ";
		}
*/

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

	
		//read all user modules;

		$modules = $this->db->QFetchRowArray(
				"SELECT * FROM " . 
					$this->tables['core:modules'] . ", " . 
					$this->tables['core:user_modules'] . " as m," . 
					$this->tables['core:user_modules_lang'] . " as l " . 
				"WHERE 
					mod_module=module_id AND 
					module_status=1 AND 
					mod_status=1 AND 
					m.mod_id = l.mod_id AND 
					l.lang_id = {$_LANG_ID}
					{$cond_2}
					{$cond_device}
				ORDER BY 
					mod_parent ASC,
					mod_order ASC"
		);


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

				if (!$val["lang_id"]) {
					$val["lang_id"] = $_LANG_ID;
				}
				
				if ($val["mod_protected"]) {
					$val["deny"] = $this->checkProtected($val["mod_groups"] , $val["mod_memberships"] , $val);
				}
										
				$this->modules[$val["mod_id"]] = $val;
			}			

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

		
		//read all the core modules

		//read the small , left join in case the language module wasnt selected

	
		//load the module data then load the module info. Else if you enable the coming soon but you dont enter the data for a certain language it wont appear on the site.

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

		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_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_protected"]) {
					$val["deny"] = $this->checkProtected($val["module_groups"] , $val["module_memberships"] ,  $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;
			}	



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



		if (is_array($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;

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

			reset($this->modules);

			$home = false;

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

				if ($home) {
					break;
				}
				

				if ($module["module_code"] == "category") {

					foreach ($this->modules as $k => $val) {
						if (($val["mod_parent"] == $module["mod_id"]) && !$val["mod_set_protect_default"] && !$module["mod_set_protect_default"]) {
							
							$this->modules[$k]["home"] = true;
							$_TSM["PUB:HOME_LINK"] = $this->modules[$k]["home_link"] =  ($this->plugins["languages"]->languages_count > 1 && $this->vars->data["set_multilanguage"]) ? $_CONF["url"] . $_LANG . "/" : $_CONF["url"];
							$home = true;
							break;
						}					
					}				
				} else {

					if ($module["mod_id"] && !$module["mod_set_protect_default"]) {
						$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"];
						$home = true;
						break;
					}
					
				}


			}
		}

		//reprocess all modules and see if any of them is denied
		if (is_Array($this->modules)) {
			foreach ($this->modules as $key => $val) {
				if ($val["deny"]) {
					unset($this->modules[$key]);
				}				
			}			
		}
		
	
	}
	

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"menu-new"					=> "menu.htm",
		);

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


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function TopMenu() {
		global $_SESS , $_TSM , $base , $_LANG_ID , $_CONF;

		$this->__init();



		$tmp = $this->modules;


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

				if ($module["home"]) {
					//$module["link"] = $module["home_link"];
				}
				
				
				if (($module["mod_id"] && !$module["mod_parent"]) && !$module["mod_invisible"]) {

					if (method_exists($this->plugins[$module["module_code"]] , "GetMenuButton")) {

						$tmp = $this->plugins[$module["module_code"]]->GetMenuButton($module);

						if (is_array($tmp)) {
							if (!is_array($tmp[0]) && count($tmp)) {
								$tmp = array( 0=> $tmp);
							}
						
							foreach ($tmp as $_key => $_val) {
								if (is_array($_val)) {
									$menu[] = $_val;
								}
								
							}
							
						}
						
					}
				}
			}		
		}

		//debug($menu);


		$template = &$this->private->templates["menu-new"];

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

				$_menu[$key]["html"] = $this->MenuItem($val , $template);
				
			}
			
		}
			
		return $base->html->Table(
			$template,
			"Menu" , 
			$_menu
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function MenuItem($menu, $template) {

		global $base , $_SESS;


		if (is_array($menu["sub"])) {
			foreach ($menu["sub"] as $key => $val) {


				$_menu[$key]["html"] = $this->MenuItem($val , $template);

				if ($val["selected"]) {
					$menu["selected"] = true;
				}
				


				if ($val["html"]) {
					$_menu[$key]["html"] = $val["html"];
				} else {
					if ($val["sub"]) {
					} else {
						$val["sub_html"] = "";
					}

					$template->blockReplace($val["sub"] ? "MenuDrop" : "MenuLink" , $val);					
				}								
			}

			$menu["sub_html"] = $base->html->Table(
				$template,
				"SubMenu" , 
				$_menu
			);
		} else {
			$menu["sub_html"] = "";
		}

		if ($menu["html"]) {
			return $menu["html"];
		}

		if ($menu["target"]) {
			$menu["target"] = $template->blockReplace(
				"MenuTarget",
				$menu
			);
		}

		if ($menu["selected"]) {
			$menu["selected"] = $template->blockReplace(
				"MenuSelected" , 
				$menu
			);
		}

		return $template->blockReplace(
			$menu["sub"] ? "MenuDrop" : "MenuLink" , 
			$menu
		);

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SubMenu($menu , $template) {
		global $base;
		
		if (is_array($menu["sub"])) {
			foreach ($menu["sub"] as $key => $val) {

				if ($val["html"]) {
					$_menu[$key]["html"] = $val["html"];
				} else {
					if ($val["sub"]) {
						$val["sub_html"] = $this->SubMenu($val , $template);
					} else {
						$val["sub_html"] = "";
					}

					$_menu[$key]["html"] = $template->blockReplace("MenuItem" , $val);					
				}								
			}

			$menu["sub_html"] = $base->html->Table(
				$template,
				"SubMenu" , 
				$_menu
			);
		}
		
	}
	

	/**
	* 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 
					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;
			}			

		}
		
	}

	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;



		$this->__preInit();

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

//			debug($this->modules,1);
			
			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) {

					switch ($val["module_code"]) {
						case "globalmodule":

							$orig_mod = array();
							//detect the parent
							foreach ($this->modules as $k => $v) {
								if ($v["module_id"] == $val["mod_global"]) {
									$orig_mod = $v;
								}								
							}
							
							
							//overwrite the name of the original module with the one from the "link"
							$orig_mod["mod_name"] = $val["mod_name"];

							$val = $orig_mod;

							//debug($orig_mod);

							$mods[$val["module_id"]] = $val;
						break;

						default:
							$mods[$val["mod_id"]] = $val;
						break;
					}
					
					
				}
				
			}			
		}

		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_module_code"] != "globalmodule") {
					if ($val["mod_url"] == $module) {
						return $val;					
					}				
				}
				
			}			
		}
	}

	function GetModuleByID($module) {

		$this->__preInit();

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

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

		return trim($tmp[count($tmp)-1]);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SetSeo($item) {
		global $_TSM;

		if ($item["seo_title"] && !$_TSM["PUB:SEO_TITLE"])
			$_TSM["PUB:SEO_TITLE"] = $item["seo_title"];

		if ($item["seo_desc"] && !$_TSM["PUB:SEO_DESC"])
			$_TSM["PUB:SEO_DESC"] = $item["seo_desc"];

		if ($item["seo_keys"] && !$_TSM["PUB:SEO_KEYS"])
			$_TSM["PUB:SEO_KEYS"] = $item["seo_keys"];
		
	}
	
	
	/**
	* 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 PrepareLink($link) {
		global $_CONF , $_LANG;

		//check if the link needs index.php ..

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

			return $_CONF["url"] . $_LANG . "/" . $link;
		} else {
			return $_CONF["url"] . $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 CheckProtected($gr_data , $mb_data , $module = array()) {
		global $_SESS;

		$groups = $plans = array();	

		

		if (trim($gr_data))
			$groups = explode("," , $gr_data);

	
		if (trim($mb_data))
			$plans = explode("," , $mb_data);

		if (count($groups) || count($plans)) {


			if (!(count($_SESS["client"]["groups"]) || $_SESS["client"]["user_membership"])) {
				return true;
			}

			//heck against groups
			if (count($_SESS["client"]["groups"]) && count($groups)) {
				foreach ($_SESS["client"]["groups"] as $key => $val) {
					if (in_array($val , $groups)) {
						return false;
					}							
				}						
			}



			if (count($plans) && $_SESS["client"]["user_membership"]) {						
				if (in_array($_SESS["client"]["user_membership"] , $plans)) {
					return false;
				}											
			}

			return true;
												
		}

		return false;
		
	}
	
}

?>