src/Controller/UserController.php line 69

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\App;
  4. use App\Entity\AgencyDocument;
  5. use App\Entity\ApplicationInfo;
  6. use App\Entity\Agency;
  7. use App\Entity\Badge;
  8. use App\Entity\RentalRecord;
  9. use App\Entity\RentalRecordFile;
  10. use App\Entity\UserApplication;
  11. use App\Entity\User;
  12. use App\Entity\DiscountCoupon;
  13. use App\Form\AgencyDocumentForm;
  14. use App\Form\AgencyType;
  15. use App\Form\ApplicationEditForm;
  16. use App\Form\ApplicationForm;
  17. use App\Form\ApplicationProfilForm;
  18. use App\Form\UserApplicationForm;
  19. use App\Form\GuarantorApplicationForm;
  20. use App\Form\UserDocumentApplicationForm;
  21. use App\Form\BadgeForm;
  22. use App\Form\PasswordChangeForm;
  23. use App\Form\PasswordResetForm;
  24. use App\Form\UserProfileForm;
  25. use App\Form\UserRegistrationForm;
  26. use App\Security\LoginFormAuthenticator;
  27. use App\Service\FileUploader;
  28. use App\Service\DfcService;
  29. use App\Service\MailSender;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  32. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  33. use Symfony\Component\Form\FormError;
  34. use Symfony\Component\HttpFoundation\File\File;
  35. use Symfony\Component\HttpFoundation\JsonResponse;
  36. use Symfony\Component\HttpFoundation\File\UploadedFile;
  37. use Symfony\Component\HttpFoundation\Request;
  38. use Symfony\Component\HttpFoundation\Response;
  39. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  40. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  41. class UserController extends AbstractController
  42. {
  43.     private $authenticationUtils;
  44.     /**
  45.      * @var MailSender
  46.      */
  47.     private $mailSender;
  48.     public function __construct(MailSender $mailSender,AuthenticationUtils $authenticationUtils)
  49.     {
  50.         $this->mailSender $mailSender;
  51.         $this->authenticationUtils $authenticationUtils;
  52.     }
  53.     /**
  54.      * @Route("/register", name="user_register")
  55.      */
  56.     public function registerAction(Request $request)
  57.     {
  58.         if ($this->getUser() instanceof User) {
  59.             return $this->redirectToRoute('homepage');
  60.         }
  61.         $em $this->getDoctrine()->getManager();
  62.         $user = new User();
  63.         $form $this->createForm(UserRegistrationForm::class, $user);
  64.         
  65.         $form->handleRequest($request);
  66.         if ($form->isSubmitted() && $form->isValid()) {
  67.             $account $form->getData();
  68.             $account->setRoles(['ROLE_USER']);
  69.             $is_pro $request->request->get('is_pro');
  70.             if(isset($is_pro) && $request->request->get('is_pro') == 'on'){
  71.                 $account->setRoles(['ROLE_PRO']);
  72.             }
  73.             $account->setCreatedAt(new \DateTime());
  74.             $account->setUsername('');
  75.             $ip $request->getClientIp();
  76.             $account->setIpAddress($ip);
  77.             $token rtrim(strtr(base64_encode(random_bytes(32)), '+/''-_'), '=');
  78.             $account->setValidationToken($token);
  79.             $account->setStatus(User::STATUS_INACTIVE);
  80.             $em->persist($account);
  81.             $em->flush();
  82.             $this->mailSender->sendActivationCode($account); 
  83.             $this->addFlash('report'"Vous allez recevoir un e-mail de confirmation à l'adresse que vous avez saisie!");
  84.             return $this->redirectToRoute('homepage');
  85.         }
  86.         return $this->render('user/register.html.twig', [
  87.             'form' => $form->createView(),
  88.             '_target_path' => $request->get('_target_path')
  89.         ]);
  90.     }
  91.     /**
  92.      * Complete profil
  93.      * @return Response
  94.      * @Route("/complete/profil", name="complete_profil")
  95.      */
  96.     public function completeProfilAction(Request $request)
  97.     {
  98.         $em $this->getDoctrine()->getManager();
  99.         $user $this->getUser();
  100.         if (in_array('ROLE_PRO'$user->getRoles()) && $user->getAgency() != null) {
  101.             return $this->redirectToRoute('homepage');
  102.         }
  103.         $agencyForm $this->createForm(AgencyType::class, $user->getAgency());
  104.         $agencyForm->handleRequest($request);
  105.         if ($agencyForm->isSubmitted() && $agencyForm->isValid()) {
  106.             if (in_array('ROLE_PRO',$user->getRoles()) ) {
  107.                 $agencyData $request->get('agency');
  108.                 $agency $user->getAgency() == null ? new Agency() : $user->getAgency();
  109.                 $agency->setName($agencyData['name']);
  110.                 $agency->setAddress($agencyData['address']);
  111.                 $agency->setSiren($agencyData['siren']);
  112.                 $agency->setWebsite($agencyData['website']);
  113.                 $agency->setPhone($agencyData['phone']);
  114.                 $agency->setCertified(false);
  115.                 $agency->setStatus(1);
  116.                 if($agency->getId()==null){
  117.                     $em->persist($agency);
  118.                 }
  119.                 $em->flush();
  120.                 $user->setFirstname($agencyData['firstname']);
  121.                 $user->setLastname($agencyData['lastname']);
  122.                 $this->createUsername($user);
  123.                 $user->setAgency($agency);
  124.                 $em->flush();
  125.                 $message '<p>Félicitation! Votre compte est activé!</p>';
  126.                 $this->addFlash('success'$message);
  127.             }else{
  128.                 $message '<p>Vous n’êtes pas inscrite en tant qu’agence!</p>';
  129.                 $this->addFlash('error'$message);
  130.             }
  131.             return $this->redirectToRoute('homepage');
  132.         }
  133.         return $this->render('user/complete_profil.html.twig',[
  134.             'form' => $agencyForm->createView()
  135.         ]);
  136.     }
  137.     /**
  138.      * Get profile
  139.      * @param Get dfc profile
  140.      * @param Request $request
  141.      * @return Response
  142.      * @Route("/get_dfc_profile", name="get_dfc_profile")
  143.      */
  144.     public function getDFCProfile(Request $request,DfcService $dfc)
  145.     {
  146.         if ($request->isMethod(Request::METHOD_GET)) {
  147.             $tenantId $request->get('tenant_id');
  148.             if(isset($tenantId)){
  149.                 try{
  150.                     $em $this->getDoctrine()->getManager();
  151.                     $application $em->getRepository('App\Entity\ApplicationInfo')->findOneBy(['tenantId' => $tenantId]);
  152.                     if($application!=null){
  153.                         return new JsonResponse(['error' => false,"response" => $dfc->getProfile($application,$em)]);
  154.                     }
  155.                 }
  156.                 catch (\Exception $ex){
  157.                     return new JsonResponse(['error' => true,'message'=>$ex->getMessage()]);
  158.                 }
  159.             }
  160.         }
  161.         return new JsonResponse(['error' => true,'message'=>"Requête invalide!"]);
  162.     }
  163.     /**
  164.      * Publish new review
  165.      * @return Response
  166.      * @Route("/search_action", name="search_action")
  167.      */
  168.     public function searchAction()
  169.     {
  170.         return $this->render('user/search_form.html.twig',[]);
  171.     }
  172.     /**
  173.      * @Route("/activate-account/{token}", name="activate_account")
  174.      */
  175.     public function activateAccountAction($token,Request $request)
  176.     {
  177.         $em $this->getDoctrine()->getManager();
  178.         $user $em->getRepository('App\Entity\User')
  179.             ->findOneBy(['validationToken' => $token]);
  180.         if ($user === null) {
  181.             throw new NotFoundHttpException('Le lien que vous avez suivi n\'existe pas ou a expiré');
  182.         }
  183.         if (in_array('ROLE_PRO',$user->getRoles()) ) {
  184.             $user->setStatus(User::STATUS_ACTIVE);
  185.         }
  186.         $user->setValidationToken(null);
  187.         $em->flush();
  188.         $this->mailSender->sendWelcomeUser($user);
  189.         $message '<p class="text-center">Bienvenue sur Emotiqhome</p><br>';
  190.         $message $message "Votre compte est activé !"."<br>";
  191.         $message $message "Pour  pouvoir accéder à toutes les fonctionnalités compléter votre profil en moins d'une minute !"."<br>";
  192.         $this->addFlash('report'$message);
  193.         $reviews $em->getRepository('App\Entity\Review')->findAll(['user' => $user]);
  194.         foreach ($reviews as $review) {
  195.             $review->setStatus(1);
  196.         }
  197.         $em->flush();
  198.         return $this->get('security.authentication.guard_handler')
  199.                 ->authenticateUserAndHandleSuccess(
  200.                     $user,
  201.                     $request,
  202.                     $this->get(LoginFormAuthenticator::class),
  203.                     'main'
  204.         );
  205.     }
  206.     /**
  207.      * @Route("/nonactivate-account", name="nonactivate_account")
  208.      */
  209.     public function nonActivateAccountAction()
  210.     {
  211.         $message '<h1 class="text-center"><b>Finalisez votre inscription</b>'."</h1><br>";
  212.         $message $message "Pour finaliser votre inscription, rendez-vous dans votre boîte e-mail pour activer votre compte.!"."<br>";
  213.         $this->addFlash('report'$message);
  214.         return $this->redirectToRoute('security_logout');
  215.     }
  216.     /**
  217.      * @Route("/account/valid", name="valid_account")
  218.      */
  219.     public function validateAccountAction()
  220.     {
  221.         $em $this->getDoctrine()->getManager();
  222.         $user $this->getUser();
  223.         if (in_array('ROLE_PRO',$user->getRoles()) ) {
  224.             if ($user->getAgency() == null) {
  225.                 $this->addFlash('error'"Compléter votre profil pour accéder à toutes les fonctionnalités du site!");
  226.                 return $this->redirectToRoute('complete_profil');
  227.             }
  228.             return $this->redirectToRoute('homepage');
  229.         }
  230.         if($user->getStatus()!= User::STATUS_ACTIVE && $user->getValidationToken()==null){
  231.             $user->setStatus(User::STATUS_ACTIVE);
  232.             $em->flush();
  233.             return $this->render('user/account_actions.html.twig',[]);
  234.         }else{
  235.            return $this->redirectToRoute('homepage');
  236.         }
  237.     }
  238.     /**
  239.      * Search logement
  240.      * @return Response
  241.      * @Route("/account/search", name="search_form")
  242.      */
  243.     public function searchFormAction()
  244.     {
  245.         return $this->render('user/search_form.html.twig',[]);
  246.     }
  247.     private function createUsername(User $user){
  248.         $em $this->getDoctrine();
  249.         $firstname explode' ',trim($user->getFirstname()));
  250.         $lastname =  explode' ',trim($user->getLastname()));
  251.         $firstname $firstname[0];
  252.         $lastname $lastname[0];
  253.         $username strtolower$firstname '.' $lastname );
  254.         $list $em->getEntityManager()->getRepositoryUser::class )->findBy(['username'=>$username]);
  255.         $length sizeof($list);
  256.         if($length>0){
  257.             $username $username.".";
  258.             $list $em->getEntityManager()->getRepositoryUser::class )->getUserByUsername($username);
  259.             $length sizeof($list);
  260.             if($length == 0){
  261.                 $username $username."1";
  262.             }else{
  263.                 $username $username.($length+1);
  264.             }
  265.             
  266.         }
  267.         $user->setUsername($username);
  268.         
  269.     }
  270.     /**
  271.      * Remove dfc account
  272.      * @param Remove dfc account
  273.      * @param Request $request
  274.      * @return Response
  275.      * @Route("/remove_dfc_account", name="remove_dfc_account")
  276.      */
  277.     public function removeDFCAccount(Request $request,DfcService $dfc)
  278.     {
  279.         if ($request->isMethod(Request::METHOD_POST)) {
  280.             $user $this->getUser();
  281.             if($user->getApplication()!=null && $user->getApplication()->getCandidateApplication()!=null){
  282.                 try{
  283.                     $em $this->getDoctrine()->getManager();
  284.                     $dfc->removeDFCAccount($user->getApplication()->getCandidateApplication());
  285.                     $rentalRecords $em->getRepository('App\Entity\RentalRecord')->getUserAdvertRental($user->getId());
  286.                     foreach ($rentalRecords as $record){
  287.                         $record->setStatus(RentalRecord::STATUS_REMOVED);
  288.                         $record->setDocumentLink("");
  289.                         $em->flush();
  290.                     }
  291.                     $application $em->getRepository('App\Entity\UserApplication')->findOneBy(["user"=>$user->getId()]);
  292.                     $em->remove($application);
  293.                     $em->flush();
  294.                     return new JsonResponse(['error' => false]);
  295.                 }
  296.                 catch (\Exception $ex){
  297.                     return new JsonResponse(['error' => true,'message'=>$ex->getMessage()]);
  298.                 }
  299.             }
  300.         }
  301.         return new JsonResponse(['error' => true,'message'=>"Requête invalide!"]);
  302.     }
  303.     /**
  304.      * User Account
  305.      * @param Request $request
  306.      * @param FileUploader $uploader
  307.      * @return Response
  308.      * @Route("/account", name="user_account")
  309.      */
  310.     public function showUserAction(Request $request,FileUploader $uploader,DfcService $dfc)
  311.     {    
  312.         $em $this->getDoctrine()->getManager();
  313.         $tab in_array($request->query->get('tab'), ['profile''advertisements''searches','favoris','reviews','applicationList','renterProfil','documentsInfo','guarantorInfo']) ? $request->query->get('tab') : 'profile';
  314.         $user $this->getUser();
  315.         if (in_array('ROLE_PRO'$user->getRoles()) && $user->getAgency() == null) {
  316.             $this->addFlash('error'"Compléter votre profil pour accéder à toutes les fonctionnalités du site!");
  317.             return $this->redirectToRoute('complete_profil');
  318.         }
  319.         $advertisements $user->getAdvertisements();
  320.         $searches $user->getSearches();
  321.         $bookmarks $user->getBookmarks();
  322.         $reviews $em->getRepository('App\Entity\Review')->findActiveReview($user->getId());
  323.         $userCoupons $em->getRepository('App\Entity\DiscountCoupon')->findActiveCoupon($user->getId());
  324.         $form $this->createForm(UserProfileForm::class, $user);
  325.         $application_form =  $this->createForm(ApplicationEditForm::class, $user->getApplication()!=null $user->getApplication()->getCandidateApplication(): new ApplicationInfo()) ;
  326.         $formBadgeUpload null;
  327.         if(!$user->hasBadge()){
  328.             $formBadgeUpload $this->createForm(BadgeForm::class, new Badge());
  329.             $formBadgeUpload->handleRequest($request);
  330.             if ($formBadgeUpload->isSubmitted() && $formBadgeUpload->isValid()) {
  331.                 $tab 'profile';
  332.                 $dataSubmited $formBadgeUpload->getData();
  333.                 $code $dataSubmited->getCode();
  334.                 $badge $em->getRepository('App\Entity\Badge')->findOneBy(['code'=>$code]);
  335.                 if($badge !=null){
  336.                     if($badge->getUserTenant()!=null){
  337.                         $this->addFlash('error''Ce code a déjà été attribué à un autre locataire');
  338.                     }else{
  339.                         $badge->setUserTenant($user);
  340.                         $em->flush();
  341.                         $this->addFlash('success''Félicitation! Vous avez obtenu votre badge bon locataire!');
  342.                     }
  343.                 }else{
  344.                     $this->addFlash('error''Ce code n\'existe pas');
  345.                 }
  346.             }
  347.         }
  348.     
  349.         $form->handleRequest($request);
  350.         $application_form->handleRequest($request);
  351.         if ($form->isSubmitted() && $form->isValid()) {
  352.             $tab 'profile';
  353.             $current_user $form->getData();
  354.             if($current_user->getUsername()==''){
  355.                 $this->createUsername($current_user);
  356.             }
  357.             $em->persist($current_user);
  358.             $em->flush();
  359.             $this->addFlash('success''Votre profil a bien été mis à jour.');
  360.         }
  361.         if ($application_form->isSubmitted() && $application_form->isValid()) {
  362.             $tab 'renterProfil';
  363.             $uploaded_application $application_form->getData();
  364.             $application $em->getRepository('App\Entity\ApplicationInfo')->find($uploaded_application->getId());
  365.             if($application->getStatus()!=ApplicationInfo::STATUS_VALIDATED){
  366.                 //document Pièce d'identité
  367.                 $identityDocument $application_form['identityDoc']->getData();
  368.                 if ($identityDocument!=null && $application->getIdentityDocument()->getStatus()!=ApplicationInfo::STATUS_VALIDATED) {
  369.                     $fileName $uploader->uploadFile($identityDocument);
  370.                     $application->setIdentityDoc(null);
  371.                     $file = new RentalRecordFile();
  372.                     $file->setPath($fileName);
  373.                     $file->setName($identityDocument->getClientOriginalName());
  374.                     $file->setSize($identityDocument->getClientSize());
  375.                     $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  376.                     $file->setDfcId($application->getIdentityDocument()->GetDfcId());
  377.                     $em->persist($file);
  378.                     $em->flush();
  379.                     $application->setIdentityDocument($file);
  380.                     $application->setIdentityDocumentType($uploaded_application->getIdentityDocumentType());
  381.                 }
  382.                 //document situation d'hebergement
  383.                 $addressProofDocument $application_form['addressDoc']->getData();
  384.                 if ($addressProofDocument && $addressProofDocument instanceof UploadedFile && $application->getAddressProofDocument()->getStatus()!=ApplicationInfo::STATUS_VALIDATED) {
  385.                     $fileName $uploader->uploadFile($addressProofDocument);
  386.                     $application->setAddressDoc(null);
  387.                     $file = new RentalRecordFile();
  388.                     $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  389.                     $file->setPath($fileName);
  390.                     $file->setName($addressProofDocument->getClientOriginalName());
  391.                     $file->setSize($addressProofDocument->getClientSize());
  392.                     $file->setDfcId($application->getAddressProofDocument()->GetDfcId());
  393.                     $em->persist($file);
  394.                     $em->flush();
  395.                     $application->setAddressProofDocument($file);
  396.                     $application->setAddressProofDocumentType($uploaded_application->getAddressProofDocumentType());
  397.                 }
  398.                 //document situation professionnel
  399.                 $situationProfessionalProofDocument $application_form['situationProfessionalDoc']->getData();
  400.                 if ($situationProfessionalProofDocument && $situationProfessionalProofDocument instanceof UploadedFile && $application->getSituationProfessionalProofDocument()->getStatus()!=ApplicationInfo::STATUS_VALIDATED) {
  401.                     $fileName $uploader->uploadFile($situationProfessionalProofDocument);
  402.                     $application->setSituationProfessionalDoc(null);
  403.                     $file = new RentalRecordFile();
  404.                     $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  405.                     $file->setPath($fileName);
  406.                     $file->setName($situationProfessionalProofDocument->getClientOriginalName());
  407.                     $file->setSize($situationProfessionalProofDocument->getClientSize());
  408.                     $file->setDfcId($application->getSituationProfessionalProofDocument()->GetDfcId());
  409.                     $em->persist($file);
  410.                     $em->flush();
  411.                     $application->setSituationProfessionalProofDocument($file);
  412.                     $application->setSituationProfessional($uploaded_application->getSituationProfessional());
  413.                 }
  414.                 //document justificatif de ressource
  415.                 $ressourceProofDocument $application_form['ressourceDoc']->getData();
  416.                 if ($ressourceProofDocument && $ressourceProofDocument instanceof UploadedFile && $application->getRessourceProofDocument()->getStatus()!=ApplicationInfo::STATUS_VALIDATED) {
  417.                     $fileName $uploader->uploadFile($ressourceProofDocument);
  418.                     $application->setRessourceDoc(null);
  419.                     $file = new RentalRecordFile();
  420.                     $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  421.                     $file->setPath($fileName);
  422.                     $file->setName($ressourceProofDocument->getClientOriginalName());
  423.                     $file->setSize($ressourceProofDocument->getClientSize());
  424.                     $file->setDfcId($application->getRessourceProofDocument()->GetDfcId());
  425.                     $em->persist($file);
  426.                     $em->flush();
  427.                     $application->setRessourceProofDocument($file);
  428.                     $application->setRessourceProofDocumentType($uploaded_application->getRessourceProofDocumentType());
  429.                 }
  430.                 //document avis d'imposition
  431.                 $taxNoticeProofDocument $application_form['taxNoticeDoc']->getData();
  432.                 if ($taxNoticeProofDocument && $taxNoticeProofDocument instanceof UploadedFile && $application->getTaxNoticeProofDocument()->getStatus()!=ApplicationInfo::STATUS_VALIDATED) {
  433.                     $fileName $uploader->uploadFile($taxNoticeProofDocument);
  434.                     $application->setTaxNoticeDoc(null);
  435.                     $file = new RentalRecordFile();
  436.                     $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  437.                     $file->setPath($fileName);
  438.                     $file->setName($taxNoticeProofDocument->getClientOriginalName());
  439.                     $file->setSize($taxNoticeProofDocument->getClientSize());
  440.                     $file->setDfcId($application->getTaxNoticeProofDocument()->GetDfcId());
  441.                     $em->persist($file);
  442.                     $em->flush();
  443.                     $application->setTaxNoticeProofDocument($file);
  444.                 }
  445.                 if($request->request->get('application_edit_form')['haveGuarantor'] == true){
  446.                     $application->setHaveGuarantor(true);
  447.                     //document Pièce d'identité garant
  448.                     $identityDocumentGuarantor $application_form['identityDocGuarantor']->getData();
  449.                     if ($identityDocumentGuarantor !=null && $identityDocumentGuarantor instanceof UploadedFile) {
  450.                         $fileName $uploader->uploadFile($identityDocumentGuarantor);
  451.                         $application->setIdentityDocGuarantor(null);
  452.                         $file = new RentalRecordFile();
  453.                         $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  454.                         $file->setPath($fileName);
  455.                         $file->setName($identityDocumentGuarantor->getClientOriginalName());
  456.                         $file->setSize($identityDocumentGuarantor->getClientSize());
  457.                         if($application->getIdentityDocumentGuarantor()!=null){
  458.                             $file->setDfcId($application->getIdentityDocumentGuarantor()->GetDfcId());
  459.                         }
  460.                         $em->persist($file);
  461.                         $em->flush();
  462.                         $application->setIdentityDocumentGuarantor($file);
  463.                     }
  464.                     //document situation d'hebergement garant
  465.                     $addressProofDocumentGuarantor $application_form['addressDocGuarantor']->getData();
  466.                     if ($addressProofDocumentGuarantor && $addressProofDocumentGuarantor instanceof UploadedFile) {
  467.                         $fileName $uploader->uploadFile($addressProofDocumentGuarantor);
  468.                         $application->setAddressDocGuarantor(null);
  469.                         $file = new RentalRecordFile();
  470.                         $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  471.                         $file->setPath($fileName);
  472.                         $file->setName($addressProofDocumentGuarantor->getClientOriginalName());
  473.                         $file->setSize($addressProofDocumentGuarantor->getClientSize());
  474.                         if($application->getAddressProofDocumentGuarantor()!=null){
  475.                             $file->setDfcId($application->getAddressProofDocumentGuarantor()->GetDfcId());
  476.                         }
  477.                         $em->persist($file);
  478.                         $em->flush();
  479.                         $application->setAddressProofDocumentGuarantor($file);
  480.                     }
  481.                     //document situation professionnel garant
  482.                     $situationProfessionalProofDocumentGuarantor $application_form['situationProfessionalDocGuarantor']->getData();
  483.                     if ($situationProfessionalProofDocumentGuarantor && $situationProfessionalProofDocumentGuarantor instanceof UploadedFile) {
  484.                         $fileName $uploader->uploadFile($situationProfessionalProofDocumentGuarantor);
  485.                         $application->setSituationProfessionalDocGuarantor(null);
  486.                         $file = new RentalRecordFile();
  487.                         $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  488.                         $file->setPath($fileName);
  489.                         $file->setName($situationProfessionalProofDocumentGuarantor->getClientOriginalName());
  490.                         $file->setSize($situationProfessionalProofDocumentGuarantor->getClientSize());
  491.                         if($application->getSituationProfessionalProofDocumentGuarantor()!=null){
  492.                             $file->setDfcId($application->getSituationProfessionalProofDocumentGuarantor()->GetDfcId());
  493.                         }
  494.                         $em->persist($file);
  495.                         $em->flush();
  496.                         $application->setSituationProfessionalProofDocumentGuarantor($file);
  497.                     }
  498.                     //document justificatif de ressource garant
  499.                     $ressourceProofDocumentGuarantor $application_form['ressourceDocGuarantor']->getData();
  500.                     if ($ressourceProofDocumentGuarantor && $ressourceProofDocumentGuarantor instanceof UploadedFile) {
  501.                         $fileName $uploader->uploadFile($ressourceProofDocumentGuarantor);
  502.                         $application->setRessourceDocGuarantor(null);
  503.                         $file = new RentalRecordFile();
  504.                         $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  505.                         $file->setPath($fileName);
  506.                         $file->setName($ressourceProofDocumentGuarantor->getClientOriginalName());
  507.                         $file->setSize($ressourceProofDocumentGuarantor->getClientSize());
  508.                         if($application->getRessourceProofDocumentGuarantor()!=null){
  509.                             $file->setDfcId($application->getRessourceProofDocumentGuarantor()->GetDfcId());
  510.                         }
  511.                         $em->persist($file);
  512.                         $em->flush();
  513.                         $application->setRessourceProofDocumentGuarantor($file);
  514.                     }
  515.                     //document avis d'imposition garant
  516.                     $taxNoticeProofDocumentGuarantor $application_form['taxNoticeDocGuarantor']->getData();
  517.                     if ($taxNoticeProofDocumentGuarantor && $taxNoticeProofDocumentGuarantor instanceof UploadedFile) {
  518.                         $fileName $uploader->uploadFile($taxNoticeProofDocumentGuarantor);
  519.                         $application->setTaxNoticeDocGuarantor(null);
  520.                         $file = new RentalRecordFile();
  521.                         $file->setStatus(RentalRecordFile::STATUS_NOT_UPLOADED);
  522.                         $file->setPath($fileName);
  523.                         $file->setName($taxNoticeProofDocumentGuarantor->getClientOriginalName());
  524.                         $file->setSize($taxNoticeProofDocumentGuarantor->getClientSize());
  525.                         if($application->getTaxNoticeProofDocumentGuarantor()!=null){
  526.                             $file->setDfcId($application->getTaxNoticeProofDocumentGuarantor()->GetDfcId());
  527.                         }
  528.                         $em->persist($file);
  529.                         $em->flush();
  530.                         $application->setTaxNoticeProofDocumentGuarantor($file);
  531.                     }
  532.                     $application->setSituationProfessionalGuarantor($uploaded_application->getSituationProfessionalGuarantor());
  533.                     $application->setIdentityDocumentGuarantorType($uploaded_application->getIdentityDocumentGuarantorType());
  534.                     $application->setAddressProofDocumentGuarantorType($uploaded_application->getAddressProofDocumentGuarantorType());
  535.                     $application->setRessourceProofDocumentGuarantorType($uploaded_application->getRessourceProofDocumentGuarantorType());
  536.                     $application->setMontantRessourceGuarantor($uploaded_application->getMontantRessourceGuarantor());
  537.                     $application->setHaveGuarantor(true);
  538.                 }else{
  539.                     //remove guarantor and document
  540.                     $application->setMontantRessourceGuarantor('0');
  541.                     $application->setHaveGuarantor(false);
  542.                 }
  543.                 $em->flush();
  544.                 $dfc->updateDFCAccount($application,$em);
  545.             }
  546.         }
  547.         return $this->render('user/account.html.twig', [
  548.             'form' => $form->createView(),
  549.             'application_form' => $application_form->createView(),
  550.             'advertisements' => $advertisements,
  551.             'searches' => $searches,
  552.             'user' => $user,
  553.             'bookmarks' => $bookmarks,
  554.             'reviews' => $reviews,
  555.             'userCoupons' => $userCoupons,
  556.             'rentalRecords' => $user->getRentalRecords(),
  557.             'badgeForm' => $formBadgeUpload!=null $formBadgeUpload->createView() : null,
  558.             'tab' => $tab
  559.         ]);
  560.     }
  561.     
  562.     
  563.     /**
  564.      * upload document for ad moderation
  565.      * @param Request $request
  566.      * @param FileUploader $uploader
  567.      * @return JsonResponse
  568.      * @Route("/account/update_avatar", name="update_avatar")
  569.      */
  570.     public function documentUpload(Request $request,  FileUploader $uploader)
  571.     {
  572.         $current_user $this->getUser();
  573.         $file $request->files->get('file');
  574.         $error true;
  575.         $message "";
  576.         if ($file instanceof UploadedFile && in_array($file->getMimeType(), ['image/png''image/jpeg'])) {
  577.             $fileName $uploader->uploadImage($file);
  578.             $current_user->setAvatarPath($fileName);
  579.             $em $this->getDoctrine()->getManager();
  580.             $em->flush();
  581.             $message "Photo mis à jour!";
  582.             $error false;
  583.         }
  584.         return new JsonResponse(['error'=>$error,'message'=>$message]);
  585.         
  586.         
  587.     }
  588.     
  589.     /**
  590.      * @Route("/password/reset", name="password_reset")
  591.      */
  592.     public function resetPasswordAction(Request $request)
  593.     {
  594.         // last username entered by the user
  595.         $lastUsername $this->authenticationUtils->getLastUsername();
  596.         $form $this->createForm(PasswordResetForm::class, [
  597.             '_username' => $lastUsername,
  598.         ]);
  599.         $error null;
  600.         $form->handleRequest($request);
  601.         if ($form->isSubmitted() && $form->isValid()) {
  602.             $form_user $form->getData();
  603.             $username $form_user['_username'];
  604.             $em $this->getDoctrine()->getManager();
  605.             $user $em->getRepository('App\Entity\User')
  606.                 ->findOneBy(['email' => $username]);
  607.             if ($user === null) {
  608.                 $form->get('_username')->addError(new FormError('Adresse email inconnue'));
  609.             }else if($user->getStatus()==0){
  610.                 $error "Un lien d'activation a été envoyé à votre adresse e-mail. Veuillez cliquer sur ce lien pour activer votre compte";
  611.             }
  612.             else {
  613.                 $token_date $user->getTokenValidAt();
  614.                 if ($token_date==null || $token_date->getTimestamp() < strtotime('+1 day')){
  615.                     $token rtrim(strtr(base64_encode(random_bytes(32)), '+/''-_'), '=');
  616.                     $user->setToken($token);
  617.                     $user->setTokenValidAt(new \DateTime());
  618.                     $em->persist($user);
  619.                     $em->flush();
  620.                     $this->mailSender->sendPasswordReset($user);
  621.                     $this->addFlash('report''Un lien de réinitialisation vous a été envoyé par mail. Cliquez sur ce lien pour réinitiliaser votre mot de passe');
  622.                     return $this->redirectToRoute('homepage');
  623.                     
  624.                 }else{
  625.                     $error 'Vous devez attendre 24h apres la dernière demande pour pouvoir changer de mot de passe';
  626.                 }
  627.                 
  628.                 
  629.             }
  630.         }
  631.         return $this->render(
  632.             'security/password_reset.html.twig', [
  633.                 'error' => $error,
  634.                 'form' => $form->createView()
  635.             ]);
  636.     }
  637.     /**
  638.      * @Route("/password/change/{token}", name="password_change")
  639.      */
  640.     public function changePasswordAction(Request $request$tokenLoginFormAuthenticator $authenticator)
  641.     {
  642.         $em $this->getDoctrine()->getManager();
  643.         $user $em->getRepository('App\Entity\User')
  644.             ->findOneBy(['token' => $token]);
  645.         if ($user === null) {
  646.             throw new NotFoundHttpException('Cette url n\'est pas valide. Veuillez effectuer une nouvelle demande');
  647.         }
  648.         $token_date $user->getTokenValidAt();
  649.         /** @var \DateTime $token_date */
  650.         if ($token_date->getTimestamp() > strtotime('+1 day')){
  651.             throw new NotFoundHttpException('Cette url a expirée. Veuillez effectuer une nouvelle demande');
  652.         }
  653.         $form $this->createForm(PasswordChangeForm::class, $user);
  654.         $form->handleRequest($request);
  655.         if ($form->isSubmitted() && $form->isValid()) {
  656.             $user->setToken(null);
  657.             $user->setTokenValidAt(null);
  658.             $em->persist($user);
  659.             $em->flush();
  660.             $this->addFlash('success''Mot de passe mis à jour');
  661.             return $this->redirectToRoute('security_login');
  662.         }
  663.         return $this->render(
  664.             'security/password_change.html.twig',
  665.             array(
  666.                 'form' => $form->createView(),
  667.             )
  668.         );
  669.     }
  670.     
  671.     /**
  672.      * Remove discountCoupon
  673.      * @param DiscountCoupon $coupon
  674.      * @param Request $request
  675.      * @Route("/coupons/remove/{id}", name="user_coupons_remove")
  676.      */
  677.     public function removeCoupon(DiscountCoupon $coupon,Request $request)
  678.     {
  679.         if ($request->isMethod(Request::METHOD_POST)) {
  680.             $user $this->getUser();
  681.             if($coupon->getUser()->getId()==$user->getId()){
  682.                 $em $this->getDoctrine()->getManager();
  683.                 $coupon->setStatus(DiscountCoupon::STATUS_REMOVED);
  684.                 $em->flush();
  685.                 return new JsonResponse(['error' => false]);
  686.             }
  687.             
  688.         }
  689.         throw new NotFoundHttpException();
  690.     }
  691.     /**
  692.  * @Route("/badge/generate", name="generate_badge")
  693.  */
  694.     public function generateBadge(Request $request)
  695.     {
  696.         $user $this->getUser();
  697.         if ($user->getAgency()!= null && $request->isMethod(Request::METHOD_POST) && $user->getAgency()->isCertified()) {
  698.             $badge = new Badge();
  699.             $badge->setCreatedAt(new \DateTime());
  700.             $badge->setCode(strtoupper($this->GenerateCode(6)));
  701.             $badge->setUserAgency($user);
  702.             $em $this->getDoctrine()->getManager();
  703.             try{
  704.                 $em->persist($badge);
  705.                 $em->flush();
  706.             }
  707.             catch (\Exception $ex){
  708.                 return new JsonResponse(['error' => true,'message'=>'Il s\'est produit une erreur pendant la génération de votre badge!']);
  709.             }
  710.             $shareLink $this->generateUrl('share_badge', array('id' => $badge->getId()));
  711.             $removeLink $this->generateUrl('user_badge_remove', array('id' => $badge->getId()));
  712.             return new JsonResponse([
  713.                 'error' => false,
  714.                 'badge' => [
  715.                     'code' => $badge->getCode(),
  716.                     'date' => $badge->getCreatedAt()->format("Y-m-d"),
  717.                     'shareLink' => $shareLink,
  718.                     'removeLink' =>$removeLink
  719.                 ]
  720.             ]);
  721.         }
  722.         return new JsonResponse(['error' => true,'message'=>'Vous n\'êtes pas autorisé à générer des badges']);
  723.     }
  724.     /**
  725.      * Remove badge
  726.      * @param Badge $badge
  727.      * @param Request $request
  728.      * @Route("/badge/remove/{id}", name="user_badge_remove")
  729.      */
  730.     public function removeBadge(Badge $badge,Request $request)
  731.     {
  732.         $user $this->getUser();
  733.         if ($request->isMethod(Request::METHOD_POST) && $user->getId() == $badge->getUserAgency()->getId()) {
  734.             $em $this->getDoctrine()->getManager();
  735.             try{
  736.                 if($badge->getUserTenant()!=null){
  737.                     $user $badge->getUserTenant();
  738.                     $user->setStatus(0);
  739.                     $user->setBadge(null);
  740.                     $em->flush();
  741.                 }
  742.                 $em->remove($badge);
  743.                 $em->flush();
  744.                 return new JsonResponse(['error' => false]);
  745.             }
  746.             catch (\Exception $ex){
  747.                 return new JsonResponse(['error' => true,'message'=>$ex->getMessage()]);
  748.             }
  749.             return new JsonResponse(['error' => true]);
  750.         }
  751.         return new JsonResponse(['error' => true]);
  752.     }
  753.     /**
  754.      * @Route("/badge/share/{id}", name="share_badge")
  755.      */
  756.     public function shareBadge(Request $request)
  757.     {
  758.         if ($request->isMethod(Request::METHOD_POST)) {
  759.             $em $this->getDoctrine()->getManager();
  760.             $badgeId $request->get("id");
  761.             $badge $em->getRepository('App\Entity\Badge')->find($badgeId);
  762.             if($badge !=null){
  763.                 $email $request->get("email");
  764.                 if (!filter_var($emailFILTER_VALIDATE_EMAIL)) {
  765.                     return new JsonResponse(['error' => true'message' => 'Format adresse email invalide!']);
  766.                 }
  767.                 $user $this->getUser();
  768.                 $this->mailSender->sendBadgeByEmail($user,$badge->getCode(),$email);
  769.                 return new JsonResponse(['error' => false'message' => 'Email envoyé à l\'adresse email : '.$email]);
  770.             }
  771.             return new JsonResponse(['error' => true'message' => 'Badge introuvable!']);
  772.         }
  773.         return new JsonResponse(['error' => true'message' => 'Requête invalide!']);
  774.     }
  775.     /**
  776.      * upload document for agency
  777.      * @param Request $request
  778.      * @param FileUploader $uploader
  779.      * @return JsonResponse
  780.      * @Route("/account/upload_agency_doc", name="upload_agency_doc")
  781.      */
  782.     public function documentAgencyUpload(Request $request,  FileUploader $uploader)
  783.     {
  784.         $current_user $this->getUser();
  785.         $file $request->files->get('file');
  786.         if ( $current_user->getAgency()!=null && $current_user->getAgency()->getStatus()!=&& $current_user->getAgency()->getStatus()!=2  && $file instanceof UploadedFile ) {
  787.             $fileName $uploader->uploadFile($file);
  788.             $doc = new AgencyDocument();
  789.             $doc->setPath($fileName);
  790.             $doc->setName($file->getClientOriginalName());
  791.             $doc->setSize($file->getClientSize());
  792.             $doc->setAgency($current_user->getAgency());
  793.             $doc->setUser($current_user);
  794.             $doc->setCreatedAt(new \DateTime());
  795.             $current_user->getAgency()->setStatus(2);
  796.             $em $this->getDoctrine()->getManager();
  797.             $em->persist($doc);
  798.             $em->flush();
  799.             return new JsonResponse(['error'=>false,'message'=>'La vérification de vos documents est en cours de traitement!','document'=>[
  800.                 'name' => $doc->getName(),
  801.                 'id' => $doc->getId()
  802.             ]]);
  803.         }
  804.         return new JsonResponse(['error'=>true,'message'=>'Requête invalide!']);
  805.     }
  806.     /**
  807.      * @Route("/activate-certified-account/{token}", name="activate_certified_account")
  808.      */
  809.     public function activateCerifiedAccountAction($token,Request $request)
  810.     {
  811.         $em $this->getDoctrine()->getManager();
  812.         $certifiedAgency $em->getRepository('App\Entity\CertifiedAgency')
  813.             ->findOneBy(['token' => $token]);
  814.         if ($certifiedAgency === null || $certifiedAgency->getAgency() == null || $certifiedAgency->getAgency()->isCertified()==true) {
  815.             throw new NotFoundHttpException('Le lien que vous avez suivi n\'existe pas ou a expiré');
  816.         }
  817.         $user $em->getRepository('App\Entity\CertifiedAgency')
  818.         ->findOneBy(['email' => $certifiedAgency->getEmail()]);
  819.         if ($user === null){
  820.             throw new NotFoundHttpException('Le lien que vous avez suivi n\'existe pas ou a expiré');
  821.         }
  822.         $certifiedAgency->setToken(null);
  823.         $em->flush();
  824.         return $this->get('security.authentication.guard_handler')
  825.             ->authenticateUserAndHandleSuccess(
  826.                 $user,
  827.                 $request,
  828.                 $this->get(LoginFormAuthenticator::class),
  829.                 'main'
  830.             );
  831.     }
  832.     /**
  833.      * Check username
  834.      * @param Request $request
  835.      * @return JsonResponse
  836.      * @Route("/check-username", name="check_username")
  837.      */
  838.     public function checkUsername(Request $request)
  839.     {
  840.         $username $request->get('username');
  841.         if(isset($username)){
  842.             try{
  843.                 $em $this->getDoctrine()->getManager();
  844.                 $list $em->getRepositoryUser::class )->getUserByUsername($username);
  845.                 $length sizeof($list);
  846.                 if($length == 0){
  847.                     return new JsonResponse(['error' => false,"taken" => false]);
  848.                 }else{
  849.                     return new JsonResponse(['error' => false,"taken" => true,"message" => "Ce nom d'utilisateur est déjà utilisé. Essayez un autre nom."]);
  850.                 }
  851.             }
  852.             catch (\Exception $ex){
  853.                 return new JsonResponse(['error' => true,'message'=>"Une erreur est survenue! Veuillez réessayer un peu plus tard!"]);
  854.             }
  855.         }
  856.         return new JsonResponse(['error' => true,'message'=>"Requête invalide!"]);
  857.     }
  858.     private function GenerateCode($n) {
  859.         $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  860.         $randomString '';
  861.         for ($i 0$i $n$i++) {
  862.             $index rand(0strlen($characters) - 1);
  863.             $randomString .= $characters[$index];
  864.         }
  865.         return $randomString;
  866.     }
  867. }