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

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}
// dependencies

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

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

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

		$this->__menuSelector();

		if ($_GET["mod"] == $this->name) {

		
			$this->tpl_module = array(
					"module_code"	=> $this->name,
					"module_name" => stristr($_GET["sub"] ,"default") ? "Available Modules" : "Instance Modules" 
			);

			parent::DoEvents();

			$sub = $_GET["sub"];
			$action = $_GET["action"];

			switch ($sub) {

				case "cats":
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"]);
					return $data->DoEvents();
				break;

				case "landing":
					$sub = "user";
				case "user":					

					$this->parent_mod = $this->getModuleInfo($_REQUEST["mod_id"] , false);

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);

					$data->forms["acl"]["edit"] = 
					$data->forms["acl"]["details"] = "{$this->parent_mod[mod_id]}:settings.general,{$this->parent_mod[mod_module_code]}:settings.general,modules:modules.edit";
					$data->forms["forms"]["details"]["buttons"]["button_edit"]["acl"]= "{$this->parent_mod[mod_id]}:settings.general,{$this->parent_mod[mod_module_code]}:settings.general,modules:modules.edit";

					$data->setAclMod($this->tpl_module);

					$this->CheckUserAdvancedSettings($data->forms["forms"]);
					$this->PrepareFields($data->forms["forms"]);
					$this->PrepareSearchBox($data->forms["forms"]);

					$data->functions = array( 
//							"onstore_prepare" => array(&$this , "StoreModule"),
							"ondelete"	=> array(&$this , "DeleteUserModule"),
							"onstore"	=> array(&$this , "UpdateModules"),
//							"list_process"	=> array(&$this , "ProcessUserModules"),
					);					
					
					return $data->DoEvents();
				break;


				case "default-language":
				case "default-settings":
					$this->DefaultDetectByCode();

					$this->parent_mod = $this->getDefaultModuleInfoById($_GET["module_id"]);

					if (!$base->acl->checkModRule($this->parent_mod , $sub == "default-language" ? "settings.static-texts" : "settings.advanced")) {
						return $base->acl->deniedAccess();
					}

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);

					$data->setAclMod($this->tpl_module);

					$this->PrepareFields($data->forms["forms"]);

					$data->functions = array( 
							"onstore_prepare"	=> array(&$this , "PreStoreModule"),
							"onstore"			=> array(&$this , "StoreModule"),
							"ondetails"			=> array(&$this , "ModuleSettingsValues" ),
							"onedit"			=> array(&$this , "ModuleSettingsValues" ),
					);					
					
					return $data->DoEvents();
				break;


				case "user-language":
				case "user-settings":

					if ($_GET["action"] == "list") {
						urlredirect("index.php?mod=modules&sub=user");
					}					

					$this->parent_mod = $this->getModuleInfo($_REQUEST["mod_id"] , false);

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);


					if ($_GET["sub"] == "user-language") {
						$data->forms["acl"]["edit"] = 
						$data->forms["acl"]["details"] = "{$this->parent_mod[mod_id]}:settings.static-texts,{$this->parent_mod[mod_module_code]}:settings.static-texts,modules:modules.edit";
					} else {					
						$data->forms["acl"]["edit"] = 
						$data->forms["acl"]["details"] = "{$this->parent_mod[mod_id]}:settings.advanced,{$this->parent_mod[mod_module_code]}:settings.advanced,modules:modules.edit";
					}

					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"]);

					$data->functions = array( 
							"onstore_prepare"	=> array(&$this , "PreStoreModule"),
							"onstore"			=> array(&$this , "StoreModule"),
							"ondetails"			=> array(&$this , "ModuleSettingsValues" ),
							"onedit"			=> array(&$this , "ModuleSettingsValues" ),
					);					
					
					return $data->DoEvents();
				break;


				case "default":
					$this->DefaultDetectByCode();

					$this->parent_mod = $this->getDefaultModuleInfoById($_GET["module_id"]);

					if (!$base->acl->checkModRule($this->parent_mod , "settings.general")) {
						return $base->acl->deniedAccess();
					}

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($main_mod);

					$this->CheckAdvancedSettings($data->forms["forms"]);
					$this->PrepareFields($data->forms["forms"]);

					$data->functions = array( 
							"ondelete" => array(&$this , "DeleteDefaultModule"),
					);					

					return $data->DoEvents();
				break;


				case "add-module":
					$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
					$this->PrepareDashboard($data->form);
					$this->LangPrepareFields($data->form);
					$this->PrepareAddToMenu($data->form);
								
					if ($data->Done()) {
						$this->StoreNewModule();
					}
					
					return $data->Show($this->vars->data);
				break;

				case "settings":
					$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
					$this->PrepareDashboard($data->form);
					$this->PrepareFields($data->form);

					if ($data->Done()) {						
						$this->vars->SetVars(
							$this->vars->ExtractVals(
								CForm::KeyFields($data->form),
								$_POST
							)
						);
					}
					
					return $data->Show(							
						$this->vars->GetVars(
							CForm::KeyFields($data->form)
						)
					
					);
				break;

				case "set.menu":
					$this->SetMenu();
				break;


			}
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function StoreNewModule() {
		global $_LANG_ID , $_SESS;		

		if (STP_ENABLE_MENU_AUTOCHAGE) {
			$_SESS["__cms"]["side_menu"] = "";
		}


		//read the installed module
		$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules']} WHERE module_id='{$_POST[set_module]}'");
		//read module settings
		$settings = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module[module_code]}' AND type=2");

		if (is_array($module)) {

			$lang = $this->module->plugins["languages"]->DefaultLang();
			//build the user module
			$user_mod = array(
				"mod_module"		=> $module["module_id"],
				"mod_module_code"	=> $module["module_code"],
				"mod_name"			=>	$_POST["set_title"],
				"mod_parent"		=>	$_POST["module_id"] != 112 ? $_POST["set_parent"] : 0,
				"mod_url"			=> ($module["module_id"] != "999") && ($module["module_code"] != "category") ? CFile::Name2Url($_POST["set_title"]) : "",

				"mod_status"		=> "2",

				"mod_long_name"		=>	$_POST["set_title"],
				"mod_urltitle"		=>	$_POST["set_title"],
				"lang_id"			=>	$lang["lang_id"],

				);

			//store the menu in database and get the id
			$id = $this->db->QueryInsert(
				$this->tables['core:user_modules'] , 
				$user_mod
			);


			//check if mod_url already exists, and append the id
			if (is_array($this->db->QFetchArray("SELECT * FROM {$this->tables['core:user_modules_lang']} WHERE mod_url LIKE '%s'" , array($user_mod["mod_url"])))) {
				$user_mod["mod_url"] .= "-" . $id;
			}
			

			$user_mod["mod_id"] = $id;

			//insert in the language table too 
			$this->db->QueryInsert(
				$this->tables['core:user_modules_lang'] , 
				$user_mod
			);


			//update the order variable
			$this->db->QueryUpdate(
				$this->tables['core:user_modules'],
				array(
					"mod_order" => $id,
				),
				"mod_id={$id}"
			);

			//process the settings
			if (is_Array($settings)) {
				foreach ($settings as $key => $val) {
					$this->db->QueryInsert(
						$this->tables['core:modules_settings'],
						array(
							"module"	=> $id,
							"type"		=> "2",
							"type_var"	=> $val["type_var"],
							"setting"	=> $val["setting"],
							"value"		=> $val["value"],
							"lang_id"	=> $val["lang_id"],
//							"default"		=> $val["default"],
//							"array"		=> $val["array"]
						)
					);
				}
			}
				
			if (is_object($this->plugins[$user_mod["mod_module_code"]])) {
				$this->plugins[$user_mod["mod_module_code"]]->onCreate($user_mod);
			}


			//inset links to menus
			if ($_POST["set_menu"]) {
				$menus = explode("," , $_POST["set_menu"]);

				foreach ($menus as $key => $val) {
					if (stristr($val , "m_")) {
						$_menu[] = array(
							"menu_id"		=> str_replace("m_" , "" , $val),
							"item_type"		=> 1,
							"item_parent"	=> "0",
							"item_module"	=> $user_mod["mod_id"],
							"lang_id"		=> $_LANG_ID,
							"item_device"	=> "1,2,3",
							"item_status"	=> "1",
							"item_elements"	=> "name"
						);
					} else {
						$cat =$this->db->QFetchArray("SELECT * FROM {$this->tables['core:menu_items']} WHERE item_id={$val}");
						$_menu[] = array(
							"menu_id"		=> $cat["menu_id"],
							"item_type"		=> 1,
							"item_parent"	=> $cat["item_id"],
							"item_module"	=> $user_mod["mod_id"],
							"lang_id"		=> $_LANG_ID,
							"item_device"	=> "1,2,3",
							"item_status"	=> "1",
							"item_elements"	=> "name"
						);
					}				
				}		

				foreach ($_menu as $key => $val) {
					$this->db->QueryUpdate(
						$this->tables["core:menu_items"],					
						array(
							"item_order"	=> ($val["item_id"] = $this->db->QueryInsert(
								$this->tables["core:menu_items"],
								$val
							))
						),
						"item_id={$val[item_id]}"
					);

					$this->db->QueryInsert(
						$this->tables['core:menu_items_lang'],
						$val
					);				
				}
				
			}
			
			
			//redirect to the edit module
			urlredirect("index.php?mod=modules&sub=user&action=edit&mod_id={$id}&returnurl=" . urlencode("index.php?mod=modules&sub=user&action=details&mod_id={$id}&t=u") . "&t=u&noback=true");
		}		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CheckUserAdvancedSettings(&$forms) {
		if ($_POST["mod_id"]) {
			$_GET["mod_id"] = $_POST["mod_id"];
		}

		if ($_GET["mod_id"]) {

			$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:user_modules']} WHERE mod_id='{$_GET[mod_id]}'");
			$config_file = $this->plugins[$module["mod_module_code"]]->forms_path . "module.xml";

			if (!file_exists($config_file)) {

				unset($forms["details"]["buttons"]["button_advanced_settings"]);
			}			


			$lang_file = $this->plugins[$module["mod_module_code"]]->forms_path . "language.xml";

			if (!file_exists($lang_file)) {

				unset($forms["details"]["buttons"]["button_language"]);
			}			

		}
	}
	

	function CheckAdvancedSettings(&$forms) {
		if ($_POST["module_id"]) {
			$_GET["module_id"] = $_POST["module_id"];
		}

		if ($_GET["module_id"]) {

			$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules']} WHERE module_id='{$_GET[module_id]}'");
			$config_file = $this->plugins[$module["module_code"]]->forms_path . "module.xml";

			if (!file_exists($config_file)) {

				unset($forms["details"]["buttons"]["button_advanced_settings"]);
			}			


			$lang_file = $this->plugins[$module["module_code"]]->forms_path . "language.xml";

			if (!file_exists($lang_file)) {

				unset($forms["details"]["buttons"]["button_language"]);
			}			

		}
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PreStoreModule($record , $forms) {
		global $_LANG_ID;


		$fields = CForm::AllFields($forms["forms"]["edit"]);

		if (is_array($fields)) {
			foreach ($fields as $key => $val) {
				switch ($val["type"]) {
					case "image":
					case "file":
					case "upload":
						$_fields[$key] = $val;
					break;
				}								
			}
			
			if (is_array($_fields)) {

				if ($_REQUEST["module_id"]) {
					$module = $this->GetDefaultModuleInfoById($_REQUEST["module_id"]);
					$old = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$module[module_code]}' AND type=2 AND (lang_id=0 OR lang_id={$_LANG_ID})");
				} elseif ($_REQUEST["mod_id"]) {
					$module = $this->GetModuleInfo($_REQUEST["mod_id"]);	
					$old = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module[mod_id]}' AND type=2 AND (lang_id=0 OR lang_id={$_LANG_ID})");
				}

				if (is_array($old)) {
					foreach ($old as $key => $val) {
						$_old[$val["setting"]] = $val;
					}

					$old = $_old;					
				}			

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

					if (!$record[$key] && $old[$key]["value"]) {
						$_POST[$key] = $old[$key]["value"];
					}					
				}				
			}			
		}

	}
	

	function StoreModule($record , $forms ) {

		if (is_array($record)) {

			$fields = CForm::AllFields($forms["forms"]["edit"]);

			if (is_array($record)) {
				foreach ($record as $key => $val) {
					if (stristr($key , "_temp") || stristr($key , "_temp_file") || stristr($key , "_radio_type") || stristr($key , "_crop_oxbc")) {
						unset($record[$key]);
					}
				}				
			}

			switch ($_GET["sub"]) {

				case "default-settings":

					$module = $this->GetDefaultMOduleInfoByID($record["module_id"]);
					$this->db->Query("DELETE FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$module[module_code]}' AND type_var=1 AND type=2 AND ( lang_id=0 OR lang_id={$record[lang_id]})");

					foreach ($record as $key => $val) {
						if (stristr($key , "set_")) {

							$this->db->QueryInsert(
								$this->tables['core:modules_settings'],
								array(
									"module"	=> $module["module_code"],
									"type"		=> "2",
									"type_var"	=> "1",
									"setting"	=> $key,
									"value"		=> is_array($val) ? serialize($val) : $val,
									"array"		=> is_array($val) ? 1:0,
									"lang_id"	=> $fields[$key]["lang"] == "true" ? $record["lang_id"] : 0,
								)
							);
							
						}				
					}
				break;


				case "default-language":

					$module = $this->GetDefaultMOduleInfoByID($record["module_id"]);

					$this->db->Query("DELETE FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$module[module_code]}' AND type_var=2 AND type=2 AND ( lang_id=0 OR lang_id={$record[lang_id]})");

					foreach ($record as $key => $val) {
						if (stristr($key , "lang_") && ($key != "lang_id")) {

							$this->db->QueryInsert(
								$this->tables['core:modules_settings'],
								array(
									"module"	=> $module["module_code"],
									"type"		=> "2",
									"type_var"	=> "2",
									"setting"	=> $key,
									"value"		=> is_array($val) ? serialize($val) : $val,
									"array"		=> is_array($val) ? 1:0,
									"lang_id"	=> $fields[$key]["lang"] == "true" ? $record["lang_id"] : 0,
								)
							);
							
						}				
					}
				break;

				case "user-language":
					$this->db->Query("DELETE FROM {$this->tables['core:modules_settings']} WHERE module='{$record[mod_id]}' AND type_var=2 AND type=2 AND ( lang_id=0 OR lang_id={$record[lang_id]})");

					foreach ($record as $key => $val) {
						if (stristr($key , "lang_") && ($key != "lang_id")) {

							$this->db->QueryInsert(
								$this->tables['core:modules_settings'],
								array(
									"module"	=> $record["mod_id"],
									"type"		=> "2",
									"type_var"	=> "2",
									"setting"	=> $key,
									"value"		=> is_array($val) ? serialize($val) : $val,
									"array"		=> is_array($val) ? 1:0,
									"lang_id"	=> $fields[$key]["lang"] == "true" ? $record["lang_id"] : 0,
								)
							);
							
						}				
					}
				break;

				case "user-settings":
					$this->db->Query("DELETE FROM {$this->tables['core:modules_settings']} WHERE module='{$record[mod_id]}' AND type_var=1 AND type=2 AND ( lang_id=0 OR lang_id={$record[lang_id]})");

					foreach ($record as $key => $val) {
						if (stristr($key , "set_")) {

							$this->db->QueryInsert(
								$this->tables['core:modules_settings'],
								array(
									"module"	=> $record["mod_id"],
									"type"		=> "2",
									"type_var"	=> "1",
									"setting"	=> $key,
									"value"		=> is_array($val) ? serialize($val) : $val,
									"array"		=> is_array($val) ? 1:0,
									"lang_id"	=> $fields[$key]["lang"] == "true" ? $record["lang_id"] : 0,
								)
							);
							
						}				
					}
				break;
			}

			$count = 1;
			while ($count < 10 ) {
				$_POST["returnurl"] = urldecode($_POST["returnurl"]);
				if (substr($_POST["returnurl"],0,1) == "/")
					break;

				$count ++;
			}


			if ($_POST["redir_lang_id"]) {

				$data = parse_url($_POST["request_uri"]);
				parse_str($data["query"] , $vars);

				$vars["lang_id"] = $_POST["redir_lang_id"];

				urlredirect( "index.php?" . http_build_query($vars));
			}		
			urlredirect($_POST["returnurl"]);
		}
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetDefaultModuleInfoById($id , $lang = null) {
		global $_LANG_ID;

		if (!$lang) {
			$lang = $_GET["lang_id"];
		}		


		if (!(int)$id) {
			return false;
		}

		//read the small 
		$module = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['core:modules']} 
			WHERE 
				module_id={$id}
			"
		);

		if ($lang) {
			$module_lang = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['core:modules_lang']} as l
				WHERE 
					module_id={$id} AND
					lang_id = {$lang}				
				"
			);
		}
		
		if (!is_array($module_lang)) {
			$module_lang = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['core:modules_lang']} as m,
					{$this->tables['core:languages']} as l
				WHERE 
					module_id={$id} AND
					lang_default=1 AND 
					m.lang_id = l.lang_id
				"
			);

			$module_lang["lang_id"] = $_GET["lang_id"];

		}
		

		if (is_array($module_lang)) {
			$module = array_merge(
				(array)$module_lang , 
				(array)$module
			);
		}
		

		//$this->LoadModuleSettings($module);

		return $module;

	}
	

	function GetModuleInfo($id , $set = true) {

		if (!(int)$id) {
			return false;
		}


		$module = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['core:user_modules']} as m,
				{$this->tables['core:languages']} as lang,
				{$this->tables['core:user_modules_lang']} as l
			
			WHERE 
				l.lang_id = lang.lang_id AND 
				lang.lang_default=1 AND 
				m.mod_id = l.mod_id AND 
				m.mod_id={$id}"
		);

		if ($module["mod_module"]) {
			$mod = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['core:modules']}
				
				WHERE 
					module_id={$module[mod_module]} 
				"
			);

			if (is_array($mod)) {
				$module = array_merge(
					$mod , 
					$module
				);
			}			

		}


		if ($set) {
			$this->LoadModuleSettings($module);
		}
		

		return $module;
	}

	function GetDefaultModuleInfo($code) {
		//read the small 
		$module = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['core:modules']} " . 
			"WHERE module_code='{$code}'"
		);

		if (is_array($module)) {
			$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 LoadModuleSettings(&$module) {

		if (!is_array($module)) {
			return false;	
		}
		


		$settings = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module['mod_id']}' AND type=2 AND (lang_id=0 OR lang_id={$module[lang_id]})");
		if (is_array($settings)) {

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

				switch ($val["type_var"]) {
					//setting
					case "1":
						if ($val["array"]) {
							$module["settings"][$val["setting"]] = unserialize($val["value"]);
						} else {
							$module["settings"][$val["setting"]] = ($val["value"]);
						}					
					break;

					//language
					case "2":
						if (!is_array($module["language"])) {
							$module["language"] = array();
						}
						
						$module["language"][$val["setting"]] = $val["value"];
					break;
				}				
				
			}				
		} 

	}

	


	function LoadDefaultModule($mod , $type = "code") {
		global $_CONF , $_LANG , $_LANG_RAW , $_LANG_ID;

		switch ($type) {
			case "id":
				$cond = "m.module_id='{$mod}' ";
			break;

			default:
				$cond = "m.module_code='{$mod}' ";
			break;

		}

		if (!$_LANG_ID) {
			$lang = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:languages']} WHERE lang_default=1 LIMIT 1");
			$_lang = $lang["lang_id"];
		} else{
			$_lang = $_LANG_ID;
		}
		

		$module = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['core:modules']} as m
			WHERE 
				{$cond}				 
			"
		);
		if (is_array($module)) {
			//try to load the language 
			$module_lang = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['core:modules_lang']}
				WHERE 
					module_id={$module[module_id]} AND
					lang_id = {$_lang}
				"
			);
		}

		if (is_array($module_lang)) {
			$module = array_merge(
				$module , 
				$module_lang
			);
		}
		

		if (is_array($module)) {

			if (!$module["lang_id"] ) {
				$module["lang_id"] = $_lang;
			}
			
			$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"]);
					}					
				}				
			} else {
				$module["settings"] = unserialize(($module["mod_settings"]));

				if (!is_array($module["settings"])) {
					$module["settings"] = unserialize(addslashes($module["mod_settings"]));
				}
				
			}

			if ($this->vars->data["set_multilanguage"]) {
				$module["link"] = $_CONF["url"] . $_LANG . "/" . $module["module_url"] . "/";
			} else {
				$module["link"] = $_CONF["url"] . $module["module_url"] . "/";
			}		

			
		}


		return $module;
	}


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

		if (is_array($module)) {
			return true;
		} else {
			return false;
		}
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DeleteDefaultModule($record) {

		if ($record["module_code"]) {

			//delete all the settings
			$this->db->Query(
				"DELETE FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$record[module_code]}'"
			);
		}
	
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DeleteUserModule($record) {

		//delete all settings
		$this->db->Query(
			"DELETE FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$record[mod_id]}'"
		);

		//delete user module data
		$widgets = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:widgets']} WHERE widget_module={$record[mod_id]}");
		//delete language data

		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {
				$this->db->Query("DELETE FROM {$this->tables['core:widgets_lang']} WHERE widget_id={$val[widget_id]}");
			}
		}
		
		
		//delete all widgets
		$this->db->Query("DELETE FROM {$this->tables['core:widgets']} WHERE widget_module={$record[mod_id]}");

		//delete all module language settings
		$this->db->Query("DELETE FROM {$this->tables['core:user_modules_lang']} WHERE mod_id={$record[mod_id]}");

		//run the local delete function
		if (is_object($this->plugins[$record["mod_module_code"]])) {
			$this->plugins[$record["mod_module_code"]]->onDelete($record);
		}

		//delete all texts
		$this->db->Query("DELETE FROM {$this->tables['core:texts']} WHERE module_id={$record[mod_id]}");
		$this->db->Query("DELETE FROM {$this->tables['core:texts_lang']} WHERE module_id={$record[mod_id]}");

		//delete from menus module if exists
		if ($this->tables['core:menu_items']) {
			$links = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:menu_items']} WHERE item_type=1 AND item_module={$record[mod_id]}");
			if (is_array($links)) {
				foreach ($links as $key => $val) {
					$this->db->Query("DELETE FROM {$this->tables['core:menu_items']} WHERE item_id={$val[item_id]}");
					$this->db->Query("DELETE FROM {$this->tables['core:menu_items_lang']} WHERE item_id={$val[item_id]}");
				}
			}
		}
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UpdateModuleSettings($mod_id , $settings) {

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

				$set = $this->db->QFetchArray(
					"SELECT * FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$mod_id}' AND setting LIKE '{$key}'"
				);

				if (is_array($set)) {
					$this->db->QueryUpdate(
						$this->tables["core:modules_settings"],
						array(
							"value"	=> $val
						),
						"module LIKE '{$mod_id}' AND setting LIKE '{$key}'"
					);
				} else {				
					$this->db->QueryInsert(
						$this->tables['core:modules_settings'],
						array(
							"type_var"	=> "1",
							"module"	=> $mod_id,
							"type"		=> "2",
							"setting"	=> $key,
							"value"		=> $val,
							"lang_id"	=> 0,
						)
					);
				}
			}
		}

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DefaultDetectByCode() {
		if ($_GET["module_code"]) {
			$module = $this->LoadDefaultModule($_GET["module_code"]);
			$_REQUEST["module_id"] = $_GET["module_id"] = $module["module_id"];
		}
		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ValidateModule($module) {
		global $_CONF;

		//check if this is not a reorder process
		if ($_GET["action"] == "ajax.reorder-records") {
		} elseif (!is_array($module)) {
			urlredirect("index.php?mod=modules&sub=user");
		}
		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareLink($module) {
		global $_CONF , $_LANG_CODE;


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


		if ($module["mod_id"] && $module["mod_status"]) {
			$return = $module["mod_url"] . "/";
		} else {

			if ($module["module_allow_url"] && $module["module_status"]) {
				$return = $module["module_url"] . "/";
			}
			
		}

		if ($this->vars->data["set_multilanguage"] && $return) {
			return $_CONF["url"] . $_LANG_CODE . "/" . $return;
		} elseif ($return) {
			return $_CONF["url"] . $return;
		}	
		
		return "";
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetInstanceModules() {
		$modules = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:languages']} as l,
					{$this->tables['core:modules']} as c,
					{$this->tables['core:user_modules']} as m,
					{$this->tables['core:user_modules_lang']} as ml
				WHERE
					{$cond}
					c.module_code = m.mod_module_code AND
					ml.lang_id = l.lang_id AND 
					l.lang_default = 1 AND 
					m.mod_id = ml.mod_id 
				ORDER BY 
					mod_parent DESC,
					mod_order ASC
				");
		return $modules;
	}

	function GetCategories() {
		$modules = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:languages']} as l,
					{$this->tables['core:user_modules']} as m,
					{$this->tables['core:user_modules_lang']} as ml
				WHERE
					ml.lang_id = l.lang_id AND 
					l.lang_default = 1 AND 
					m.mod_id = ml.mod_id AND 
					mod_module_code = 'category'
				ORDER BY 
					mod_order ASC
				");

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

			$modules = $_modules;
			
		}
		
		return $modules;
	}

	function GetModulesByParent($parent) {
		if (!$parent) {
			return null;
		}
		
		$modules = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:languages']} as l,
					{$this->tables['core:user_modules']} as m,
					{$this->tables['core:user_modules_lang']} as ml
				WHERE
					
					ml.lang_id = l.lang_id AND 
					l.lang_default = 1 AND 
					m.mod_id = ml.mod_id AND 
					mod_parent = {$parent}
				");

		return $modules;
	}


	function GetCoreModules($set = false) {
		global $_LANG_ID;

		$modules = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:languages']} as l,
				{$this->tables['core:modules']} as m,
				{$this->tables['core:modules_lang']} as ml
			WHERE
				{$cond}
				ml.lang_id = l.lang_id AND 
				l.lang_default = 1 AND 
				m.module_id = ml.module_id AND 
				module_status=1 AND 
				module_type=2 
					
			");

		if ($set == true) {
				
			if (is_Array($modules)) {
				foreach ($modules as $key => $val) {
					$codes[] = $val["module_code"];
					$_modules[$val["module_code"]] = $val;
				}

				$modules = $_modules;
				
				$settings = $this->db->QFetchRowArray("
					SELECT * FROM 
						{$this->tables['core:modules_settings']} 
					
					WHERE (module in ('" . implode("','" , $codes) . "') AND type=2 AND (lang_id=0 OR lang_id={$_LANG_ID}))"
				);

				if (is_array($settings)) {
					foreach ($settings as $key => $val) {
						$modules[$val["module"]]["settings"][$val["setting"]] = $val["value"];
					}
					
				}
			}				
		}
		

		return $modules;
	}

	
	function GetInstanceModulesTemplates() {

		$modules = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:languages']} as l,
				{$this->tables['core:modules']} as m,
				{$this->tables['core:modules_lang']} as ml
			WHERE
				{$cond}
				ml.lang_id = l.lang_id AND 
				l.lang_default = 1 AND 
				m.module_id = ml.module_id AND 
				module_status=1 AND 
				module_type=1 
				
			ORDER BY 
				module_name ASC
			");


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

			$modules = $_modules;
		}
		

		return $modules;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AddTextPage($title , $content , $parent = 0  , $options = array()) {

			$lang = $this->module->plugins["languages"]->DefaultLang();
			//build the user module
			$user_mod = array(
				"mod_module"		=> 124,
				"mod_module_code"	=> "text",
				"mod_name"			=>	$title,
				"mod_parent"		=>	$parent,
				"mod_url"			=> CFile::Name2Url($title),

				"mod_status"		=> "1",

				"mod_long_name"		=>	$title,
				"mod_urltitle"		=>	$title,
				"lang_id"			=>	$lang["lang_id"],
				"mod_set_protect_default"	=>	$options["mod_set_protect_default"],

			);

			//store the menu in database and get the id
			$id = $this->db->QueryInsert(
				$this->tables['core:user_modules'] , 
				$user_mod
			);


			//check if mod_url already exists, and append the id
			if (is_array($this->db->QFetchArray("SELECT * FROM {$this->tables['core:user_modules_lang']} WHERE mod_url LIKE '%s'" , array($user_mod["mod_url"])))) {
				$user_mod["mod_url"] .= "-" . $id;
			}
			

			$user_mod["mod_id"] = $id;

			//insert in the language table too 
			$this->db->QueryInsert(
				$this->tables['core:user_modules_lang'] , 
				$user_mod
			);


			//update the order variable
			$this->db->QueryUpdate(
				$this->tables['core:user_modules'],
				array(
					"mod_order" => $id,
				),
				"mod_id={$id}"
			);


			//insert content in body

			$tid = $this->db->QueryInsert(
				$this->tables["core:texts"],
				array(
					"module_id"	=> $id ,
				)
			);

			$this->db->QueryInsert(
				$this->tables["core:texts_lang"],
				array(
					"module_id"		=> $id, 
					"lang_id"		=> $lang["lang_id"],
					"text_title"	=> $title , 
					"text_header"	=> $content , 
					"seo_title"		=> $title,
					"seo_meta"		=> $options["seo_meta"],
				)
			);

			return $id;


	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UpdateModules($record) {

		//trigget user modules if exists
		if ($this->plugins["users"]) {
			$this->plugins["users"]->UpdateMenuItems();
		}
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ShortcodesBrowser() {
		global $base;

		$modules = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:languages']} as l,
					{$this->tables['core:user_modules']} as m,
					{$this->tables['core:user_modules_lang']} as ml
				WHERE
					{$cond}
					ml.lang_id = l.lang_id AND 
					l.lang_default = 1 AND 
					m.mod_id = ml.mod_id 
				ORDER BY 
					m.mod_parent ASC,
					m.mod_order ASC
				");
				
		if (is_array($modules)) {
			foreach ($modules as $key => $val) {

				if (!$val["mod_parent"]) {
					$_modules[$val["mod_id"]] = $val;
				} else {
					$_modules[$val["mod_parent"]]["sub"][$val["mod_id"]] = $val;
				}
				
			}			
		}

		$modules = $_modules;

		$tpl = new CTEmplateDynamic($this->tpl_path . "admin.shortcodes.htm");


		$cnt = 0;
		if (is_array($modules)) {
			foreach ($modules as $key => $val) {
				$val["id"] = $val["mod_id"];

				$items[] = array(
					"cnt"	=> ++$cnt,
					"title"	=> $val["mod_name"],
					"codes"	=> is_array($val["sub"]) ? $tpl->blockReplace("NoCodes" , $val ) : $tpl->blockReplace("Codes" , $val ),
				);

				if (is_Array($val["sub"])) {
					foreach ($val["sub"] as $k => $v) {

						$v["id"] = $v["mod_id"];

						$items[] = array(
							"cnt"	=> ++$cnt,
							"title"	=> "---" . $v["mod_name"],
							"codes"	=> $tpl->blockReplace("Codes" , $v ),
						);

					}					
				}				
			}			
		}


		//process core modules
		$core = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:languages']} as l,
				{$this->tables['core:modules']} as m,
				{$this->tables['core:modules_lang']} as ml
			WHERE
				ml.lang_id = l.lang_id AND 
				l.lang_default = 1 AND 
				m.module_id = ml.module_id AND 
				module_allow_url = 1 AND 
				module_type=2 					
			");

		if (is_array($core)) {

			foreach ($core as $key => $val) {
				$val["id"] = $val["module_code"];

				$items[] = array(
					"cnt"	=> ++$cnt,
					"title"	=> $val["module_name"],
					"codes"	=> $tpl->blockReplace("Codes" , $val ),
				);
			}

		}
		
		
		
		return array(
			"title"				=> "Modules" , 
			"html"				=> $base->html->Table(
				$tpl, 
				"" , 
				$items
			)
		);			
	
	}


	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareFields(&$forms , $core = false) {
		global $_TSM , $_LANG_ID;

		parent::PrepareFields($forms); 

		if ($_GET["sub"] == "cats") {
			return true;
		}
		

		if (!($_REQUEST["module_id"] || $_REQUEST["mod_id"])) {
			return false;
		}

		if ($_REQUEST["module_id"]) {
			$module = $this->GetDefaultModuleInfoById($_REQUEST["module_id"]);
			$settings = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$module[module_code]}' AND type=2 AND (lang_id=0 OR lang_id={$_LANG_ID})");

			//prepare the title
			$_TSM["PUB:MODULE_NAME"] = $module["module_name"] ? $module["module_name"] : $module["module_type_name"] ;
			$_TSM["PUB:MODULE_LINK"] = $this->PrepareLink($module);

			if ($module["module_name"] == "Media") {
				$_TSM["PUB:MODULE_NAME"] = "General";
			}

			//remove certain fields;

		} elseif ($_REQUEST["mod_id"]) {

			$module = $this->GetModuleInfo($_REQUEST["mod_id"]);	
			$settings = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module[mod_id]}' AND type=2 AND (lang_id=0 OR lang_id={$_LANG_ID})");

			//prepare the title
			$_TSM["PUB:MODULE_NAME"] = $module["mod_name"];
			$_TSM["PUB:MODULE_LINK"] = $this->PrepareLink($module);

			if ($module["mod_parent"]) {
				$parent = $this->plugins["modules"]->GetModuleInfo($module["mod_parent"],false);

				$_TSM["PUB:MODULE_NAME_PARENT"] = array(
						"title"	=> $parent["mod_name"],
						"id"	=> $parent["mod_id"],
				);

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

		if ($module["mod_id"]) {
			$tabs_file = $this->plugins[$module["module_code"]]->forms_path . "dashboard.xml";
		} elseif ( $module["module_type"] != "1") {
			$tabs_file = $this->plugins[$module["module_code"]]->forms_path . "dashboard.xml";
		}

		switch ($_GET["sub"]) {
			case "default":
			case "user":			
				$perms = $this->plugins[$module["module_code"]]->forms_path . "config.xml";
			break;

			case "default-settings":
			case "user-settings":
				$config_file = $this->plugins[$module["module_code"]]->forms_path . "module.xml";
			break;

			case "default-language":
			case "user-language":
				$config_file = $this->plugins[$module["module_code"]]->forms_path . "language.xml";
			break;
		}
		
		//custom settings for each module 
		if ($config_file && file_exists($config_file)) {
			$config = new CConfig($config_file);
			$form = $config->vars["form"];
			//check for new fiels
			if (is_array($form["fields"])) {
				foreach ($form["fields"] as $key => $val) {

					if ($key == "box") {

						if (is_array($forms["edit"]["fields"]["box"])) {
							foreach ($val as $k => $v) {
								$forms["edit"]["fields"]["box"][] = $forms["details"]["fields"]["box"][] = $v;
							}						
						} else {
							$forms["edit"]["fields"]["box"] =	$forms["details"]["fields"]["box"] = $val;
						}

					} else {
						$forms["edit"]["fields"][$key] = $forms["details"]["fields"][$key] = $val;
					}				
				}			
			}

			//custom title
			if ($form["title"]) {
				$forms["edit"]["title"] = $forms["details"]["title"] = $form["title"];
			}
			
			//custom skin
			if ($form["skin"]) {
				$forms["edit"]["skin"] = $forms["details"]["skin"] = $form["skin"];
			}

			//custom javascript
			if ($form["javascript"]["after"]) {
				$forms["edit"]["javascript"]["after"] .= $form["javascript"]["after"];
				$forms["details"]["javascript"]["after"] .= $form["javascript"]["after"];
			}
		}

		//remove fields based on module type
		if (file_exists($perms)) {
			$conf = new CConfig($perms);

			if ($module["mod_id"] && is_array($conf->vars["module"]["fields"]["instance"])) {
				foreach ($conf->vars["module"]["fields"]["instance"] as $key => $val) {
					//remove field
					if ($val == "false") {
						CForm::DeleteFields($forms["edit"] , array($key));
						CForm::DeleteFields($forms["details"] , array($key));
					}							
				}						
			} elseif (!$module["mod_id"] && is_array($conf->vars["module"]["fields"]["system"])) {
				foreach ($conf->vars["module"]["fields"]["system"] as $key => $val) {
					//remove field
					if ($val == "false") {
						CForm::DeleteFields($forms["edit"] , array($key));
						CForm::DeleteFields($forms["details"] , array($key));
					}							
				}						
			}
		}

		//remove static fields
		$remove = array(
			"category"		=> array("mod_global" , "subtitle_details" ,"mod_url" , "mod_urltitle" , "mod_long_name", "seo_title" , "seo_desc" , "subtitle_seo" ),
		);

		if ($remove[$module["mod_module_code"]]) {
			CForm::DeleteFields($forms["edit"] , $remove[$module["mod_module_code"]]);
			CForm::DeleteFields($forms["details"] , $remove[$module["mod_module_code"]]);
		} else {
			CForm::DeleteFields($forms["edit"] , array("mod_global"));
			CForm::DeleteFields($forms["details"] , array("mod_global"));
		}

						
		//process tabs
		if (file_exists($tabs_file)) {
			$tabs = new CConfig($tabs_file);
			$forms["edit"]["tabs"] = 
			$forms["details"]["tabs"] = $this->PrepareTabsAcl($tabs->vars["tabs"] , $module);
		}

	}


	function ModuleSettingsValues($data, $forms = array()) {

		if (!($_REQUEST["module_id"] || $_REQUEST["mod_id"])) {
			return false;
		}

		if ($_REQUEST["module_id"]) {
			$module = $this->GetDefaultModuleInfoById($_REQUEST["module_id"]);
			$settings = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module LIKE '{$module[module_code]}' AND type=2 AND (lang_id=0 OR lang_id={$_GET[lang_id]})");
		} elseif ($_REQUEST["mod_id"]) {
			$module = $this->GetModuleInfo($_GET["mod_id"]);	
			$settings = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:modules_settings']} WHERE module='{$module[mod_id]}' AND type=2 AND (lang_id=0 OR lang_id={$_GET[lang_id]})");
		}
		
		if (is_array($settings)) {
			foreach ($settings as $key => $val) {
				$data[$val["setting"]] = ($val["value"]);
			}	
		} 

		return $data;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CreateLangRecord($table , $table_lang , $fid , $oid , $data) {
		global $_LANG_ID;

		$id = $this->db->QueryInsert(
			$table , 
			$data
		);

		//update the order
		$this->db->QueryUpdate(
			$table , 
			array(
				$oid => $id
			),
			"{$fid} = {$id}"
		);

		$data["lang_id"] = $_LANG_ID;

		if ($table_lang) {
			$data[$fid] = $id;

			$this->db->QueryInsert(
				$table_lang , 
				$data
			);
		}		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareAddToMenu(&$form) {
		global $_LANG_ID;

		$menus = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:menu_zones']} ORDER BY menu_name ASC");

		if (is_array($menus)) {

			//debug($form,1);
			foreach ($menus as $key => $val) {
				$form["fields"]["set_menu"]["options"]["m_" . $val["menu_id"]]  = $val["menu_name"];

				//get the categories
				$cats = $this->db->QFetchRowArray("
					SELECT  * FROM 
						{$this->tables['core:menu_items']} as m,
						{$this->tables['core:menu_items_lang']} as l
					WHERE
						m.item_id = l.item_id AND 
						l.lang_id = {$_LANG_ID} AND 
						m.item_type = 4 AND 
						m.item_cat_type = 0 
					ORDER BY 
						item_order ASC
				");

				if (is_array($cats)) {
					foreach ($cats as $k => $v) {
						$form["fields"]["set_menu"]["options"][$v["item_id"]]  = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $v["item_name"];
					}					
				}
			}
			
		}
		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __menuSelector() {
		global $_TSM ,$base, $_SESS , $_USER;

		if (!is_array($_USER) || $_GET["ajax"]) {
			return "";
		}
		

		$tpl = new CTEmplateDynamic($this->tpl_path . "admin.menu-selector.htm");


		$items = array(
			array(
				"title"	=> "Instance Modules",
				"icon"	=> "file-text",
				"link"	=> "0",
				"selected" => $_SESS["__cms"]["site_menu"] ? true : false,
			)
		);


		if (is_array($mod = $this->plugins["modules"]->GetDefaultModuleInfo("menus")) && is_object($this->plugins["menus"])) {
			$menus = $this->plugins["menus"]->GetAdminMenus();


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

					$items[] = array(
						"title"		=> $val["title"],
						"link"		=> $val["link"],
						"icon"		=> $val["icon"],
						"selected"	=> $_SESS["__cms"]["side_menu"] == $val["link"] ? true : false,
					);
				}			
			}			
		}



		foreach ($items as $key => $val) {
			$items[$key]["selected"] = $val["selected"] ? $tpl->blockReplace("Selected" , $val) : "";
			if ($val["selected"]) {
				$selected = $val;
			}
		}
		
		if (!$selected) {
			$selected = $items[0];
			$items[0]["selected"] = $tpl->blockReplace("Selected");
		}

						
		$_TSM["PUB:MENU_SELECTOR"] = $base->html->table(
			$tpl , 
			"",
			$items,
			array(
				"current"	=> $tpl->blockReplace("Current" , $selected)
			)
		);

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SetMenu() {
		global $_SESS;
		$_SESS["__cms"]["side_menu"] = $_POST["menu"];

		return "1";
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __adminMenu() {
		global $_USER;

		if (!is_array($_USER) || $_GET["ajax"]) {
			return "";
		}

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


		$this->__initedMenu = true;
		


		parent::__adminMenu();

		global $_USER , $_SESS;

		$mod = $this->plugins["modules"]->GetDefaultModuleInfo("menus");

		//was installed the menus module
		if (is_array($mod) && is_object($this->plugins["menus"])) {
			$menu = $_SESS["__cms"]["side_menu"];
			$menus = $this->plugins["menus"]->GetAdminMenus();

			if (is_array($menus)) {
				foreach ($menus as $key => $val) {
					if ($val["link"] == $_SESS["__cms"]["side_menu"]) {
							$items = $this->plugins["menus"]->__getAdminMenu($val["link"]);
						break;
					} 
				}			
			}

			if (is_array($items)) {
				foreach ($items as $key => $val) {
					$this->private->menu[] = $val;
				}			

				return true;

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

		global $_USER;
		//get all the modules
		$modules = $this->db->QFetchRowArray("
			SELECT * FROM 
				{$this->private->tables['core:user_modules']} as p ,
				{$this->private->tables['core:languages']} as l ,
				{$this->private->tables['core:user_modules_lang']} as i
			WHERE
				p.mod_id=i.mod_id and 
				l.lang_id=i.lang_id AND 
				lang_default=1
			ORDER BY mod_parent ASC , mod_order ASC");
	
		if ($_USER["user_level"]) {
			$perm = explode("," , $_USER["user_perm"]);
		}



		//remove modules without permission
		if (is_array($modules)) {
			foreach ($modules as $key => $val) {
				if ($val["mod_module_code"] == "category") {
					$_modules[] = $val;
					unset($modules[$key]);
				}				
			}

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

			$modules = $_modules;



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

				if (($_USER["user_level"] && !in_array($val["mod_id"] , $perm))  ) {
					unset($modules[$key]);
				}
			}			
		}

		if (is_array($modules)) {			

			foreach ($modules as $k => $v) {


				if ($v["mod_parent"]) {
					$mod[$v["mod_parent"]]["sub"][] = $v;
				} else {

					if (is_Array($mod[$v["mod_id"]])) {
						$mod[$v["mod_id"]] = array_merge(
							$mod[$v["mod_id"]] , 
							$v
						);
					} else {					
						$mod[$v["mod_id"]]= $v;
					}
				}
			}


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

				$sel = false;

				if (is_array($val["sub"])) {

					$links = array();

					foreach ($val["sub"] as $k => $v) {

						if (
								(($_GET["mod"] == $v["mod_module_code"] ) && ($_GET["module_id"] == $v["mod_id"])) ||
								(($_GET["mod"] == "modules" ) && ($_GET["mod_id"] == $v["mod_id"])) ||
								(($_GET["mod"] == "widgets" ) && ($_GET["module_id"] == $v["mod_id"]))
							) {
							$sel = true;
						}

						$eclass = "";
	
						switch ($v["mod_status"]) {
							//enabled
							case "1":
								$eclass .= " green";
							break;

							//pending
							case "2":
								$eclass .= " orange";
							break;

							//disabled
							default:
								$eclass .= " red";
							break;
						}											

						switch ($v["mod_module_code"]) {
							case "multidropdown":
								$icon = "sign-multidrop";
							break; 

							case "category":
								$icon = "sign-folder-open";
							break;

							case "globalmodule":
							case "manuallink":
								$icon = "sign-link";
							break;

							default:
								$icon = "sign-file-text";
							break;
						}
						


						$links[] = array(
							"title"		=> $v["mod_name"],
							"link"		=> "index.php?mod=" . $v["mod_module_code"] . "&sub=landing&module_id=" . $v["mod_id"],
							"selected"	=>  (($_GET["mod"] == $v["mod_module_code"] ) && ($_GET["module_id"] == $v["mod_id"])) || 
											(($_GET["mod"] == "modules" ) && ($_GET["mod_id"] == $v["mod_id"])) ||
											(($_GET["mod"] == "widgets" ) && ($_GET["module_id"] == $v["mod_id"]))							
											? true : false,
							"e_class"	=> $eclass . " " . ($v["mod_protected"] == "1"  ? " is-protected " : ""),
							"icon"		=> $icon,
							"protected"	=> $v["mod_protected"] == "1" ? 1 : 0 ,
							"acl"		=> $v["mod_id"] . ":*," . $v["mod_module_code"] . ":*"
						);
					}					
				} else {
					$links = "index.php?mod=" . $val["mod_module_code"] . "&sub=landing&module_id=" . $val["mod_id"];
					if (
						(($_GET["mod"] == $val["mod_module_code"] ) && ($_GET["module_id"] == $val["mod_id"])) ||
						(($_GET["mod"] == "modules" ) && ($_GET["mod_id"] == $val["mod_id"]))	
					) {
						$sel = true;
					}

				}

				if ($val["mod_invisible"]) {
					$eclass = ""; //"dark";
				} else{ 
					$eclass = "";
				}

				switch ($val["mod_status"]) {
					//enabled
					case "1":
						$eclass .= " green";
					break;

					//pending
					case "2":
						$eclass .= " orange";
					break;

					//disabled
					default:
						$eclass .= " red";
					break;
				}						
				

				switch ($val["mod_module_code"]) {
					case "multidropdown":
						$icon = "sign-multidrop";
					break; 

					case "category":
						$icon = "sign-folder-open";
					break;

					case "globalmodule":
					case "manuallink":
						$icon = "sign-link";
					break;

					default:
						$icon = "sign-file-text";
					break;
				}
				

				$this->private->menu[] = array(
					"title"		=> $val["mod_name"],
					//"link"	=> $val["mod_module_code"] == "category" ? (array)$links : $links,
					"cat"		=> is_array($links) ? 1 : 0,
					"link"		=> $links,
					"prio"		=> 20,
					"selected"	=> $sel,
					"e_class"	=> $eclass . " " . ($val["mod_protected"] == "1"  ? " is-protected " : ""),
					"protected"	=> $val["mod_protected"] == 1  ? 1 : 0,
					"icon"		=> $icon,
					"acl"		=> is_array($links)  ? "" : ($val["mod_id"] . ":*," . $val["mod_module_code"] . ":*")
				);
			}
		}		


		//debug($this->private->menu,1);

		if (is_array($this->private->menu)) {
			foreach ($this->private->menu as $key => $val) {
				if (!$val["title"] && is_array($val["link"])) {
					$this->private->menu[$key]["title"]  = "<i>Deleted</i>";
					$this->private->menu[$key]["icon"]  = "sign-folder-open";
				}
			}
		}

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareSearchBox(&$forms) {
		global $_CONF; 

		if (!in_array($_GET["action"] , array("details" , "edit" , "store" , "ajax.reorder-records"))) {

			$data = new CFormSettings($this->forms_path  . "user/filter.xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
			$forms["search"]["after"] = $data->Show($_GET, array() , null , true);

			if ($_GET["type"] == "1") {
				//unset($forms["search"]["search"]["sql_fields"]["mod_parent"]);
				if ($_GET["parent"]) {
					$_GET["mod_parent"] = $_GET["parent"];
				} else {
					unset($forms["search"]["search"]["sql_fields"]["mod_parent"]);
				}

				if (!$_GET["order"]) {
					$forms["list"]["sql"]["vars"]["order"]["import"] = "mod_name";
				}

			} else {
				$_GET["mod_parent"] = $_GET['cat'];
			}
		}
		

	}
	

}

?>