<?php
/*
	PHPbase web framework
	copyright (c) 2003 @authors

	$Id: name.php,v 0.0.1 dd/mm/yyyy hh:mm:ss author Exp $
	description
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CAuth extends CPlugin{

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/


	var $messages = array(
		"reset_success"		=> array(
			"title"	=> "Success",
			"text"	=> "We successfully sent you an email with the reset instructions!",
		),

		"reset_error"		=> array(
			"title"	=> "Error",
			"text"	=> "Invalid username or email address!",
		),

		"reset_suspended"	=> array(
			"title"	=> "Error",
			"text"	=> "This user account is suspended! Please contact an administrator for more details!",
		),

		"login_success"		=> array(
			"title"	=> "Success",
			"text"	=> "Logging in… any second now.",
		),

		"login_invalid"		=> array(
			"title"	=> "Error",
			"text"	=> "Invalid username or email address!",
		),

		"login_suspended"	=> array(
			"title"	=> "Error",
			"text"	=> "This user account is suspended! Please contact an administrator for more details!",
		),

		"login_password"	=> array(
			"title"	=> "Error",
			"text"	=> "Invalid password! Also, note that the field is case-sensitive.",
		),

		"captcha"			=> array(
			"title"	=> "Error",
			"text"	=> "captcha:Invalid CAPTCHA!"
		)



	);
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CAuth() {
		//parent::CModule("auth");
	}

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

		parent::DoEvents();

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

			$this->__init();
		
			switch ($_GET["sub"]) {

				case "login":
					return $this->LoginUser();
				break;

				case "recover":
					return $this->ResetPassword();
				break;



				case "verify":
					return $this->ResetVerify();
				break;
	#LOGOUT
				case "logout":
					unset($_SESS["minibase"]);
					if (isset($_USER)) {
						unset($_USER);
					}

					//remove the cookie
					setcookie("autologin", "", time() - 3600);  
					setcookie("username", "", time() - 3600);  
					setcookie("keycode" , "" , time() - 3600);

					header("Location: index.php");
					exit;
				break;

	#USERS MANAGEMENT


			}
		}		
	}	



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

		$username = $_POST["username"];
		$pass = $_POST["password"];
		$code = $_POST["image_code"] ;


		global $_SESS , $_USER;

		if ($_SESS["minibase"]["user"]) {
			return $this->Success(
				"login_success",
				$_POST["redirect"] ? $_POST["redirect"] : "index.php"
			);
		}
		

		//read the user
		$user = $this->db->QFetchArray("SELECT * FROM {$this->private->tables[users]} WHERE (`user_login`='%s' AND user_login !='') OR (user_email='%s' AND user_email!= '') ", array($username , $username));

		if ((max($user["user_log_tries"],$_SESS["minibase"]["tries"]) >= 3) && (!$code)) {
			return $this->Error("captcha");
		}

		if ($code && ($_SESS["XML_verify_key"] != $code)) {		
			return $this->Error("captcha");
		}

		$_SESS["minibase"]["tries"] ++;

		if (!is_array($user)) 
			return $this->Error("login_invalid");

		//update the tries
		$this->db->QueryUpdate(
			$this->private->tables["users"],
			array(
				"user_log_tries" => $user["user_log_tries"] + 1
			),
			"user_id={$user[user_id]}"
		);

		//check for user status
		if ($user["user_log_status"])
			return $this->Error("login_suspended");

				


		//check for the password
		if ($user["user_password"] != md5($pass))
			return $this->Error("login_password");


		if ($_POST["remember"]) {
			$time = time()+3600 *24 * 3600 ; // one year ahead
			setcookie("autologin", "true", $time);  
			setcookie("username", $user["user_login"], $time);  
			setcookie("keycode" , md5($user["user_login"] . $user["user_password"]) , $time);
		}

		//reset the tries and save the last login info
		$this->db->QueryUpdate(
			$this->private->tables["users"],
			array(
				"user_log_tries" => 0,
				"user_log_last_login" => time(),
				"user_log_last_ip" => $_SERVER["REMOTE_ADDR"]
			),
			"user_id={$user[user_id]}"
		);

		$_SESS["minibase"]["tries"] = 0;
		$_SESS["minibase"]["user"] = 1;
		$_SESS["minibase"]["raw"] = $user;
		$_USER = $user;


		return $this->Success("login_success",$_POST["redirect"] ? $_POST["redirect"] : "index.php");

	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Error($error) {

		$title = $this->messages[$error]["title"];
		$message = $this->messages[$error]["text"];

		return $this->private->templates["error"]->blockReplace(
			"Error",
			array(
				"title"		=> $title , 
				"message"	=> $message
			)
		);
	}
	

	function Success($error , $link = null) {

		$title = $this->messages[$error]["title"];
		$message = $this->messages[$error]["text"];

		return $this->private->templates["error"]->blockReplace(
			"Success",
			array(
				"title"		=> $title , 
				"message"	=> $message ,
				"redirect"		=> $link != null ? $this->private->templates["error"]->BlockReplace("Link" , array("link" => $link)) : "",
			)
		);
	}


	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"error"		=> "error.htm",
			"mail"		=> "mail.htm",
		);

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

		$this->tpl_module = array(
			"mod_name"	=> "Admin Panel Users",
		);
	} 



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

	

		if (is_array($user = $this->db->QFetchArray("SELECT * FROM {$this->private->tables[users]} WHERE user_email LIKE '{$_POST[username]}' OR user_login like '{$_POST[username]}'"))) {

			if ($user["user_log_status"]) {
				return $this->Error("reset_suspended");
			}
			


			//geenrate the key 
			$key = strtoupper(md5($user["user_login"] . time())) ;
			$user["user_key"] = $key;

			$url = 	dirname((strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" :  "http://") . 
				$_SERVER["HTTP_HOST"] . 
				($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') .
				$_SERVER["SCRIPT_NAME"] ) . "/";	

			$user["user_link"] = $url;

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

			require_once _MODPATH . "mail/admin.php";

			CMail::SendMail(
				array(
					"email_to" => $user["user_email"],
					"email_to_name" => $user["user_first_name"] . " " . $user["user_last_name"],

					"email_from_name" => "Stempora Support Team", 
					"email_from" => "support@stempora.com", 

					"email_subject" => "Password Recovery Instructions",

					"email_body" => $this->private->templates["mail"]->blockReplace("Recover" , $user),
				),
				$user						
			);

			return $this->Success("reset_success");
		} else {
			return $this->Error("reset_error");
		}
	}

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


		if (!$_GET["key"]) {
			urlredirect("index.php?mod=auth");
		}


		if (is_array($user = $this->db->QFetchArray("SELECT * FROM {$this->private->tables[users]} WHERE user_key LIKE '{$_GET[key]}' AND !user_log_status "))) {

			$url = 	dirname((strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" :  "http://") . 
				$_SERVER["HTTP_HOST"] . 
				($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') .
				$_SERVER["SCRIPT_NAME"] ) . "/";	

			$user["user_link"] = $url;
			//$user["pass"] = RandomWord(6);

			//reset the key
			//$this->db->Query("UPDATE {$this->private->tables[users]} SET user_password=md5('$user[pass]'),user_key='' WHERE user_key='{$user[user_key]}'");

			$_SESS["minibase"]["user"] = 1;
			$_SESS["minibase"]["raw"] = $user;
			$_SESS["minibase"]["newpass"] = 1;

			urlredirect("index.php?mod=administrators&sub=users&action=edit&user_id={$user[user_id]}&returnurl=" . 
				urlencode("index.php?mod=administrators&sub=myprofile")
			);
		} else {
			urlredirect("index.php?mod=auth");
		}

		

	}
	
}

?>