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

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CAdministrators extends CPlugin{
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __construct() {
		$this->name = "administrators";
	}

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


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

			$this->tpl_module = array(
				"module_code"	=> $this->name,
				"module_name"	=> "System Admins",
			);

			parent::DoEvents();

			$sub = $_GET["sub"];

			switch ($sub) {

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

				case "users":
				case "groups":

					if (!$base->acl->checkRule("superadmin")) {
						return $base->acl->deniedAccess();
					}
					

					$data = new CSQLAdmin($sub, $_CONF["forms"]["admintemplate"],$this->db,$this->private->tables,$extra);
					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"], $sub);

					if (!strlen($_POST["user_password"]))
						unset($_POST["user_password"]);

					switch ($sub) {
						case "users":
							$data->functions = array( 
									"onstore" => array(&$this , "__call_user_store"),
									"ondelete"	=> array(&$this , "DeleteAdmin"),
							);
						break;

						case "groups":
							$data->functions = array( 
								"onstore"			=> array(&$this , "PermissionsUpdate"),
								"ondetails"			=> array(&$this , "PermissionsValues" ),
								"onedit"			=> array(&$this , "PermissionsValues" ),

							);					

						break;

					}
					
					return $data->DoEvents();
				break;

				case "profile":
				case "myprofile":
					$sub = "profile";
					if (!$_GET["action"]) {
						$_GET["action"] = "details";
					}
					$_POST["user_id"] - $_GET["user_id"] = $_USER["user_id"];


					$data = new CSQLAdmin($sub, $_CONF["forms"]["admintemplate"],$this->db,$this->private->tables,$extra);
					$this->PrepareMyFields($data->forms["forms"], $sub);

					//set only certain variabiles, just in case anyone will get an ideea to se other vars using the inspector to triegger a superadmin level 
					$_POST = array(
						"user_first_name"		=> $_POST["user_first_name"],
						"user_last_name"		=> $_POST["user_last_name"],
						"user_login"			=> $_POST["user_login"],
						"user_email"			=> $_POST["user_email"],
						"user_password"			=> $_POST["user_password"],
						"user_password_confirm"	=> $_POST["user_password_confirm"],
						"user_password_old"		=> $_POST["user_password_old"],
					);

					if (!strlen($_POST["user_password"]))
						unset($_POST["user_password"]);

					$data->functions = array( 
							"onstore" => array(&$this , "__call_user_store"),
					);

					
					return $data->DoEvents();

				break;


				case "logs":

					if (!$base->acl->checkRule("superadmin")) {
						return $base->acl->deniedAccess();
					}

					$data = new CSQLAdmin($_GET["sub"], $_CONF["forms"]["admintemplate"],$this->db,$this->private->tables,$extra);
					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"], $sub);

					return $data->DoEvents();
				break;

				case "duplicate.group":
					return $this->DuplicateGroup();
				break;

				case "unblock":
					return $this->UnblockUser();
				break;

			}
		}		
	}	

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

		if ($_POST["user_password"]) {			
			$this->db->Query("UPDATE {$this->private->tables[users]} SET user_password=md5('$_POST[user_password]') WHERE user_id='{$record[user_id]}'");
		}		
	}

	function LogAction() {
		global $_SESS , $_PAGE , $_ADMIN;

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


		if (!$_SESS["minibase"]) {
			return "";
		}

		if ($_PAGE == "ajax") {
			return "";
		}
		
		
		$post = array();

		if (is_array($_POST)) {
			foreach ($_POST as $key => $val) {
				if (stristr($key , "pass")) {
					$post[$key] = "*****";
				} else {
					$post[$key] = $val;
				}
				
			}
			
		}
		

		

		$log = array(
			"log_date"			=> time(),
			"log_user"			=> $_SESS["minibase"]["raw"]["user_id"],
			"log_ip"			=> $_SERVER["REMOTE_ADDR"],
			"log_url"			=> $_SERVER["REQUEST_URI"],
			"log_url_referer"	=> $_SERVER["HTTP_REFERER"],

			"log_vars_get"		=> serialize($_GET),
			"log_vars_post"		=> serialize($post),
			"log_vars_files"	=> serialize($_FILES),

		);

		$this->db->QueryInsert(
			$this->private->tables['users_log'],
			$log
		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CheckGlobalPermission($module_name, $acl = false) {
		global $_SESS , $_USER;

		/*

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

		if ($_USER["user_perm2"]) {

			if ($this->tables["core:modules"]) {

				$modules = $this->db->Linear($this->db->QFetchRowArray("SELECT module_code FROM {$this->tables['core:modules']} WHERE module_id in ({$_USER[user_perm2]})"));

				
				if (in_array( $module_name , $modules)) {
					return true;
				}

			}
		}
		

		
		return false;		
		*/
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareFields(&$fields , $sub) {
		parent::PrepareFields($fields , $sub);

		switch ($sub) {
			case "groups":
				$this->PrepareGroupFields($fields);
			break;
		}

		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareGroupFields(&$fields) {


		$acl = array();

		//global modules 
		foreach ($this->plugins as $key => &$val) {
			if ($val->acl) {				
				$this->ProcessGlobalAcl(
					$acl, 
					$val->acl["rules"] , 
					array( 
						"code" => $key , 
						"module" => $val->acl["_module"] , 
						"parent" => $val->acl["_parent"]
					)
				);
			}				
		}	


		$templates = $this->plugins["modules"]->GetInstanceModulesTemplates();

		if (is_array($acl) && count($acl)) {
			$fields["add"]["fields"]["box"]["0"]["fields"] = 
			$fields["details"]["fields"]["box"]["0"]["fields"] = 
			$fields["edit"]["fields"]["box"]["0"]["fields"] = array();				

			//sor modules based on acl parent
			foreach ($acl as $key => $module) {

				if ($module["perms"]) {
			
					if (!$templates[$module["code"]]) {

						if ($module["_parent"]) {
							$_acl["root"][$module["module"]] = $module;
						} else {						
							$_acl[$module["parent"]][$module["module"]] = $module;
						}
					}
				}

			}
			
			ksort($_acl);
			$id = 1;
			foreach ($_acl as $key => $parent) {	
					$i ++;

					$fields["add"]["fields"]["box"]["0"]["fields"]["subtitlex_" . $i] = 
					$fields["details"]["fields"]["box"]["0"]["fields"]["subtitlex_" . $i] = 
					$fields["edit"]["fields"]["box"]["0"]["fields"]["subtitlex_" . $i] = array(
						"type"			=> "subtitle",
						"collapsed"		=> "true",
						"title"			=> $key != "" ? $key : "[ ungroupped ]",
					);

					ksort($parent);
					foreach ($parent as $key => $module) {
						if (!$templates[$module["code"]]) {
							$fields["add"]["fields"]["box"]["0"]["fields"]["selector_module_" . $module["code"]] = 
							$fields["details"]["fields"]["box"]["0"]["fields"]["select_module_" . $module["code"]] = 
							$fields["edit"]["fields"]["box"]["0"]["fields"]["selector_module_" . $module["code"]] = array(
								"extend"		=> "true",
								"type"			=> "radiolist",
								"title"			=> $module["module"],
								"options"		=> array(
									"0"			=> "denied access",
									"1"			=> "full access",
									"2"			=> "custom access",							
								),
								"newline"		=> "false"
							);


							$fields["add"]["fields"]["box"]["0"]["fields"]["module_" . $module["code"]] = 
							$fields["details"]["fields"]["box"]["0"]["fields"]["module_" . $module["code"]] = 
							$fields["edit"]["fields"]["box"]["0"]["fields"]["module_" . $module["code"]] = array(
								"extend"		=> "true",
								"type"			=> "checklist",
								"title"			=> "",
								"options"		=> $module["perms"]

							);
						}

					}					

			}
			
		}

		if (is_array($templates)) {
			$fields["add"]["fields"]["box"]["1"]["fields"] = 
			$fields["details"]["fields"]["box"]["1"]["fields"] = 
			$fields["edit"]["fields"]["box"]["1"]["fields"] = array();

			foreach ($acl as $key => $_val) {			
				$_acl[$_val["code"]] = $_val;
			}
			
			foreach ($templates as $key => $module) {

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

					$fields["add"]["fields"]["box"]["1"]["fields"]["selector_module_" . $module["module_code"]] = 
					$fields["details"]["fields"]["box"]["1"]["fields"]["select_module_" . $module["module_code"]] = 
					$fields["edit"]["fields"]["box"]["1"]["fields"]["selector_module_" . $module["module_code"]] = array(
						"extend"		=> "true",
						"type"			=> "radiolist",
						"title"			=> "[ " . $_acl[$module["module_code"]]["module"] . " ]",
						"options"		=> array(
							"0"			=> "denied access",
							"1"			=> "full access",
							"2"			=> "custom access",							
						),
						"newline"		=> "false"
					);


					$fields["add"]["fields"]["box"]["1"]["fields"]["module_" . $module["module_code"]] = 
					$fields["details"]["fields"]["box"]["1"]["fields"]["module_" . $module["module_code"]] = 
					$fields["edit"]["fields"]["box"]["1"]["fields"]["module_" . $module["module_code"]] = array(
						"extend"		=> "true",
						"type"			=> "checklist",
	//					"title"			=> $_acl[$module["module_code"]]["module"],
						"options"		=> $_acl[$module["module_code"]]["perms"]

					);
				}
			}			
		}
		


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

		$acl = array();

		if (is_array($modules)) {

			$fields["details"]["fields"]["box"]["2"]["fields"] = 
			$fields["add"]["fields"]["box"]["2"]["fields"] = 
			$fields["edit"]["fields"]["box"]["2"]["fields"] = array();


			foreach ($modules as $key => $module) {
				$cats[$module["mod_parent"]]["mods"][] = $module;				
			}
			
			foreach ($cats as $key => $cat) {

				if (is_array($cat["mods"]) && count($cat["mods"])) {

					$fields["add"]["fields"]["box"]["2"]["fields"]["subtitle_" . $cat["mod_id"]] = 
					$fields["details"]["fields"]["box"]["2"]["fields"]["subtitle_" . $cat["mod_id"]] = 
					$fields["edit"]["fields"]["box"]["2"]["fields"]["subtitle_" . $cat["mod_id"]] = array(
						"type"			=> "subtitle",
						"collapsed"		=> "true",
						"title"			=> $cat["mod_name"] ? $cat["mod_name"] : "[ root ]",
					);

					foreach ($cat["mods"] as $k => $module) {

						if ($module["mod_module_code"] != "category") {
						
							$acl = array(); 
							$this->ProcessGlobalAcl(
								$acl, 
								$this->plugins[$module["mod_module_code"]]->acl["rules"] , 
								array( 
									"code"	=> "m_" . $module["mod_id"] , 
									"module" => "[ " . $module["module_type_name"] . " ] " . $module["mod_name"]
								)
							);


							if (count($acl)) {
								foreach ($acl as $_ => $perm) {
									$fields["add"]["fields"]["box"]["2"]["fields"]["selector_" . $perm["code"]] = 
									$fields["details"]["fields"]["box"]["2"]["fields"]["select_" . $perm["code"]] = 
									$fields["edit"]["fields"]["box"]["2"]["fields"]["selector_" . $perm["code"]] = array(
										"extend"		=> "true",
										"type"			=> "radiolist",
										"title"			=> $perm["module"],
										"options"		=> array(
											"0"			=> "inherited access",
											"1"			=> "full access",
											"2"			=> "custom access",							
										),
										"newline"		=> "false"
									);


									$fields["details"]["fields"]["box"]["2"]["fields"][$perm["code"]] = 
									$fields["add"]["fields"]["box"]["2"]["fields"][$perm["code"]] = 
									$fields["edit"]["fields"]["box"]["2"]["fields"][$perm["code"]] = array(

										"extend"	=> "true",
										"type"		=> "checklist",
										"title"		=> "",
										"options"	=> $perm["perms"]

									);
								}
								
							}
						}
						
					}					

				}
				
			}
		}
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessGlobalAcl(&$acl , $perms , $mod) {

		$local_acl = array();

		//$local_acl["all"] = "[ full permission ]";


		foreach ($perms as $key => $val) {
			if (is_Array($val)) {
				if (($val["type"] == "group") && is_array($val["acl"])){

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

						$local_acl[$k] = $val["title"] . " > " . $v;
					}
					

				}				
			} elseif (!in_array($key , array("_module" , "type" , "parent"))) {
				$local_acl[$key] = $val;
			}
			
		}

		$acl[] = array(
			"parent"	=> $mod["parent"],
			"module"	=> $mod["module"],
			"code"		=> $mod["code"],
			"perms"		=> $local_acl
		);
		
	}

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

		$this->db->Query("DELETE FROM {$this->tables['users_acl']} WHERE acl_group=%d" , array($record["group_id"]));

		foreach ($record as $key => $val) {
			if (stristr($key , "module_")) {
				$mod = explode("," , $val);
				$mid = str_replace("module_" , "" , $key);

				foreach ($mod as $k => $v) {
					if (trim($v)) {
						$this->db->QueryInsert(
							$this->tables['users_acl'],
							array(
								"acl_type"		=> "1",
								"acl_group"		=> $record["group_id"],
								"acl_module"	=> $mid,
								"acl_code"		=> $v
							)
						);
					}					
				}
			} elseif (stristr($key , "m_")) {

				$mod = explode("," , $val);
				$mid = str_replace("m_" , "" , $key);
				


				foreach ($mod as $k => $v) {
					if (trim($v)) {

						$this->db->QueryInsert(
							$this->tables['users_acl'],
							array(
								"acl_type"		=> "1",
								"acl_group"		=> $record["group_id"],
								"acl_mod_id"	=> $mid,
								"acl_code"		=> $v
							)
						);
					}					
				}
			}			
		}		
	}
	

	function PermissionsValues($record) {
		$acl = $this->db->QFetchRowArray("
			SELECT * FROM 
				{$this->tables['users_acl']}
			WHERE 
				acl_group = {$record[group_id]}	
			"
		);

		if (is_array($acl)) {
			foreach ($acl as $key => $val) {
				if ($val["acl_mod_id"]) {
					$_acl["m_" . $val["acl_mod_id"]][] = $val["acl_code"];
				} elseif($val["acl_module"]) {
					$_acl["module_" . $val["acl_module"]][] = $val["acl_code"];
				}
			}			
		}
		
		if (is_Array($_acl)) {
			$record = array_merge(
				$record , 
				$_acl
			);
		}
		
		return $record;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareMyFields(&$forms, $sub) {
		global $_TSM;
		$_TSM["PUB:MODULE_NAME"] = "My Profile";			

		unset($_POST["user_groups"]);
		unset($_POST["user_status"]);

	}


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

		if ($record["user_protect_delete"]) {
			$base->acl->deniedAccess();
		}		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DuplicateGroup() {
		$group = $this->db->QFetchArray("SELECT * FROM {$this->tables['users_groups']} WHERE group_id=%d" , array($_GET["group_id"]));
		$acl = $this->db->QFetchRowArray("
				SELECT 
					* 
				FROM
					{$this->tables['users_acl']}
				WHERE
					acl_group = {$group[group_id]}
				"
			);


		unset($group["group_id"]);
		$group["group_name"] .= " (Copy)";

		$id = $this->db->QueryInsert(
			$this->tables['users_groups'],
			$group
		);

		if (is_array($acl)) {
			foreach ($acl as $key => $val) {
				unset($val["acl_id"]);
				$val["acl_group"] = $id;

				$this->db->QueryInsert(
					$this->tables["users_acl"],
					$val
				);
			}			
		}		

		urlredirect("index.php?mod=administrators&sub=groups&group_id={$id}&action=edit&module_id=&returnurl=" . urlencode("index.php?mod=administrators&sub=groups"));
	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function unblockUser() {
		$this->db->QueryUpdate(
			$this->tables['users'],
			array(
				"user_block"	=> "0"
			),
			$this->db->Statement("user_id = %d" , array($_GET["user_id"]))
		);

		urlredirect("index.php?mod=administrators&sub=users");

	}
	
}

?>