<?php
/**
 * Formulario para el logado en la Web del Banco del Tiempo de M�laga.
 **/
class UsuarioBtMalagaLoginForm extends Form {

	protected $authenticator_class = 'UsuarioBtMalagaAuthenticator';
	
	/**
	 * Constructor
	 *
	 * @param Controller $controller The parent controller, necessary to
	 *                               create the appropriate form action tag.
	 * @param string $name The method on the controller that will return this
	 *                     form object.
	 * @param FieldSet|FormField $fields All of the fields in the form - a
	 *                                   {@link FieldSet} of {@link FormField}
	 *                                   objects.
	 * @param FieldSet|FormAction $actions All of the action buttons in the
	 *                                     form - a {@link FieldSet} of
	 *                                     {@link FormAction} objects
	 * @param bool $checkCurrentUser If set to TRUE, it will be checked if a
	 *                               the user is currently logged in, and if
	 *                               so, only a logout button will be rendered
	 * @param string $authenticatorClassName Name of the authenticator class that this form uses.
	 */
	function __construct($controller, $name, $fields = null, $actions = null,
											 $checkCurrentUser = true, $validator = null) {

		if(isset($_REQUEST['BackURL'])) {
			$backURL = $_REQUEST['BackURL'];
		} else {
			$backURL = Session::get('BackURL');
		}

		if($checkCurrentUser && Member::currentUserID()) {
			$fields = new FieldSet();
			$actions = new FieldSet(new FormAction("logout", _t('Member.BUTTONLOGINOTHER', "Log in as someone else")));
		} else {
			if(!$fields) {
				$fields = new FieldSet(
					new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this),
					new TextField("Email", _t('Member.EMAIL', 'Email'), Session::get('SessionForms.MemberLoginForm.Email'), null, $this),
					new PasswordField("Password", _t('Member.PASSWORD', 'Password'))
				);
				if(SecurityBtMalaga::$autologin_enabled) {
					$fields->push(new CheckboxField(
						"Remember", 
						_t('Member.REMEMBERME', "Remember me next time?")
					));
				}
			}
			if(!$actions) {
				$actions = new FieldSet(
					new FormAction('dologin', _t('Member.BUTTONLOGIN', "Log in"))
				);
			}
		}

		if(isset($backURL)) {
			$fields->push(new HiddenField('BackURL', 'BackURL', $backURL));
		}

		parent::__construct($controller, $name, $fields, $actions, $validator);

		//esto esta en LoginForm (no extiende de LoginForm para poder poner validaciones)
		$this->disableSecurityToken();	

