Beispiel #1
0
 public function isValid($data)
 {
     // add email to request data as
     // isValid seems to remove any data currently loaded into the form
     $email = $this->getElement('email')->getValue();
     $data['email'] = $email;
     $validationResult = parent::isValid($data);
     // Perform login validation
     $auth = Zend_Auth::getInstance();
     $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
     if ($data['password'] != '') {
         // Process login
         $customerManager = new Manager_Core_Customer();
         $adapter = $customerManager->getAuthAdapter(array('email' => $data['email'], 'password' => $data['password']));
         $result = $auth->authenticate($adapter);
         if ($result->isValid()) {
             $email = $this->getElement('email');
             $newCustomer = $customerManager->getCustomerByEmailAddress($email->getValue());
             if ($newCustomer->getEmailValidated() !== true) {
                 $auth->clearIdentity();
                 $this->setDescription("Unfortunately you haven't validated your email address yet. We've sent you an email which includes a link to validate your My HomeLet account. You'll need to validate your account to continue. If you've not received your validation email or if you're unable to access your account, please call us on 0845 117 6000.");
                 return false;
             }
             $storage = $auth->getStorage();
             $storage->write($adapter->getResultRowObject(array('title', 'first_name', 'last_name', 'email_address', 'id')));
         } else {
             $this->setDescription('Your account details are incorrect, please try again');
             return false;
         }
     }
     // All valid above, return parents validation result
     return $validationResult;
 }
 /**
  * check customer registration and carry on the registration process if it is not completed 
  *
  * Returns True if valid, false otherwise.
  *
  * @param string $email_address
  *
  * @return int
  */
 public function checkRegister($refno, $email, $isChangeEmail)
 {
     (string) ($refno = preg_replace('/X/', '', $refno));
     $customermgr = new Manager_Core_Customer();
     $customer = $customermgr->getCustomerByEmailAddress($email);
     $params = Zend_Registry::get('params');
     $mac = new Application_Core_Security($params->myhomelet->activation_mac_secret, false);
     $digest = $mac->generate(array('email' => $email));
     $activationLink = 'refno=' . $refno . '&' . 'email=' . $email . '&' . 'mac=' . $digest;
     $customerMap = new Datasource_Core_CustomerMaps();
     if ($customer) {
         if (!$customerMap->getMap(Model_Core_Customer::LEGACY_IDENTIFIER, $refno)) {
             $customermgr->linkLegacyToNew($refno, $customer->getIdentifier(Model_Core_Customer::IDENTIFIER));
         }
         if (!$customer->getEmailValidated()) {
             $mail = new Application_Core_Mail();
             $mail->setTo($email, null);
             $mail->setFrom('*****@*****.**', 'HomeLet');
             $mail->setSubject('My HomeLet account validation');
             $mail->applyTemplate('core/account-validation', array('activationLink' => $activationLink, 'homeletWebsite' => $params->homelet->domain, 'firstname' => $customer->getFirstName(), 'templateId' => 'HL2442 12-12', 'heading' => 'Validating your My HomeLet account', 'imageBaseUrl' => $params->weblead->mailer->imageBaseUrl), false, '/email-branding/homelet/portal-footer.phtml', '/email-branding/homelet/portal-header.phtml');
             $mail->applyTextTemplate('core/account-validationtxt', array('activationLink' => $activationLink, 'homeletWebsite' => $params->homelet->domain, 'firstname' => $customer->getFirstName(), 'templateId' => 'HL2442 12-12', 'heading' => 'Validating your My HomeLet account'), false, '/email-branding/homelet/portal-footer-txt.phtml', '/email-branding/homelet/portal-header-txt.phtml');
             // Send email
             $mail->send();
             return 1;
         } else {
             return 0;
         }
     } else {
         if ($isChangeEmail) {
             $cMap = $customerMap->getMap(Model_Core_Customer::LEGACY_IDENTIFIER, $refno);
             if ($cMap) {
                 $customer = $customermgr->getCustomer(Model_Core_Customer::IDENTIFIER, $cMap->getIdentifier());
                 $customer->setEmailAddress($email);
                 $customermgr->updateCustomer($customer);
                 $legacyids = $customerMap->getLegacyIDs($customer->getIdentifier());
                 foreach ($legacyids as $legacyid) {
                     if ($legacyid != $refno) {
                         $customer = $customermgr->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $legacyid);
                         $customer->setEmailAddress($email);
                         $customermgr->updateCustomer($customer);
                     }
                 }
                 return 0;
             }
         }
         $oldCustomer = $customermgr->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $refno);
         $mail = new Application_Core_Mail();
         $mail->setTo($email, null);
         $mail->setFrom('*****@*****.**', 'HomeLet');
         $mail->setSubject("Don't forget to register your My HomeLet account");
         $mail->applyTemplate('core/partial-registration', array('activationLink' => $activationLink, 'homeletWebsite' => $params->homelet->domain, 'firstname' => $oldCustomer->getFirstName(), 'templateId' => 'HL2469 12-12', 'heading' => 'Get even more with your My HomeLet account', 'imageBaseUrl' => $params->weblead->mailer->imageBaseUrl), false, '/email-branding/homelet/portal-footer.phtml', '/email-branding/homelet/portal-header.phtml');
         $mail->applyTextTemplate('core/partial-registrationtxt', array('activationLink' => $activationLink, 'homeletWebsite' => $params->homelet->domain, 'firstname' => $oldCustomer->getFirstName(), 'templateId' => 'HL2469 12-12', 'heading' => 'Get even more with your My HomeLet account'), false, '/email-branding/homelet/portal-footer-txt.phtml', '/email-branding/homelet/portal-header-txt.phtml');
         // Send email
         $mail->send();
         return 2;
     }
 }
 public function updatePersonalDetails($email, $title, $firstName, $lastName)
 {
     $customerManager = new Manager_Core_Customer();
     $customer = $customerManager->getCustomerByEmailAddress($email);
     if ($customer) {
         // Customer found in web database, update their personal details
         $customer->setTitle($title);
         $customer->setFirstName($firstName);
         $customer->setLastName($lastName);
         $customerManager->updateCustomer($customer);
         return 1;
     } else {
         // No customer found, update nothing
         return 0;
     }
 }
 public function isValid($formData = array())
 {
     if (isset($formData['property_postcode']) && trim($formData['property_postcode']) != '') {
         $postcode = trim($formData['property_postcode']);
         $postcodeLookup = new Manager_Core_Postcode();
         $addresses = $postcodeLookup->getPropertiesByPostcode(preg_replace('/[^\\w\\ ]/', '', $postcode));
         $addressList = array('' => '--- please select ---');
         foreach ($addresses as $address) {
             $addressList[$address['id']] = $address['singleLineWithoutPostcode'];
         }
         $ins_address = $this->getElement('property_address');
         $ins_address->setMultiOptions($addressList);
         $validator = new Zend_Validate_InArray(array('haystack' => array_keys($addressList)));
         $validator->setMessages(array(Zend_Validate_InArray::NOT_IN_ARRAY => 'Insured address does not match with postcode'));
         $ins_address->addValidator($validator, true);
     }
     // If a value for an address lookup is present, the house name or number is not required
     if (isset($formData['property_postcode'])) {
         $this->getElement('property_number_name')->setRequired(false);
     }
     // If a landline phone number is given, mobile is not mandatory
     if (isset($formData['phone_number']) && trim($formData['phone_number']) != '') {
         $this->getElement('mobile_number')->setRequired(false);
     }
     // If a mobile phone number is given, landline is not mandatory
     if (isset($formData['mobile_number']) && trim($formData['mobile_number']) != '') {
         $this->getElement('phone_number')->setRequired(false);
     }
     $result = parent::isValid($formData);
     $customerManager = new Manager_Core_Customer();
     $customer = $customerManager->getCustomerByEmailAddress($formData['email']);
     if ($customer) {
         // Customer exists, error the form
         $this->email->addError('This email is already in use. Have you signed up before?')->markAsError();
         return false;
     } else {
         return $result;
     }
 }
 /**
  * RRP Inception Form
  */
 public function rentRecoveryPlusAction()
 {
     // Ensure address lookup JS is available
     $this->view->headScript()->appendFile('/assets/connect/js/rentguaranteeclaims/addressLookup.js');
     // Ensure date picker CSS and JS are available
     $this->view->headLink()->appendStylesheet('/assets/vendor/jquery-datepicker/css/datePicker.css');
     $this->view->headScript()->appendFile('/assets/vendor/jquery-date/js/date.js');
     $this->view->headScript()->appendFile('/assets/vendor/jquery-datepicker/js/jquery.datePicker.js');
     $request = $this->getSymfonyRequest();
     $data = null;
     $policyNumberManager = new Manager_Core_PolicyNumber();
     if ($request->isMethod('GET')) {
         $quoteNumber = $request->get('policyNumber');
         if ($policyNumberManager->isRentRecoveryPlusQuote($quoteNumber)) {
             $applicationDecoratorClass = $this->getContainer()->get('rrp.application.decorator.class');
             /** @var RRP\Application\Decorators\RentRecoveryPlusQuote $quote */
             $quote = $applicationDecoratorClass::getDecorator('RentRecoveryPlusQuote');
             $data = $quote->getApplicationData($quoteNumber);
         }
     }
     $form = $this->_getRentRecoveryPlusApplicationForm($data, array('currentAsn' => $this->_agentSchemeNumber));
     if ($request->isMethod('POST')) {
         $form->submit($request);
         if ($form->isValid()) {
             if ($request->isXmlHttpRequest()) {
                 $update = true;
             } else {
                 $update = $form->get('update')->isClicked();
             }
             if (!$update) {
                 /** @var RRP\Model\RentRecoveryPlusApplication $application */
                 $application = $form->getData();
                 $applicationDecoratorClass = $this->getContainer()->get('rrp.application.decorator.class');
                 /** @var RRP\Application\Decorators\RentRecoveryPlusQuote $quote */
                 $quote = $applicationDecoratorClass::getDecorator('RentRecoveryPlusQuote');
                 $quote->setFromApplication($application);
                 if ($quote->getAppData()->getRefNo() === null) {
                     $customerManager = new Manager_Core_Customer();
                     $sudoEmailAddress = $customerManager->generateAgentSudoEmailAddress($this->_agentSchemeNumber);
                     $customer = $customerManager->getCustomerByEmailAddress($sudoEmailAddress);
                     $isNewCustomer = false;
                     if (!$customer) {
                         $isNewCustomer = true;
                         $customer = $customerManager->createNewCustomer($sudoEmailAddress, Model_Core_Customer::AGENT, true);
                         $customer->setLastName($this->_agentObj->name);
                         if ($this->_agentObj->contact[0]->address->flatNumber) {
                             $line1 = $this->_agentObj->contact[0]->address->flatNumber . ' ';
                         } else {
                             if ($this->_agentObj->contact[0]->address->houseName) {
                                 $line1 = $this->_agentObj->contact[0]->address->houseName . ' ';
                             } else {
                                 if ($this->_agentObj->contact[0]->address->houseNumber) {
                                     $line1 = $this->_agentObj->contact[0]->address->houseNumber . ' ';
                                 } else {
                                     $line1 = '';
                                 }
                             }
                         }
                         if ($this->_agentObj->contact[0]->address->addressLine1 && $this->_agentObj->contact[0]->address->addressLine2) {
                             $line1 .= $this->_agentObj->contact[0]->address->addressLine1 . ', ' . $this->_agentObj->contact[0]->address->addressLine2;
                         } else {
                             if ($this->_agentObj->contact[0]->address->addressLine1) {
                                 $line1 .= $this->_agentObj->contact[0]->address->addressLine1;
                             } else {
                                 if ($this->_agentObj->contact[0]->address->addressLine2) {
                                     $line1 .= $this->_agentObj->contact[0]->address->addressLine2;
                                 }
                             }
                         }
                         $customer->setAddressLine(Model_Core_Customer::ADDRESSLINE1, $line1);
                         $customer->setAddressLine(Model_Core_Customer::ADDRESSLINE2, $this->_agentObj->contact[0]->address->town);
                         $customer->setAddressLine(Model_Core_Customer::ADDRESSLINE3, $this->_agentObj->contact[0]->address->county);
                         $customer->setPostCode($this->_agentObj->contact[0]->address->postCode);
                         $customer->setCountry($this->_agentObj->contact[0]->address->country);
                         $customerManager->updateCustomer($customer);
                     }
                     // Now get the reference number from the newly created customer
                     $refNo = $customer->getIdentifier(Model_Core_Customer::LEGACY_IDENTIFIER);
                     $quote->getAppData()->setRefNo($refNo);
                     if ($isNewCustomer) {
                         $customerManager->updateCustomerAgentSchemeNumber($this->_agentSchemeNumber, $refNo);
                     }
                     if ($application->getPolicyNumber()) {
                         $policyNumber = $application->getPolicyNumber();
                     } else {
                         $policyNumber = $policyNumberManager->generateApplicationNumber(Manager_Core_PolicyNumber::QUOTE_IDENTIFIER);
                     }
                     $quote->setDefaults($policyNumber, $application->getReferenceType(), $application->getIsContinuationOfExistingPolicy(), $application->getPropertyLetType(), $application->getPropertyDeposit(), Model_Insurance_RentRecoveryPlus_LegacyPolicy::STATUS_QUOTE)->getAppData()->setAgentSchemeNumber($this->_agentSchemeNumber)->setUnderwritingQuestionSetID($this->_params->connect->settings->rentRecoveryPlus->underwritingQuestionSetID)->setRiskArea($this->_params->connect->settings->rentRecoveryPlus->riskArea);
                 } else {
                     $policyNumber = $quote->getAppData()->getPolicyNumber();
                 }
                 $this->referralModel->setPolicyNumber($policyNumber);
                 $this->rateManager = $this->initialiseRateManager($application);
                 $quote->setPolicyOptions($application->getPropertyRental(), $this->rateManager->getPremium(), $this->rateManager->getNilExcessOption())->getAppData()->setPremium($this->rateManager->getPremium())->setIpt($this->rateManager->getIpt())->setQuote($this->rateManager->getQuote())->setRateSetID($this->rateManager->getRateSetID());
                 // Does the given reference satisfy the policy criteria for this particular reference?
                 $referralRequired = false;
                 $reference = $this->getReferenceFromSession($application->getReferenceNumber());
                 $referenceSatisfiesCriteria = $this->referenceSatisfiesCriteria($reference);
                 // Does the application satisfy the application criteria?
                 $this->referralModel->setFromApplication($application, $this->rateManager->getPremium());
                 $applicationSatisfiesCriteria = $this->applicationSatisfiesCriteria();
                 if (!$referenceSatisfiesCriteria || !$applicationSatisfiesCriteria) {
                     // Fire a POLICY_REFERRED event to handle all referral related actions.
                     $referredEvent = new ReferredEvent($this->referralModel);
                     $this->eventDispatcher->dispatch(RRPEvents::POLICY_REFERRED, $referredEvent);
                     // Mark this application as referred.
                     $quote->getAppData()->setPayStatus(Model_Insurance_RentRecoveryPlus_LegacyPolicy::PAY_STATUS_REFERRED);
                     $referralRequired = true;
                 }
                 if ($application->getIsContinuationOfExistingPolicy()) {
                     $mailManager = new Application_Core_Mail();
                     if ($application->getIsExistingPolicyToBeCancelled()) {
                         $subject = str_replace('{$existingPolicyRef}', $application->getExistingPolicyRef(), $this->_params->connect->settings->rentRecoveryPlus->cancelExisting->emailSubject);
                         $message = $this->getContainer()->get('twig')->render('rent-recovery-plus-cancel-existing-mail.plain.twig', array('agentName' => $this->_agentObj->name, 'agentSchemeNumber' => $this->_agentSchemeNumber, 'policyNumber' => $policyNumber));
                         $mailManager->setTo($this->_params->connect->settings->rentRecoveryPlus->cancelExisting->emailToAddress, $this->_params->connect->settings->rentRecoveryPlus->cancelExisting->emailToName)->setFrom($this->_params->connect->settings->rentRecoveryPlus->cancelExisting->emailFromAddress, $this->_params->connect->settings->rentRecoveryPlus->cancelExisting->emailFromName)->setSubject($subject)->setBodyText($message);
                     } else {
                         $subject = str_replace('{$existingPolicyRef}', $application->getExistingPolicyRef(), $this->_params->connect->settings->rentRecoveryPlus->cancelExisting->emailSubject);
                         $message = $this->getContainer()->get('twig')->render('rent-recovery-plus-keep-existing-mail.plain.twig', array('agentName' => $this->_agentObj->name, 'agentSchemeNumber' => $this->_agentSchemeNumber, 'existingPolicyRef' => $application->getExistingPolicyRef()));
                         $mailManager->setTo($this->_params->connect->settings->rentRecoveryPlus->keepExisting->emailToAddress, $this->_params->connect->settings->rentRecoveryPlus->keepExisting->emailToName)->setFrom($this->_params->connect->settings->rentRecoveryPlus->keepExisting->emailFromAddress, $this->_params->connect->settings->rentRecoveryPlus->keepExisting->emailFromName)->setSubject($subject)->setBodyText($message);
                         if (isset($this->_params->connect->settings->rentRecoveryPlus->keepExisting->emailCcAddress)) {
                             $mailManager->setCC($this->_params->connect->settings->rentRecoveryPlus->keepExisting->emailCcAddress);
                         }
                     }
                     $mailManager->send();
                 }
                 if (!$quote->save()) {
                     return $this->renderTwigView('/rentguarantee/rent-recovery-plus-error.html.twig');
                 }
                 if ($referralRequired) {
                     // Render the referral text to the user.
                     return $this->renderTwigView('/rentguarantee/rent-recovery-plus-referral.html.twig', array('policyNumber' => $policyNumber));
                 }
                 if ($application->getIsPayMonthly()) {
                     $paymentDetails = sprintf('This will appear on your invoices as %d monthly payments of' . ' £%.02f plus £%.02f (IPT at %d%%). Total monthly payment £%.02f. ', $application->getPolicyLength(), $this->rateManager->getPremium(), $this->rateManager->getIpt(), $this->rateManager->getIptPercent(), $this->rateManager->getQuote());
                 } else {
                     $paymentDetails = sprintf('This will appear on your next invoices as £%.02f plus £%.02f (IPT at %d%%). Total £%.02f. ', $this->rateManager->getPremium(), $this->rateManager->getIpt(), $this->rateManager->getIptPercent(), $this->rateManager->getQuote());
                 }
                 return $this->renderTwigView('/rentguarantee/rent-recovery-plus-quote.html.twig', array('policyNumber' => $policyNumber, 'paymentDetails' => $paymentDetails));
             }
         }
     }
     if ($this->getRequest()->isXmlHttpRequest()) {
         $this->_helper->viewRenderer->setNoRender(true);
         $this->_helper->layout->disableLayout();
     }
     $agent = new Datasource_Core_AgentUser();
     if ($agent->canDisplayRRPI($this->_agentSchemeNumber, $this->_agentUserName)) {
         $this->renderTwigView('/rentguarantee/rent-recovery-plus-application.html.twig', array('form' => $form->createView()));
     } else {
         $this->renderTwigView('/rentguarantee/rent-recovery-plus-information.html.twig');
     }
 }
 /**
  * Display a list of quotes that can be retrieved after a user has identified themselves with an auth token via
  * retrieveQuoteAction().  Having this separate action allows an end user to press "Back" for up to an hour if they
  * have chosen to continue the wrong quote.
  *
  * @return void
  */
 public function retrieveMultipleQuotesAction()
 {
     if ($this->getRequest()->getParam('auth') != '') {
         $params = Zend_Registry::get('params');
         $mac = $this->getRequest()->getParam('auth');
         $securityManager = new Application_Core_Security($params->myhomelet->retrieveWithoutAccount->macSecret, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance != 0, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance);
         $dataKeys = array('customerEmail');
         $securityCheck = $securityManager->authenticate($mac, $dataKeys);
         if (isset($securityCheck['result']) && $securityCheck['result']) {
             // Customer has multiple quotes associated with their email address - look them up and generate a set of
             // auth tokens, show user the selection
             $email = $securityCheck['data']['customerEmail'];
             $policyCoverDatasource = new Datasource_Insurance_LegacyPolicyCovers();
             $customerManager = new Manager_Core_Customer();
             // Get all legacy quote IDs by customer e-mail address
             $legacyIDs = array();
             // Try to look up a customer record's quotes' IDs by the e-mail provided
             $newCustomer = $customerManager->getCustomerByEmailAddress($email);
             if ($newCustomer) {
                 $legacyCustomerMap = new Datasource_Core_CustomerMaps();
                 $legacyIDs = $legacyCustomerMap->getLegacyIDs($newCustomer->getIdentifier(Model_Core_Customer::IDENTIFIER));
             }
             // Also check in the legacy DB only to ensure landlords quotes are found
             $customer = $customerManager->getLegacyCustomerByEmailAddress($email);
             if ($customer) {
                 $legacyCustomerId = $customer->getIdentifier(Model_Core_Customer::LEGACY_IDENTIFIER);
                 if (!in_array($legacyCustomerId, $legacyIDs)) {
                     $legacyIDs[] = $legacyCustomerId;
                 }
             }
             // Retrieve all quotes for the linked customer reference numbers
             $quoteDatasource = new Datasource_Insurance_LegacyQuotes();
             $quotes = $quoteDatasource->getActiveQuotes($legacyIDs, '', array('policynumber', 'startdate'));
             // Build the list of policy covers and generate auth tokens for each policy
             // Should be done in a manager, but the quote manager has been written with the row data gateway
             // design pattern in mind.
             $authTokens = array();
             foreach ($quotes as $quote) {
                 // Create list of policy covers
                 $policyCoverList = array();
                 $policyOptionsplit = explode('|', $quote->policyOptions);
                 $sumInsuredSplit = explode('|', $quote->amountsCovered);
                 for ($i = 0; $i < count($policyOptionsplit); $i++) {
                     if ($sumInsuredSplit[$i] == 'yes' || floatval($sumInsuredSplit[$i]) > 0) {
                         // A sum insured value has been set so assume cover is in force
                         $policyCover = $policyCoverDatasource->getPolicyCoverByLabel($policyOptionsplit[$i]);
                         if ($policyCover) {
                             array_push($policyCoverList, array('cover' => $policyOptionsplit[$i], 'name' => $policyCover->getName()));
                         }
                     }
                 }
                 $quote->policyCovers = $policyCoverList;
                 // Generate a policy-specific authentication token
                 $securityManager = new Application_Core_Security($params->myhomelet->retrieveWithoutAccount->macSecret, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance != 0, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance);
                 $securityData = array('quoteNumber' => $quote->policyNumber);
                 $authTokens[$quote->policyNumber] = $securityManager->generate($securityData);
             }
             // Pass quotes and auth tokens into view and finish
             $this->view->quotes = $quotes;
             $this->view->authTokens = $authTokens;
             return;
         }
     }
     // Failover for non-auth or other issue - go to main retrieve quote form
     $this->_helper->redirector->gotoUrl('/my-homelet/retrieve-quote');
 }
 /**
  * Helper function to populate the zend form elements with database data
  *
  * @param Zend_Form $pageForm form definition for this step
  * @param int $stepNum current step number
  *
  * @return void
  */
 private function _formStepCommonPopulate($pageForm, $stepNum)
 {
     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
     // First of all check that this form should be viewable and the user isn't trying to skip ahead
     $this->view->stepNum = $stepNum;
     $this->view->stepMax = $this->_stepMax;
     // Check to see if the user is trying to skip ahead in the quote
     $tooFarAhead = false;
     if ((!isset($pageSession->completed) || is_null($pageSession->completed)) && $stepNum != 1) {
         $tooFarAhead = true;
         $lastCompleted = 1;
     } elseif ($stepNum > 1) {
         // Check to see if any pages previous to the one the user's trying to get to are incomplete
         $tooFarAhead = false;
         for ($i = 1; $i < $stepNum; $i++) {
             if (!isset($pageSession->completed[$i]) || !$pageSession->completed[$i]) {
                 $tooFarAhead = true;
                 $lastCompleted = $i;
                 break;
                 break;
             }
         }
     }
     if ($tooFarAhead) {
         // Drop user onto page that needs completing
         $this->_helper->redirector->gotoUrl('/tenants/insurance-quote-b/step' . $lastCompleted);
         return false;
     }
     // Now check to see if they need to login (using an existing email address without being logged in)
     if ($stepNum > 1) {
         // Before we do ANYTHING we need to check to see if the email address entered matches a customer record
         // we already have - if it does we need to ask them to login before they proceed.
         $customerReferenceNumber = $pageSession->CustomerRefNo;
         $customerManager = new Manager_Core_Customer();
         $legacyCustomer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $customerReferenceNumber);
         $emailAddress = $legacyCustomer->getEmailAddress();
         $customer = $customerManager->getCustomerByEmailAddress($emailAddress);
         if ($customer) {
             // There is already a customer entry for this email address - so we need to see if they are logged in
             // if not we need to force them to login
             $auth = Zend_Auth::getInstance();
             $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
             /*if ($auth->hasIdentity()) {
             					$loggedInEmail = $auth->getStorage()->read()->email_address;
             					if ($loggedInEmail != $customer->getEmailAddress()) {
             						// They are logged in but not who they should be to do this quote
             						$this->_helper->redirector->gotoUrl('/account/login?refer=tenants-insurance&step='. $stepNum);
             
             						return false;
             					}
             				} else {
             					// They aren't logged in and need to
             					$this->_helper->redirector->gotoUrl('/account/login?refer=tenants-insurance&step='. $stepNum);
             
             					return false;
             				}*/
         }
     }
     // Echo out some debug info if not in production mode
     Application_Core_Logger::log("Policy Number : " . $this->_policyNumber);
     Application_Core_Logger::log("Customer Ref No : " . $this->_customerReferenceNumber);
     Application_Core_Logger::log("agentSchemeNumber : " . $this->_agentSchemeNumber);
     $formData = array();
     // If step 1 and not in session (so producing a quick quote) - we need to pre-populate
     // a few bits if the customer is already logged into the site
     if ($stepNum == 1 && !isset($pageSession->CustomerRefNo)) {
         $auth = Zend_Auth::getInstance();
         $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
         if ($auth->hasIdentity()) {
             // Customer is logged in and starting a new quote - so we need to pre-populate the customers details from stored details
             $customerID = $auth->getStorage()->read()->id;
             $customerManager = new Manager_Core_Customer();
             $customer = $customerManager->getCustomer(Model_Core_Customer::IDENTIFIER, $customerID);
             // Get the customer's legacy record too as DoB is only in the old system
             $legacyCustomer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $customerID);
             $formData['title'] = $customer->getTitle();
             $formData['first_name'] = $customer->getFirstName();
             $formData['last_name'] = $customer->getLastName();
             $formData['phone_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE1);
             $formData['mobile_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE2);
             $formData['email_address'] = $customer->getEmailAddress();
             // Fetch DoB from old customer manager
             $formData['date_of_birth_at'] = $legacyCustomer->getDateOfBirth();
             $pageForm->populate($formData);
         }
     }
     // Only populate from DB if we are in session and have a reference number
     if (isset($pageSession->CustomerRefNo)) {
         $customerReferenceNumber = $pageSession->CustomerRefNo;
         $policyNumber = $pageSession->PolicyNumber;
         // Populate $formData with data from model, if available
         switch ($stepNum) {
             case 1:
                 // Personal Details section
                 $customerManager = new Manager_Core_Customer();
                 $customer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $customerReferenceNumber);
                 $titleOptions = TenantsInsuranceQuoteB_Form_Subforms_PersonalDetails::$titles;
                 if (in_array($customer->getTitle(), $titleOptions)) {
                     $formData['title'] = $customer->getTitle();
                 } else {
                     $formData['title'] = "Other";
                     $formData['other_title'] = $customer->getTitle();
                 }
                 $formData['first_name'] = $customer->getFirstName();
                 $formData['last_name'] = $customer->getLastName();
                 $formData['phone_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE1);
                 $formData['mobile_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE2);
                 $formData['email_address'] = $customer->getEmailAddress();
                 $dob = $customer->getDateOfBirthAt();
                 if (null != $dob && '0000-00-00' != $dob) {
                     $formData['date_of_birth_at'] = Application_Core_Utilities::mysqlDateToUk($dob);
                 }
                 // Data Protection section
                 $dpaManager = new Manager_Core_DataProtection();
                 $dpaItems = $dpaManager->getItems($customerReferenceNumber, Model_Core_DataProtection_ItemEntityTypes::INSURANCE);
                 foreach ($dpaItems as $currentItem) {
                     switch ($currentItem->constraintTypeId) {
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_PHONEANDPOST:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_phone_post'] = 0;
                             } else {
                                 $formData['dpa_phone_post'] = 1;
                             }
                             break;
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_SMSANDEMAIL:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_sms_email'] = 0;
                                 // For Redmine Ref #8003, "Updated marketing preference questions on online quotes"
                             } else {
                                 $formData['dpa_sms_email'] = 1;
                                 // For Redmine Ref #8003, "Updated marketing preference questions on online quotes"
                             }
                             break;
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_THIRDPARTY:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_resale'] = 1;
                             } else {
                                 $formData['dpa_resale'] = 0;
                             }
                             break;
                     }
                 }
                 // Contents Insurance section
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 // If we've retrieved this quote we need to setup some session variables to match the quote (agent scheme number mostly)
                 $session = new Zend_Session_Namespace('homelet_global');
                 $session->agentSchemeNumber = Manager_Core_Agent::filterAsn($quoteManager->getAgentSchemeNumber());
                 $contentsSI = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::CONTENTS);
                 // TODO: Remove the hard-coded contents insured splits - should be loaded from DB
                 if ($contentsSI == '5000' || $contentsSI == '7500' || $contentsSI == '10000' || $contentsSI == '15000') {
                     $formData['contents_cover_a'] = $contentsSI;
                 } else {
                     $formData['contents_cover_a'] = '15000+';
                     $formData['contents_cover_b'] = $contentsSI;
                 }
                 // Shares section
                 $sharersManager = new Manager_Insurance_TenantsContentsPlus_Sharers();
                 $existingSharers = $sharersManager->getSharers($policyNumber);
                 $formData['policy_sharers'] = 0;
                 if ($existingSharers) {
                     if ($existingSharers->getSharerOccupation(1) != '') {
                         $formData['policy_sharers'] = 1;
                         $formData['policy_sharer1_occupation'] = $existingSharers->getSharerOccupation(1);
                     }
                     if ($existingSharers->getSharerOccupation(2) != '') {
                         $formData['policy_sharers'] = 2;
                         $formData['policy_sharer2_occupation'] = $existingSharers->getSharerOccupation(2);
                     }
                 }
                 for ($i = 1; $i <= $pageForm->maxSharers; $i++) {
                     $formData["policy_sharer{$i}_occupation"] = $existingSharers->getSharerOccupation($i);
                 }
                 // Decide max number of sharers allowed based on contents insured value
                 $contentsAmount = new Zend_Currency(array('value' => $contentsSI, 'precision' => 0));
                 $sharersAllowed = $sharersManager->getNoOfSharersAllowed($contentsAmount);
                 // Push this into Javascript on the page
                 $this->view->headScript()->appendScript("var sharersAllowed = {$sharersAllowed};");
                 // Initial Disclosure Agreement section
                 // As we have a customer reference number they must have saved step 1 at some point which means
                 // they must have agreed to the IDD section
                 $formData['idd'] = 1;
                 break;
             case 2:
                 // Unspecified Possessions section
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 $unspecSI = $quoteManager->getCoverAmount(Manager_Insurance_TenantsContentsPlus_Quote::UNSPECIFIEDPOSSESSIONS);
                 // If step has been completed before we can assume some defaults that we'll over-write later
                 if (isset($pageSession->completed[2]) && $pageSession->completed[2] == true or $quoteManager->getPropertyPostcode() != '') {
                     $formData['away_from_home'] = 'no';
                     $formData['above_x'] = 'no';
                     $formData['bicycle'] = 'no';
                 }
                 // TODO: Re-factor this so that it doesn't use hardcoded pricing breaks anymore
                 if ($unspecSI > 0) {
                     $formData['away_from_home'] = 'yes';
                     $formData['possessions_cover'] = $unspecSI;
                 }
                 //TODO: This should be talking to the quote manager NOT directly to the datasource
                 $possessions = new Datasource_Insurance_Policy_SpecPossessions($pageSession->PolicyNumber);
                 if ($possessions->countPossessions() > 0) {
                     $formData['above_x'] = 'yes';
                 }
                 // Bicycle section
                 //TODO: This should be talking to the quote manager NOT directly to the datasource
                 $bicycle = new Datasource_Insurance_Policy_Cycles($this->_customerReferenceNumber, $this->_policyNumber);
                 if ($bicycle->countBikes() > 0) {
                     $formData['bicycle'] = 'yes';
                 }
                 break;
             case 3:
                 // Insured Address section
                 // Fetch previously stored address
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 $addressArray = $quoteManager->getPropertyAddress();
                 if ($addressArray['postcode'] != '') {
                     if (strpos($addressArray['address1'], ',') !== false) {
                         $formData['ins_house_number_name'] = preg_replace('/,.*$/', '', $addressArray['address1']);
                     } else {
                         $formData['ins_house_number_name'] = preg_replace('/ .*$/', '', $addressArray['address1']);
                     }
                     $formData['ins_postcode'] = $addressArray['postcode'];
                     // Look up address again to populate dropdown
                     $postcodeLookup = new Manager_Core_Postcode();
                     $addresses = $postcodeLookup->getPropertiesByPostcode(preg_replace('/[^\\w\\ ]/', '', $formData['ins_postcode']));
                     $addressList = array('' => '--- please select ---');
                     $filterString = is_numeric($formData['ins_house_number_name']) ? $formData['ins_house_number_name'] . ", " : $formData['ins_house_number_name'];
                     foreach ($addresses as $address) {
                         $addressList[$address['id']] = $address['singleLineWithoutPostcode'];
                         if (stripos($address['singleLineWithoutPostcode'], $filterString) === 0) {
                             $addressID = $address['id'];
                         }
                     }
                     // Add some validation
                     $ins_address = $pageForm->getSubForm('subform_insuredaddress')->getElement('ins_address');
                     $ins_address->setMultiOptions($addressList);
                     $validator = new Zend_Validate_InArray(array('haystack' => array_keys($addressList)));
                     $validator->setMessages(array(Zend_Validate_InArray::NOT_IN_ARRAY => 'Insured address does not match with postcode'));
                     $ins_address->addValidator($validator, true);
                     // Set the address to selected
                     $ins_address->setValue($addressID);
                     $addressID = null;
                     // Make sure we don't use this again for the correspondance address!
                     // Upsell Message section
                     $pageSession = new Zend_Session_Namespace('tenants_insurance_quote');
                     $session = new Zend_Session_Namespace('homelet_global');
                     $agentSchemeNumber = $session->agentSchemeNumber;
                 }
                 // Correspondance Address section
                 $customerManager = new Manager_Core_Customer();
                 $customer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $this->_customerReferenceNumber);
                 $addressLine1 = $customer->getAddressLine(Model_Core_Customer::ADDRESSLINE1);
                 $addressPostcode = $customer->getPostCode();
                 if ($addressPostcode != '') {
                     if (strpos($addressLine1, ',') !== false) {
                         $formData['cor_house_number_name'] = preg_replace('/,.*$/', '', $addressLine1);
                     } else {
                         $formData['cor_house_number_name'] = preg_replace('/ .*$/', '', $addressLine1);
                     }
                     $formData['cor_postcode'] = $addressPostcode;
                     // TODO: Surely if this postcode and house number matches the previous one
                     // we can just tick the YES box and hide the correspondance address form??
                     $postcodeLookup = new Manager_Core_Postcode();
                     $addresses = $postcodeLookup->getPropertiesByPostcode(preg_replace('/[^\\w\\ ]/', '', $formData['cor_postcode']));
                     $addressList = array('' => '--- please select ---');
                     $filterString = is_numeric($formData['cor_house_number_name']) ? $formData['cor_house_number_name'] . ", " : $formData['cor_house_number_name'];
                     foreach ($addresses as $address) {
                         $addressList[$address['id']] = $address['singleLineWithoutPostcode'];
                         if (stripos($address['singleLineWithoutPostcode'], $filterString) === 0) {
                             $addressID = $address['id'];
                         }
                     }
                     $cor_address = $pageForm->getSubForm('subform_correspondencedetails')->getElement('cor_address');
                     $cor_address->setMultiOptions($addressList);
                     $validator = new Zend_Validate_InArray(array('haystack' => array_keys($addressList)));
                     $validator->setMessages(array(Zend_Validate_InArray::NOT_IN_ARRAY => 'Insured address does not match with postcode'));
                     $cor_address->addValidator($validator, true);
                     $cor_address->setValue($addressID);
                 }
                 if ($addressPostcode != '' && $addressArray['postcode'] != '') {
                     if ($cor_address->getValue() == $ins_address->getValue()) {
                         $formData['cor_same_address'] = 'yes';
                     } else {
                         $formData['cor_same_address'] = 'no';
                     }
                 }
                 // Letting Agent section
                 // If the agent scheme number is not our default one - load the agent details
                 $params = Zend_Registry::get('params');
                 $agentSchemeNumber = Manager_Core_Agent::filterAsn($quoteManager->getAgentSchemeNumber());
                 // How did you hear about us section
                 $marketQuestion = new Manager_Core_ManagementInformation();
                 $formData['how_hear'] = $marketQuestion->getMarketingAnswers($this->_policyNumber);
                 //Campaign code section
                 $webLeadManager = new Manager_Core_WebLead();
                 $webLeadSummary = $webLeadManager->getSummary($this->_webLeadSummaryId);
                 $formData['campaign_code'] = $webLeadSummary->promotionCode;
                 // Start and end date
                 $startDate = $quoteManager->getStartDate();
                 if ($startDate != '' && $startDate != '0000-00-00') {
                     $formData['policy_start'] = substr($startDate, 8, 2) . '/' . substr($startDate, 5, 2) . '/' . substr($startDate, 0, 4);
                 }
                 break;
             case 4:
                 // Important Information section
                 // If this page has previously passed validation, we know what the answers
                 //   given must have been without hitting the DB (as anything else refers)
                 if (isset($pageSession->completed[$stepNum]) && $pageSession->completed[$stepNum]) {
                     $formData['declaration1'] = 'no';
                     $formData['declaration2'] = 'no';
                     $formData['declaration3'] = 'no';
                     $formData['declaration4'] = 'no';
                     $formData['declaration_confirmation'] = 'yes';
                     // If the step is completed we can also assume they said yes to the declaration agreement
                     $formData['declaration_statement'] = 1;
                 }
                 break;
             case 5:
                 // Not sure if we should really be loading payment methods back in
                 // surely it would be best to just let them choose again
                 break;
             case 'dd':
                 $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
                 $this->view->payMonthly = strtolower($quoteManager->getPayBy()) == 'monthly';
                 break;
         }
         $pageForm->populate($formData);
         // Populate the quick quote box
         $quoteManager = new Manager_Insurance_TenantsContentsPlus_Quote(null, null, $this->_policyNumber);
         $premiums = $quoteManager->calculatePremiums();
         $fees = $quoteManager->getFees();
         $this->view->premiums = $premiums;
         $this->view->fees = $fees;
     } else {
         // Not in session but there are some defaults we need to set for step 1
         // TODO: Write the javascript better so we don't need to do fudges like this
         $this->view->headScript()->appendScript("var sharersAllowed = 0;");
     }
     return true;
 }
 /**
  * Helper function to populate the zend form elements with database data
  *
  * @param Zend_Form $pageForm form definition for this step
  * @param int $stepNum current step number
  *
  * @return void
  */
 private function _formStepCommonPopulate($pageForm, $stepNum)
 {
     $this->view->stepNum = $stepNum;
     $this->view->stepMax = $this->_stepMax;
     // Check to see if the user is trying to skip ahead in the quote
     $pageSession = new Zend_Session_Namespace('landlords_insurance_quote');
     $tooFarAhead = false;
     if ((!isset($pageSession->completed) || is_null($pageSession->completed)) && $stepNum != 1) {
         $tooFarAhead = true;
         $lastCompleted = 1;
     } elseif ($stepNum > 1) {
         // Check to see if any pages previous to the one the user's trying to get to are incomplete
         $tooFarAhead = false;
         for ($i = 1; $i < $stepNum; $i++) {
             if (!isset($pageSession->completed[$i]) || !$pageSession->completed[$i]) {
                 $tooFarAhead = true;
                 $lastCompleted = $i;
                 break;
             }
         }
     }
     if ($tooFarAhead) {
         // Drop user onto page that needs completing
         $this->_helper->redirector->gotoUrl('/landlords/insurance-quote/step' . $lastCompleted);
         return false;
     }
     if ($stepNum > 1) {
         // Before we do ANYTHING we need to check to see if the email address entered matches a customer record
         // we already have - if it does we need to ask them to login before they proceed.
         $customerReferenceNumber = $this->_customerReferenceNumber;
         $customerManager = new Manager_Core_Customer();
         $legacyCustomer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $customerReferenceNumber);
         $emailAddress = $legacyCustomer->getEmailAddress();
         $customer = $customerManager->getCustomerByEmailAddress($emailAddress);
         if ($customer) {
             // There is already a customer entry for this email address - so we need to see if they are logged in
             // if not we need to force them to login
             $auth = Zend_Auth::getInstance();
             $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
             if ($auth->hasIdentity()) {
                 $loggedInEmail = $auth->getStorage()->read()->email_address;
                 if ($loggedInEmail != $customer->getEmailAddress()) {
                     // They are logged in but not who they should be to do this quote
                     $this->_helper->redirector->gotoUrl('/account/login?refer=landlords-insurance&step=' . $stepNum);
                     return false;
                 }
             } else {
                 // TODO: Check that removing the login redirection will not break other processes
                 // They aren't logged in and need to
                 /*$this->_helper->redirector->gotoUrl('/account/login?refer=landlords-insurance&step='. $stepNum);
                 		return false;*/
             }
         }
     }
     $formData = array();
     // If step 1 and not in session (so producing a quick quote) - we need to pre-populate
     // a few bits if the customer is already logged into the site
     if ($stepNum == 1 && !isset($pageSession->CustomerRefNo)) {
         $auth = Zend_Auth::getInstance();
         $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
         if ($auth->hasIdentity()) {
             // Customer is logged in and starting a new quote - so we need to pre-populate the customers details from stored details
             $customerID = $auth->getStorage()->read()->id;
             $customerManager = new Manager_Core_Customer();
             $customer = $customerManager->getCustomer(Model_Core_Customer::IDENTIFIER, $customerID);
             $formData['title'] = $customer->getTitle();
             $formData['first_name'] = $customer->getFirstName();
             $formData['last_name'] = $customer->getLastName();
             $formData['phone_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE1);
             $formData['mobile_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE2);
             $formData['email_address'] = $customer->getEmailAddress();
             $formData['date_of_birth_at'] = $customer->getDateOfBirthAt();
             $pageForm->populate($formData);
         }
     }
     if (isset($this->_quoteID) && $this->_quoteID > 0) {
         $quoteManager = new Manager_Insurance_LandlordsPlus_Quote($this->_quoteID);
         $premiums = $quoteManager->calculatePremiums();
         if ($premiums != '') {
             $this->view->premiums = array('annual' => $premiums['totalGrossAnnualPremium'] + $premiums['totalGrossAnnualIPT'], 'monthly' => $premiums['totalGrossMonthlyPremium'] + $premiums['totalGrossMonthlyIPT']);
             $this->view->premiumsFull = $premiums;
         }
         $fees = $quoteManager->getFees();
         $this->view->fees = $fees;
         switch ($stepNum) {
             case 1:
                 $customerManager = new Manager_Core_Customer();
                 $customer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $quoteManager->getLegacyCustomerReference());
                 // Populate the customer details
                 $titleOptions = LandlordsInsuranceQuote_Form_Subforms_PersonalDetails::$titles;
                 if (in_array($customer->getTitle(), $titleOptions)) {
                     $formData['title'] = $customer->getTitle();
                 } else {
                     $formData['title'] = "Other";
                     $formData['other_title'] = $customer->getTitle();
                 }
                 $formData['first_name'] = $customer->getFirstName();
                 $formData['last_name'] = $customer->getLastName();
                 $formData['phone_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE1);
                 $formData['mobile_number'] = $customer->getTelephone(Model_Core_Customer::TELEPHONE2);
                 $formData['email_address'] = $customer->getEmailAddress();
                 $dob = $customer->getDateOfBirthAt();
                 if (null != $dob && '0000-00-00' != $dob) {
                     $formData['date_of_birth_at'] = Application_Core_Utilities::mysqlDateToUk($dob);
                 }
                 // Populate the correspondence address details
                 $formData['cor_address_line1'] = $customer->getAddressLine(Model_Core_Customer::ADDRESSLINE1);
                 $formData['cor_address_line2'] = $customer->getAddressLine(Model_Core_Customer::ADDRESSLINE2);
                 $formData['cor_address_line3'] = $customer->getAddressLine(Model_Core_Customer::ADDRESSLINE3);
                 $formData['cor_address_postcode'] = $customer->getPostcode();
                 $formData['country'] = $customer->getCountry();
                 // Populate the insured property address details
                 $properties = $quoteManager->getProperties();
                 if (count($properties) > 0) {
                     $formData['ins_address_line1'] = $properties[0]['line_1'];
                     $formData['ins_address_line2'] = $properties[0]['line_2'];
                     $formData['ins_address_line3'] = $properties[0]['town'];
                     $formData['ins_address_postcode'] = $properties[0]['postcode'];
                     $formData['owned_for'] = $properties[0]['ownership_length_id'];
                     $formData['no_claims'] = $properties[0]['no_claims_years_id'];
                     $formData['tenants_type'] = $properties[0]['tenant_type_id'];
                     $formData['have_letting_agent'] = $quoteManager->getAgentSchemeNumber() != Manager_Core_Agent::filterAsn($quoteManager->getAgentSchemeNumber()) ? 'yes' : 'no';
                     $formData['through_letting_agent'] = $properties[0]['letting_agent_managed'] ? 'yes' : 'no';
                     // Check to see if this postcode is in a flood risk area - if it is then populate the exclude flood cover data
                     // Populating this will also cause the question to be shown on the front end
                     $landlordsRiskAreas = new Datasource_Insurance_LandlordsPlus_RiskAreas();
                     $riskAreas = $landlordsRiskAreas->getByPostcode($properties[0]['postcode']);
                     if ($riskAreas['floodArea'] == '600') {
                         $formData['exclude_flood_cover'] = $properties[0]['exclude_flood_cover'] ? 'no' : 'yes';
                         // Backwards true/false stuff - I'm sooo sorry :(
                     }
                 }
                 // Populate agent details if one has been chosen
                 $agentSchemeNumber = Manager_Core_Agent::filterAsn($quoteManager->getAgentSchemeNumber());
                 $defaultASN = $this->_params->homelet->defaultAgent;
                 if ($formData['have_letting_agent'] == 'yes') {
                     $agents = new Datasource_Core_Agents();
                     $agent = $agents->getAgent($agentSchemeNumber);
                     $formData['letting_agent_name'] = $agent->name;
                     $formData['letting_agent_town'] = $agent->town;
                     $formData['letting_agent_asn'] = $agent->agentSchemeNumber;
                     // Fix for Redmine Ref. #10511:
                     $agentDropdown = $pageForm->subform_lettingagent->letting_agent;
                     $agentDropdown->setMultiOptions(array($agent->agentSchemeNumber => $agent->name . ', ' . $agent->town));
                     $formData['letting_agent'] = $agent->agentSchemeNumber;
                 }
                 // Load the policy start date
                 $startDate = $quoteManager->getStartDate();
                 if ($startDate != '' && $startDate != '0000-00-00') {
                     $formData['policy_start'] = substr($startDate, 8, 2) . '/' . substr($startDate, 5, 2) . '/' . substr($startDate, 0, 4);
                 }
                 // If step1 has been marked complete - we can assume they said yes to the IDD question
                 $pageSession = new Zend_Session_Namespace('landlords_insurance_quote');
                 if (isset($pageSession->completed[$stepNum]) && $pageSession->completed[$stepNum] == true) {
                     $formData['idd'] = true;
                 }
                 // Data Protection section
                 $customerReferenceNumber = $customer->getIdentifier(Model_Core_Customer::LEGACY_IDENTIFIER);
                 $dpaManager = new Manager_Core_DataProtection();
                 $dpaItems = $dpaManager->getItems($customerReferenceNumber, Model_Core_DataProtection_ItemEntityTypes::INSURANCE);
                 foreach ($dpaItems as $currentItem) {
                     switch ($currentItem->constraintTypeId) {
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_PHONEANDPOST:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_phone_post'] = 0;
                             } else {
                                 $formData['dpa_phone_post'] = 1;
                             }
                             break;
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_SMSANDEMAIL:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_sms_email'] = 0;
                                 // For Redmine Ref #8003, "Updated marketing preference questions on online quotes"
                             } else {
                                 $formData['dpa_sms_email'] = 1;
                                 // For Redmine Ref #8003, "Updated marketing preference questions on online quotes"
                             }
                             break;
                         case Model_Core_DataProtection_ItemConstraintTypes::MARKETING_BY_THIRDPARTY:
                             if ($currentItem->isAllowed) {
                                 $formData['dpa_resale'] = 1;
                             } else {
                                 $formData['dpa_resale'] = 0;
                             }
                             break;
                     }
                 }
             case 2:
                 // If step2 has been marked complete - we can assume they said no to the questions unless
                 // they've been set in the quote manager
                 if (isset($pageSession->completed[$stepNum]) && $pageSession->completed[$stepNum] == true) {
                     $formData['need_building_insurance'] = 'no';
                     $formData['need_contents_insurance'] = 'no';
                 }
                 if ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::BUILDING_COVER)) {
                     $formData['need_building_insurance'] = 'yes';
                     $productMeta = $quoteManager->getProductMeta(Manager_Insurance_LandlordsPlus_Quote::BUILDING_COVER);
                     $formData['building_built'] = $productMeta['build_year'];
                     $formData['building_bedrooms'] = $productMeta['bedroom_quantity'];
                     $formData['building_type'] = $productMeta['building_type'];
                     $formData['building_insurance_excess'] = $productMeta['excess'];
                     $formData['building_accidental_damage'] = $productMeta['accidental_damage'];
                     $quote = $quoteManager->getModel();
                     if ((int) $productMeta['rebuild_value'] > 0) {
                         // There's a manually entered rebuild value - need to work out if it is because they
                         // chose £500k+ - or if it's because we don't have a dsi
                         $premiums = $quoteManager->calculatePremiums();
                         if ($premiums['calculatedDSIValue'] > 0) {
                             $formData['override_dsi'] = 1;
                         }
                         $formData['building_value'] = $productMeta['rebuild_value'];
                     }
                 }
                 if ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::CONTENTS_COVER) || $quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::UNFURNISHED_CONTENTS_COVER)) {
                     $formData['need_contents_insurance'] = 'yes';
                     if ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::CONTENTS_COVER)) {
                         $formData['property_furnished'] = 'yes';
                         $productMeta = $quoteManager->getProductMeta(Manager_Insurance_LandlordsPlus_Quote::CONTENTS_COVER);
                         $formData['contents_amount'] = $productMeta['cover_amount'];
                         $formData['contents_excess'] = $productMeta['excess'];
                         $formData['contents_accidental_damage'] = $productMeta['accidental_damage'];
                     } else {
                         $formData['property_furnished'] = 'no';
                     }
                 }
                 break;
             case 3:
                 if (isset($pageSession->completed[$stepNum]) && $pageSession->completed[$stepNum] == true) {
                     $formData['need_emergency_assistance'] = 'no';
                     $formData['need_prestige_rent_guarantee'] = 'no';
                     $formData['need_legal_expenses'] = 'no';
                     $formData['need_boiler_heating'] = 'no';
                 }
                 // If we have contents/buildings cover then EAS is already included for free so we can hide the form
                 if ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::BUILDING_COVER) || $quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::CONTENTS_COVER)) {
                     // Change the subforms view script to one that just says it's already included for free
                     // yeah yeah.. this aint pretty :(
                     $emergencyAssistanceForm = $pageForm->getSubForm('subform_emergencyassistance');
                     $emergencyAssistanceForm->setDecorators(array(array('ViewScript', array('viewScript' => 'subforms/emergency-assistance-free.phtml'))));
                     if ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::BOILER_HEATING)) {
                         $formData['need_boiler_heating'] = 'yes';
                     }
                 } else {
                     // We can allow stand-alone EAS - so we hide the boiler and heating section
                     // yes... this is waaay too complex... I know :(
                     $pageForm->removeSubForm('subform_boilerheating');
                     if ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::EMERGENCY_ASSISTANCE)) {
                         $formData['need_emergency_assistance'] = 'yes';
                     }
                 }
                 if ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::RENT_GUARANTEE)) {
                     $formData['need_prestige_rent_guarantee'] = 'yes';
                     $productMeta = $quoteManager->getProductMeta(Manager_Insurance_LandlordsPlus_Quote::RENT_GUARANTEE);
                     $formData['rent_amount'] = $productMeta['monthly_rent'];
                 } elseif ($quoteManager->hasProduct(Manager_Insurance_LandlordsPlus_Quote::LEGAL_EXPENSES)) {
                     $formData['need_legal_expenses'] = 'yes';
                 }
                 break;
             case 4:
                 if (isset($pageSession->completed[$stepNum]) && $pageSession->completed[$stepNum] == true) {
                     // Load underwriting answers from the database as they've already been answered
                     $answersManager = new Manager_Insurance_Answers();
                     $quote = $quoteManager->getModel();
                     $policyNumber = $quote->legacyID;
                     $customerReferenceNumber = $quote->legacyCustomerID;
                     $answers = $answersManager->getUnderwritingAnswers($policyNumber);
                     foreach ($answers as $answer) {
                         switch ($answer->getQuestionNumber()) {
                             case '53':
                                 $formData['declaration1'] = $answer->getAnswer();
                                 break;
                             case '54':
                                 $formData['declaration2'] = $answer->getAnswer();
                                 break;
                             case '55':
                                 $formData['declaration2b'] = $answer->getAnswer();
                                 break;
                             case '56':
                                 $formData['declaration2c'] = $answer->getAnswer();
                                 break;
                             case '57':
                                 $formData['declaration2d'] = $answer->getAnswer();
                                 break;
                             case '58':
                                 $formData['declaration3'] = $answer->getAnswer();
                                 break;
                             case '59':
                                 $formData['declaration4'] = $answer->getAnswer();
                                 break;
                             case '60':
                                 $formData['declaration6'] = $answer->getAnswer();
                                 break;
                             case '61':
                                 $formData['declaration7'] = $answer->getAnswer();
                                 break;
                             case '62':
                                 $formData['declaration8'] = $answer->getAnswer();
                                 break;
                             case '63':
                                 $formData['declaration9'] = $answer->getAnswer();
                                 break;
                             case '64':
                                 $formData['declaration10'] = $answer->getAnswer();
                                 break;
                         }
                     }
                     // Also need to see if they said yes or no to bank interest on the propery…
                     $bankInterestManager = new Manager_Insurance_LegacyBankInterest();
                     $bankInterestArray = $bankInterestManager->getAllInterests($policyNumber, $customerReferenceNumber);
                     $model = array();
                     if (!empty($bankInterestArray)) {
                         $formData['declaration11'] = 'yes';
                     } else {
                         $formData['declaration11'] = 'no';
                     }
                     // They must have agreed to the declaration or they wouldn't have been able to continue
                     $formData['declaration_confirmation'] = 'yes';
                 }
                 break;
             case 5:
                 // Payment Selection section
                 if (isset($pageSession->paymentSelectionDetails) && is_array($pageSession->paymentSelectionDetails)) {
                     $formData = $pageSession->paymentSelectionDetails;
                 }
                 break;
         }
     }
     $pageForm->populate($formData);
     return true;
 }