<?php
/**
 * Controlador para manipular la seguridad en la Web Banco del Tiempo de M�laga.
 **/
class SecurityBtMalaga extends Security {

	/**
	 * Template thats used to render the pages.
	 *
	 * @var string
	 */
	public static $template_main = 'Page';

	/**
	 * Sobreescribe el m�todo para devolver s�lo el autenticator de la Web.
	 */
	protected function GetLoginForms()
	{
		$forms = array();

		$authenticator = new UsuarioBtMalagaAuthenticator();
		array_push($forms,call_user_func(array($authenticator, 'get_login_form'), $this));
		return $forms;
	}

	/**
	 * Register that we've had a permission failure trying to view the given page
	 *
	 * This will redirect to a login page.
	 * If you don't provide a messageSet, a default will be used.
	 *
	 * @param Controller $controller The controller that you were on to cause the permission
	 *              failure.
	 * @param string|array $messageSet The message to show to the user. This
	 *                                  can be a string, or a map of different
	 *                                  messages for different contexts.
	 *                                  If you pass an array, you can use the
	 *                                  following keys:
	 *                                    - default: The default message
	 *                                    - logInAgain: The message to show
	 *                                                  if the user has just
	 *                                                  logged out and the
	 *                                    - alreadyLoggedIn: The message to
	 *                                                       show if the user
	 *                                                       is already logged
	 *                                                       in and lacks the
	 *                                                       permission to
	 *                                                       access the item.
	 */
	static function permissionFailure($controller = null, $messageSet = null) {
		if(Director::is_ajax()) {
			$response = ($controller) ? $controller->getResponse() : new HTTPResponse();
			$response->setStatusCode(403);
			$response->setBody('NOTLOGGEDIN:');
			return $response;
		} else {
			// Prepare the messageSet provided
			if(!$messageSet) {
				if(self::$default_message_set) {
					$messageSet = self::$default_message_set;
				} else {
					$messageSet = array(
						'default' => _t(
							'Security.NOTEPAGESECURED', 
							"That page is secured. Enter your credentials below and we will send you right along."
						),
						'alreadyLoggedIn' => _t(
							'Security.ALREADYLOGGEDIN', 
							"You don't have access to this page.  If you have another account that can access that page, you can log in below."
						),
						'logInAgain' => _t(
							'Security.LOGGEDOUT',
							"You have been logged out.  If you would like to log in again, enter your credentials below."
						)
					);
				}
			}

			if(!is_array($messageSet)) {
				$messageSet = array('default' => $messageSet);
			}

			// Work out the right message to show
			if(Member::currentUserID()) {
				$message = isset($messageSet['alreadyLoggedIn']) ? $messageSet['alreadyLoggedIn'] : $messageSet['default'];
				if($member = Member::currentUser()) {
					$member->logOut();
				}
			} else if(substr(Director::history(),0,15) == 'SecurityBtMalaga/logout') {
				$message = $messageSet['logInAgain'] ? $messageSet['logInAgain'] : $messageSet['default'];
			} else {
				$message = $messageSet['default'];
			}

			Session::set("Security.Message.message", $message);
			Session::set("Security.Message.type", 'warning');

			Session::set("BackURL", $_SERVER['REQUEST_URI']);

			// TODO AccessLogEntry needs an extension to handle permission denied errors
			// Audit logging hook
			if($controller) $controller->extend('permissionDenied', $member);

			Director::redirect("SecurityBtMalaga/login");
		}
		return;
	}

	/**
	 * Get a link to a security action
	 *
	 * @param string $action Name of the action
	 * @return string Returns the link to the given action
	 */
	public static function Link($action = null) {
		return "SecurityBtMalaga/$action";
	}

	/**
	 * Get the login form to process according to the submitted data
	 */
	protected function LoginForm() {
		$authenticator = new UsuarioBtMalagaAuthenticator();
		return call_user_func(array($authenticator, 'get_login_form'), $this);
	}

	/**
	 * Factory method for the lost password form
	 *
	 * @return Form Returns the lost password form
	 */
	public function LostPasswordForm() {
		return new UsuarioBtMalagaLoginForm(
			$this,
			'LostPasswordForm',
			new FieldSet(
				new EmailField('Email', _t('Member.EMAIL', 'Email'))
			),
			new FieldSet(
				new FormAction(
					'forgotPassword',
					_t('Security.BUTTONSEND', 'Send me the password reset link')
				)
			),
			false
		);
	}