		//Desactiva la validaci�n mediante javascript, porque vamos a utilizar otro framework
		//$this->getValidator()->setJavascriptValidationHandler('none');

	}

	/**
	 * Get the authenticator class
	 * @return Authenticator Returns the authenticator class for this login form.
	 */
	
	public function getAuthenticator() {
		if(!class_exists($this->authenticator_class) || !is_subclass_of($this->authenticator_class, 'Authenticator')) {
			user_error("The form uses an invalid authenticator class! '{$this->authenticator_class}' is not a subclass of 'Authenticator'", E_USER_ERROR);
			return;
		}
		
		return new $this->authenticator_class;
	}


	/**
	 * Get message from session
	 */
	protected function getMessageFromSession() {
		parent::getMessageFromSession();
		if(($member = Member::currentUser()) &&
				!Session::get('MemberLoginForm.force_message')) {
			$this->message = sprintf(_t('Member.LOGGEDINAS', "You're logged in as %s."), $member->FirstName);
		}
		Session::set('MemberLoginForm.force_message', false);
	}


	/**
	 * Login form handler method
	 *
	 * This method is called when the user clicks on "Log in"
	 *
	 * @param array $data Submitted data
	 */
	public function dologin($data) {
		if($this->performLogin($data)) {
			Session::clear('SessionForms.MemberLoginForm.Email');
			Session::clear('SessionForms.MemberLoginForm.Remember');
			if(Member::currentUser()->isPasswordExpired()) {
				if(isset($_REQUEST['BackURL']) && $backURL = $_REQUEST['BackURL']) {
					Session::set('BackURL', $backURL);
				}

				$cp = new ChangePasswordForm($this->controller, 'ChangePasswordForm');
				$cp->sessionMessage('Your password has expired.  Please choose a new one.', 'good');
				
				Director::redirect('SecurityBtMalaga/changepassword');
			} elseif(
				isset($_REQUEST['BackURL']) 
				&& $_REQUEST['BackURL'] 
				// absolute redirection URLs may cause spoofing 
				&& Director::is_site_url($_REQUEST['BackURL'])
			) {
				//Director::redirect($_REQUEST['BackURL']);
				//Nota: mejorar esto
				if (stripos($_REQUEST['BackURL'],'verDatosOferta') === false) {
				  Director::redirect('/silverstripe/participantes');
				} else {
				  Director::redirect($_REQUEST['BackURL']);	
				}  
			} else {
				$member = Member::currentUser();
				if($member) {
					$firstname = Convert::raw2xml($member->FirstName);
					
					if(!empty($data['Remember'])) {
						Session::set('SessionForms.MemberLoginForm.Remember', '1');
						$member->logIn(true);
					} else {
						$member->logIn();
					}
					
					Session::set('Security.Message.message',
						sprintf(_t('Member.WELCOMEBACK', "Welcome Back, %s"), $firstname) 
					);
					Session::set("Security.Message.type", "good");
				}
				Director::redirectBack();
			}
		} else {
			Session::set('SessionForms.MemberLoginForm.Email', $data['Email']);
			Session::set('SessionForms.MemberLoginForm.Remember', isset($data['Remember']));

			if(isset($_REQUEST['BackURL'])) $backURL = $_REQUEST['BackURL']; 
			else $backURL = null; 

		 	if($backURL) Session::set('BackURL', $backURL);			
			
			if($badLoginURL = Session::get("BadLoginURL")) {
				Director::redirect($badLoginURL);
			} else {
				// Show the right tab on failed login
				$loginLink = Director::absoluteURL(SecurityBtMalaga::Link("login")); 
				if($backURL) $loginLink .= '?BackURL=' . urlencode($backURL); 
				Director::redirect($loginLink . '#' . $this->FormName() .'_tab');
			}
		}
	}


	/**
	 * Log out form handler method
	 *
	 * This method is called when the user clicks on "logout" on the form
	 * created when the parameter <i>$checkCurrentUser</i> of the
	 * {@link __construct constructor} was set to TRUE and the user was
	 * currently logged in.
	 */
	public function logout() {
		$s = new SecurityBtMalaga();
		$s->logout();
	}


  /**
   * Try to authenticate the user
   *
   * @param array Submitted data
   * @return Member Returns the member object on successful authentication
   *                or NULL on failure.
   */
	public function performLogin($data) {
		if($member = UsuarioBtMalagaAuthenticator::authenticate($data, $this)) {
			$member->LogIn(isset($data['Remember']));
			return $member;

		} else {
			$this->extend('authenticationFailed', $data);
			return null;
		}
	}


	/**
	 * Forgot password form handler method
	 *
	 * This method is called when the user clicks on "I've lost my password"
	 *
	 * @param array $data Submitted data
	 */
	function forgotPassword($data) {
		$SQL_data = Convert::raw2sql($data);
		$SQL_email = $SQL_data['Email'];
		$member = DataObject::get_one('Member', "Email = '{$SQL_email}'");

		if($member) {
			$member->generateAutologinHash();

			$member->sendInfo(
				'forgotPassword',
				array(
					'PasswordResetLink' => SecurityBtMalaga::getPasswordResetLink($member->AutoLoginHash)
				)
			);

			Director::redirect('SecurityBtMalaga/passwordsent/' . urlencode($data['Email']));
		} elseif($data['Email']) {
			$this->sessionMessage(
				_t('Member.ERRORSIGNUP', 'Sorry, but I don\'t recognise the e-mail address. Maybe you need ' .
					'to sign up, or perhaps you used another e-mail address?'
				),
				'bad'
			);
			
			Director::redirectBack();
		} else {
			$this->sessionMessage(
				_t('Member.ENTEREMAIL', 'Please enter an email address to get a password reset link.'),
				'bad'
			);
			
			Director::redirect('SecurityBtMalaga/lostpassword');
		}
	}

	/**
	 * Registra un nuevo usuario.
	 **/
	public function registrarUsuario($data, $form) {
		$usuario = new UsuarioBtMalaga();
	    $form->saveInto($usuario);
	    
	    //comprueba que no exista otro usuario con el mismo correo electr�nico.
	    $usuarioExistente = DataObject::get_one('UsuarioBtMalaga',"Email='".$usuario->Email."'");
	    if ($usuarioExistente == null) {
	    	$usuario->write();	        
	    	$componenteUsuario = new ComponenteUsuarioBtMalaga();
	    	$componenteUsuario->UsuarioID = $usuario->ID;
	    	$usuarioAdministrador = DataObject::get_one('UsuarioBtMalaga', "Email = 'AdministradorBtMalaga'");
	    	$componenteUsuario->AutorID = $usuarioAdministrador->ID;
	    	$contenedorComponenteUsuario = DataObject::get_one('CarpetaBtMalaga', "Nombre = 'ContenedorComponenteUsuarioBtMalaga'");
	    	$componenteUsuario->ParentID = $contenedorComponenteUsuario->ID;
	    	$componenteUsuario->write();
	    	Session::set("Security.Message.message", 'El registro se ha realizado correctamente, ahora ya puedes entrar en el sistema con tus credenciales.');
			Session::set("Security.Message.type", 'warning');
			Director::redirect('SecurityBtMalaga/login');
			
			//guarda los sistemas
			if (isset($data['Sistemas'])) {
		    	$sistemas = $data['Sistemas'];
		    	if ($sistemas != null) {
		    		foreach ($sistemas as $sistema) {
		    			$sistemaUsuario = new SistemaUsuarioBtMalaga();
		    			$sistemaUsuario->UsuarioID = $usuario->ID;
		    			$sistemaUsuario->SistemaID = $sistema;
		    			$sistemaUsuario->write();
		    		}
		    	}
			}	
			
			//envia un mensaje al administrador indicando el registro del usuario para su activaci�n
			GestorMensajesBtMalaga::enviarMensajeRegistroAdministrador($usuario);
			GestorMensajesBtMalaga::enviarMensajeRegistroUsuario($usuario);
	    }	
		
	}
}

?>