src/Controller/HomeController.php line 79

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Repository\EmailInvoiceRepository;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  8. use Symfony\Component\HttpFoundation\StreamedResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use App\Repository\UsersRepository;
  13. use App\Repository\ArticlesRepository;
  14. use App\Repository\InvoiceDownloadsRepository;
  15. use App\Repository\InvoiceRepository;
  16. use App\Service\S3Service;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use DateTime;
  19. use App\Service\MailerService;
  20. use App\Entity\Users;
  21. class HomeController extends AbstractController
  22. {
  23.     private $mailerService;
  24.     /**
  25.      * @var Status|MailerService
  26.      */
  27.     /**
  28.      *
  29.      */
  30.     public function __construct(
  31.         UsersRepository $usersRepository,
  32.         UserPasswordHasherInterface $passwordEncoder,
  33.         EntityManagerInterface $em,
  34.         MailerService $mailerService,
  35.         ArticlesRepository $articlesRepository,
  36.         InvoiceDownloadsRepository $invoiceDownloadsRepository,
  37.         InvoiceRepository $invoiceRepository,
  38.         S3Service $s3Service,
  39.         EmailInvoiceRepository $emailInvoiceRepository
  40.     )
  41.     {
  42.         $this->usersRepository $usersRepository;
  43.         $this->mailerService $mailerService;
  44.         $this->passwordEncoder $passwordEncoder;
  45.         $this->em $em;
  46.         $this->articlesRepository $articlesRepository;
  47.         $this->invoiceDownloadsRepository $invoiceDownloadsRepository;
  48.         $this->invoiceRepository $invoiceRepository;
  49.         $this->s3Service $s3Service;
  50.         $this->emailInvoiceRepository $emailInvoiceRepository;
  51.     }
  52.     /**
  53.      * @Route("/", name="index")
  54.      */
  55.     public function index(): Response
  56.     {
  57.         return $this->redirectToRoute('admin_index');
  58. //        return $this->render('admin/base.html.twig');
  59.     }
  60.     /**
  61.      * @Route("/login-d", name="login")
  62.      */
  63.     public function login(): Response
  64.     {
  65.         return $this->render('login.html.twig');
  66.     }
  67.     /**
  68.      * @Route("/recover-pw", name="recover_pw")
  69.      */
  70.     public function recoverPw(): Response
  71.     {
  72.         return $this->render('recoverpw.html.twig');
  73.     }
  74.     /**
  75.      * @Route("/pdf-news-full", name="admin_pdf_news_full")
  76.      */
  77.     public function pdfNewsFull(): Response
  78.     {
  79.         return $this->render('PDF_Full.html.twig');
  80.     }
  81.     /**
  82.      * @Route("/reset-pw/{token}", name="reset_pw")
  83.      */
  84.     public function resetPw($token): Response
  85.     {
  86.         return $this->render('resetpw.html.twig', ['token' => $token]);
  87.     }
  88.     /**
  89.      * @Route("/password-generate-code", name="password_generate_code")
  90.      */
  91.     public function passwordGenerateCode(Request $request): Response
  92.     {
  93.         $user $this->usersRepository->findOneBy(['email'=>$request->get('email'), 'deleted'=>false]);
  94.         $random random_int(10009999);
  95.         $date = new DateTime();
  96.         if ($user !== null) {
  97.             $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  98.             $charactersLength strlen($characters);
  99.             $token1 '';
  100.             $token2'';
  101.             for ($i 0$i 5$i++) {
  102.                 $token1 .= $characters[rand(0$charactersLength 1)];
  103.             }
  104.             for ($i 0$i 5$i++) {
  105.                 $token2 .= $characters[rand(0$charactersLength 1)];
  106.             }
  107.             $token $token1 $user->getId() . $token2;
  108.             $user->setNewPasswordToken($token);
  109.             $user->setNewPasswordCode($random);
  110.             $user->setNewPasswordCreatedAt($date);
  111.             $this->em->persist($user);
  112.             $this->em->flush();
  113.             $params = [
  114.                 'code' => $random
  115.             ];
  116.             $this->mailerService->load(
  117.                 $params,
  118.                 'd-bc246c84331d4d749634ac496a62751a',
  119.                 $user
  120.             );
  121.             return new JsonResponse([
  122.                 'data'=>[
  123.                     'text'=>'success',
  124.                     'token' => $user->getNewPasswordToken()
  125.                 ]
  126.             ]);
  127.         }
  128.         else{
  129.             return new JsonResponse([
  130.                 'data'=>[
  131.                     'text'=>'error'
  132.                 ]
  133.             ]);
  134.         }
  135.     }
  136.     /**
  137.      * @Route("/email-verification/{token}", name="email_verification")
  138.      */
  139.     public function emailVerification($token): Response
  140.     {
  141.         $user $this->usersRepository->findOneBy(['emailValidationToken'=>$token]);
  142.         if($user){
  143.             $user->setEmailValidated(true);
  144.             $this->em->persist($user);
  145.             $this->em->flush();
  146.             return $this->render('verified-email.html.twig',[
  147.                 'text1' => "Votre email a été bien verifié",
  148.                 'text2' => "Merci !",
  149.             ]);        }
  150.         else{
  151.             return $this->render('verified-email.html.twig',[
  152.                 'text1' => "Erreur lors de la vérification de votre email",
  153.                 'text2' => "Veuillez réessayer...",
  154.             ]);
  155.         }
  156.     }
  157.     /**
  158.      * @Route("/recover-pw-confirm/{token}", name="recover_pw_confirm")
  159.      */
  160.     public function recoverPwConfirm($token): Response
  161.     {
  162.         return $this->render('recoverpw-confirm.html.twig', ['token'=>$token]);
  163.     }
  164.     /**
  165.      * @Route("/recover-pw-verify-code", name="recover_pw_verify-code")
  166.      */
  167.     public function recoverPwVerifyCode(Request $request): Response
  168.     {
  169.         $user $this->usersRepository->findOneBy(['newPasswordToken'=>$request->get('token'), 'deleted' => false]);
  170.         $paswordTime=$user->getNewPasswordCreatedAt();
  171.         $date = new DateTime();
  172.         $timeNow $date;
  173.         $diff date_diff($timeNow$paswordTime);
  174.         if($diff->format('%h%i') < 11){
  175.             if($user->getNewPasswordCode() == $request->get('code')){
  176.                 return new JsonResponse(['comment' => 'code ok'], Response::HTTP_OK);
  177.             }
  178.             else{
  179.                 return new JsonResponse(['comment' => 'wrong code'], Response::HTTP_BAD_REQUEST);
  180.             }
  181.         }
  182.         return new JsonResponse(['comment' => 'user not found'], Response::HTTP_FORBIDDEN);
  183.     }
  184.     /**
  185.      * @Route("/password-generate-new", name="password_generate_new")
  186.      */
  187.     public function passwordGenerateNew(Request $request): Response
  188.     {
  189.         $user $this->usersRepository->findOneBy(['newPasswordToken'=>$request->get('token'), 'deleted' => false]);
  190.         $user->setPassword($this->passwordEncoder->hashPassword($user$request->get('password')));
  191.         $user->setNewPasswordToken(NULL);
  192.         $this->em->persist($user);
  193.         $this->em->flush();
  194.         return new JsonResponse(['comment' => 'password update'], Response::HTTP_OK);
  195.     }
  196.     /**
  197.      * @Route("/download-invoice-range/{id}/{token}", name="downalod_invoice_range")
  198.      */
  199.     public function downlaodInvoiceRange(int $idstring $token): Response
  200.     {
  201.         $invoiceDownload $this->invoiceDownloadsRepository->find($id);
  202.         if (!$invoiceDownload)
  203.             return new Response('Invoices not found'Response::HTTP_NOT_FOUND);
  204.         else if ($invoiceDownload->getToken() !== $token)
  205.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  206.         else if ($invoiceDownload->isDeleted())
  207.             return new Response('This link expired'Response::HTTP_UNAUTHORIZED);
  208.         $link $_ENV['DOMAIN_EMAIL'] . "download-zip-invoices/" $invoiceDownload->getId() . "/" $invoiceDownload->getToken();
  209.         return $this->render('downloadInvoices.html.twig', [
  210.             "range" => true,
  211.             "link" => $link
  212.         ]);
  213.     }
  214.     /**
  215.      * @Route("download-invoice/{id}/{token}", name="download_invoice")
  216.      */
  217.     public function downloadInvoice(int $idstring $token): Response
  218.     {
  219.         $emailInvoice $this->emailInvoiceRepository->find($id);
  220.         if (!$emailInvoice)
  221.             return new Response('Invoice not found'Response::HTTP_NOT_FOUND);
  222.         else if ($emailInvoice->getToken() !== $token)
  223.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  224.         else if ($emailInvoice->isDeleted())
  225.             return new Response('No pdf file found for this invoice.'Response::HTTP_NOT_FOUND);
  226.         else if (!$emailInvoice->getInvoice()->getPdfName())
  227.             return new Response('No pdf file found for this invoice.'Response::HTTP_NOT_FOUND);
  228.         $link $_ENV['DOMAIN_EMAIL'] . "download-pdf-invoice/" $emailInvoice->getId() . "/" $emailInvoice->getToken();
  229.         return $this->render('downloadInvoices.html.twig', [
  230.             "range" => false,
  231.             "link" => $link
  232.         ]);
  233.     }
  234.     /**
  235.      * @Route("/download-zip-invoices/{id}/{token}", name="download_zip_invoices")
  236.      */
  237.     public function downloadZipInvoices(int $idstring $token): Response
  238.     {
  239.         $invoiceDownload $this->invoiceDownloadsRepository->find($id);
  240.         if (!$invoiceDownload)
  241.             return new Response('Invoices not found'Response::HTTP_NOT_FOUND);
  242.         else if ($invoiceDownload->getToken() !== $token)
  243.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  244.         else if ($invoiceDownload->isDeleted())
  245.             return new Response('This link expired'Response::HTTP_UNAUTHORIZED);
  246.         $invoices $this->invoiceRepository->findInvoicesBetween(
  247.             $invoiceDownload->getEstablishment(),
  248.             $invoiceDownload->getStartDate(),
  249.             $invoiceDownload->getEndDate()
  250.         );
  251.         $invoices array_filter($invoices, function ($invoice) {
  252.             return $invoice->getPdfName();
  253.         });
  254.         $zipFilePath tempnam(sys_get_temp_dir(), 'invoices_zip');
  255.         $zip = new \ZipArchive();
  256.         if ($zip->open($zipFilePath, \ZipArchive::CREATE) === true)
  257.         {
  258.             foreach ($invoices as $invoice)
  259.             {
  260.                 $invoiceUrl $this->s3Service->getViewInvoice($invoice->getPdfName());
  261.                 $pdfContent file_get_contents($invoiceUrl);
  262.                 if ($pdfContent !== false)
  263.                     $zip->addFromString("invoice_{$invoice->getIdPunch()}.pdf"$pdfContent);
  264.             }
  265.             $zip->close();
  266.         }
  267.         $response = new BinaryFileResponse($zipFilePath);
  268.         $response->headers->set('Content-Type''application/zip');
  269.         $response->headers->set('Content-Disposition''attachment; filename="invoices.zip"');
  270.         return $response;
  271.     }
  272.     /**
  273.      * @Route ("/download-pdf-invoice/{id}/{token}", name="download_pdf_invoice")
  274.      */
  275.     public function downloadPdfInvoice(int $idstring $token): Response
  276.     {
  277.         $emailInvoice $this->emailInvoiceRepository->find($id);
  278.         if (!$emailInvoice)
  279.             return new Response('Invoice not found'Response::HTTP_NOT_FOUND);
  280.         else if ($emailInvoice->getToken() !== $token)
  281.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  282.         else if ($emailInvoice->isDeleted())
  283.             return new Response('This link expired'Response::HTTP_UNAUTHORIZED);
  284.         else if (!$emailInvoice->getInvoice()->getPdfName())
  285.             return new Response('No pdf file found for this invoice.'Response::HTTP_NOT_FOUND);
  286.         $invoice $emailInvoice->getInvoice();
  287.         $invoiceUrl $this->s3Service->getViewInvoice($invoice->getPdfName());
  288.         $response = new StreamedResponse(function () use ($invoiceUrl) {
  289.             readfile($invoiceUrl);
  290.         });
  291.         $response->headers->set('Content-Type''application/pdf');
  292.         $response->headers->set('Content-Disposition''attachment; filename="invoice_' $invoice->getIdPunch() . '.pdf"');
  293.         return $response;
  294.     }
  295. }