src/Controller/RegistrationController.php line 267

  1. <?php
  2. // src/Acme/UserBundle/Controller/RegistrationController.php
  3. namespace App\Controller;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use FOS\UserBundle\Controller\RegistrationController as BaseController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Doctrine\ORM\EntityManager;
  11. use Symfony\Component\Form\Forms;
  12. // use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  13. use App\Entity\User;
  14. use App\Services\ConfigurationManager;
  15. use App\Services\SettingsManager;
  16. use App\Services\WebServiceUsuarios;
  17. use App\Services\WebServiceFunciones;
  18. use App\Utils\Util;
  19. use Doctrine\Persistence\ManagerRegistry;
  20. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  21. use Symfony\Component\Form\Extension\Core\Type\TextType;
  22. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  23. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  24. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  25. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  26. use Doctrine\ORM\EntityManagerInterface;
  27. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  28. use FOS\UserBundle\Form\Factory\FactoryInterface;
  29. use FOS\UserBundle\Model\UserManagerInterface;
  30. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  31. use FOS\UserBundle\CompatibilityUtil;
  32. use Symfony\Component\Form\FormFactoryInterface;
  33. use App\Form\Type\CheckDniType;
  34. use App\Form\Type\CheckDniDateType;
  35. use App\Form\Type\UserRegistrationNoCorreoType;
  36. use App\Form\Type\UserRegistrationCheckCorreoType;
  37. use FOS\UserBundle\Event\FormEvent;
  38. use FOS\UserBundle\FOSUserEvents;
  39. use FOS\UserBundle\Event\GetResponseUserEvent;
  40. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  41. use FOS\UserBundle\Event\FilterUserResponseEvent;
  42. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  43. use Symfony\Component\HttpClient\HttpClient;
  44. use Symfony\Component\Process\Process;
  45. use Symfony\Component\HttpFoundation\File\File;
  46. use Symfony\Bundle\SecurityBundle\Security;
  47. class RegistrationController extends BaseController
  48. {
  49.     private $wsu;
  50.     private $sm;
  51.     private $ffi;
  52.     private $params;
  53.     
  54.     public function __construct(EventDispatcherInterface $eventDispatcherFactoryInterface $formFactoryUserManagerInterface $userManagerTokenStorageInterface $tokenStorageWebServiceUsuarios $wsuSettingsManager $smFormFactoryInterface $ffiWebServiceFunciones $wsfEntityManagerInterface $emParameterBagInterface $paramsConfigurationManager $cm)
  55.     {
  56.         $this->eventDispatcher CompatibilityUtil::upgradeEventDispatcher($eventDispatcher);
  57.         $this->formFactory $formFactory;
  58.         $this->userManager $userManager;
  59.         $this->tokenStorage $tokenStorage;
  60.         $this->wsu $wsu;
  61.         $this->wsf $wsf;
  62.         $this->sm $sm;
  63.         $this->ffi $ffi;
  64.         $this->em $em;
  65.         $this->params $params;
  66.         $this->cm $cm;
  67.     }
  68.     
  69.     
  70.     public function authenticateUser($userSecurity $security)
  71.     {
  72.         $redirectResponse $security->login($user,'security.authenticator.form_login.main');
  73.         return $redirectResponse;
  74.     }
  75.     #[Route(path: [
  76.         'es' => '/registro/{email}',
  77.         'en' => '/en/register/{email}'
  78.     ], name'fos_user_registration_register')]
  79.     public function registerAction(Request $request, ?string $email nullSecurity $security null): Response
  80.     {
  81.         $wsu $this->wsu;
  82.         $wsf $this->wsf;
  83.         $sm $this->sm;
  84.         $em $this->em;
  85.         $cm $this->cm;
  86. //         $options = $this->container->get('dinamic_settings.manager');
  87.         
  88.         /**** Bloque de formulario de usuario sin correo en el ERP *******/
  89.         $formNoCorreo =  $this->ffi->create(UserRegistrationNoCorreoType::class,null,["sm" => $sm]);
  90.         
  91.         $formNoCorreo->handleRequest($request);
  92. //         dump($formNoCorreo);die();
  93.         if($formNoCorreo->isSubmitted() and $formNoCorreo->isValid()){
  94.             $data=$formNoCorreo->getData();
  95. //             $WSU = $this->container->get('web.service.usuarios',$em);
  96. //             $WSF=$this->container->get('web.service.funciones',$em);
  97.             $userERP=$wsf->getClienteporNumId($data['Dni_correo_sin']);
  98.             $userERPD $wsu->findBy('No',$userERP);
  99.             if($userERP){
  100.                 $wsf->modificarEmail($userERP,$data['email']);
  101.                 $user = new User();
  102.                 $user->setIdCard($data['Dni_correo_sin']);
  103.                 $user->setEmail($data['email']);
  104.                 $user->setPassword($data['password1']);
  105.                 $user->setPlainPassword($data['password1']);
  106.                 $user->setName($userERPD['Name']. ' '.$userERPD['Name2']);
  107.                 $user->setErpId($userERP);
  108.                 $user->setEnabled(1);
  109. //                 $userManager = $this->container->get('fos_user.user_manager');
  110.                 $this->userManager->updatePassword($user);
  111.                 $em->persist($user);
  112.                 $em->flush();
  113. //                 $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
  114.                 if ($request->query->has('t')) {
  115.                     $url $this->generateUrl('fos_user_registration_confirmed', ['t' => $request->query->get('t')]);
  116.                 } else {
  117.                     $url $this->generateUrl('fos_user_registration_confirmed');
  118.                 }
  119.                 $response = new RedirectResponse($url);
  120.                 $this->authenticateUser($user$security);
  121.                 return $response;
  122.             }
  123.         }
  124.         else{
  125.             //echo $formNoCorreo->getErrorsAsString();
  126.         }
  127.         /***** Bloque de codigo de usuario con correo en el ERP ********/
  128.         
  129.         $user $this->userManager->createUser();
  130.         $user->setEnabled(true);
  131.         $event = new GetResponseUserEvent($user$request);
  132.         $this->eventDispatcher->dispatch($eventFOSUserEvents::REGISTRATION_INITIALIZE);
  133.         
  134.         if (null !== $event->getResponse()) {
  135.             return $event->getResponse();
  136.         }
  137.         
  138.         
  139.         $locale $request->getLocale();
  140.         $fullForm $this->formFactory->createForm(["sm" => $sm]);
  141.         
  142.         $fullForm->setData($user);
  143.         
  144.         $fullForm->handleRequest($request);
  145.         $confirmationEnabled    $this->params->get('fos_user.registration.confirmation.enabled');
  146.         
  147. //         dump($fullForm->handleRequest($request));die();
  148.         
  149.         
  150.         if ($fullForm->isSubmitted()) {
  151.             if ($fullForm->isValid()) {
  152. //                 dump($fullForm->getData());dump($fullForm->getData()->getFechaCaducidad());dump($user->getName());die();
  153.                 $event = new FormEvent($fullForm$request);
  154.                 $this->eventDispatcher->dispatch($eventFOSUserEvents::REGISTRATION_SUCCESS);
  155.                     
  156.                     // dump($user);die();
  157.                 
  158.                 if ($this->onRegistrationSuccess($user)) {
  159.                     if ($confirmationEnabled) {
  160.         //                     $userERP = $user->getErpId();
  161.         //                     dump($userERP);
  162.         //                     $userERPD = $wsu->findBy('No',$userERP);
  163.         //                     dump($userERPD);die();
  164.         //                     $request->getSession()->set('fos_user_send_confirmation_email/email', $userERPD['email']);
  165.                         if ($request->query->has('t')) {
  166.                             $user->setEnabled(true);
  167.                             $this->userManager->updateUser($user);
  168.                             $this->authenticateUser($user$security);
  169.                             $url $this->generateUrl('app_cart_3', ['t' => $request->query->get('t')]);
  170.                         } else {
  171.                             $user->setEnabled(false);
  172.                             $url $this->generateUrl('fos_user_registration_check_email');
  173.                             $this->userManager->updateUser($user);
  174.                         }
  175.                             
  176.                         $response = new RedirectResponse($url);
  177.                         return $response;
  178.                     }
  179.                         
  180.                     $this->userManager->updateUser($user);
  181.                     if (null === $response $event->getResponse()) {
  182.                         if ($request->query->has('t')) {
  183.                             $url $this->generateUrl('fos_user_registration_confirmed', ['t' => $request->query->get('t')]);
  184.                         } else {
  185.                             $url $this->generateUrl('fos_user_registration_confirmed');
  186.                         }
  187.                         $response = new RedirectResponse($url);
  188.                     }
  189.                     $this->eventDispatcher->dispatch(new FilterUserResponseEvent($user$request$response), FOSUserEvents::REGISTRATION_COMPLETED);
  190.         //                 $this->onRegistrationCompleted($user);
  191.                     return $response;
  192.                 }
  193.                 else {
  194.                     $this->addFlash('error'$this->sm->getValue('error.registro'));
  195.                 }
  196. //                 }
  197.             }
  198.             $event = new FormEvent($fullForm$request);
  199.             $this->eventDispatcher->dispatch($eventFOSUserEvents::REGISTRATION_FAILURE);
  200.             if (null !== $response $event->getResponse()) {
  201.                 return $response;
  202.             }
  203.         }
  204.         
  205.         //Formulario busqueda cliente   
  206.         $formShortReg =  $this->ffi->create(CheckDniType::class,null,["sm" => $sm]);
  207.         $formShortRegDate =  $this->ffi->create(CheckDniDateType::class,null,["sm" => $sm]);
  208.         if ($request->query->has('dni')) {
  209.             $dniTrans $request->query->get('dni');
  210.         } else {
  211.             $dniTrans null;
  212.         }
  213.         //Formulario de comprobacion de correo
  214.         $formCorreo =  $this->ffi->create(UserRegistrationCheckCorreoType::class,null,["sm" => $sm]);
  215.             
  216.         $formCorreo->handleRequest($request);
  217.         if($formCorreo->isSubmitted() and  $formCorreo->isValid()){
  218.             $data=$formCorreo->getData();
  219.             $user=$em->getRepository('App\Entity\User')->findOneByUsername(strtolower($data['Dni_correo_con']));
  220.             if($user && $user->getConfirmationToken()==$data['codigo_correo']){
  221.                 $user->setPlainPassword($data['password1']);
  222.                 $user->setConfirmationToken(null);
  223.                 $user->setPasswordRequestedAt(null);
  224.                 if ($request->query->has('t')) {
  225.                     $url $this->generateUrl('fos_user_registration_confirmed', ['t' => $request->query->get('t')]);
  226.                 } else {
  227.                     $url $this->generateUrl('fos_user_registration_confirmed');
  228.                 }
  229.                 $response = new RedirectResponse($url);
  230.                 $this->authenticateUser($user$security);
  231.                 return $response;
  232.             }
  233.             else{
  234.                 
  235.             }
  236.         }
  237.         else{
  238.             //echo "ERROR";
  239.             //die;
  240.         }
  241.         return $this->render('@FOSUser/Registration/register.html.twig', array(
  242.             'formShortReg'      => $formShortReg->createView(),
  243.             'formShortRegDate'  => $formShortRegDate->createView(),
  244.             'formCorreo'        => $formCorreo->createView(),
  245.             'fullForm'          => $fullForm->createView(),
  246.             'formNoCorreo'      => $formNoCorreo->createView(),
  247.             'dniTrans'          => $dniTrans
  248.         ));
  249.     }
  250.     
  251.     
  252.     /**
  253.      * Tell the user to check their email provider.
  254.      */
  255.     public function checkEmailAction(Request $request): Response
  256.     {
  257.         $email $request->getSession()->get('fos_user_send_confirmation_email/email');
  258. // dump($email); die();
  259.         if (empty($email)) {
  260.             return new RedirectResponse($this->generateUrl('fos_user_registration_register'));
  261.         }
  262.         $request->getSession()->remove('fos_user_send_confirmation_email/email');
  263.         $user $this->userManager->findUserByEmail($email);
  264.         
  265.         if (null === $user) {
  266.             return new RedirectResponse($this->container->get('router')->generate('fos_user_security_login'));
  267.         }
  268.         return $this->render('@FOSUser/Registration/check_email.html.twig', [
  269.             'user' => $user,
  270.         ]);
  271.     }
  272.     /**
  273.      * Receive the confirmation token from user email provider, login the user.
  274.      *
  275.      * @param string $token
  276.      */
  277.     public function confirmAction(Request $request$token): Response
  278.     {
  279.         $userManager $this->userManager;
  280.         $user $userManager->findUserByConfirmationToken($token);
  281.         if (null === $user) {
  282.             return new RedirectResponse($this->container->get('router')->generate('fos_user_security_login'));
  283.         }
  284.         $user->setConfirmationToken(null);
  285.         $user->setEnabled(true);
  286.         $event = new GetResponseUserEvent($user$request);
  287.         $this->eventDispatcher->dispatch($eventFOSUserEvents::REGISTRATION_CONFIRM);
  288.         $userManager->updateUser($user);
  289. //         $this->onRegistrationCompleted($user);
  290.         if (null === $response $event->getResponse()) {
  291.             $url $this->generateUrl('fos_user_registration_confirmed');
  292.             $response = new RedirectResponse($url);
  293.         }
  294.         $this->eventDispatcher->dispatch(new FilterUserResponseEvent($user$request$response), FOSUserEvents::REGISTRATION_CONFIRMED);
  295.        
  296.         return $response;
  297.     }
  298.     /**
  299.      * Tell the user his account is now confirmed.
  300.      */
  301.     public function confirmedAction(Request $request): Response
  302.     {
  303.         $user $this->getUser();
  304.         
  305. //         dump($user);
  306. //         dump($user instanceof UserInterface); die();
  307. //         dump($user); die();
  308.         if (!is_object($user) || !$user instanceof User) {
  309.             throw new AccessDeniedException('This user does not have access to this section.');
  310.         }
  311.         
  312.         new RedirectResponse($this->container->get('router')->generate('app_profile'));
  313.         return $this->render('@FOSUser/Registration/confirmed.html.twig', [
  314.             'user' => $user,
  315.             'targetUrl' => ''
  316.             //'targetUrl' => $this->getTargetUrlFromSession($request->getSession()),
  317.         ]);
  318.     }
  319.     private function getTargetUrlFromSession(SessionInterface $session): ?string
  320.     {
  321.         $key sprintf('_security.%s.target_path'$this->tokenStorage->getToken()->getProviderKey());
  322.         if ($session->has($key)) {
  323.             return $session->get($key);
  324.         }
  325.         return null;
  326.     }
  327.     
  328.     
  329.     
  330.     
  331.     public function onRegistrationSuccess($user)
  332.     {
  333.         $user->setUsername($user->getIdCard());
  334.         $ERPCODE=$this->wsf->getClienteporNumId($user->getIdCard());
  335.         $user->setRoles([]);
  336.         
  337.         //Ya está en la base de datos del ERP
  338.         if($ERPCODE){
  339.             $user->setErpId($ERPCODE);
  340.             if($this->em->getRepository('App\Entity\User')->findOneByErpId($ERPCODE)){
  341.                 //User already in db
  342.                 //echo "Ya estas en la base de datos";
  343.                 return false;
  344.             }
  345.         }
  346.         else{
  347.             $salidaERP=$this->wsf->RegistrarCliente($user);
  348.             if(!$salidaERP) {
  349.                 $this->userManager->updateUser($user);
  350.                 return false;
  351.             }
  352.             $user->setErpId($salidaERP);
  353.         }
  354.         
  355.         $this->userManager->updateUser($user);
  356.         $this->processImages($user);
  357.         
  358.         return true;
  359.     }
  360.     
  361.     public function processImages($user)
  362.     {
  363.         $em $this->em;
  364.         $SM $this->sm;
  365.         $WS $this->wsf;
  366.         if($user->getUrlImagen()){
  367.             $file $user->getUrlImagen();
  368.             if ($file->guessExtension() == 'pdf') {
  369.                 $randName md5(uniqid());
  370.                 $pdfName $randName '.pdf';
  371.                 $file->move($this->getParameter('dni_directory'), $pdfName);
  372.                 $pdfFile $this->getParameter('dni_directory').'/'.$pdfName;
  373.                 $outputFile $this->getParameter('dni_directory').'/'.$randName.'.jpg';
  374.                 //exec("/usr/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r150 -dFirstPage=1 -dLastPage=1 -sOutputFile=\"$outputFile\" \"$pdfFile\"", $output, $returnVar);
  375.                 shell_exec("/bin/gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r150 -dFirstPage=1 -dLastPage=1 -sOutputFile=\"$outputFile\" \"$pdfFile\"");
  376.                 unlink($this->getParameter('dni_directory').'/'.$pdfName);
  377.                 if (!file_exists($outputFile)) {
  378.                     throw new \Exception("Error al convertir PDF a JPG");
  379.                 }
  380.                 $fileName $randName.'.jpg';
  381.             } else {
  382.                 $newName $fileNamemd5(uniqid()).'.'.$file->guessExtension();
  383.                 $file->move(
  384.                     $this->params->get('dni_directory'),
  385.                     $fileName
  386.                 );
  387.             }
  388.             // $newName = $fileName= md5(uniqid()).'.'.$file->guessExtension();
  389.             // $file->move(
  390.             //     $this->params->get('dni_directory'),
  391.             //     $fileName
  392.             // );
  393.             $fileName_r $fileName;
  394.             $file_image Util::smart_resize_image($this->params->get('dni_directory').'/'.$fileName,null12001200true$this->params->get('dni_directory').'/'.$fileNametruefalse100);
  395.             //$file_image = imagecreatefromjpeg($this->params->get('dni_directory').'/'.$fileName);
  396.             
  397.             $file_image imagecreatefromstring(file_get_contents($this->params->get('dni_directory').'/'.$fileName));
  398.             
  399.             $fileNameee $this->params->get('dni_directory').'/'.$newName;
  400.             
  401. // dump($fileNameee);
  402.             $fileName1=NULL;
  403.             if ($user->getUrlImagen2()) {
  404.               $file1 $user->getUrlImagen2();
  405.               $newName1=$fileName1 md5(uniqid()).'.'.$file1->guessExtension();
  406.               $file1->move($this->params->get('dni_directory'), $fileName1);
  407.               $file1_image Util::smart_resize_image($this->params->get('dni_directory').'/'.$fileName1,null12001200true$this->params->get('dni_directory').'/'.$fileName1truefalse100);
  408.               $file1_image imagecreatefromstring(file_get_contents($this->params->get('dni_directory').'/'.$fileName1));
  409.               
  410.               $tamano1 getimagesize($this->params->get('dni_directory').'/'.$fileName);
  411.               $tamano2 getimagesize($this->params->get('dni_directory').'/'.$fileName1);
  412.               $anchoGrande 0;
  413.               
  414.               if($tamano1[0] > $tamano2[0]){
  415.                 $anchoGrande $tamano1[0];
  416.               }else{
  417.                 $anchoGrande $tamano2[0];
  418.               }
  419.               $altura $tamano1[1]+$tamano2[1];
  420.               $altura1 $altura $tamano2[1];
  421.               $image_aux imagecreatetruecolor($anchoGrande,$altura);
  422.               imagecopymerge($image_aux$file_image0000$tamano1[0], $tamano1[1], 100);
  423.               imagecopymerge($image_aux$file1_image0$altura100$tamano2[0], $tamano2[1], 100);
  424.               $filename_image11 md5(uniqid());
  425.               imagepng($image_aux,$this->params->get('dni_directory').'/'.$filename_image11.'.png');
  426.               $file $image_aux;
  427.               $fileName $filename_image11.'.png';
  428.               $fileNameFinal $fileName;
  429.               $fileNameee $this->params->get('dni_directory').'/'.$filename_image11.'.png';
  430.               $newName$filename_image11.'.png';
  431.             }
  432. // dump($fileNameee);
  433. // die();
  434.             try{
  435.                 //Upload the image to Eurochange FTP
  436.                 $ftp_server      $this->params->get('get_ftp_domain');
  437.                 $ftp_user_name   $this->params->get('get_ftp_user');
  438.                 $ftp_user_pass   $this->params->get('get_ftp_password');
  439.                 $ftp_user_folder $this->params->get('get_ftp_dni_folder');
  440.                 $conn_id         ftp_connect($ftp_server);
  441.                 $login_result ftp_login($conn_id$ftp_user_name$ftp_user_pass);
  442.                 if ((!$conn_id) || (!$login_result)) {
  443.                     //echo "conexion fallida";
  444.                     dump("error");
  445.                 }
  446. //                 dump($login_result);
  447.                   //turn passive mode on
  448.                 ftp_pasv($conn_idtrue);
  449.                 $dni_path=$this->params->get('dni_directory');
  450.                 $upload ftp_put($conn_id$ftp_user_folder.$newName$fileNameeeFTP_BINARY);
  451. //                 dump($upload);
  452.                 //TODO activar en produccion
  453.                 $WS->CargarImagen($user->getErpId(),$newName);
  454.                 //Tras subir la imagen al FTP del ERP, borramos la nuestra
  455.                 // if(file_exists($fileNameee)){
  456.                 //     unlink($fileNameee);
  457.                 // }
  458.                 if(file_exists($dni_path.'/'$fileName1)){
  459.                     unlink($dni_path.'/'.$fileName1);
  460.                 }
  461.                 if(file_exists($dni_path.'/'.$fileName_r)){
  462.                     unlink($dni_path.'/'.$fileName_r);
  463.                 }
  464.             }catch(\Exception $e){
  465.                 //$logger = $this->get('logger');
  466.                 //$logger->error('[DINAMIC][ERROR][SUBIDA DNI] ' . $e->getCode() . ' ' . $e->getMessage());
  467.             }
  468.             //Register the new image
  469.             $user->setUrlImagen($newName);
  470.             $user->setUrlImagen2($fileName1);
  471.         }
  472. // die();
  473.         $this->userManager->updateUser($user);
  474.     }
  475.     
  476. }