<?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();

		//debug($_POST);

		if ($_GET["mod"] == "modules") {
			$sub = $_GET["sub"];
			$action = $_GET["action"];

			//$this->__install();

			$this->tpl_module = array("mod_name" => stristr($_GET["sub"] ,"default") ? "Available Modules" : "Manage Pages" );



			switch ($sub) {

				case "user":
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$this->CheckUserAdvancedSettings($data->forms["forms"]);
					$this->PrepareFields($data->forms["forms"]);
					$data->functions = array( 
//							"onstore_prepare" => array(&$this , "StoreModule"),
							"ondelete"	=> array(&$this , "DeleteUserModule"),
					);					
					
					return $data->DoEvents();
				break;


				case "user-settings":

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


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

					$data->functions = array( 
							"onstore_prepare" => array(&$this , "StoreModule"),
					);					
					
					return $data->DoEvents();
				break;

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

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

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

					$data->functions = array( 
							"onstore_prepare" => array(&$this , "StoreModule"),
					);					
					
					return $data->DoEvents();
				break;


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

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$this->CheckAdvancedSettings($data->forms["forms"]);
					$this->PrepareFields($data->forms["forms"] , true);
					//$this->ProcessModuleFields(&$data->forms["forms"]);

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

					);					

					return $data->DoEvents();
				break;

				case "default-language":

					$this->DefaultDetectByCode();

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

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

					$data->functions = array( 
							"onstore_prepare" => array(&$this , "StoreModule"),
					);					
					
					return $data->DoEvents();
				break;


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

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

					$this->ProcessModuleFields($data->forms["forms"] , false , true);
					$this->PrepareFields($data->forms["forms"] , true);

					$data->functions = array( 
							"onstore_prepare" => array(&$this , "StoreModule"),
					);					
					
					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);

					if ($data->Done()) {

						$this->StoreNewModule();
					}
					
					return $data->Show($this->vars->data);
				break;

			}
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function StoreNewModule() {

		//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)) {

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

			$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"			=> CFile::Name2Url($_POST["set_title"]),

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

				"mod_global"		=> $module["module_id"] =="999" ? $link["module_id"] : ""

//				"mod_settings"		=> addslashes(serialize($module["settings"]))
			);

			//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 ($module["module_code"] == "category") {
				//urlredirect("index.php?mod=stembase&sub=stembase.plugin.modules.user");
			}

	
			if (is_object($this->plugins[$user_mod["mod_module_code"]])) {
				$this->plugins[$user_mod["mod_module_code"]]->onCreate($user_mod);
			}
			
			
			//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"]);
			}			

		}
	}

	function ProcessModuleFields(&$forms , $_lang= false , $core = false) {
		global $_TSM;

		if ($core) {
			if ($_POST["module_id"]) {
				$_GET["module_id"] = $_POST["module_id"];
			}
		} else {		
			if ($_POST["mod_id"]) {
				$_GET["mod_id"] = $_POST["mod_id"];
			}
		}


		if ($_GET["mod_id"] || $_GET["module_id"]) {

			if (!$_GET["lang_id"]) {
				$lang = $this->module->plugins["languages"]->DefaultLang();
				$_GET["lang_id"] = $lang["lang_id"];

			}		


			if ($core) {
				$module = $this->GetDefaultModuleInfoById($_GET["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]})");

				$_TSM["PUB:MODULE_NAME"] = $module["module_name"];

			} else {
				$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]})");

				$_TSM["PUB:MODULE_NAME"] = $module["mod_name"];

			}

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

			
			} 


			if ($_lang == true) {
				$config_file = $this->plugins[$module["module_code"]]->forms_path . "language.xml";
			} else {
				$config_file = $this->plugins[$module["module_code"]]->forms_path . "module.xml";
			}
			

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

			if (file_exists($config_file)) {

				//read the module
				$conf = new CConfig($config_file);
				//small fix if there is only one box
				if (is_array($conf->vars["form"]["fields"]["box"]["fields"])) {
					$conf->vars["form"]["fields"]["box"] = array(
						$conf->vars["form"]["fields"]["box"]
					);
				}

				if ($conf->vars["form"]["title"]) {
					$forms["edit"]["title"] = $forms["details"]["title"] = $conf->vars["form"]["title"];
				}
				
				if (is_array($conf->vars["form"]["fields"])) {
					foreach ($conf->vars["form"]["fields"] as $key => $val) {

						if ($key == "box") {


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

							foreach ($val as $k => $box) {
								if (is_array($box["fields"])) {
									foreach ($box["fields"] as $_k => $_v) {

										$_v["default"] = $module_settings[$_k];

										$forms["details"]["fields"][$key][$k]["fields"][$_k] = 
										$forms["edit"]["fields"][$key][$k]["fields"][$_k] = $_v;
										$forms["details"]["fields"][$key][$k]["fields"][$_k]["forcevalue"] = $_v["default"];


										if ($_v["type"] == "droplist") {
											if ($_v["options"]) {
												$_v["type"] = "text";
												$_v["default"] = $_v["options"][$_v["default"]];
											}								
										}

										$_v["editable"] = "false";

	//									$forms["details"]["fields"][$key][$k]["fields"][$_k] = $_v;


									}
									
								}
								
								//$forms["edit"]["fields"]["box"][] = $val;
								
							}


							
						} else {					
							$val["default"] = $module_settings[$key];

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


							if ($val["type"] == "droplist") {
								if ($val["options"]) {
									$val["type"] = "text";
									$val["default"] = $val["options"][$val["default"]];
								}								

							}

							$val["editable"] = "false";

						}
						//add the tabs to details
					}
				}

				//debug($forms,1);
				
				if ($conf->vars["form"]["tabs"]) {
				}


				if (is_array($conf->vars["form"]["javascript"])) {
					foreach ($conf->vars["form"]["javascript"] as $key => $script) {
						$forms["edit"]["javascript"][$key] .= $script;
					}
					
				}
				
			

			}	

			if (!$core) {

				if (file_exists($tabs_file)) {

					$tabs = new CConfig($tabs_file);
					$forms["details"]["tabs"] = $tabs->vars["tabs"];
				} else {
					if ($this->plugins[$module["mod_module_code"]]->global_tabs) {
						$forms["details"]["tabs"] = $this->plugins[$module["mod_module_code"]]->global_tabs;
					}
				}

				$remove = array(
					"manuallink"	=> array("mod_invisible" , "mod_url" , "mod_urltitle" , "mod_long_name" , "seo_desc" , "seo_title" , "subtitle_seo" , "subtitle_details"),
					"category"		=> array("subtitle_details" ,"mod_url" , "mod_urltitle" , "mod_long_name", "seo_title" , "seo_desc" , "subtitle_seo" ),
					"globalmodule"	=> array("mod_invisible" , "mod_user_position" , "mod_groups" , "mod_memberships" , "mod_protected" , "subtitle_private" , "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 {

				$remove = array(
					"globalmodule"	=> array("mod_invisible" , "mod_user_position" , "mod_groups" , "mod_protected" , "mod_memberships"  , "subtitle_private" , "subtitle_details" ,"mod_url" , "mod_urltitle" , "mod_long_name", "seo_title" , "seo_desc" , "subtitle_seo" ),

				);

				if ($remove[$module["module_code"]]) {
					CForm::DeleteFields($forms["edit"] , $remove[$module["module_code"]]);
					CForm::DeleteFields($forms["details"] , $remove[$module["module_code"]]);
				}		


			}


			//process the title 
			$forms["edit"]["title"] = CTemplateStatic::Replace($forms["edit"]["title"] , $module);
			$forms["details"]["title"] = CTemplateStatic::Replace($forms["details"]["title"] , $module);
			
		}		
	}

	function StoreModule($record , $forms ) {

		if (is_array($record)) {


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


			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) {
		global $_LANG_ID;


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

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

		$module_lang = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['core:modules_lang']} as l
			WHERE 
				module_id={$id} AND
				lang_id = {$_GET[lang_id]}				
			"
		);
		
		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;
		}
		
		//read the small 
		$module = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['core:modules']} as c,
				{$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 
				module_id=m.mod_module AND 
				m.mod_id={$id}"
		);

		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}'"
		);

		$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 $_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;
		}
		
		
		//read the small 
		$module = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['core:modules']} as m
			LEFT JOIN  {$this->tables['core:modules_lang']} as l
				ON m.module_id = l.module_id AND 
				l.lang_id = {$_lang} 
			WHERE 
				{$cond}				 
			"
		);

		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"]));
				}
				
			}

		}

		return $module;
	}

	
	function __install() {
	
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __adminMenu() {

		parent::__adminMenu();

		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 (($_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;
						}

						if ($v["mod_status"]) {
							if ($v["mod_invisible"]) {
								$eclass = "dark";
							} else {
								$eclass = "green";
							}							
						} else {
							$eclass = "red";
						}
						
						

						$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,
						);
					}					
				} 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_status"]) {
					if ($val["mod_invisible"]) {
						$eclass = "dark";
					} else {
						$eclass = "green";
					}							
				} else {
					$eclass = "red";
				}


				$this->private->menu[] = array(
					"title"	=> $val["mod_name"],
					//"link"	=> $val["mod_module_code"] == "category" ? (array)$links : $links,
					"link"	=> $links,
					"prio"	=> 20,
					"selected" => $sel,
					"e_class"	=> $eclass,
				);
			}
		}		

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

	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 PrepareFields(&$forms , $core = false) {
		global $_TSM;

		parent::PrepareFields($forms); 


		if ($_GET["mod_id"]) {
			$module = $this->GetModuleInfo($_GET["mod_id"]);

			$forms["details"]["title"] = CTemplateStatic::REplace($forms["details"]["title"] , $module);
			$forms["edit"]["title"] = CTemplateStatic::REplace($forms["edit"]["title"] , $module);

			switch ($module["mod_module_code"]) {
				case "globalmodule":
					CForm::DeleteFields($forms["edit"] , array("mod_url"));
					CForm::DeleteFields($forms["details"] , array("mod_url"));
				break;

				default:
					CForm::DeleteFields($forms["edit"] , array("mod_global"));
					CForm::DeleteFields($forms["details"] , array("mod_global"));
				break;
			}
			

			$_TSM["PUB:MODULE_NAME"] = $module["mod_name"];



			if (file_exists($this->module->plugins[$module["mod_module_code"]]->forms_path . "config.xml")) {

				$conf = new CConfig($this->module->plugins[$module["mod_module_code"]]->forms_path . "config.xml");

				if (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));
						}							
					}						
				}					
				
			}
		}

		if ($_GET["module_id"]) {


				$module = $this->db->QFetchArray(
					"SELECT * FROM 
						{$this->tables['core:modules']} as m,
						{$this->tables['core:modules_lang']} as l,
						{$this->tables['core:languages']} as lg
					WHERE 
						m.module_id = l.module_id AND 
						l.lang_id = lg.lang_id AND 
						lg.lang_default = 1 AND 
						m.module_id='{$_GET[module_id]}'
					"
				);

				$_TSM["PUB:MODULE_NAME"] = $module["module_name"];

				if (file_exists($this->module->plugins[$module["module_code"]]->forms_path . "config.xml")) {

					$conf = new CConfig($this->module->plugins[$module["module_code"]]->forms_path . "config.xml");

					if (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));
							}							
						}						
					}					
					
				}
								
		}
		
		



		if ($_GET["t"] == "u") {

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

			if (file_exists($tabs_file)) {

				$tabs = new CConfig($tabs_file);
				$tabs = $tabs->vars["tabs"];

				$forms["details"]["tabs"] = $tabs;
				$forms["edit"]["tabs"] = $tabs;

			}			
		}	
	}


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


	}

	/**
	* 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={$mod_id} AND setting LIKE '{$key}'"
				);

				if (is_array($set)) {
					$this->db->QueryUpdate(
						$this->tables["core:modules_settings"],
						array(
							"value"	=> $val
						),
						"module={$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"]);

			$_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");
		}
		
	}
	

}

?>