src/Controller/Advertiser/Generic/GenericDefaultController.php line 161

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Advertiser\Generic;
  3. use App\Controller\AbstractClass\AbstractDefaultController;
  4. use App\Controller\Endpoint\DefaultController;
  5. use App\Entity\Advertiser;
  6. use App\Entity\Export;
  7. use App\Entity\News;
  8. use App\Entity\OperationFamily;
  9. use App\Entity\User;
  10. use App\Form\LoginFom;
  11. use App\Form\LostPasswordForm;
  12. use App\Repository\UserRepository;
  13. use App\Service\Access;
  14. use App\Service\AdvertisingManagement;
  15. use App\Service\ContentService;
  16. use App\Service\DataLogger;
  17. use App\Service\EmailService;
  18. use App\Service\Language;
  19. use App\Service\User as UserService;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\RequestStack;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  25. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  26. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  27. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  28. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  29. use Symfony\Component\Routing\RouterInterface;
  30. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  31. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  32. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  33. /**
  34.  * Class DefaultController
  35.  */
  36. class GenericDefaultController extends AbstractDefaultController
  37. {
  38.     private DataLogger $logger;
  39.     private Request $request;
  40.     // private RequestStack $requestStack;
  41.     public function __construct(RequestStack $requestStackDataLogger $dataLogger)
  42.     {
  43.         // $this->requestStack = $requestStack;
  44.         $this->logger $dataLogger;
  45.         $this->request $requestStack->getMainRequest();
  46.     }
  47.     /**
  48.      * @throws \Exception
  49.      */
  50.     public function index(Access $accessAdvertisingManagement $advertiserServiceContentService $contentServiceEntityManagerInterface $em): Response
  51.     {
  52.         $access->check('view'null);
  53.         $user $this->getUser();
  54.         $advertiser $advertiserService->getCurrentAdvertiser();
  55.         $homepage $contentService->getHomepage($advertiser);
  56.         $operationFamilies $em->getRepository(OperationFamily::class)->findBy([
  57.             'advertiser' => $advertiser,
  58.             'status'     => true,
  59.         ]);
  60.         $newsList = [];
  61.         if (!empty($operationFamilies)) {
  62.             foreach ($operationFamilies as $key => $operationFamily) {
  63.                 $familyNews $em->getRepository(News::class)->findBy(
  64.                     [
  65.                         'operationFamily' => $operationFamily,
  66.                         'status'          => true,
  67.                     ],
  68.                     ['createdAt' => 'DESC'],
  69.                     2
  70.                 );
  71.                 if (!empty($familyNews)) {
  72.                     $newsList array_merge($newsList$familyNews);
  73.                 }
  74.             }
  75.         }
  76.         return $this->render('homepage/show.html.twig', [
  77.             'homepage'          => $homepage,
  78.             'newsList'          => $newsList,
  79.         ]);
  80.     }
  81.     /**
  82.      * @throws \Exception
  83.      */
  84.     public function login(AuthenticationUtils $authenticationUtilsAdvertisingManagement $advertiserServiceUserService $userServiceUserPasswordHasherInterface $userPasswordHasherInterfaceRouterInterface $routerServiceTokenStorageInterface $tokenStorage): Response
  85.     {
  86.         if ($this->isGranted('ROLE_USER')) {
  87.             return $this->redirectToRoute('index');
  88.         }
  89.         $error $authenticationUtils->getLastAuthenticationError();
  90.         $lastUsername $authenticationUtils->getLastUsername();
  91.         $this->logger->add('Visualisation de la page login/'nullnull'info');
  92.         $advertiserData = [];
  93.         $currentAdvertiser $advertiserService->getCurrentAdvertiser();
  94.         if ($currentAdvertiser instanceof Advertiser) {
  95.             $advertiserData = [
  96.                 'logo'        => '/uploads/logos/' $currentAdvertiser->getLogo(),
  97.                 'name'        => $currentAdvertiser->getTitle(),
  98.                 'firstColor'  => $currentAdvertiser->getFirstColor(),
  99.                 'secondColor' => $currentAdvertiser->getSecondColor(),
  100.             ];
  101.         }
  102.         $goTo '/';
  103.         $gotoSessionValue $this->request->getSession()->get('rgoto');
  104.         if (!empty($gotoSessionValue) && !filter_var($gotoSessionValueFILTER_VALIDATE_URL)) {
  105.             $goTo $gotoSessionValue;
  106.         }
  107.         $form $this->createForm(LoginFom::class);
  108.         $form->handleRequest($this->request);
  109.         if ($form->isSubmitted() && $form->isValid()) {
  110.             $error 'Aucun compte ne correspond à ces identifiants.';
  111.             $datas $form->getData();
  112.             $login $datas['username'];
  113.             $password $datas['password'];
  114.             $user $userService->getUserByLogin($currentAdvertiser$login);
  115.             if ($user instanceof User) {
  116.                 if ($userPasswordHasherInterface->isPasswordValid($user$password)) {
  117.                     // Manually authenticate user in controller
  118.                     // $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
  119.                     $token = new UsernamePasswordToken($user'main'$user->getRoles());
  120.                     $tokenStorage->setToken($token);
  121.                     $this->request->getSession()->set('_security_main'serialize($token));
  122.                     return $this->redirect($goTo);
  123.                 }
  124.             }
  125.         }
  126.         return $this->render('default/login.html.twig', [
  127.             'form'           => $form->createView(),
  128.             'last_username'  => $lastUsername,
  129.             'error'          => $error,
  130.             'advertiserData' => $advertiserData,
  131.         ]);
  132.     }
  133.     /**
  134.      * @throws \Exception
  135.      */
  136.     public function logout(): Response
  137.     {
  138.         $user $this->getUser();
  139.         $this->logger->add('Déconnexion'$user instanceof User $user->getId() : 0null'info');
  140.         $this->request->getSession()->clear();
  141.         return $this->redirectToRoute('login');
  142.     }
  143.     /**
  144.      * @throws \Exception
  145.      */
  146.     public function lostpassword(UserRepository $repositoryEmailService $emailServiceEntityManagerInterface $em): Response
  147.     {
  148.         $form $this->createForm(LostPasswordForm::class);
  149.         $form->handleRequest($this->request);
  150.         $msg '';
  151.         $this->logger->add('Visualisation de la page lostpassword/'nullnull'info');
  152.         if ($form->isSubmitted() && $form->isValid()) {
  153.             $datas $form->getData();
  154.             $user $repository->findByEmail($datas['email']);
  155.             if (null !== $user) {
  156.                 $token uniqid();
  157.                 $user->setlastToken($token);
  158.                 $em->flush();
  159.                 $this->logger->add('Demande de mot de passe par un utilisateur'$user->getId(), null'info');
  160.                 $url $this->request->getScheme() . '://' $this->request->getHost() . $this->generateUrl('user_resetpassword', ['token' => $user->getToken()]);
  161.                 $to $user->getEmail();
  162.                 $mailBody $this->render('emails/lostpassword.html.twig', [
  163.                     'firstname' => $user->getFirstname(),
  164.                     'lastname'  => $user->getLastname(),
  165.                     'url'       => $url,
  166.                 ]);
  167.                 $mailPart $this->render('emails/lostpassword.txt.twig', [
  168.                     'firstname' => $user->getFirstname(),
  169.                     'lastname'  => $user->getLastname(),
  170.                     'url'       => $url,
  171.                 ]);
  172.                 $params = [
  173.                     'part' => $mailPart,
  174.                     'type' => 'lostpassword',
  175.                 ];
  176.                 $emailService->send('Lost Password''no-reply@staci-animations.com'$to$mailBody$params);
  177.             }
  178.             $msg 'SENT';
  179.         }
  180.         return $this->render('default/lostpassword.html.twig', [
  181.             'form' => $form->createView(),
  182.             'msg'  => $msg,
  183.         ]);
  184.     }
  185.     /**
  186.      * @throws \Exception
  187.      */
  188.     public function download(Access $accessEntityManagerInterface $emAdvertisingManagement $advertiserService): Response
  189.     {
  190.         $access->check('view'null);
  191.         $exportType = [
  192.             'Commandes',
  193.             'Report',
  194.             'Quota',
  195.             'Commandes',
  196.             'Report',
  197.             'Quota',
  198.             'Commandes',
  199.             'Report',
  200.             'Quota',
  201.         ];
  202.         $exportStatus = [
  203.             'en attente',
  204.             'en cours',
  205.             'fini',
  206.             'erreur',
  207.         ];
  208.         $currentAdvertiser $advertiserService->getCurrentAdvertiser();
  209.         $downloads $em->getRepository(Export::class)->findBy([
  210.             'user'       => $this->getUser(),
  211.             'advertiser' => $currentAdvertiser,
  212.         ]);
  213.         $downloadArray = [];
  214.         foreach ($downloads as $download) {
  215.             $downloadArray[] = [
  216.                 'uuid'   => $download->getUuid(),
  217.                 'type'   => $exportType[$download->getType()],
  218.                 'date'   => !empty($download->getDate()) ? date('d-m-Y H:i'$download->getDate()) : '',
  219.                 'start'  => !empty($download->getStartedAt()) ? date('d-m-Y H:i'$download->getStartedAt()) : '',
  220.                 'end'    => !empty($download->getEndedAt()) ? date('d-m-Y H:i'$download->getEndedAt()) : '',
  221.                 'status' => $exportStatus[$download->getStatus()],
  222.                 'file'   => $download->getFile(),
  223.             ];
  224.         }
  225.         return $this->render('default/download.html.twig', [
  226.             'downloadArray' => $downloadArray,
  227.         ]);
  228.     }
  229.     /**
  230.      * @throws \Exception
  231.      */
  232.     public function downloadFile(EntityManagerInterface $emAccess $accessstring $uuid): Response
  233.     {
  234.         $access->check('view'null);
  235.         $file $em->getRepository(Export::class)->findOneBy([
  236.             'uuid' => $uuid,
  237.         ]);
  238.         if ($file instanceof Export && $file->getUser() === $this->getUser()) {
  239.             return $this->file(__DIR__ '/../../../../var/exports/' $file->getFile(), $file->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  240.         }
  241.         return new Response('<html><body></body></html>');
  242.     }
  243.     public function admin(): Response
  244.     {
  245.         return new Response('<html><body>Admin page!</body></html>');
  246.     }
  247.     public function switchLanguage(Language $languageUrlMatcherInterface $urlMatcher): Response
  248.     {
  249.         $currentLanguage $language->getLanguage();
  250.         $newlanguage $this->request->query->get('switch-language'$currentLanguage);
  251.         if ($currentLanguage !== $newlanguage) {
  252.             $language->setLanguage($newlanguage);
  253.         }
  254.         return $this->redirectToRoute($this->getRefererRoute($urlMatcher));
  255.     }
  256.     private function getRefererRoute(UrlMatcherInterface $urlMatcher): string
  257.     {
  258.         $referer $this->request->headers->get('referer');
  259.         $lastPath substr($referer\strlen($this->request->getScheme() . '://'));
  260.         $lastPath substr($lastPath, (int) strpos($lastPath'/'));
  261.         try {
  262.             $parameters $urlMatcher->match($lastPath);
  263.             return $parameters['_route'];
  264.         } catch (ResourceNotFoundException|MethodNotAllowedException) {
  265.             return 'index';
  266.         }
  267.     }
  268. }