<?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 CUserProfile extends CPlugin{
	
	var $tplvars; 

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

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

		parent::DoEvents();

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

			$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 "profile":
					$this->plugins["users"]->CheckUserPermission($this->tpl_module);
					return $this->Profile();
				break;


				case "landing":
					return $this->Main();
				break;

				case "combo":
					return $this->Combo();
				break;

				case "signin":
					return $this->SignIn();
				break;

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

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


				case "ajax.password":
					$this->plugins["users"]->CheckUserPermission($this->tpl_module , true);

					return $this->AjaxUpdatePassword();
				break;

				case "ajax.profile":
					$this->plugins["users"]->CheckUserPermission($this->tpl_module , true);

					return $this->AjaxUpdateProfile();
				break;

				case "json.search":
					//$this->plugins["users"]->CheckUserPermission($this->tpl_module , true);

					return $this->JsonSearch();
				break;

				case "ajax.upload":
					$this->plugins["users"]->CheckUserPermission($this->tpl_module , true);
					return $this->AjaxUpload();
				break;

				
			}
		}
		
	}

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"profile.edit"	=> "profile.edit.htm",

		);

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

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

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

		$user_data = $_SESS["client"];

		$user_data["script_update"] = $this->plugins["modules"]->ScriptLink("ajax.userprofile.profile.php");
		$user_data["script_upload"] = $this->plugins["modules"]->ScriptLink("ajax.userprofile.upload.php");
		$user_data["script_password"] = $this->plugins["modules"]->ScriptLink("ajax.userprofile.password.php");
		$user_data["token"]	= $user_data["user_key"];
		$user_data["avatar_src"] = $user_data["user_image"] ? $user_data["user_id"] . ".jpg" : "user.png";


		$profile = $this->private->templates["profile.edit"]->blockReplace(
			"Edit",
			$user_data,
			array(
				"old_password"	=> $user_data["user_password"] ? $this->private->templates["profile.edit"]->blockReplace("OldPassword" . $profile ) : "",
			),
			$this->tpl_module["settings"]			
		);

		$mods = &$this->plugins["modules"]->modules;

		if (is_Array($mods)) {
			foreach ($mods as $key => $val) {
				if (method_exists($this->plugins[$val["module_code"]] , "onUserProfileEdit")) {

					$profile .= call_user_func(	
						array(
							&$this->plugins[$val["module_code"]] , 
							"onUserProfileEdit"
						),
						$val
					);
				}				
			}			
		}

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

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



		return $this->module->plugins["layouts"]->Render(
			$this->plugins["layouts"]->Detect(
				$this->tpl_module["settings"]["set_layout"],
				true
			),
			$profile,
			$this->tpl_module["settings"]["set_widgets"]
		);
	}
	

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

		$data = $_POST;

		$fields = array(
			"password"	=> "lang_profile_err_old",
			"password_new"	=> "lang_profile_err_new",
			"password_confirm"	=> "lang_profile_err_confirm",
		);

		if (!$_SESS["client"]["user_password"]) {
			unset($fields["password"]);
		}
		

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

			if (!$data[$key]) {
					return $this->module->plugins["common"]->ErrorMSG(
						$this->tpl_module["settings"][$val]
					);
			}
		}


		if ($_SESS["client"]["user_password"]) {
			if (md5($data["password"]) != $_SESS["client"]["user_password"]) {
				return $this->module->plugins["common"]->ErrorMSG(
					$this->tpl_module["settings"]["lang_profile_err_old"]
				);
			}
		}
		

		if ($data["password_new"] != $data["password_confirm"]) {
			return $this->module->plugins["common"]->ErrorMSG(
				$this->tpl_module["settings"]["lang_profile_err_confirm"]
			);
		}
		

		$this->db->QueryUpdate(
			$this->tables["plugin:users"],
			array(
				"user_password"			=> md5($data["password_new"]),
				"user_password_date"	=> time(),
			),
			"user_id={$_SESS[client][user_id]}"			
		);

		$this->plugins["users"]->RefreshUserData();


		$this->plugins["users"]->LogAction(array("action"	=> "Changed account password."));
		
		return $this->module->plugins["common"]->SuccessMSG(
			$this->tpl_module["settings"]["lang_profile_success_pass"]
		);

	}


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

		$data = $_POST;

		$fields = array(
			"user_first_name"	=> "lang_profile_edit_err_fn",
			"user_last_name"	=> "lang_profile_edit_err_ln",
			"user_email"		=> "lang_profile_edit_err_email",
		);

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

			if (!$data[$key]) {
					return $this->module->plugins["common"]->ErrorMSG(
						$this->tpl_module["settings"][$val]
					);
			}
		}

		//check if the email already exists 
		if (is_array($this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_email LIKE '%{$_POST[user_email]}%' AND user_id!={$_SESS['client']['user_id']}"))) {
			return $this->module->plugins["common"]->ErrorMSG(
				$this->tpl_module["settings"]["lang_profile_edit_err_email_exists"]
			);
		}
		

		if ($_POST["user_email"] != $_SESS["client"]["user_email"]) {
			$this->db->QueryInsert(
				$this->tables["plugin:users_emails"],
				array(
					"email_user"	=> $_SESS["client"]["user_id"] , 
					"email_date"	=> time(),
					"email_address"	=> $_SESS["client"]["user_email"]
					
				)
			);
		}
		

		$this->db->QueryUpdate(
			$this->tables["plugin:users"],
			array(
				"user_first_name"		=> $_POST["user_first_name"],
				"user_last_name"		=> $_POST["user_last_name"],
				"user_email"			=> $_POST["user_email"],
			),
			"user_id={$_SESS[client][user_id]}"			
		);


		///check for avatar
	/*
		$source = "upload/tmp/" . $_SESS["client"]["user_key"] . "_" . $data["ff"] ;
		$tmp = new CImage();

		if (file_exists($source) && $tmp->isImage($source)) {

			$tmp->Crop(
				$source, 
				"upload/users/" . $_SESS["client"]["user_id"] . ".jpg" , 
				170,
				NULL, 
				NULL , 
				NULL , 
				NULL , 
				NULL , 
				NULL , 
				NULL , 
				null,
				170
			);

			$this->db->QueryUpdate(
				$this->tables["plugin:users"],
				array(
					"user_image"		=> 1,
				),
				"user_id={$_SESS[client][user_id]}"			
			);

		}

*/

		$this->plugins["users"]->RefreshUserData();

		$this->plugins["users"]->LogAction(array("action"	=> "Changed personal profile."));

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


	}
	

	
	function AjaxUpload() {
		global $_CONF , $_SESS;

		$types = $this->tpl_module["settings"]["set_uploader_extensions"];

		$types = "jpg, png";

		if (!$types) {
			return "Please configure the allowed extensions!";
		}

		$types = explode("," , $types);

		if (count($types)) {
			foreach ($types as $key => $val) {
				$fileTypes[] = trim($val);
			}			
		}
		
		$verifyToken = $_SESS["client"]["user_key"];

		if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
				$tempFile   = $_FILES['Filedata']['tmp_name'];
				$uploadDir  = $_CONF["upload"] . "tmp/";
				$targetFile = $uploadDir . $_POST["token"] . "_" . $_FILES['Filedata']['name'];

				// Validate the filetype
				$fileParts = pathinfo($_FILES['Filedata']['name']);
		
				if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
					// Save the file
					move_uploaded_file($tempFile, $targetFile);
					return 1;
			} else {

					return 'Invalid file type.';

			}
		}
	}


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

		$this->__init();

		return array(
/*
			array(
				"html"	=> $this->private->templates["menu"]->blockReplacE(
					"Account" , 
					$module["settings"]
				 ),
			),
*/			
			array(
				
				"title"	=> $module["module_name"], 
				"link"	=> $module["link"] ,
				"target"	=> "",
				"selected"	=> ($_GET["mod"] == $this->name ) && ($_GET["sub"] == "profile") ? "true" : "",

				"priority"	=> "-1",

			),

		);

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function UserMenuAppend($module){

		return array(
			array(
				"title"	=> $module["module_name"], 
				"link"	=> $module["link"],
				"priority"	=> $module["module_user_position"],
				"current"	=> ($_GET["mod"] == $this->name ) ? true : "",
			),
		);
	}

	

}

?>