<?php
/*
	DevSaver web framework
	copyright (c) 2002-2018 DevSaver
		web:  www.devsaver.com
		mail: support@devsaver.com
*/

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

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

	function __construct() {
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;


		if ($_GET["mod"] == "dashboard") {

			switch ($_GET["sub"]) {
				default:
					return $this->BuildDashboard();
				break;

				case "redirect":
					return $this->Redirect();
				break;

				case "sitemap":
					return $this->SiteMap();
				break;
			}
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function BuildDashboard() {
		global $base , $_TSM , $_CONF;
		$_GET["showempty"] = 1;

		$_TSM["PUB:MODULE_NAME"] = "My Dashboard";

		$modules = $this->db->QFetchRowArray("SELECT * FROM {$this->private->tables['core:user_modules']} WHERE mod_status=1 ORDER BY mod_order ASC");

		$core = $this->db->QFetchRowArray("SELECT * FROM {$this->private->tables['core:modules']} WHERE module_type=2 AND module_status=1 ORDER BY module_type_name");
	
		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($core)) {
			foreach ($core as $key => $val) {
				if (is_object($this->module->plugins[$val["module_code"]])) {
					$widget = $this->module->plugins[$val["module_code"]]->DashboardWidgets($val["module_id"]);

					if (is_array($widget) && count($widget)) {
						foreach ($widget as $k => $v) {
							$_widgets[] = $v;
						}				
					}			

					$nr = $this->module->plugins[$val["module_code"]]->DashboardNumbers($val["module_id"]);

					if (is_array($nr) && count($nr)) {
						foreach ($nr as $k => $v) {

							if (($v["acl"] && $base->acl->checkModRule($val , $v["acl"])) || !$v["acl"]) {							
								$_nr[] = $v;
							}
						}				
					}			

					$butt = $this->module->plugins[$val["module_code"]]->DashboardButtons($val["module_id"]);


					if (is_array($butt) && count($butt)) {
						foreach ($butt as $k => $v) {

							if (($v["acl"] && $base->acl->checkModRule($val , $v["acl"])) || !$v["acl"]) {							
								$_butt[] = $v;
							}
						}				
					}			
				}

			}
		}
		
		if (is_array($modules)) {
			foreach ($modules as $key => $val) {
				if (is_object($this->module->plugins[$val["mod_module_code"]])) {
					$widget = $this->module->plugins[$val["mod_module_code"]]->DashboardWidgets($val["mod_id"]);

					if (is_array($widget) && count($widget)) {
						foreach ($widget as $k => $v) {
							$_widgets[] = $v;
						}				
					}			

					$nr = $this->module->plugins[$val["mod_module_code"]]->DashboardNumbers($val["mod_id"]);

					if (is_array($nr) && count($nr)) {
						foreach ($nr as $k => $v) {

							if (($v["acl"] && $base->acl->checkModRule($val , $v["acl"])) || !$v["acl"]) {							
								$_nr[] = $v;
							}
						}				
					}			

					$butt = $this->module->plugins[$val["mod_module_code"]]->DashboardButtons($val["mod_id"]);

					if (is_array($butt) && count($butt)) {
						foreach ($butt as $k => $v) {

							if (($v["acl"] && $base->acl->checkModRule($val , $v["acl"])) || !$v["acl"]) {							
								$_butt[] = $v;
							}
						}				
					}			

				}				
			}
		}

		//$_widgets[] = $this->DashboardWidgets();

		if (is_array($_widgets)) {
			foreach ($_widgets as $key => $val) {
			}			
		} else {

			//no widgets redirect to manage pages
			//show nothing because it might not have access to moduels
			//urlredirect("index.php?mod=modules&sub=user");
		}

		$template = new CTemplateDynamic($this->tpl_path . "main.htm");

		return $template->blockReplace(
			"Main" , 
			array(
				"widgets"	=> count($_widgets) ? $base->html->table(
					$template , 
					"" , 
					$_widgets
				) : "",

				"nr" => count($_nr) ? $base->html->table(
					$template , 
					"Nr" , 
					$_nr
				) : "",

				"buttons" => count($_butt) ? $base->html->table(
					$template , 
					"Buttons" , 
					$_butt
				) : "",
			)
		);	

	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function TopNotifications(&$template , $ajax = false) {
		global $base , $_USER;

		if ($_GET["mod"] == "statusquo") {
			return "";
		}
		

		if (!$_USER["user_id"]) {
			return "";
		}
		

		$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("dashboard");

		if (!is_array($this->tpl_module)) {
			return "";
		}
		

		$modules = $this->db->QFetchRowArray("SELECT * FROM {$this->private->tables['core:user_modules']} WHERE mod_status=1 ORDER BY mod_order ASC");

		$core = $this->db->QFetchRowArray("SELECT * FROM {$this->private->tables['core:modules']} WHERE module_type=2 AND module_status=1 ORDER BY module_type_name");
	
		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($core)) {
			foreach ($core as $key => $val) {
				if (is_object($this->module->plugins[$val["module_code"]])) {
					$nr = $this->module->plugins[$val["module_code"]]->DashboardNumbers($val["module_id"]);

					if (is_array($nr) && count($nr)) {
						foreach ($nr as $k => $v) {
							if (($v["acl"] && $base->acl->checkModRule($val , $v["acl"])) || !$v["acl"]) {							
								$_nr[] = $v;
							}
						}				
					}			
				}

			}
		}
		
		if (is_array($modules)) {
			foreach ($modules as $key => $val) {
				if (is_object($this->module->plugins[$val["mod_module_code"]])) {
					$nr = $this->module->plugins[$val["mod_module_code"]]->DashboardNumbers($val["mod_id"]);

					if (is_array($nr) && count($nr)) {
						foreach ($nr as $k => $v) {
							if (($v["acl"] && $base->acl->checkModRule($val , $v["acl"])) || !$v["acl"]) {							
								$_nr[] = $v;
							}
						}				
					}			

				}				
			}
		}

		//$_widgets[] = $this->DashboardWidgets();

		if (is_array($_nr)) {
			$cnt = 0;
			foreach ($_nr as $key => &$val) {
				if ($val["count"]) {
					$cnt+= $val["count"];
					$val["count"] = $template->blockReplace("Count" , $val);
				} else {
					$val["count"] = "";
				}
				
			}			
		} else {

		}

		if ($cnt ) {

			$fav = $template->blockreplace(
				"FavIcon",
				array(
					"count"	=> $cnt > 10 ? "10+" : $cnt
				)
			);
		}
		

		return $template->blockReplace(
			$ajax ? "Ajax" : "Main", 
			array(
				"items" => $base->html->table(
					$template , 
					"" , 
					$_nr
				),

				"fav"	=> $fav
			)
		);	

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UpdateModuleAction($module) {
		global $_USER , $_ADMIN , $_SESS;

		if (((constant("STP_ENABLE_DEMO") == 1) && ($_ADMIN ==true)) || ($_SESS["minibase"]["raw"]["acl"] == "viewonly")){
			return "";
		}		


		$info = $this->db->QFetchArray("
			SELECT * 
			FROM 
				{$this->tables['core:dashboard_admin_notify']}
			WHERE
				module_id=%d AND 
				user_id=%d
			",array(
					$module , 
					$_USER["user_id"]
			)
		);

		if (is_array($info)) {
			$this->db->QueryUpdate(
				$this->tables['core:dashboard_admin_notify'],
				array(
					"notify_date"	=> time()
				),
				"notify_id={$info[notify_id]}"
			);
		} else {
			$this->db->QueryInsert(
				$this->tables['core:dashboard_admin_notify'],
				array(
					"user_id"		=> $_USER["user_id"],
					"module_id"		=> $module,
					"notify_date"	=> time()
				)
			);
		}		
	}

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

		$info = $this->db->QFetchArray("
			SELECT * 
			FROM 
				{$this->tables['core:dashboard_admin_notify']}
			WHERE
				module_id=%d AND 
				user_id=%d
			",array(
					$module , 
					$_USER["user_id"]
			)
		);

		if (!is_array($info)) {
			return 0;
		} else {
			return $info["notify_date"];
		}		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Sitemap() {
		global $_MODULES;


		foreach ($_MODULES as $_MOD => $_MODULE) {

			//execute the admin generation function
			$_MODULES[$_MOD]->__adminMenu();

			if (is_array($_MODULES[$_MOD]->private->menu)) {
				foreach ($_MODULES[$_MOD]->private->menu as $key => $val) {
					if ($val["pos"]) {
						$menu[$val["pos"]][] = $val;
					}							
				}						
			}
		}

		if (is_array($menu["top"])) {
			foreach ($menu["top"] as $k => $v) {
				if (!$v["parent"]) {
					$top_menu[$v["id"]] = $v;
				}				
			}	
			
			foreach ($menu["top"] as $k => $v) {
				if ($v["parent"]) {
					$tmp_args = array();
					$tmp = parse_url($v["link"]);
					
					parse_str($tmp["query"], $tmp_args);
					$v["_mod"] = $tmp_args["mod"];
					$top_menu[$v["parent"]]["sub"][] = $v;
				} else {

					if ($v["link"]) {

						$tmp_args = array();
						$tmp = parse_url($v["link"]);
						
						parse_str($tmp["query"], $tmp_args);
						$top_menu[$v["id"]]["_mod"] = $tmp_args["mod"];
					}
					
				}
			}			
		}


		//build the side menu

		$cats = $this->plugins["modules"]->GetCategories();
		$modules = $this->plugins["modules"]->GetInstanceModules();

//		debug($cats,1);

		if (is_array($cats)) {
			foreach ($cats as $key => $val) {
				$cats[$key] = array(
					"icon"	=> "folder-open",
					"title"	=> $val["mod_name"],
					"prio"	=> $val["mod_order"],
				);
			}			
		}

		if (is_Array($modules)) {
			foreach ($modules as $key => $val) {
				if ($val["mod_parent"]) {

					$cats[$val["mod_parent"]]["sub"][] = array(
						"id"	=> $val["mod_id"],
						"icon"	=> "file-text",
						"prio"	=> $val["mod_order"],
						"title"	=> $val["mod_name"],
						"_mod"	=> $val["mod_module_code"],
						"module_id"	=> $val["mod_id"],
					);
				} elseif ($val["module_code"] != "category") {
					//add the no parent ones
					$cats[$val["mod_id"]] = array(
						"id"	=> $val["mod_id"],
						"icon"	=> "file-text",
						"prio"	=> $val["mod_order"],
						"title"	=> $val["mod_name"],
						"_mod"	=> $val["mod_module_code"],
						"module_id"	=> $val["mod_id"],
					);
				}
				
			}			
		}

		$this->tpl["map"] = new CTemplateDynamic($this->tpl_path . "sitemap.htm");


		$instance_modules =  $this->buildTopMenuSitemap($cats);
		$global_modules =  $this->buildTopMenuSitemap($top_menu);


		return $this->tpl["map"]->blockReplace(
			"Main",
			array(
				"global"	=> $global_modules,
				"instance"	=> $instance_modules,
			)
		);

	}


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


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

			if (is_array($val["sub"])) {
	
				foreach ($val["sub"] as $k => $v) {
					$top_menu[$key]["sub"][$k]["menu"] = $this->readDashboard("modules/" . $v["_mod"] . "/forms/dashboard.xml");

					if (!count($top_menu[$key]["sub"][$k]["menu"])) {
						unset($top_menu[$key]["sub"][$k]);
					} else {
						foreach ($top_menu[$key]["sub"][$k]["menu"] as $_k => $_v) {

							if (
								($_v["restricted"] && CForm::__isRestricted($_v["restricted"])) || 
								!$base->acl->checkRule($this->processAcl($_v["acl"] , $v["_mod"] , $v["module_id"]))
							) {
								unset($top_menu[$key]["sub"][$k]["menu"][$_k]);
							} else {
								$top_menu[$key]["sub"][$k]["menu"][$_k]["link"] = CTemplateStatic::Replace($_v["link"] , $v);
								//$top_menu[$key]["sub"][$k]["menu"][$_k]["acl"] = $this->processAcl($_v["acl"] , $v["_mod"] , $v["module_id"]);
							}
						}						
					}
				}				
			} else {
				$top_menu[$key]["menu"] = $this->readDashboard("modules/" . $val["_mod"] . "/forms/dashboard.xml");

				if (!count($top_menu[$key]["menu"])) {
					unset($top_menu[$key]);
				} else {
					foreach ($top_menu[$key]["menu"] as $_k => $_v) {

						

						if (
							($_v["restricted"] && CForm::__isRestricted($_v["restricted"])) || 
							!$base->acl->checkRule($this->processAcl($_v["acl"] , $val["_mod"] , $val["module_id"]))
						) {
							unset($top_menu[$key]["menu"][$_k]);
						} else {
							$top_menu[$key]["menu"][$_k]["link"] = CTemplateStatic::Replace($_v["link"] , $val);
							$top_menu[$key]["menu"][$_k]["acl"] = $this->processAcl($_v["acl"] , $val["_mod"] , $val["module_id"]);
						}
					}						
				}				
			}
		}

		$tpl = $this->tpl["map"];

		usort($top_menu , array($this , "SortMenu"));

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

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

				usort($val["sub"] , array($this , "SortMenu"));

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

					if (count($v["menu"])) {
						$_menus[] = array(
							"_title"		=> $tpl->blockReplace(
								"TitleParent",
								array(	
									"title"			=> $v["title"],
									"icon"			=> $v["icon"],
									"parent_title"	=> $val["title"],
									"parent_icon"	=> $val["icon"],
									"link"			=> $v["module_id"] ? "index.php?mod={$v[_mod]}&sub=landing&module_id={$v[module_id]}" : "index.php?mod={$v[_mod]}&sub=landing",
								)
							),

							"icon"		=> $val["icon"],
							"content"	=> $base->html->Table(
								$tpl,
								"Module",
								$v["menu"]
							)
						);
					}
					
				}
			} 
		}
		
		foreach ($top_menu as $key => $val) {

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

				if (count($val["menu"])) {
					$_menus[] = array(
						"_title"		=> $tpl->blockReplace(
							"Title",
							array(	
								"title"			=> $val["title"],
								"icon"			=> $val["icon"],
								"link"			=> $val["module_id"] ? "index.php?mod={$val[_mod]}&sub=landing&module_id={$val[module_id]}" : "index.php?mod={$val[_mod]}&sub=landing",
							)
						),

						"icon"		=> $val["icon"],
						"content"	=> $base->html->Table(
							$tpl,
							"Module",
							$val["menu"]
						)
					);

				}
				
			}
		}

		return $base->html->table(
			$tpl , 
			"Modules",
			$_menus
		);
	}
	

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

		$menu = array();


		if (file_exists($file)) {
			$tmp = new CConfig($file);
			if (is_array($tmp->vars)) {
				$tmp = $tmp->vars["tabs"];

				if ($tmp["link"]) {
					$tmp = new CConfig(str_replace("../../" , "modules/" , $tmp["link"]));
					$tmp = $tmp->vars["tabs"];

				}				

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

					if (is_array($v["link"])) {

						//fix for forms with one link only
						if (!is_array($v["link"][0])) {
							$v["link"] = array( 0 => $v["link"]);
						}

						foreach ($v["link"] as $_k => $_v) {
							$menu[] = array(
								"icon"		=> $_v["icon"],
								"color"		=> $v["color"] ? $v["color"] : "Blue",
								"link"		=> $_v["link"],
								"title"		=> $v["title"] . " > " . $_v["title"],
								"subtitle"	=> $_v["subtitle"],
								"acl"		=> $_v["acl"],
								"restricted"=> $_v["restricted"],
							);
						}						

					} else {
						$menu[] = array(
							"icon"		=> $v["icon"],
							"color"		=> $v["color"] ? $v["color"] : "Blue",
							"icon"		=> $v["icon"],
							"link"		=> $v["link"],
							"title"		=> $v["title"],
							"subtitle"	=> $v["subtitle"],
							"acl"		=> $v["acl"],
							"restricted"=> $v["restricted"],
						);
					}					
				}				
			}			
		}

		return $menu;
		
	}

	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function sortMenu($a , $b) {
		if ($a["prio"] == $b["prio"]) {
			return 0;
		}
		return ($a["prio"] < $b["prio"]) ? -1 : 1;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function processAcl($acl , $mod , $mod_id) {

		if (stristr(":" , $acl)) {
			return $acl;
		}

		if ($acl == "superadmin") {
			return $acl;
		}

		if ($mod_id) {
			return $mod_id . ":" . $acl . "," . $mod . ":" . $acl;
		}

		return $mod . ":" . $acl;				
	}

}

