src/Controller/DefaultController.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Competitor;
  4. use App\Entity\Pharmacovigilance;
  5. use App\Entity\Privacy;
  6. use App\Entity\Profile;
  7. use App\Entity\User;
  8. use App\Form\ContactUs;
  9. use App\Form\PasswordCreationType;
  10. use App\Form\PharmacovigilanceType;
  11. use App\Form\RegistrationType;
  12. use App\Form\Model\Contact;
  13. use App\Service\UserService;
  14. use Doctrine\Persistence\ManagerRegistry;
  15. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  18. use Symfony\Component\Form\FormError;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\Mailer\MailerInterface;
  22. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  25. class DefaultController extends AbstractController
  26.     protected $mr;
  27.     public function __construct(ManagerRegistry $managerRegistry)
  28.     {
  29.         $this->mr $managerRegistry;
  30.     }
  31.     /**
  32.      * @Route("/", name="homepage")
  33.      */
  34.     public function index(Request $requestAuthenticationUtils $authenticationUtilsMailerInterface $mailer): Response
  35.     {
  36.         if($this->getUser() != null){
  37.             if($this->getUser()->getRole() == "ROLE_ADMIN")
  38.                 return $this->redirectToRoute("admin_index");
  39.             elseif($this->getUser()->getRole() == "ROLE_USER")
  40.                 return $this->redirectToRoute("user_index");
  41.         }
  42.         
  43.         $em $this->mr->getManager();
  44.         $registerTab false;
  45.         // LOGIN
  46.         $error $authenticationUtils->getLastAuthenticationError();
  47.         $lastUsername $authenticationUtils->getLastUsername();
  48.         
  49.         // REGISTER
  50.         $user = new User();
  51.         $form $this->createForm(RegistrationType::class, $user);
  52.         $form->handleRequest($request);
  53.         if($form->isSubmitted()){
  54.             $valid true;
  55.             // TERMINI E CONDIZIONI
  56.             if($form->get('terms')->getData() == false){
  57.                 $valid false;
  58.                 $form->get('terms')->addError(new FormError("Per registrarti devi accettare i termini e condizioni di utilizzo."));
  59.                 $registerTab true;
  60.             }
  61.             // PASSWORD RESISTENTE
  62.             if($valid){
  63.                 $psw $form->get('password')->getData();
  64.                 $count 0;
  65.                 if(preg_match('/[0-9]/'$psw)) $count++;
  66.                 if(preg_match('/[a-z]/'$psw)) $count++;
  67.                 if(preg_match('/[A-Z]/'$psw)) $count++;
  68.                 if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/'$psw)) $count++;
  69.                 if($count 3)
  70.                 {
  71.                     $valid false;
  72.                     $this->addFlash('notice_warning''Inserisci una password resistente. Per maggiori informazioni clicca sulla parola RESISTENTE');
  73.                     $registerTab true;
  74.                 }
  75.             }
  76.             
  77.             // RECAPTCHA
  78.             $path 'https://www.google.com/recaptcha/api/siteverify?secret=6LfCPG4UAAAAAMY34gnUymU_hzD6Ekpeune_Rnim&response='.$request->request->get("g-recaptcha-response");    
  79.             $ch curl_init();
  80.             curl_setopt($chCURLOPT_HTTPHEADER, array( 'Content-Type: application/json''Accept: application/json'));
  81.             curl_setopt($chCURLOPT_URL,$path);
  82.             curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  83.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  84.             curl_setopt($chCURLOPT_CUSTOMREQUEST"GET");
  85.             $result curl_exec($ch);
  86.             curl_close($ch);
  87.             
  88.             $res json_decode($resulttrue);
  89.             
  90.             if($valid && !$res["success"]){
  91.                 $valid false;
  92.                 $this->addFlash('notice_warning''Per registrarti devi provare di non essere un robot.');
  93.                 $registerTab true;
  94.             }
  95.             if($valid && $form->isValid()){
  96.                 // PASSWORD
  97.                 $encoder $this->get('security.encoder_factory')->getEncoder($user);
  98.                 $password $encoder->encodePassword($form->get('password')->getData(), null);
  99.                 $user->setPassword($password);
  100.                 // ONETIMECODE
  101.                 $user->setOneTimeCode(md5(uniqid()));
  102.                 // TIPO ACCOUNT FARMACISTA
  103.                 $accountType $em->getRepository("App\Entity\AccountType")->findOneBySlug('external');
  104.                 $user->setAccountType($accountType);
  105.                 // CREAZIONE CARTELLE
  106.                 $directoryPath uniqid();
  107.                 mkdir($this->getParameter('kernel.project_dir').'/'.$this->getParameter('web_path').'/users/'.$directoryPath);
  108.                 mkdir($this->getParameter('kernel.project_dir').'/'.$this->getParameter('web_path').'/users/'.$directoryPath.'/personal_documents/');
  109.                 $user->setDirectoryPath($directoryPath);
  110.                 // PERSISTO
  111.                 $em->persist($user);
  112.                 $em->flush();
  113.                 // PROFILO
  114.                 $profile = new Profile();
  115.                 $profile->setUser($user);
  116.                 $em->persist($profile);
  117.                 // PRIVACY
  118.                 $date = new \DateTime();
  119.                 $privacy = new Privacy();
  120.                 $privacy->setUser($user);
  121.                 $privacy->setIsTermsAccepted(true);
  122.                 $privacy->setIsNewsAccepted($form->get('news')->getData());
  123.                 $privacy->setLastUpdateDateTime($date);
  124.                 $em->persist($privacy);
  125.                 $em->flush();
  126.                 
  127.                 $message = (new TemplatedEmail())
  128.                     ->from($this->getParameter('sender_email'))
  129.                     ->to($user->getEmail())
  130.                     ->subject($this->getParameter('object_registration'))
  131.                     ->htmlTemplate('email/account_activation.html.twig')
  132.                     ->context([
  133.                         'user' => $user
  134.                     ]);
  135.                 $mailer->send($message);
  136.                     
  137.                 $this->addFlash('notice_success'"Registrazione completata. Riceverai una e-mail per l'attivazione all'indirizzo email inserito.");
  138.                 $registerTab false;
  139.             }
  140.         }
  141.         return $this->render('default/index.html.twig', array(
  142.             'last_username' => $lastUsername,
  143.             'error' => $error,
  144.             'form' => $form->createView(),
  145.             'registerTab' => $registerTab
  146.         ));
  147.     }
  148.     
  149.     /**
  150.      * @Route("/recupera-password", name="password_recovery")
  151.      */
  152.     public function passwordRecovery(Request $requestMailerInterface $mailer)
  153.     {
  154.         $em $this->mr->getManager();
  155.         $user $em->getRepository('App\Entity\User')->findOneByEmail($request->request->get('recovery'));
  156.                 
  157.         if(!$user){
  158.             $this->addFlash('notice_warning'"L'e-mail inserita non รจ associata a nessun account");
  159.         }
  160.         else{
  161.             $user->setOneTimeCode(md5(uniqid()));
  162.             $user->setExpirationOneTimeCode(new \Datetime());
  163.             
  164.             $em->persist($user);
  165.             $em->flush();
  166.                 
  167.             $message = (new TemplatedEmail())
  168.                 ->from($this->getParameter('sender_email'))
  169.                 ->to($user->getEmail())
  170.                 ->subject($this->getParameter('object_recovery'))
  171.                 ->htmlTemplate('email/password_recovery.html.twig')
  172.                 ->context([
  173.                     'user' => $user
  174.                 ]);
  175.             $mailer->send($message);
  176.             $this->addFlash('notice_success'"Ti รจ stata inviata una email per creare la tua nuova password");
  177.         }
  178.         return $this->redirect($request->server->get('HTTP_REFERER'));
  179.     }
  180.     
  181.     /**
  182.      * @Route("/attiva/{oneTimeCode}", name="registration_activation", requirements={"oneTimeCode" = "[\w\d]{32}"})
  183.      */
  184.     public function registrationActivation(Request $request$oneTimeCode)
  185.     {
  186.         $this->get('security.token_storage')->setToken(null);
  187.         $em $this->mr->getManager();
  188.         
  189.         $user $em->getRepository('App\Entity\User')->findOneBy(array('oneTimeCode' => $oneTimeCode));
  190.     
  191.         if(!$user)
  192.             $this->addFlash('notice_danger'"Nessun account corrisponde al codice inserito");
  193.         else if($user->isIsActive() == 1)
  194.             $this->addFlash('notice_warning'"L'account รจ giร  stato attivato con successo");
  195.         else{
  196.             $user->setIsActive(1);
  197.             $em->flush();
  198.             $this->addFlash('notice_success'"L'Account รจ stato attivato con successo");
  199.         }
  200.         return $this->redirectToRoute('homepage');
  201.     }
  202.     
  203.     /**
  204.      * @Route("/crea-password/{oneTimeCode}", name="password_creation", requirements={"oneTimeCode" = "[\w\d]{32}"})
  205.      */
  206.     public function passwordCreation(Request $requestUserPasswordHasherInterface $passwordHasher$oneTimeCode)
  207.     {
  208.         $em $this->mr->getManager();
  209.         
  210.         $user $em->getRepository('App\Entity\User')->findOneBy(array('oneTimeCode' => $oneTimeCode));
  211.         $now = new \DateTime('now');
  212.         $expiration date($now->format("YmdHis"), strtotime('+3 hours'));
  213.         if($user->getExpirationOneTimeCode() != null){
  214.             if($expiration $user->getExpirationOneTimeCode()->format("YmdHis")){
  215.                 $form $this->createForm(PasswordCreationType::class, $user);
  216.                 $form->handleRequest($request);
  217.                 if($form->isSubmitted()){
  218.                     $valid true;
  219.                     if($form->get('password')->getData() != null){
  220.                         $psw $form->get('password')->getData();
  221.                         $count 0;
  222.                         if(preg_match('/[0-9]/'$psw)) $count++;
  223.                         if(preg_match('/[a-z]/'$psw)) $count++;
  224.                         if(preg_match('/[A-Z]/'$psw)) $count++;
  225.                         if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/'$psw)) $count++;
  226.                         if($count 3)
  227.                         {
  228.                             $form->get('password')->addError(new FormError("Inserisci una password resistente."));
  229.                             $valid false;
  230.                         }
  231.                     }
  232.                     if($valid && $form->isValid()){
  233.                         $password $passwordHasher->hashPassword($user$form->get("password")->getData());
  234.                         $user->setPassword($password);
  235.                         $user->setIsActive(1);
  236.                         $em->flush();
  237.                     
  238.                         $this->addFlash('notice_success'"La nuova password รจ stata creata correttamente");
  239.                         return $this->redirectToRoute("homepage");
  240.                     }
  241.                 }
  242.                 
  243.                 return $this->render('default/create_password.html.twig', array(
  244.                     'oneTimeCode' => $oneTimeCode,
  245.                     'form' => $form->createView()
  246.                 ));
  247.             }
  248.             else{
  249.                 $this->addFlash('notice_warning'"Il cambio password deve avvenire entro 3 ore dalla richiesta.<br> Per modificare la password, effettuare una nuova richiesta.");
  250.                 return $this->redirectToRoute("homepage");
  251.             }
  252.         }
  253.         else{
  254.             $form $this->createForm(PasswordCreationType::class, $user);
  255.             $form->handleRequest($request);
  256.             if($form->isSubmitted()){
  257.                 $valid true;
  258.                 if($form->get('password')->getData() != null){
  259.                     $psw $form->get('password')->getData();
  260.                     $count 0;
  261.                     if(preg_match('/[0-9]/'$psw)) $count++;
  262.                     if(preg_match('/[a-z]/'$psw)) $count++;
  263.                     if(preg_match('/[A-Z]/'$psw)) $count++;
  264.                     if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/'$psw)) $count++;
  265.                     if($count 3)
  266.                     {
  267.                         $form->get('password')->addError(new FormError("Inserisci una password resistente. Per maggiori informazioni clicca sulla parola verde RESISTENTE"));
  268.                         $valid false;
  269.                     }
  270.                 }
  271.                 if($valid && $form->isValid()){
  272.                     $password $passwordHasher->hashPassword($user$form->get("password")->getData());
  273.                     
  274.                     $user->setPassword($password);
  275.                     $user->setIsActive(1);
  276.                     $em->flush();
  277.                 
  278.                     $this->addFlash('notice_success'"La nuova password รจ stata creata correttamente");
  279.                     return $this->redirectToRoute("homepage");
  280.                 }
  281.             }
  282.             
  283.             return $this->render('default/create_password.html.twig', array(
  284.                 'oneTimeCode' => $oneTimeCode,
  285.                 'form' => $form->createView()
  286.             ));
  287.         }
  288.     }
  289.     /**
  290.      * @Route("/cookie", name="cookies")
  291.      */
  292.     public function cookies(Request $request)
  293.     {
  294.         return $this->render('default/cookies.html.twig');
  295.     }
  296.     
  297.     /**
  298.     * @Route("/aggiorna-comuni", name="update_cities")
  299.     */
  300.     public function updateCities(Request $request)
  301.     {
  302.         $em $this->mr->getManager();
  303.         $name $request->request->get('name');
  304.         $cities $em->getRepository("App\Entity\City")->findByName($name);
  305.         $serializer $this->container->get('serializer');
  306.         $jsonCities $serializer->serialize($cities'json');
  307.         $response = array("code" => 100"success" => true"cities" => $jsonCities);
  308.         return new Response(json_encode($response));
  309.     }
  310.     
  311.     /**
  312.     * @Route("/aggiungi-concorrente", name="add_competitor")
  313.     */
  314.     public function addCompetitor(Request $request)
  315.     {
  316.         $em $this->mr->getManager();
  317.         $value $request->request->get('value');
  318.         $competitor = new Competitor();
  319.         $competitor->setValue($value);
  320.         $em->persist($competitor);
  321.         $em->flush();
  322.         $response = array("code" => 100"success" => true"id" => $competitor->getId());
  323.         return new Response(json_encode($response));
  324.     }
  325.     
  326.     /**
  327.     * @Route("/aggiorna-concorrenti", name="update_competitors")
  328.     */
  329.     public function updateCompetitors(Request $request)
  330.     {
  331.         $em $this->mr->getManager();
  332.         $value $request->request->get('value');
  333.         $competitors $em->getRepository("App\Entity\Competitor")->findAllByValue($value);
  334.         $first true;
  335.         $json '[';
  336.         foreach($competitors as $c){
  337.             if($first)
  338.                 $first false;
  339.             else
  340.                 $json .= ',';                
  341.     
  342.             $json .= '{ "id":'.$c->getId().', "value":'.json_encode($c->getValue()).'}';
  343.         }
  344.         $json .= ']';
  345.         $response = array("code" => 100"success" => true"competitors" => $json);
  346.         return new Response(json_encode($response));
  347.     }
  348.     /**
  349.     * @Route("/aggiorna-referenti", name="update_referents")
  350.     */
  351.     public function updateReferents(Request $request)
  352.     {
  353.         $em $this->mr->getManager();
  354.         $filterSurname $request->request->get('filterSurname');
  355.         $filterName $request->request->get('filterName');
  356.         $filterEmail $request->request->get('filterEmail');
  357.         $referents $em->getRepository("App\Entity\User")->findByAccountTypeAndSurnameAndNameAndEmail($filterSurname$filterName$filterEmail);
  358.         $refs = array();
  359.         if($filterEmail == "")
  360.             $refs $em->getRepository("App\Entity\Referent")->findBySurnameAndName($filterSurname$filterName);
  361.         $first true;
  362.         $jsonReferents '[';
  363.         foreach($referents as $referent){
  364.             if($first)
  365.                 $first false;
  366.             else
  367.                 $jsonReferents.= ',';
  368.             $jsonReferents.= '{"id":"'.$referent->getId().'", "surname":'.json_encode($referent->getSurname()).', "name":'.json_encode($referent->getName()).', "email":'.json_encode($referent->getEmail()).', "phone":'.json_encode($referent->getProfile()->getPhone()).'}';
  369.         }
  370.         $jsonReferents .= ']';
  371.         $first true;
  372.         $jsonRefs '[';
  373.         foreach($refs as $ref){
  374.             if($first)
  375.                 $first false;
  376.             else
  377.                 $jsonRefs.= ',';
  378.             $jsonRefs.= '{"id":"'.$ref->getId().'", "surname":'.json_encode($ref->getSurname()).', "name":'.json_encode($ref->getName()).', "phone":'.json_encode($ref->getPhone()).'}';
  379.         }
  380.         $jsonRefs .= ']';
  381.         $response = array("code" => 100"success" => true"referents" => $jsonReferents"refs" => $jsonRefs);
  382.         return new Response(json_encode($response));
  383.     }
  384.     /**
  385.     * @Route("/aggiorna-enti-fatturanti", name="update_hospitals")
  386.     */
  387.     public function updateHospitals(Request $request)
  388.     {
  389.         $em $this->mr->getManager();
  390.         $name $request->request->get('name');
  391.         $city $request->request->get('city');
  392.         
  393.         $hospitals $em->getRepository("App\Entity\Hospital")->findHospitalByNameAndCity($name$city);
  394.         
  395.         $first true;
  396.         $json '[';
  397.         foreach($hospitals as $hospital){
  398.             if($first)
  399.                 $first false;
  400.             else
  401.                 $json .= ',';                
  402.     
  403.             $json .= '{ "id":'.$hospital->getId().', "name":'.json_encode($hospital->getName()).', "city":'.json_encode($hospital->getCity()->getName()).', "address": '.json_encode($hospital->getAddress()).' }';
  404.         }
  405.         $json .= ']';
  406.         
  407.         $response = array("code" => 100"success" => true"hospitals" => $json);
  408.         return new Response(json_encode($response));
  409.     }
  410.     /**
  411.     * @Route("/aggiorna-strutture-sanitarie", name="update_facilities")
  412.     */
  413.     public function updateFacilities(Request $request)
  414.     {
  415.         $em $this->mr->getManager();
  416.         $name $request->request->get('name');
  417.         $city $request->request->get('city');
  418.         
  419.         $facilities $em->getRepository("App\Entity\Facility")->findFacilityByNameAndCity($name$city);
  420.         
  421.         $first true;
  422.         $json '[';
  423.         foreach($facilities as $f){
  424.             if($first)
  425.                 $first false;
  426.             else
  427.                 $json .= ',';                
  428.     
  429.             $json .= '{ "id":'.$f->getId().', "name":'.json_encode($f->getName()).', "city":'.json_encode($f->getCity()->getName()).', "address": '.json_encode($f->getAddress()).' }';
  430.         }
  431.         $json .= ']';
  432.         
  433.         $response = array("code" => 100"success" => true"facilities" => $json);
  434.         return new Response(json_encode($response));
  435.     }
  436.     /**
  437.     * @Route("/aggiorna-dipartimenti", name="update_departments")
  438.     */
  439.     public function updateDepartments(Request $request)
  440.     {
  441.         $em $this->mr->getManager();
  442.         $facilityId $request->request->get('facilityId');
  443.         $filterValue $request->request->get('value');
  444.         $departments $em->getRepository("App\Entity\Department")->findByFacilityAndDepartmentType($facilityId$filterValue);
  445.         
  446.         $first true;
  447.         $jsonDepartments '[';
  448.         foreach($departments as $department){
  449.             if($first)
  450.                 $first false;
  451.             else
  452.                 $jsonDepartments.= ',';
  453.             $jsonDepartments.= '{"id":"'.$department->getId().'", "department":'.json_encode($department->getDepartmentType()->getValue()).', "notes":'.json_encode($department->getNotes()).'}';
  454.         }
  455.         $jsonDepartments .= ']';
  456.         $response = array("code" => 100"success" => true"departments" => $jsonDepartments);
  457.         return new Response(json_encode($response));
  458.     }
  459.     /**
  460.     * @Route("/aggiorna-tipi-dipartimento", name="update_department_types")
  461.     */
  462.     public function updateDepartmentTypes(Request $request)
  463.     {
  464.         $em $this->mr->getManager();
  465.         $facilityId $request->request->get('facilityId');
  466.         $value $request->request->get('value');
  467.         
  468.         $notPairedDepartmentTypes $em->getRepository("App\Entity\DepartmentType")->findNotPairedWithFacilityFiltered($facilityId$value);
  469.         $first true;
  470.         $jsonNotPairedDepartmentTypes '[';
  471.         foreach($notPairedDepartmentTypes as $notPairedDepartmentType){
  472.             if($first)
  473.                 $first false;
  474.             else
  475.                 $jsonNotPairedDepartmentTypes.= ',';
  476.             $jsonNotPairedDepartmentTypes.= '{"id":"'.$notPairedDepartmentType->getId().'", "value":'.json_encode($notPairedDepartmentType->getValue()).'}';
  477.         }
  478.         $jsonNotPairedDepartmentTypes .= ']';
  479.     
  480.         $response = array("code" => 100"success" => true"departmentTypes" => $jsonNotPairedDepartmentTypes);
  481.         return new Response(json_encode($response));
  482.     }
  483.     /**
  484.     * @Route("/aggiorna-gruppi-ospedalieri", name="update_hospital_groups")
  485.     */
  486.     public function updateHospitalGroups(Request $request)
  487.     {
  488.         $session $request->getSession();
  489.         $name $request->request->get('name');
  490.         $em $this->mr->getManager();
  491.         $hospitalGroups $em->getRepository("App\Entity\HospitalGroup")->findByName($name);
  492.         $first true;
  493.         $json '[';
  494.         foreach($hospitalGroups as $hg){
  495.             if($first)
  496.                 $first false;
  497.             else
  498.                 $json.= ',';
  499.             $json.= '{"id":"'.$hg->getId().'", "name":'.json_encode($hg->getName()).'}';
  500.         }
  501.         $json .= ']';
  502.         $response = array("code" => 100"success" => true"hospitalGroups" => $json);
  503.         return new Response(json_encode($response));
  504.     }
  505.     
  506.     /**
  507.     * @Route("/aggiorna-esterni", name="update_users")
  508.     */
  509.     public function updateUsers(Request $request)
  510.     {
  511.         $em $this->mr->getManager();
  512.         $value $request->request->get('value');
  513.         
  514.         $users $em->getRepository("App\Entity\User")->findExternalsBySurnameAndNameAndEmailAndPhone($value);
  515.         $first true;
  516.         $jsonUsers '[';
  517.         foreach($users as $u){
  518.             if($first)
  519.                 $first false;
  520.             else
  521.                 $jsonUsers.= ',';
  522.             $jsonUsers.= '{"id":"'.$u->getId().'", "surname":'.json_encode($u->getSurname()).', "name":'.json_encode($u->getName()).', "email":'.json_encode($u->getEmail()).', "phone":'.json_encode($u->getProfile()->getPhone()).'}';
  523.         }
  524.         $jsonUsers .= ']';
  525.     
  526.         $response = array("code" => 100"success" => true"users" => $jsonUsers);
  527.         return new Response(json_encode($response));
  528.     }
  529.     /**
  530.      * @Route("/aiuto", name="help")
  531.      */
  532.     public function help(Request $request)
  533.     {
  534.         $em $this->mr->getManager();
  535.         $slug $request->request->get('slug');
  536.         $help $em->getRepository("App\Entity\Help")->findOneBySlug($slug);
  537.         $response = array("code" => 100"success" => true"title" => $help->getTitle(), "text" => $help->getText());
  538.         return new Response(json_encode($response)); 
  539.     }
  540.     
  541.     /**
  542.      * @Route("/logout", name="logout")
  543.      */
  544.     public function logout()
  545.     {
  546.         
  547.     }
  548. }