<?php
/*
	Stempora web framework
	copyright (c) 2002-2013 Stempora
		web:  www.stempora.com
		mail: support@stempora.com
*/

// dependencies

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

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

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


		parent::DoEvents();

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

			$this->__init();
			$this->plugins["globalhooks"]->SetModule($this->tpl_module);

			switch ($_GET["sub"]) {

				case "dashboard":
					$this->plugins["users"]->CheckUserPermission($this->tpl_module);
					return $this->Dashboard();
				break;


				case "signin":
					if ( $_SESS["client"]) {
						return $this->Dashboard();
					}

					return $this->Combo();
				break;

				case "logout":
					return $this->AjaxLogout();
				break;

				/*ajax requests*/
				case "ajax.login":
					return $this->AjaxLogin();
				break;

				case "facebook":
					return $this->AjaxFacebook();
				break;

				case "ajax.register":
					return $this->AjaxRegister();
				break;

				case "ajax.recover":
					return $this->AjaxRecover();
				break;

				case "ajax.resend":
					return $this->AjaxResend();
				break;

				case "ajax.reset":
					return $this->AjaxResetPassword();
				break;

				case "ajax.confirm":
					return $this->AjaxConfirm();
				break;

			}
		}
		
	}

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"combo"					=> "combo.htm",
			"combo.login"			=> "combo.login.htm",
			"combo.register"		=> "combo.register.htm",

			"widget.login"			=> "widget.login.htm",
			"widget.register"		=> "widget.register.htm",
			"widget.recover"		=> "widget.recover.htm",
			"widget.menu"			=> "widget.menu.htm",

			"menu"					=> "menu.htm",
		);

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

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

		//force jump on https if available
		$this->tpl_module["module_protected"] = "1";

		//$this->tpl_module["settings"]["link_dashboard"] = $this->tpl_module["link"] . "dashboard/";	
	} 


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function RegisterUser($data) {

		//init module in case i use this in other module and else i wont see the mails to sent
		$this->__init();


		if (!$data["user_status"]) {
			$data["user_status"] = $this->tpl_module["settings"]["set_local_status"];
		}	


		$old = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:users']} WHERE user_email=\"%s\"" ,
			array(
				$data["user_email"]
			)
		);

		if (is_array($old)) {
			return $old;
		}

		$user = array(
			"user_email"			=> $data["user_email"],
			"user_email_original"	=> $data["user_email"],
			"user_first_name"		=> $data["user_first_name"],
			"user_last_name"		=> $data["user_last_name"],

			"user_password"			=> $data["user_password"] ? md5($data["user_password"]) : "",
			"user_password_plain"	=> $data["user_password"],
			

			"user_date"				=> time(),
			"user_key"				=> md5($data["user_email"] . time()),
			"user_key_code"			=> md5($data["user_email"] . time()),

			"user_key_date"			=> time(),
			"user_status"			=> $data["user_status"],

			"user_groups"			=> $data["user_groups"],

			//facebook
			"user_fbid"				=> $data["user_fbid"],

			//save data
			"user_register_ip"		=> $_SERVER["REMOTE_ADDR"], 
			"user_referrer_url"		=> $_COOKIE["uref"]

		);


		$id = $this->db->QueryInsert(
			$this->tables["plugin:users"],
			$user
		);

		//update the id in user
		$user["user_id"] = $id;


		//run any operations that might apply for other modules
		foreach ($this->plugins["modules"]->modules as $key => $val) {
			if (method_exists($this->plugins[$val["module_code"]] , "UserOnRegister")) {

				if ($val["mod_protected"] || $val["module_protected"]) {
					$tmp_menu = $this->plugins[$val["module_code"]]->UserOnRegister($user);
				}				
			}						
		}

		//send the notification emails based on status

		if ($data["nomail"] != "true") {

			//debug($user);

			switch ($user["user_status"]) {
				//inactive
				case "1":
					$email = "set_mail_confirm";
				break;

				//active
				case "2":
					$email = "set_mail_welcome";
				break;

				case "3":
					$email = "set_mail_pending";
				break;
			}

			//send the mail 

			//facebook register
			if ($user["user_fbid"]) {
				$email = "set_mail_welcome_facebook";
			}


			$email = $this->module->plugins["mail"]->SendMail(
				$this->module->plugins["mail"]->GetMail(
					$this->tpl_module["settings"][$email],
					$user
				)
			);

			$email = $this->module->plugins["mail"]->SendMail(
				$this->module->plugins["mail"]->GetMail(
					$this->tpl_module["settings"]["set_mail_admin"],
					$user
				)
			);
		}
		


		//read the userdata from database
		$user_data = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:users']} WHERE user_id={$id}"
		);

		return $user_data;
	}
	

	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CheckUserPermission($module , $ajax = false) {
		global $_SESS;

		$this->__init();


		if (!$_SESS["client"]) {


			if ($ajax) {

				echo $this->plugins["common"]->ErrorMsg("Your session expired");
				die();
			} else {

				urlredirect(				
					$this->tpl_module["link"] . "signin/?r=" . urlencode($_SERVER["REQUEST_URI"])
				);
			}
			
		}		

		return true;
	}

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

		$this->__init();

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

		if ($_SESS["client"]) {

			if ($this->tpl_module["settings"]["set_menu_in"]) {
				//prepare some links
				$data = $_SESS["client"];


				$avatar = $this->Avatar();

				switch ($this->tpl_module["settings"]["set_menu_in"]) {
					case "1":
						$data["link_dashboard"] = $this->tpl_module["link"] ;
						$data["link_profile"] = $this->plugins["modules"]->modules["userprofile"]["link"];

						$data["link_logout"] = $this->tpl_module["link"] . "logout/";
						$data["avatar"] = $data["user_image"] ? $data["user_image"] . ".jpg" : "user.png";

						$menu_items = array(
							array(
								"title"	=> $this->plugins["modules"]->modules["userprofile"]["module_name"],
								"link"	=> $this->plugins["modules"]->modules["userprofile"]["link"],
								"current"	=> $_GET["mod"] == "userprofile" ? 1 : 0,
							),
							array(
								"title"	=> $this->plugins["modules"]->modules["userlogout"]["module_name"],
								"link"	=> $this->plugins["modules"]->modules["userlogout"]["link"],
							),
						);
					break;

					case "2":
						$menu_items = $this->GetTopMenuItems();


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

								if ($val["current"]) {
									$cur = true;
								}
								
								$menu_items[$key]["selected"] = $val["current"] ? $template->blockReplace("selected") : "";
							}					
						}
					break;
				}

				return CTemplateStatic::REplace(
					$this->private->templates["menu"]->blockReplace(
						"Account",
						array(
							"menu"	=> $base->html->Table(
								$this->private->templates["menu"], 
								"" , 
								$menu_items
							),

							"selected" => $cur ? $template->BlockReplace("selected") : "",

							"avatar"	=> $avatar,
						)
					),

					$this->tpl_module["settings"]				
				);
			} else {
				return "";
			}
			

		} else {

			if ($this->tpl_module["settings"]["set_menu_out"]) {

				if (FACEBOOK_SUPPORT && $this->tpl_module["settings"]["set_facebook"] && $this->vars->data["set_facebook_app"] && $this->vars->data["set_facebook_secret"]) {
					$facebook = new Facebook(array(
					  'appId'  => $this->vars->data["set_facebook_app"],
					  'secret' => $this->vars->data["set_facebook_secret"],
					));

					$user = $facebook->getUser();

					$facebook_link = htmlspecialchars($facebook->getLoginUrl(
							array(
								"redirect_uri"		=> $this->tpl_module["link"] . "facebook/",
								"scope"				=> "email"
							)
						)
					);
				}

				return $template->blockReplace(
					"Login",
					array(
						"link_login"	=> $this->tpl_module["link"],

						"register"		=> $this->tpl_module["settings"]["set_local"] ? $template->blockreplace("Register")  :"",


						"facebook"	=> $facebook_link ? $template->BlockReplace(
							"Facebook",
							array(
								"facebook_link"	=> $facebook_link
							)
						) : "",

						"selected"	=> $_GET["mod"] == $this->name ? $template->blockReplace("selected") : "",
					),
					array(
						
					),
					$this->tpl_module["settings"],
					$this->tpl_module				
				);
			} else {
				return "";
			}
		}
		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Dashboard() {
		global $_SESS;

		//check if membership is required and available 
		$this->__init();



		if (is_object($this->plugins["userplans"])) {

			if ($this->plugins["modules"]->modules["userplans"]["settings"]["set_membership_force"]) {

				if (!$this->plugins["userplans"]->CheckMembership()) {
					urlredirect($this->plugins["modules"]->modules["userplans"]["link"]);
				}

			}
		}
		


		$this->module->plugins["breadcrumb"]->Add(
			"Dashboard",
			array(
				$this->tpl_module["link"] . ""	=> "Account",
			)
		);


		urlredirect($this->GetAfterLoginLink());

		return $this->module->plugins["layouts"]->Render(
			$this->tpl_module["settings"]["set_layout_dashboard"],				
			""
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function RefreshUserData($user = null) {
		global $_SESS , $_CONF;

		
		if (!is_array($user)) {
			$user = $this->db->QFetchArray(
				"SELECT * FROM {$this->tables['plugin:users']} WHERE user_id={$_SESS[client][user_id]}"
			);
		}
		
		if ($user["user_image"]) {
			$user["avatar"] = $_CONF["url"] . "upload/users/{$user[user_id]}.jpg";
		} else {
			$user["avatar"] = $_CONF["url"] . "upload/users/user.png";
		}

		if ($user["user_groups"]) {
			$user["groups"] = explode("," , $user["user_groups"]);
		}
		
		if ($user["user_membership"]) {

			if ($user["user_membership_expire"] < time()) {

				if ($user["user_membership_expire"] != "-1") {

					unset($user["user_membership"]);
					//update the table record with the membership to avoid checking nex ttime
					$this->db->QueryUpdate(
						$this->tables["plugin:users"],
						array(
							"user_membership"			=> "0",
							"user_membership_expire"	=> 0,
						),
						"user_id={$user[user_id]}"
					);
				}
				

			}


		}
		

		$_SESS["client"] = $user;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetUserInfo($id) {
		global $_CONF;

		if ($this->cache[$id]) {
			return $this->cache[$id];
		}
		
		
		if ((int)$id) {
			$user = $this->db->QFetchArray(
				"SELECT * FROM {$this->tables['plugin:users']} WHERE user_id={$id}"
			);

			$user["avatar"] = $_CONF["url"] . "upload/users/user.png";

			$this->cache[$id] = $user;

			return $user;
		} else {
	
			$user = $this->db->QFetchArray(
				"SELECT * FROM {$this->tables['plugin:users']} WHERE user_login LIKE '{$id}'"
			);

			$user["avatar"] = $_CONF["url"] . "upload/users/user.png";

			$this->cache[$id] = $user;

			return $user;
		} 
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetMenuButton($module) {
		return "";

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function LogAction($data) {
		global $_SESS;

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

		$log = array(
			"log_date"			=> time(),
			"log_user"			=> $_SESS["client"]["user_id"],
			"log_ip"			=> $_SERVER["REMOTE_ADDR"],
			"log_url"			=> $data["url"],
			"log_description"	=> $data["action"],

			"log_module"		=> $data["module"],
			"log_module_type"	=> $data["module_type"],

		);

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


/*NEW MODULE */

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

		$texts = $this->GetTexts();

		$this->plugins["seo"]->PageMeta($texts);

		$this->module->plugins["breadcrumb"]->Add(
			array(
				"title"		=> $texts["text_title"],
				"subtitle"	=> $texts["text_subtitle"],
				"show"		=> $texts["text_status"],
			),
			array(
				$this->tpl_module["link"] . ""	=> $texts["text_title"],
			)
		);


		$content = $this->private->templates["combo"]->blockReplace(
			"Main",
			array(
				"script"	=> $this->plugins["modules"]->ScriptLink("ajax.login.php"),
				"r"			=> urldecode($_GET["r"]),

				"title"		=> $texts["text_signin_title"],
				"header"	=> $texts["text_signin_header"],
			)
		);

		return $this->module->plugins["layouts"]->Render(
			$this->tpl_module["settings"]["set_layout_login"],							
			$this->private->templates["combo"]->blockReplace(
				"Main",
				array(		
					"login"		=> $this->ComboSignin(),
					"register"	=> $this->ComboSignUp(),
					"header"	=> $texts["text_header"] ? $this->private->templates["combo"]->blockReplace("Header" , $texts) : "",
				),
				$texts
			)
		);

	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ComboSignin() {
		global $_CONF , $_SESS;

		if (FACEBOOK_SUPPORT && $this->tpl_module["settings"]["set_facebook"]) {
			$facebook = new Facebook(array(
			  'appId'  => $this->vars->data["set_facebook_app"],
			  'secret' => $this->vars->data["set_facebook_secret"],
			));

			$user = $facebook->getUser();

			if ($_GET["r"]) {
				$_SESS["facebook_redirect"] = $_GET["r"];
			}


			$facebook_link = htmlspecialchars($facebook->getLoginUrl(
					array(
						"redirect_uri"		=> $this->tpl_module["link"] . "facebook/",
						"scope"				=> "email"
					)
				)
			);

		}


		return $this->private->templates["combo.login"]->blockREplace(
			"Main" , 
			array(
				"script"		=> $this->plugins["modules"]->ScriptLink("ajax.login.php"),
				"script_forgot"	=> $this->plugins["modules"]->ScriptLink("ajax.forgot.php"),
				"r"				=> urldecode($_GET["r"]),				
				"captcha_r"		=> $this->plugins["captcha"]->GetCaptchaField($this->tpl_module["settings"]["set_captcha_recover"]),
				"captcha"		=> $this->plugins["captcha"]->GetCaptchaField($this->tpl_module["settings"]["set_captcha_login"]),

				"facebook"	=> $facebook_link ? $this->private->templates["combo.login"]->BlockReplace(
					"Facebook",
					array(
						"facebook_link"	=> $facebook_link
					)
				) : "",
			),
			$this->tpl_module["settings"]
		);
	}

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

		if (!$this->tpl_module["settings"]["set_local"]) {
			return "";
		}

		return $this->private->templates["combo.register"]->blockREplace(
			"Main" , 
			array(
				"script"	=> $this->plugins["modules"]->ScriptLink("ajax.register.php"),
				"r"			=> urldecode($_GET["r"]),				

				"user_name"	=> $this->tpl_module["settings"]["set_name"] ? $this->private->templates["combo.register"]->blockReplace(
					"UserName"
				): "",

				"captcha"	=> $this->plugins["captcha"]->GetCaptchaField($this->tpl_module["settings"]["set_captcha"])

			),
			$this->tpl_module["settings"]
		);
	}


################WIDGETS
	function Widget($widget) {


		$this->__init();

		switch ($widget["widget_type"]) {
			case "1":
				return $this->widgetLogin($widget);
			break;

			case "2":
				return $this->widgetMenu($widget);
			break;

			case "3":
				return $this->widgetRegister($widget);
			break;

			case "4":
				return $this->widgetRecover($widget);
			break;
		}
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetLogin($widget) {
		global $_SESS;

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

	
		if (FACEBOOK_SUPPORT && $widget["mod_settings"]["set_facebook"]) {

			$facebook = new Facebook(array(
			  'appId'  => $this->vars->data["set_facebook_app"],
			  'secret' => $this->vars->data["set_facebook_secret"],
			));

			$user = $facebook->getUser();


			if ($_GET["r"]) {
				$_SESS["facebook_redirect"] = $_GET["r"];
			}

			$facebook_link = htmlspecialchars($facebook->getLoginUrl(
					array(
						"redirect_uri"		=> $this->tpl_module["link"] . "facebook/",
						"scope"				=> "email"
					)
				)
			);

		}
		
		$this->__init();

		return $this->private->templates["widget.login"]->BlockReplace(
			"Widget" , 
			array(
				"title"		=> $widget["widget_name"],
				"script"	=> $this->plugins["modules"]->ScriptLink("ajax.login.php"),
				"r"			=> $_GET["r"],

				"facebook"	=> $facebook_link ? $this->private->templates["widget.login"]->BlockReplace(
					"Facebook",
					array(
						"facebook_link"	=> $facebook_link
					)
				) : "",


				"captcha"	=> $this->plugins["captcha"]->GetCaptchaField($widget["mod_settings"]["set_captcha_login"]),



			),
			$widget["settings"],
			$widget["mod_settings"],
			$widget

		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetRegister($widget) {
		global $_SESS;

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

		if (!$widget["mod_settings"]["set_local"]) {
			return "";
		}
		

		$this->__init();

		return $this->private->templates["widget.register"]->BlockReplace(
			"Widget" , 
			array(
				"r"			=> $_GET["r"],
				"script"	=> $this->plugins["modules"]->ScriptLink("ajax.register.php"),

				"user_name"	=> $widget["mod_settings"]["set_name"] ? $this->private->templates["widget.register"]->blockReplace(
					"UserName"
				): "",

				"captcha"	=> $this->plugins["captcha"]->GetCaptchaField($widget["mod_settings"]["set_captcha"]),

			),
			$widget["settings"],
			$widget["mod_settings"],
			$widget
		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetRecover($widget) {
		global $_SESS;

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

		$this->__init();

		return $this->private->templates["widget.recover"]->BlockReplace(
			"Widget" , 
			array(
				"script"	=> $this->plugins["modules"]->ScriptLink("ajax.forgot.php"),
				"captcha"	=> $this->plugins["captcha"]->GetCaptchaField($widget["mod_settings"]["set_captcha_recover"]),

			),
			$widget["settings"],
			$widget["mod_settings"],
			$widget
		);
	}

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

		foreach ($this->plugins["modules"]->modules as $key => $val) {

			if (method_exists($this->plugins[$val["module_code"]] , "UserMenuAppend")) {

				if (/*$val["mod_protected"] || $val["module_protected"] */ !$val["deny"] && (($val["mod_invisible"] && $val["mod_id"]) || !$val["mod_id"])) {

					$tmp_menu = $this->plugins[$val["module_code"]]->UserMenuAppend($val);

					if (is_array($tmp_menu)) {
						foreach ($tmp_menu as $_k => $_v) {
							$menu[] = $_v;
						}
					}

				}				
			}						
		}	
		
		foreach ($menu as $key => $val) {
			if ($val["priority"] == "-1") {
				unset($menu[$key]);
			}			
		}

		function umenuSort($a , $b) {
		   if ($a["priority"] == $b["priority"]) {
				return 0;
			}
			return ($a["priority"] < $b["priority"]) ? -1 : 1;

		}		

		if (is_array($menu)) {
			usort($menu , "umenuSort");
		}


		return $menu;

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetMenu($widget) {
		global $_SESS;

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

		
		$this->__init();


		//process all the modules and ask for new menus

		//debug($this->plugins["modules"]->modules,1);

		foreach ($this->plugins["modules"]->modules as $key => $val) {

			if (method_exists($this->plugins[$val["module_code"]] , "UserMenuAppend")) {

				if (/*$val["mod_protected"] || $val["module_protected"] */ !$val["deny"]) {

					$tmp_menu = $this->plugins[$val["module_code"]]->UserMenuAppend($val);

					if (is_array($tmp_menu)) {
						foreach ($tmp_menu as $_k => $_v) {
							$menu[] = $_v;
						}
					}
				}				
			}						
		}	
		
		foreach ($menu as $key => $val) {
			if ($val["priority"] == "-1") {
				unset($menu[$key]);
			}			
		}
		

		function menuSort($a , $b) {
		   if ($a["priority"] == $b["priority"]) {
				return 0;
			}
			return ($a["priority"] < $b["priority"]) ? -1 : 1;

		}		

		if (is_array($menu)) {
			usort($menu , "menuSort");
		}
		


		//start processing the menu

		$template = &$this->private->templates["widget.menu"];
		global $base;

		if (is_array($menu)) {

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

				$val["key"] = $key;

				$cur_note = 0;

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

					$act = false;

					foreach ($val["sub"] as $k => $v) {
						$cur_note += $v["notify"];
						$notifs += $v["notify"];
						$val["sub"][$k]["badge"] = $v["notify"] ? $template->blockReplace("Badge" , $v) : "";
						$val["sub"][$k]["class"] = $v["current"] ? $template->blockReplace("Active" , $v) : "";

						if ($v["current"]) {
							$act = true;
						}
						
					}

					$val["notify"] = $cur_note ? $template->blockReplace("Notify" , array("notify" => $cur_note)) : "";

					

					$menu[$key]["content"] = $template->blockReplace("Submenu" , $val);
					$menu[$key]["sub"] = CTemplateStatic::Replace(
						$base->html->Table(
							$template , 
							"Submenu" , 
							$val["sub"]
						),
						array(
							"key"		=> $key,
						)
					);

					$menu[$key]["class"] = $act ? $template->blockReplace( "Active" , $val) : "";

				} else {

					$notifs += $val["notify"];

					$val["notify"] = $val["notify"] ? $template->blockReplace("Notify" , array("notify" => $val["notify"])) : "";

					$menu[$key]["content"] = $template->blockReplace("Simple" , $val);
					$menu[$key]["sub"] = "";
					$menu[$key]["class"] = $val["current"] ? $template->blockReplace( "Active", $val) : "";
				}				

			}

			$user_info = $_SESS["client"];
			$user_info["notify"] = $notifs ? $template->blockReplace("UserNotify" , array("notify" => $notifs)) : "";
			$user_info["link_dashboard"] = $widget["link"];

			

			return CTemplateStatic::Replace(
				$template->blockReplace(
					"Widget" , 
					array(
						"title"	=> $widget["widget_name"] , 
						"menu"	=> $base->html->table(
							$template , 
							"" , 
							$menu
						),

						"user_info"	=> $template->blockReplace(
							"User",
							$user_info
						)
					),
					array(
						"class"	=> "",
					),
					$widget
				),
				$this->tpl_module["settings"]
			);
		}
		
		
	}




################AJAX OPERATIONS*/


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/

	function AjaxLogin($nocaptcha = false) {
		global $_SESS , $_CONF;

		if ($_GET["uid"]) {

			if ($_SESS["minibase"]["raw"]) {

				$user = $this->db->QFetchArray(
					"SELECT * FROM {$this->tables['plugin:users']} WHERE user_id={$_GET[uid]}"
				);
				

			}			
		} else {

			if (!$nocaptcha ) {
				if (!$this->plugins["captcha"]->Validate($this->tpl_module["settings"]["set_captcha_login"])) {
					return $this->plugins["captcha"]->ErrorMSG();
				}
			}
			
	
			//login with email
			if (stristr($_POST["email"] , "@")) {
				$user = $this->db->QFetchArray(
					"SELECT * FROM {$this->tables['plugin:users']} WHERE user_email LIKE '%s'",
					array(
						$_POST["email"]
					)
				);
				
			} else {
				//login with user
				$user = $this->db->QFetchArray(
					"SELECT * FROM {$this->tables['plugin:users']} WHERE user_login LIKE '%s'",
					array(
						$_POST["email"]
					)

				);

			}

			
			if (!is_array($user)) {
				return $this->module->plugins["common"]->ErrorMSG(
					$this->tpl_module["settings"]["lang_login_err_user"]
				);
			}
			
			if ($user["user_password"] != md5($_POST["password"])) {
				return $this->module->plugins["common"]->ErrorMSG(
					//$this->tpl_module["settings"]["lang_login_err_pass"]
					$this->tpl_module["settings"]["lang_login_err_user"]

				);
			}


			//check if user status is oka
			switch ($user["user_status"]) {
				case "1":
					return $this->module->plugins["common"]->ErrorMSG(
						$this->tpl_module["settings"]["lang_login_err_confirmed"]
					);
				break;

				case "3":
					return $this->module->plugins["common"]->ErrorMSG(
						$this->tpl_module["settings"]["lang_login_err_admin"]
					);
				break;

				case "4":
					return $this->module->plugins["common"]->ErrorMSG(
						$this->tpl_module["settings"]["lang_login_err_suspended"]
					);
				break;

			}		
		}

		if (is_array($user)) {
			global $_SESS;

			//update the login info
			$this->db->QueryUpdate(
				$this->tables["plugin:users"],
				array(
					"user_last_login_ip"	=> $_SERVER["REMOTE_ADDR"],
					"user_last_login"		=> time(),
				),
				"user_id={$user[user_id]}"
			);

			$this->RefreshUserData($user);

			$redir = $this->GetAfterLoginLink();
			
			$return = $this->module->plugins["common"]->SuccessMSG(
				"Login successful....",
				$redir
			);



			if ($_GET["uid"]) {
				return '<html><head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script></head><body>' . $return . "</body></html>";
			} else {
				return $return;
			}
					
		} 
		

		return $this->module->plugins["common"]->ErrorMSG(
			$this->tpl_module["settings"]["lang_login_err_user"]
		);

		
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxRegister() {
		global $_SESS;

		if (!$this->tpl_module["mod_settings"]["set_local"]) {
			return $this->module->plugins["common"]->ErrorMSG(
				"Registrations are disabled!"
			);			
		}


		if ($this->tpl_module["settings"]["set_name"]) {
			if(!$_POST["first_name"]){
				$errors[] =  $this->tpl_module["settings"]["lang_register_err_first_name"];
			}

			if(!$_POST["last_name"]){
				$errors[] =  $this->tpl_module["settings"]["lang_register_err_last_name"];
			}

		}
		
		if(!Validate::Email($_POST["email"])){
			$errors[] = $this->tpl_module["settings"]["lang_register_err_email"];
		}


		//check if users already exists
		if ($_POST[""]) {
		}
		
		$user = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:users']} WHERE user_email=\"%s\"" ,
			array(
				$_POST["email"]
			)
		);

		if(is_array($user)){
			$errors[] = $this->tpl_module["settings"]["lang_register_err_email_2"];
		}

		if(strlen($_POST["password"]) < 6){
			$errors[] = $this->tpl_module["settings"]["lang_register_err_pass"];
		}
		
		/*
		if($_POST["password"] != $_POST["confirm"]){
			return  $this->module->plugins["common"]->ErrorMsg(
				$this->tpl_module["settings"]["lang_register_err_confirm"]
			);
		}
		*/

		if (is_array($errors)) {
			return $this->module->plugins["common"]->ErrorMSG(
				$errors
			);
		}
		


		if (!$this->plugins["captcha"]->Validate($this->tpl_module["settings"]["set_captcha"])) {
			return $this->plugins["captcha"]->ErrorMSG();
		}


		$user = $this->registerUser(array(
			"user_email"			=> $_POST["email"],
			"user_first_name"		=> ucWords($_POST["first_name"]),
			"user_last_name"		=> ucWords($_POST["last_name"]),
			"user_password"			=> $_POST["password"],
			"user_groups"			=> $this->tpl_module["settings"]["set_local_group"],
			"user_status"			=> $this->tpl_module["settings"]["set_local_status"],
			"user_referrer_url"		=> $_COOKIE["uref"],
		));


		//perform autologin if registation is to active state
		if ($user["user_status"] == "2") {

			$_POST["email"] = $_POST["email"];
			$_POST["password"] = $_POST["password"];
			return $this->AjaxLogin(false);

		}
		

		return  $this->module->plugins["common"]->SuccessMsg(
			"reset:" . $this->tpl_module["settings"]["lang_register_err_success"]
		);

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxResend() {
		$user = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:users']} WHERE user_email LIKE '%s' AND user_status=1" , 
			array($_POST["email"])
		);


		if (is_array($user)) {

			//upgrade the key
			$this->db->QueryUpdate(
				$this->tables['plugin:users'] , 
				$user_info = array(
					"user_key_date"		=> time(),
					"user_key_code"		=> md5($user["user_email"] . time()) ,
				) ,
				"user_id={$user[user_id]}"
			);			

			$email = $this->module->plugins["mail"]->SendMail(
				$this->module->plugins["mail"]->GetMail(
					$this->tpl_module["settings"]["set_mail_reconfirm"],
					array_merge(
						$user,  
						$user_info
					)
				)
			);

			return  $this->module->plugins["common"]->SuccessMsg(
				$this->tpl_module["settings"]["lang_register_err_reconfirm"]
			);
		} else {
			return  $this->module->plugins["common"]->ErrorMsg(
				"UNKNOWN ERROR"
			);
		}
		



	}
	


	function AjaxResetPassword(){

		//get the user with the key valid 
		$user = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:users']} WHERE user_key_code LIKE \"%s\" AND user_key_date <= " . (time() + 3600 * 48 ),
			array($_GET["key"])
		);

		if (!is_array($user)) {
			return $this->module->plugins["modules"]->RedirectToModule(
				$this->tpl_module["settings"]["set_page_recover_invalid"]
			);
		}


		$user["user_password"] = RandomWord(6);

		$this->db->QueryUpdate(
			$this->tables['plugin:users'] , 
			array(
				"user_password"		=> md5($user["user_password"]),
				"user_key_date"		=> "0",
				"user_key_code"		=> "",

			) ,
			"user_id={$user[user_id]}"
		);

		///send the mail with the new password
		$email = $this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_forgot_new"],
				$user
			)
		);			

		return $this->module->plugins["modules"]->RedirectToModule(
			$this->tpl_module["settings"]["set_page_recover"]
		);
	}


	function AjaxConfirm(){

		//get the user with the key valid 
		$user = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:users']} WHERE user_status=1 AND user_key_code LIKE \"%s\" AND user_key_date <= " . (time() + 3600 * 48 ),
			array($_GET["key"])
		);

		if (!is_array($user)) {
			$this->module->plugins["modules"]->RedirectToModule(
				$this->tpl_module["settings"]["set_page_confirmed_invalid"]
			);
		}


		$this->db->QueryUpdate(
			$this->tables['plugin:users'] , 
			array(
				"user_status"		=> "2",
				"user_key_date"		=> "0",
				"user_key_code"		=> "",

			) ,
			"user_id={$user[user_id]}"
		);

		///send the mail with the new password
		$email = $this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_welcome"],
				$user
			)
		);			


		$this->RefreshUserData($user);
		urlredirect($this->tpl_module["link"]);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxRecover() {
		global $_SESS;

		if(!$_POST["email"]){
			return  $this->module->plugins["common"]->ErrorMsg(
				$this->tpl_module["settings"]["lang_forgot_err_user"]
			);
		}


		if (!$this->plugins["captcha"]->Validate($this->tpl_module["settings"]["set_captcha_recover"])) {
			return $this->plugins["captcha"]->ErrorMSG();
		}

		$user = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:users']} WHERE user_email LIKE \"%s\"" , 
			array($_POST["email"])
		);

		if(!is_array($user)){
			return  $this->module->plugins["common"]->ErrorMsg(
				$this->tpl_module["settings"]["lang_forgot_err_user"]
			);
		}

		//check if user is suspended
		switch ($user["user_status"]) {
			case "1":
			case "3":
				return  $this->module->plugins["common"]->ErrorMsg(
					$this->tpl_module["settings"]["lang_forgot_err_confirmed"]
				);
			break;

			case "4":
				return  $this->module->plugins["common"]->ErrorMsg(
					$this->tpl_module["settings"]["lang_forgot_err_suspended"]
				);
			break;
		}
		
		$key = md5($_POST["email"] . time());
		$user["user_key_code"] = $key;

		$this->db->QueryUpdate(
			$this->tables["plugin:users"],
			array(				
				"user_key_date"	=> time(),
				"user_key_code"		=> $key,
			),
			"user_id={$user[user_id]}"
		);

		$email = $this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_forgot_link"],
				$user
			)
		);			

		return  $this->module->plugins["common"]->SuccessMsg(
			"reset:" . $this->tpl_module["settings"]["lang_forgot_err_success"]
		);

	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxLogout() {
		global $_SESS;

		$client= $_SESS["client"];

		//remove the session
		unset($_SESS["client"]);

		if ($client["user_fbid"]) {
			
			/*
			//check if i allow facebook logins / registers
			if ($this->tpl_module["settings"]["set_facebook"] && FACEBOOK_SUPPORT) {

				$facebook = new Facebook(array(
					'appId'  => $this->vars->data["set_facebook_app"],
					'secret' => $this->vars->data["set_facebook_secret"],
				));
			}
		
			urlredirect(
				$facebook->getLogoutUrl(array(
				"next"	=> $this->tpl_module["link"]
				))
			); 

			*/

			unset($_SESSION['fb_' . $this->vars->data["set_facebook_app"] . '_code']);
			unset($_SESSION['fb_' . $this->vars->data["set_facebook_app"] . '_access_token']);
			unset($_SESSION['fb_' . $this->vars->data["set_facebook_app"] . '_user_id']);

			
		}

		//redirect 
		urlredirect($this->tpl_module["link"]);		
	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxFacebook() {
		global $_SESS;

		//check if i allow facebook logins / registers
		if (!$this->tpl_module["settings"]["set_facebook"]) {
			urlredirect($this->tpl_module["link"]);
		}
		

		if (!FACEBOOK_SUPPORT) {
			return "0";
		}
	

		$facebook = new Facebook(array(
			'appId'  => $this->vars->data["set_facebook_app"],
			'secret' => $this->vars->data["set_facebook_secret"],
			'allowSignedRequest' => true
		));


		$fbuid = $facebook->getUser();

		if ($fbuid) {
			//read the full profile
			$profile = $facebook->api('/me','GET');

			//check if thre is any user with this id
			$user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_fbid={$fbuid}");

			//try by mail address
			if (!is_array($user)){
				$user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_email LIKE '{$profile[email]}'");

				
				if (is_array($user)) {
					//update the fbid to this user
					$this->db->QueryUpdate(
						$this->tables["plugin:users"],
						array(
							"user_fbid" => $fbuid, 
						),
						"user_id={$user[user_id]}"
					);
				}
				
			}
			

			if (!is_array($user)) {
				//register the user
				$user = $this->registerUser(array(
					"user_fbid"			=> $profile["id"],
					"user_email"		=> $profile["email"],
					"user_first_name"	=> $profile["first_name"],
					"user_last_name"	=> $profile["last_name"],
					"user_status"		=> $profile["verified"] == "1" ? "2" : "1",
					"user_groups"		=> $this->tpl_module["settings"]["set_facebook_group"],
				));
			}			
			
			$this->RefreshUserData($user);	

		} 

		if ($_SESS["facebook_redirect"]) {
			urlredirect(urldecode($_SESS["facebook_redirect"]));
		}
		if ($_GET["r"]) {
			urlredirect($_GET["r"]);
		} else {		
			//redirect to main page
			urlredirect($this->tpl_module["link"]);
		}

	}


	function AccountLink() {
		$this->__init();

		return array(
			"link"	=> $this->tpl_module["link"] ,
			"title"	=> "Account"//$this->tpl_module["module_name"]
		);
	}



	//protect module

	function onGlobalHooksExecute($module) {
		global $_SESS , $_PAGE;

		$this->__init();

		if ($module["mod_id"] && $module["mod_protected"] && !is_array($_SESS["client"])) {


			if ($_PAGE == "ajax") {

				echo $this->plugins["common"]->ErrorMsg("Your session expired. Please login again.");
				die();
			} else {

				urlredirect(				
					$this->tpl_module["link"] . "signin/?r=" . urlencode($_SERVER["REQUEST_URI"])
				);
			}

		}	
	}


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

		if ($_POST["r"]) {
			$redir = $_POST["r"];
		} elseif ($this->tpl_module["settings"]["set_login_success_type"]){

			switch ($this->tpl_module["settings"]["set_login_success_type"]) {
				//site page
				case "1":
					$redir = $this->plugins["modules"]->modules[$this->tpl_module["settings"]["set_login_success"]]["link"];
				break;
				
				//global page
				case "2":
					$mod = $this->plugins["modules"]->LoadDefaultModule($this->tpl_module["settings"]["set_login_success_module"] , false , "id");
					$redir = $mod["link"];
				break;
			}
			
		} else {
			$redir = $_CONF["url"];
		}

		//fallback on homepage
		if (!$redir) {
			$redir = $_CONF["url"];
		}
			

		return $redir;
	}
	


	function GetAllLinks($module , &$links) {		
		$links[] = array(
			"url" => $module["link"],
		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Avatar($user = null) {
		global $_SESS , $_CONF;

		if ($user === null) {
			$user = $_SESS["client"];
		}

	
		if ($user["user_fbid"]) {
			$file = "//graph.facebook.com/{$user[user_fbid]}/picture";
		} else {
			//try gravatar with fallback to current default image
			$file = "https://secure.gravatar.com/avatar/" . md5(strtolower(trim($user["user_email"]))) . "?r=g&default=" . urlencode($_CONF["url"] . "upload/default-images/avatar.jpg");
		}
		
		return $file;		
	}
	

}

?>