/**
  * Login to add another quote to an existing customer account
  *
  * @return mixed
  */
 public function loginAction()
 {
     $this->_setBreadcrumbs(array('/' => 'Home', '/my-homelet' => 'My HomeLet', '/my-homelet/login' => 'Registration & Login'));
     $auth = Zend_Auth::getInstance();
     $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
     $loginForm = new Account_Form_Login();
     $loginForm->submit->setLabel('Login');
     $request = $this->getRequest();
     $params = $request->getParams();
     $stepNum = $request->getParam('step');
     $referrer = $request->getParam('refer');
     $message = $request->getParam('message');
     $statusMessage = '';
     $referrerUrl = $request->getParam('referrerUrl');
     if ($this->getRequest()->isPost()) {
         if (isset($params['resendValidation'])) {
             // User wants a new validation link
             $customerManager = new Manager_Core_Customer();
             $customer = $customerManager->getCustomerByEmailAddress($params['email']);
             if ($customer) {
                 $customer->sendAccountValidationEmail();
                 $loginForm->setDescription('Thank you, we have sent a new account validation link to your email address.');
             } else {
                 $loginForm->setDescription('Sorry, we could not find a customer with that email address. Please check the details you entered are correct and try again');
             }
         } elseif (isset($params['forgottenPassword'])) {
             // User has forgotten password
             $customerManager = new Manager_Core_Customer();
             $customer = $customerManager->getCustomerByEmailAddress($params['email']);
             if ($customer) {
                 $customer->resetPassword();
                 $customerManager->updateCustomer($customer);
                 $newPassword = $customer->getPassword();
                 $customerID = $customer->getIdentifier(Model_Core_Customer::IDENTIFIER);
                 // Now we have a new customer password - we also (sadly) need to update ALL the linked legacy customer entries
                 // or next time an old quote is opened it over-writes this new password (you couldn't make this stuff up!)
                 $legacyCustomerMap = new Datasource_Core_CustomerMaps();
                 $legacyIDs = $legacyCustomerMap->getLegacyIDs($customerID);
                 foreach ($legacyIDs as $legacyID) {
                     $oldCustomer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $legacyID);
                     $oldCustomer->setPassword($newPassword);
                     $customerManager->updateLegacyCustomer($oldCustomer);
                 }
                 // That's hopefully done it so we can show a nice message
                 $loginForm->setDescription("Thank you, we have sent a new password to your email address.");
             } else {
                 $loginForm->setDescription("Sorry, we could not find a customer with that email address. Please check the details you entered are correct and try again");
             }
         } elseif ($loginForm->isValid($_POST)) {
             // Values are valid - attempt a customer login
             // The forms passed validation so we now need to check the identity of the user
             $customerManager = new Manager_Core_Customer();
             $adapter = $customerManager->getAuthAdapter($loginForm->getValues());
             $result = $auth->authenticate($adapter);
             if (!$result->isValid()) {
                 // Invalid credentials
                 $loginForm->setDescription('Sorry, those login details seem to be incorrect');
             } else {
                 $storage = $auth->getStorage();
                 $storage->write($adapter->getResultRowObject(array('title', 'first_name', 'last_name', 'email_address', 'id')));
                 // Check the customer has validated their account
                 // Must be done after successful authentication to protect against unauthorised data exposure
                 $customer = $customerManager->getCustomerByEmailAddress($_POST['email']);
                 if ($customer->getEmailValidated() !== true) {
                     $auth->clearIdentity();
                     // Clear authentication performed to prevent login
                     // Customer has not validated their user account. Put the form in to an error status
                     // For some reason, this login form must use the form description to pass errors
                     // through to the view.
                     $loginForm->setDescription('Hello, at the moment you\'re unable to access My HomeLet  because you haven\'t validated your email address yet. We\'ve sent you an email which includes a link to confirm your email address and validate your My HomeLet account. If you\'ve not received your validation email or if you\'re unable to access your account, please call us on 0845 117 6000 - we\'re always happy to help!')->markAsError();
                 } else {
                     // Valid credentials - store the details we need from the database and move the user to the index page
                     if ($stepNum) {
                         // We were sent here from a quote step - so we need to link that quote to the newly logged in customer and redirect
                         if ($referrer != '') {
                             if ($referrer == 'tenants-insurance') {
                                 $customerManager = new Manager_Core_Customer();
                                 $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
                                 $legacyCustomerReference = $pageSession->CustomerRefNo;
                                 // This will create a customer record as we don't currently have one (only a legacy one)
                                 $customerManager->linkLegacyToNew($legacyCustomerReference, $auth->getStorage()->read()->id, Model_Core_Customer::CUSTOMER);
                                 $this->_helper->redirector->gotoUrl('/tenants/insurance-quote/step' . $stepNum);
                             } elseif ($referrer == 'landlords-insurance') {
                                 $customerManager = new Manager_Core_Customer();
                                 $pageSession = new Zend_Session_Namespace('landlords_insurance_quote');
                                 $legacyCustomerReference = $pageSession->customerRefNo;
                                 // This will create a customer record as we don't currently have one (only a legacy one)
                                 $customerManager->linkLegacyToNew($legacyCustomerReference, $auth->getStorage()->read()->id, Model_Core_Customer::CUSTOMER);
                                 $this->_helper->redirector->gotoUrl('/landlords/insurance-quote/step' . $stepNum);
                             }
                         }
                     }
                     // Set the customer id in the referencing session. This allows referencing to continue working
                     // with the new customer table
                     $referencing_session = new Zend_Session_Namespace('referencing_global');
                     $referencing_session->customerId = $customer->getIdentifier(Model_Core_Customer::IDENTIFIER);
                     // Simple session to track that an account logged in, but this does not expire with the real log in details, it's only cleared on logout or actual session close - this is used to accurately know when the real session has expired and to say so.
                     $account_session = new Zend_Session_Namespace('account_logged_in');
                     $account_session->loggedIn = true;
                     // This is the only parameter it ever sets
                     $referrerUrl = $loginForm->getElement('referrerUrl')->getValue();
                     if ($referrerUrl != '') {
                         $this->_helper->redirector->gotoUrl($referrerUrl);
                     } else {
                         $this->_helper->redirector->gotoUrl('/my-homelet');
                         return;
                     }
                 }
             }
         }
     } else {
         // Validate the referer url is relative to the current server
         if (preg_match('/\\/*/', $referrerUrl)) {
             $loginForm->getElement('referrerUrl')->setValue($referrerUrl);
         }
         if ($message == 'session-expired') {
             $this->getResponse()->setHttpResponseCode(403);
             // Required to allow ajax to detect session expiration
         }
         $statusMessage = "";
         if ($message != '') {
             $statusMessage = $message;
         }
     }
     $systemParams = Zend_Registry::get('params');
     $this->view->connectRootUrl = $systemParams->connectUrl->connectRootUrl;
     $this->view->message = $statusMessage;
     $this->view->stepNum = $stepNum;
     $this->view->ref = $referrer;
     $this->view->form = $loginForm;
 }
 public function loginAction()
 {
     $form = new LandlordsInsuranceQuote_Form_Login();
     $request = $this->getRequest();
     $pageSession = new Zend_Session_Namespace('landlords_insurance_quote');
     $pageForm = new LandlordsInsuranceQuote_Form_Step1();
     $pageForm->populate($pageSession->step1FormValues);
     $subFormPersonalDetails = $pageForm->getSubForm('subform_personaldetails');
     $form->getElement('email')->setValue($subFormPersonalDetails->getElement('email_address')->getValue());
     // Look up customer details if possible, note if the customer has already validated their My HomeLet account
     $customerValidated = false;
     $customerFirstName = '';
     $customerManager = new Manager_Core_Customer();
     $customer = $customerManager->getCustomerByEmailAddress($form->getElement('email')->getValue('email'));
     if ($customer) {
         $customerValidated = $customer->getEmailValidated();
         $customerFirstName = $customer->getFirstName();
     }
     if ($request->isPost()) {
         if (isset($_POST['resendValidation'])) {
             // User wants a new validation link
             if ($customer) {
                 $customer->sendAccountValidationEmail();
                 $form->setDescription('Thank you, we’ve sent you an email to validate your My HomeLet account, please make sure you check your inbox and your junk folder just in case.');
             } else {
                 $form->setDescription('Sorry, we could not find a customer with that email address. Please check the details you entered are correct and try again.');
             }
         } else {
             if (isset($_POST['forgottenPassword'])) {
                 // User has forgotten password
                 if ($customer) {
                     $customer->resetPassword();
                     $customerManager->updateCustomer($customer);
                     $newPassword = $customer->getPassword();
                     $customerID = $customer->getIdentifier(Model_Core_Customer::IDENTIFIER);
                     // Now we have a new customer password - we also (sadly) need to update ALL the linked legacy customer entries
                     // or next time an old quote is opened it over-writes this new password (you couldn't make this stuff up!)
                     $legacyCustomerMap = new Datasource_Core_CustomerMaps();
                     $legacyIDs = $legacyCustomerMap->getLegacyIDs($customerID);
                     foreach ($legacyIDs as $legacyID) {
                         $oldCustomer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $legacyID);
                         $oldCustomer->setPassword($newPassword);
                         $customerManager->updateLegacyCustomer($oldCustomer);
                     }
                     // That's hopefully done it so we can show a nice message
                     $form->setDescription('Thank you, we’ve sent you an email to reset your password, please make sure you check your inbox and your junk folder just in case.');
                 } else {
                     $form->setDescription('Sorry, we could not find a customer with that email address. Please check the details you entered are correct and try again.');
                 }
             } else {
                 if ($form->isValid($_POST)) {
                     // Save step1 form data and move to step 2
                     // Null off all reference numbers that may have been set via a new customer who has gone
                     // back and used an existing customer email address.
                     $this->_customerReferenceNumber = null;
                     $pageSession->CustomerRefNo = null;
                     $this->quoteID = null;
                     $pageSession->quoteID = null;
                     $this->_webLeadSummaryId = null;
                     $pageSession->webLeadSummaryId = null;
                     $this->saveStep1($pageForm);
                     $this->_helper->redirector->gotoUrl('/landlords/insurance-quote/step2');
                 } else {
                     $form->setDescription('Sorry, we could not log you in with the details given. Please check the details you entered are correct and try again.');
                 }
             }
         }
     }
     $this->view->form = $form;
     $this->view->customerValidated = $customerValidated;
     $this->view->customerFirstName = $customerFirstName;
 }