	/**
	 * Show the "registro" page
	 *
	 * @return string Returns the "registro" page as HTML code.
	 */
	public function registrarse() {
		Requirements::javascript(THIRDPARTY_DIR . '/prototype.js');
		Requirements::javascript(THIRDPARTY_DIR . '/behaviour.js');
		Requirements::javascript(THIRDPARTY_DIR . '/loader.js');
		Requirements::javascript(THIRDPARTY_DIR . '/prototype_improvements.js');
		Requirements::javascript(THIRDPARTY_DIR . '/scriptaculous/effects.js');

		$tmpPage = new WebBtMalaga();
		$tmpPage->Title = 'Registrarse en el sistema';
		$tmpPage->URLSegment = 'SecurityBtMalaga';
		$controller = new WebBtMalaga_Controller($tmpPage);
		$controller->init();

		$customisedController = $controller->customise(array(
			'Content' => 
				'<h1>Rellene el siguiente formulario para registrarse en el sistema:</h1>',
			'Form' => $this->registrarUsuarioForm(),
		));
		
		//Controller::$currentController = $controller;
		return $customisedController->renderWith(array('Page', $this->stat('template_main')));
	}



	/**
	 * Devuelve el formulario de registro de un usuario.
	 **/
	public function registrarUsuarioForm() {
		/*$usuario = new UsuarioBtMalaga();
		return new UsuarioBtMalagaLoginForm(
			$this,
			'registrarUsuarioForm',
			$usuario->camposFormularioRegistro(),
			new FieldSet(
				new FormAction(
					'registrarUsuario',
					'Registrarse'
				)
			),
			false,
			$usuario->validadorFormularioRegistro()
		);*/
            return new FormularioRegistroUsuarioBtMalaga($this,'FormularioRegistroUsuarioBtMalaga');
	}

	/**
	 * Show the "login" page
	 *
	 * @return string Returns the "login" page as HTML code.
	 */
	public function login() {
		// Event handler for pre-login, with an option to let it break you out of the login form
		$eventResults = $this->extend('onBeforeSecurityLogin');
		// If there was a redirection, return
		if(Director::redirected_to()) return;
		// If there was an HTTPResponse object returned, then return that
		else if($eventResults) {
			foreach($eventResults as $result) {
				if($result instanceof HTTPResponse) return $result;
			}
		}
		
		
		$customCSS = project() . '/css/tabs.css';
		if(Director::fileExists($customCSS)) {
			Requirements::css($customCSS);
		}

		$tmpPage = new WebBtMalaga();
		$tmpPage->Title = _t('Security.LOGIN', 'Log in');
		$tmpPage->URLSegment = "SecurityBtMalaga";
		$tmpPage->ID = -1; // Set the page ID to -1 so we dont get the top level pages as its children

		$controller = new WebBtMalaga_Controller($tmpPage);
		$controller->init();
		//Controller::$currentController = $controller;

		$content = '';
		$forms = $this->GetLoginForms();
		if(!count($forms)) {
			user_error('No login-forms found, please use Authenticator::register_authenticator() to add one', E_USER_ERROR);
		}
		
		// only display tabs when more than one authenticator is provided
		// to save bandwidth and reduce the amount of custom styling needed 
		if(count($forms) > 1) {
			Requirements::javascript(THIRDPARTY_DIR . "/loader.js");
			Requirements::javascript(THIRDPARTY_DIR . "/prototype.js");
			Requirements::javascript(THIRDPARTY_DIR . "/behaviour.js");
			Requirements::javascript(THIRDPARTY_DIR . "/prototype_improvements.js");
			Requirements::javascript(THIRDPARTY_DIR . "/scriptaculous/effects.js");
			Requirements::css(SAPPHIRE_DIR . "/css/Form.css");
			
			// Needed because the <base href=".."> in the template makes problems
			// with the tabstrip library otherwise
			$link_base = Director::absoluteURL($this->Link("login"));
			
			Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery.js");
			Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery_improvements.js");
			Requirements::javascript(THIRDPARTY_DIR . '/jquery/plugins/livequery/jquery.livequery.js');
			Requirements::javascript(THIRDPARTY_DIR . "/tabstrip/tabstrip.js");
			Requirements::css(THIRDPARTY_DIR . "/tabstrip/tabstrip.css");
			
			$content = '<div id="Form_EditForm">';
			$content .= '<ul class="tabstrip">';
			$content_forms = '';

			foreach($forms as $form) {
				$content .= "<li><a href=\"$link_base#{$form->FormName()}_tab\">{$form->getAuthenticator()->get_name()}</a></li>\n";
				$content_forms .= '<div class="tab" id="' . $form->FormName() . '_tab">' . $form->forTemplate() . "</div>\n";
			}

			$content .= "</ul>\n" . $content_forms . "\n</div>\n";
		} else {
			$content .= $forms[0]->forTemplate();
		}
		
		if(strlen($message = Session::get('Security.Message.message')) > 0) {
			$message_type = Session::get('Security.Message.type');
			if($message_type == 'bad') {
				$message = "<p class=\"message $message_type\">$message</p>";
			} else {
				$message = "<p>$message</p>";
			}

			$customisedController = $controller->customise(array(
				"Content" => $message,
				"Form" => $content,
			));
		} else {
			$customisedController = $controller->customise(array(
				"Content" => $content,
			));
		}
		
		Session::clear('Security.Message');

		// custom processing
		return $customisedController->renderWith(array('Page', $this->stat('template_main')));
	}

