<?php

if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOOPS_MODULE_PATH . "/user/forms/LostPassEditForm.class.php";
require_once XOOPS_MODULE_PATH . "/user/class/LostPassMailBuilder.class.php";

class User_LostPassAction extends User_Action
{
	var $mActionForm = null;
	
	function prepare(&$controller, &$xoopsUser)
	{
		$this->mActionForm =& new LostPassEditForm();
		$this->mActionForm->prepare();
	}
	
	function isSecure()
	{
		return false;
	}
	
	function hasPerm(&$controller, &$xoopsUser)
	{
		return !is_object($xoopsUser);
	}

	function getDefaultView(&$controller, &$xoopsUser)
	{
		if ((!isset($_REQUEST['code']))||(!isset($_REQUEST['email']))) {
			return USER_FRAME_VIEW_INPUT;
		} else {
			return $this->_updatePassword($controller);
		}
	}
	function _updatePassword(&$controller) {
		$this->mActionForm->fetch();

		$userHandler =& xoops_gethandler('user');
		$lostUserArr =& $userHandler->getObjects(new Criteria('email', $this->mActionForm->get('email')));
		if (is_array($lostUserArr) && count($lostUserArr) > 0) {
			$lostUser =& $lostUserArr[0];
		}
		else {
			return USER_FRAME_VIEW_SUCCESS;
		}

		$newpass = xoops_makepass();
		$extraVars['newpass'] = $newpass;
		$builder =& new LostPass2MailBuilder();
		$director =& new LostPassMailDirector($builder, $lostUser, $controller->mConfig, $extraVars);
		$director->contruct();
		$xoopsMailer =& $builder->getResult();
		if (!$xoopsMailer->send()) {
			// $xoopsMailer->getErrors();
			return USER_FRAME_VIEW_ERROR;
		}
		$lostUser->setVar('pass',md5($newpass), true);
		$userHandler->insert($lostUser, true);

		return USER_FRAME_VIEW_SUCCESS;
	}

	function execute(&$controller, &$xoopsUser)	
	{
		$this->mActionForm->fetch();
		$this->mActionForm->validate();
		
		if ($this->mActionForm->hasError()) {
			return USER_FRAME_VIEW_INPUT;
		}
		
		$userHandler =& xoops_gethandler('user');
		$lostUserArr =& $userHandler->getObjects(new Criteria('email', $this->mActionForm->get('email')));

		if (is_array($lostUserArr) && count($lostUserArr) > 0) {
			$lostUser =& $lostUserArr[0];
		}
		else {
			return USER_FRAME_VIEW_SUCCESS;
		}

		$builder =& new LostPass1MailBuilder();
		$director =& new LostPassMailDirector($builder, $lostUser, $controller->mConfig);
		$director->contruct();
		$xoopsMailer =& $builder->getResult();

		if (!$xoopsMailer->send()) {
			// $xoopsMailer->getErrors();
			return USER_FRAME_VIEW_ERROR;
		}

		return USER_FRAME_VIEW_SUCCESS;
	}
	
	function executeViewInput(&$controller, &$xoopsUser, &$render)
	{
		$render->setTemplateName("user_lostpass.html");
		$render->setAttribute("actionForm", $this->mActionForm);
	}

	function executeViewSuccess(&$controller, &$xoopsUser, &$render)
	{
	}

	function executeViewError(&$controller, &$xoopsUser, &$render)
	{
		redirect_header(XOOPS_URL, 3, _MD_ERROR_SEND_MAIL);
	}
}

?>