/**
  * @param LoanOfficer $loanOfficer
  */
 protected function addLoanOfficerUser(LoanOfficer $loanOfficer)
 {
     $loUser = $loanOfficer->getUser();
     $loSite = $loanOfficer->getOfficerSite();
     $loCreateUser = $loanOfficer->getAutoCreateUser();
     if ($loCreateUser && !isset($loUser) && isset($loSite)) {
         $loRole = $this->em->getRepository('SudouxCmsUserBundle:Role')->findOneBy(array('role' => 'ROLE_LOAN_OFFICER'));
         // check if user already exists by email
         $existingUser = $this->em->getRepository('SudouxCmsUserBundle:User')->findOneBy(array('email' => $loanOfficer->getEmail()));
         if (isset($existingUser)) {
             // assign existing user to lo
             $loanOfficer->setUser($existingUser);
             $this->em->persist($loanOfficer);
         } else {
             $user = new User();
             $username = strtolower(substr($loanOfficer->getFirstName(), 0, 1) . $loanOfficer->getLastName());
             $username = str_replace(' ', '', preg_replace("/[^A-Za-z0-9 ]/", '', $username));
             $user->setUsername($this->getLoanOfficerUsername($username));
             $factory = $this->container->get('security.encoder_factory');
             $encoder = $factory->getEncoder($user);
             $password = $encoder->encodePassword($user->generatePassword(), $user->getSalt());
             $user->setPassword($password);
             $user->setEmail($loanOfficer->getEmail());
             $user->setFirstName($loanOfficer->getFirstName());
             $user->setLastName($loanOfficer->getLastName());
             $user->addSite($loanOfficer->getOfficerSite());
             $user->addRole($loRole);
             $user->addToken();
             $user->setTimezone($loanOfficer->getSite()->getTimezone());
             $loanOfficer->setUser($user);
             $this->em->persist($loanOfficer);
             $emailUtil = $this->container->get('sudoux.cms.message.email_util');
             $email = new Email();
             $email->setRecipient($user->getEmail());
             $email->setRecipientName($user->getFullName());
             $email->setSubject($this->container->get('sudoux.cms.site')->getSiteVar('New Website Account', 'loan_officer_user_add_email_subject'));
             $email->setUser($user);
             $email->setSite($loanOfficer->getSite());
             $resetPasswordUrl = sprintf("https://%s%s", $loanOfficer->getOfficerSite()->getPrimaryDomain()->getDomain(), $this->router->generate('sudoux_cms_user_reset_password', array('token' => $user->getToken())));
             // default message
             $message = sprintf('<p>An account has been created for you on your new website. Your username is %s</p>', $user->getUsername());
             $message .= sprintf('<p><a href="%s">Click here</a> to set your password and confirm your account.</p>', $resetPasswordUrl);
             $tokens = array('username' => $user->getUsername(), 'email' => $user->getEmail(), 'reset_password_url' => $resetPasswordUrl, 'first_name' => $user->getFirstName(), 'last_name' => $user->getLastName(), 'website_url' => 'https://' . $loanOfficer->getOfficerSite()->getPrimaryDomain()->getDomain());
             $message = $this->container->get('sudoux.cms.site')->getSiteVar($message, 'loan_officer_user_add_email_message', $tokens);
             $email->setMessage($message);
             $emailUtil->logAndSend($email);
         }
         $this->em->flush($loanOfficer);
     }
 }
 /**
  * @param Request $request
  * @param $id
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  * @throws \AccessDeniedHttpException
  * @throws \Symfony\Component\Form\Exception\FormException
  * @throws \Symfony\Component\Form\Exception\UnexpectedTypeException
  */
 public function memberAction(Request $request, $id)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $securityContext = $this->container->get('security.context');
     $user = $securityContext->getToken()->getUser();
     $siteRequest = $this->get('sudoux.cms.site');
     $site = $siteRequest->getSite();
     $portalEnabled = $site->getSettings()->getInheritedMemberPortalEnabled();
     if (!$portalEnabled) {
         $request->getSession()->getFlashBag()->add('error', $this::LOAN_LOCKED_MESSAGE);
         return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan'));
     }
     $session = $request->getSession();
     $documentVocab = $site->getSettings()->getInheritedLoanDocumentVocab();
     $document = new LoanDocument();
     $documentForm = $this->createForm(new LoanDocumentType($documentVocab), $document);
     $application = $em->getRepository('SudouxMortgageBundle:LoanApplication')->findOneBySite($site, $id);
     if (!isset($application)) {
         throw $this->createNotFoundException($this::LOAN_NOT_FOUND_MESSAGE);
     }
     if ($application->getStatus() < 2) {
         $application->setStatus(2);
         $em->persist($application);
         $em->flush();
     }
     $loanForm = $this->createForm(new LoanApplicationType($site, $application), $application, array('validation_groups' => array('status')));
     $availableUsers = $em->getRepository('SudouxCmsUserBundle:User')->findAllBySingleSite($site);
     $loanUsers = $application->getClientUser();
     // remove the application user
     $applicationUser = $application->getUser();
     if (isset($applicationUser)) {
         foreach ($availableUsers as $key => $u) {
             if ($u->getId() == $applicationUser->getId()) {
                 unset($availableUsers[$key]);
             }
         }
     }
     // remove the existing client users
     foreach ($loanUsers as $loanUser) {
         foreach ($availableUsers as $key => $siteUser) {
             if ($siteUser->getId() == $loanUser->getId()) {
                 unset($availableUsers[$key]);
             }
         }
     }
     $userForm = $this->createFormBuilder()->add('additional_user_email', 'text', array('label' => 'Invite an additional person to follow the status of this loan', 'required' => true, 'attr' => array('placeholder' => 'Email'), 'constraints' => array(new NotBlank(), new \Symfony\Component\Validator\Constraints\Email())))->getForm();
     $documentChecklist = $site->getSettings()->getLoanDocumentVocab();
     $message = new Message();
     $messageForm = $this->createForm(new MessageType(), $message);
     if ($request->getMethod() == 'POST') {
         $formName = $request->query->get('form');
         $emailUtil = $this->get('sudoux.cms.message.email_util');
         switch ($formName) {
             case 'loan':
                 $loanForm->bindRequest($request);
                 if ($loanForm->isValid()) {
                     $email = new Email();
                     $email->setSubject("Your loan application status has been updated.");
                     $email->setMessage(sprintf('Your loan has been updated to %s. Please <a href="%s">click here</a> to view.', $application->getStatusName(), $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId()), true)));
                     $email->setRecipient($application->getBorrower()->getEmail());
                     $email->setRecipientName($application->getBorrower()->getFullName());
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $em->persist($application);
                     $em->flush();
                     $session->getFlashBag()->add('success', 'Your loan has been updated.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId())));
                 }
                 break;
             case 'document':
                 $documentForm->bindRequest($request);
                 if ($documentForm->isValid()) {
                     $documentData = $documentForm['file_field']->getData();
                     $file = new File();
                     $file->setName($documentForm['name']->getData());
                     $file->setUser($user);
                     $file->setSite($site);
                     $file->setFile($documentData);
                     $file->setPublic(false);
                     $document->setFile($file);
                     $document->setStatus(3);
                     // accepted
                     $em->persist($document);
                     $email = new Email();
                     $email->setSubject("A new document has been added to your loan application.");
                     $email->setMessage(sprintf('A new document has been added to your loan application. Please <a href="%s">click here</a> to view.', $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId()), true)));
                     $email->setRecipient($application->getBorrower()->getEmail());
                     $email->setRecipientName($application->getBorrower()->getFullName());
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $application->addDocument($document);
                     $em->persist($application);
                     $em->flush();
                     // queue the document
                     $job = new Job('sudoux:mortgage:loan', array('add_document', sprintf('--loan_id=%s', $application->getId()), sprintf('--document_id=%s', $document->getId()), '--env=' . $this->get('kernel')->getEnvironment(), '--no-debug'), true, 'loan_process_queue');
                     $em->persist($job);
                     $em->flush();
                     $session->getFlashBag()->add('success', 'The document has been added successfully.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId())));
                 }
                 break;
             case 'message':
                 $messageForm->bindRequest($request);
                 if ($messageForm->isValid()) {
                     $thread = $application->getMessageThread();
                     if (!isset($thread)) {
                         $thread = new Thread();
                         $thread->setSubject(sprintf("Loan Application #%s Message Thread", $application->getId()));
                         $application->setMessageThread($thread);
                     }
                     $message->setThread($thread);
                     $message->setUser($user);
                     $email = new Email();
                     $email->setSubject("You have a new message about your loan application.");
                     $email->setMessage(sprintf('You have a new message about your loan application. Please <a href="%s">click here</a> to view.', $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId(), 'tab' => 'messages'), true)));
                     $email->setRecipient($application->getBorrower()->getEmail());
                     $email->setRecipientName($application->getBorrower()->getFullName());
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $em->persist($application);
                     $em->persist($message);
                     $em->flush();
                     $session->getFlashBag()->add('success', 'Your message was sent successfully.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $id, 'tab' => 'messages')));
                 }
                 break;
             case 'user':
                 $userForm->bindRequest($request);
                 if ($userForm->isValid()) {
                     $resetPasswordUrl = null;
                     $additionalUserEmail = $userForm['additional_user_email']->getData();
                     $additionalUser = $em->getRepository('SudouxCmsUserBundle:User')->findOneBy(array('email' => $additionalUserEmail));
                     if (isset($additionalUser)) {
                         $message = sprintf('You have been invited to view a loan application for %s. Please <a href="%s">click here</a> to login and view the application.', $application->getBorrower()->getFullName(), $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId()), true));
                     } else {
                         $additionalUser = new User();
                         $additionalUser->setUsername($additionalUserEmail);
                         $factory = $this->get('security.encoder_factory');
                         $encoder = $factory->getEncoder($additionalUser);
                         $password = $encoder->encodePassword($additionalUser->generatePassword(), $additionalUser->getSalt());
                         $additionalUser->setPassword($password);
                         $additionalUser->setEmail($additionalUserEmail);
                         $additionalUser->addSite($site);
                         $memberRole = $em->getRepository('SudouxCmsUserBundle:Role')->findOneBy(array('role' => 'ROLE_MEMBER'));
                         $additionalUser->addRole($memberRole);
                         $additionalUser->addToken();
                         $additionalUser->setTimezone($site->getTimezone());
                         $resetPasswordUrl = $this->generateUrl('sudoux_cms_user_reset_password', array('token' => $additionalUser->getToken()), true);
                         $message = sprintf('You have been invited to view a loan application for %s. Please <a href="%s">click here</a> to complete your registration.', $application->getBorrower()->getFullName(), $resetPasswordUrl);
                         $em->persist($additionalUser);
                     }
                     $application->addClientUser($additionalUser);
                     $em->persist($application);
                     // add to audit log
                     $auditLog = new AuditLog();
                     $auditLog->setObject('Loan Application');
                     $auditLog->setAction(sprintf('%s has been added to loan application #%s', $additionalUserEmail, $application->getId()));
                     $auditLog->setUser($user);
                     $auditLog->setSite($site);
                     $em->persist($auditLog);
                     $em->flush();
                     // notify the user
                     $email = new Email();
                     $email->setRecipient($additionalUserEmail);
                     $email->setRecipientName($additionalUserEmail);
                     $email->setSubject($this->get('sudoux.cms.site')->getSiteVar('You have been invited to view a loan application', 'loan_application_invite_user_email_subject'));
                     $email->setUser($user);
                     $email->setSite($site);
                     $tokens = array('email' => $additionalUserEmail, 'reset_password_url' => $resetPasswordUrl);
                     $message = $this->get('sudoux.cms.site')->getSiteVar($message, 'loan_application_invite_user_email_message', $tokens);
                     $email->setMessage($message);
                     $this->get('sudoux.cms.message.email_util')->logAndSend($email);
                     $session->getFlashBag()->add('success', 'An additional user has been added to your application.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId(), 'tab' => 'users')));
                 }
                 break;
         }
     }
     return $this->render('SudouxMortgageBundle:LoanApplicationAdmin:member.html.twig', array('loanApp' => $application, 'documentChecklist' => $documentChecklist, 'documentForm' => $documentForm->createView(), 'messageForm' => $messageForm->createView(), 'loanForm' => $loanForm->createView(), 'userForm' => $userForm->createView()));
 }
 /**
  * @param \Sudoux\Cms\UserBundle\Entity\User $user
  * @return bool
  * @author Eric Haynes
  */
 public function isClientUser(User $user)
 {
     $isClientUser = false;
     if (isset($this->client_user)) {
         if ($this->client_user->count() > 0) {
             foreach ($this->client_user as $clientUser) {
                 if ($clientUser->getId() == $user->getId()) {
                     $isClientUser = true;
                     break;
                 }
             }
         }
     }
     return $isClientUser;
 }
 /**
  *
  */
 public function loanAccountRegistrationAction(Request $request, $guid)
 {
     $securityContext = $this->container->get('security.context');
     $user = $securityContext->getToken()->getUser();
     $site = $this->get('sudoux.cms.site')->getSite();
     $em = $this->getDoctrine()->getEntityManager();
     $application = $em->getRepository('SudouxMortgageBundle:LoanApplication')->findOneBySiteAndGuid($site, $guid);
     if (!isset($application)) {
         throw $this->createNotFoundException($this::LOAN_NOT_FOUND_MESSAGE);
     }
     $showForm = true;
     $appUser = $application->getUser();
     if (isset($appUser)) {
         if ($appUser->hasRole('ROLE_MEMBER')) {
             // a user is already assigned
             $showForm = false;
         }
     }
     $user = new User();
     $user->setAlert(true);
     $user->setTimezone($site->getTimezone());
     // set the borrower info
     $user->setFirstName($application->getBorrower()->getFirstName());
     $user->setLastName($application->getBorrower()->getLastName());
     $user->setEmail($application->getBorrower()->getEmail());
     $user->setHomePhone($application->getBorrower()->getPhoneHome());
     $user->setCellPhone($application->getBorrower()->getPhoneMobile());
     $form = $this->createForm(new MemberType($site), $user);
     if ($request->getMethod() == 'POST') {
         $form->bindRequest($request);
         $this->container->get('validator');
         // make sure ssn for borrower and user match
         if (preg_replace("/[^0-9]/", "", $form['ssn']->getData()) != preg_replace("/[^0-9]/", "", $application->getBorrower()->getSsn())) {
             $form['ssn']->addError(new FormError('Your ssn does not match the borrower ssn that is on this loan.'));
         }
         if ($form->isValid()) {
             $em = $this->getDoctrine()->getEntityManager();
             $factory = $this->get('security.encoder_factory');
             $encoder = $factory->getEncoder($user);
             $password = $encoder->encodePassword($form['plain_password']->getData(), $user->getSalt());
             $user->setPassword($password);
             $user->setActive(true);
             $user->addSite($site);
             $memberRole = $em->getRepository('SudouxCmsUserBundle:Role')->findOneBy(array('role' => 'ROLE_MEMBER'));
             $user->addRole($memberRole);
             $em->persist($user);
             $application->setUser($user);
             $em->persist($application);
             $em->flush();
             $request->getSession()->getFlashBag()->add('success', 'Your account has been created. Please login to view your loan.');
             return $this->redirect($this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId())));
         }
     }
     return $this->render('SudouxMortgageBundle:LoanApplicationFront:loanAccountRegistration.html.twig', array('loanApp' => $application, 'form' => $form->createView(), 'showForm' => $showForm));
 }
 /**
  * @param \Sudoux\Cms\UserBundle\Entity\User $user
  * @return string
  * @author Eric Haynes
  */
 public function getLoanUserRoleType(User $user)
 {
     $roleType = 'Website Admin';
     if ($this->isClientUser($user)) {
         $roleType = 'Additional User';
     } elseif (isset($this->user)) {
         if ($user->getId() == $this->user->getId()) {
             if ($user->hasRole('ROLE_LOAN_OFFICER')) {
                 $roleType = 'Loan Officer';
             } else {
                 $roleType = 'Applicant';
             }
         }
     }
     return $roleType;
 }
 /**
  * @param Site $site
  * @param User $user
  * @return array
  */
 public function findNewMessagesCountByUserQuery(Site $site, User $user)
 {
     $q = $this->createQueryBuilder('l')->select('count(t.id) as messages')->join('l.message_thread', 't')->join('t.message', 'm')->where('l.site = :site')->andWhere('m.user != :user_id')->andWhere('l.user = :user_id')->andWhere('l.deleted = 0')->andWhere('m.status = 0')->setParameter('user_id', $user->getId())->setParameter('site', $site->getId());
     //echo $q->getDQL(); exit;
     return $q->getQuery()->getScalarResult();
 }