	/**
	 * Show the "password sent" page, after a user has requested
	 * to reset their password.
	 *
	 * @param HTTPRequest $request The HTTPRequest for this action. 
	 * @return string Returns the "password sent" page as HTML code.
	 */
	public function passwordsent($request) {
		Requirements::javascript(THIRDPARTY_DIR . '/behaviour.js');
		Requirements::javascript(THIRDPARTY_DIR . '/loader.js');
		Requirements::javascript(THIRDPARTY_DIR . '/prototype.js');
		Requirements::javascript(THIRDPARTY_DIR . '/prototype_improvements.js');
		Requirements::javascript(THIRDPARTY_DIR . '/scriptaculous/effects.js');

		$tmpPage = new WebBtMalaga();
		$tmpPage->Title = _t('Security.LOSTPASSWORDHEADER');
		$tmpPage->URLSegment = 'SecurityBtMalaga';
		$controller = new WebBtMalaga_Controller($tmpPage);
		$controller->init();

		$email = Convert::raw2xml($request->param('ID') . '.' . $request->getExtension());
		
		$customisedController = $controller->customise(array(
			'Title' => sprintf(_t('Security.PASSWORDSENTHEADER', "Password reset link sent to '%s'"), $email),
			'Content' =>
				"<p>" . 
				sprintf(_t('Security.PASSWORDSENTTEXT', "Thank you! The password reset link has been sent to '%s'."), $email) .
				"</p>",
		));
		
		//Controller::$currentController = $controller;
		return $customisedController->renderWith(array('Page', $this->stat('template_main')));
	}


	
	/**
	 * Show the "change password" page
	 *
	 * @return string Returns the "change password" page as HTML code.
	 */
	public function changepassword() {
		$tmpPage = new WebBtMalaga();
		$tmpPage->Title = _t('Security.CHANGEPASSWORDHEADER', 'Change your password');
		$tmpPage->URLSegment = 'SecurityBtMalaga';
		$controller = new ContenidoGestionWebBtMalaga_Controller($tmpPage);
		$controller->init();

		if(isset($_REQUEST['h']) && Member::member_from_autologinhash($_REQUEST['h'])) {
			// The auto login hash is valid, store it for the change password form
			Session::set('AutoLoginHash', $_REQUEST['h']);

			$customisedController = $controller->customise(array(
				'Content' =>
					'<p>' . 
					_t('Security.ENTERNEWPASSWORD', 'Please enter a new password.') .
					'</p>',
				'Form' => $this->ChangePasswordForm(),
			));

		} elseif(Member::currentUser()) {
			// let a logged in user change his password
			$customisedController = $controller->customise(array(
				'Content' => '<p>' . _t('Security.CHANGEPASSWORDBELOW', 'You can change your password below.') . '</p>',
				'Form' => $this->ChangePasswordForm()));

		} else {
			// show an error message if the auto login hash is invalid and the
			// user is not logged in
			if(isset($_REQUEST['h'])) {
				$customisedController = $controller->customise(
					array('Content' =>
						sprintf(
							_t('Security.NOTERESETLINKINVALID',
								'<p>The password reset link is invalid or expired.</p><p>You can request a new one <a href="%s">here</a> or change your password after you <a href="%s">logged in</a>.</p>'
							),
							$this->Link('lostpassword'),
							$this->link('login')
						)
					)
				);
			} else {
				self::permissionFailure(
					$this,
					_t('Security.ERRORPASSWORDPERMISSION', 'You must be logged in in order to change your password!')
				);
				return;
			}
		}

		//Controller::$currentController = $controller;
		return $customisedController->renderWith(array('Page', $this->stat('template_main')));
	}
	
	/**
	 * Log the currently logged in user out
	 *
	 * @param bool $redirect Redirect the user back to where they came.
	 *                         - If it's false, the code calling logout() is
	 *                           responsible for sending the user where-ever
	 *                           they should go.
	 */
	public function logout($redirect = true) {
	  //Session::clear(ComponenteBtMalagaControl::SISTEMA);
	  session_unset(); 
	  parent::logout($redirect);
	}

	public function ejecutaOpcion($request) {
		$parametros = $request->allParams();
		$ID = $parametros['ID'];
            Director::redirect('/silverstripe/participantes/ejecutaOpcion/'.$ID);
	}

}
?>