src/Controller/FrontController.php line 330

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: Mamy
  5.  * Date: 25/11/2019
  6.  * Time: 14:59
  7.  */
  8. namespace App\Controller;
  9. use App\Entity\Logo;
  10. use App\Entity\Offer;
  11. use App\Entity\Slider;
  12. use App\Entity\Video;
  13. use App\Kernel;
  14. use App\Service\APIRequestService;
  15. use App\Service\Taggage;
  16. use App\Service\Tools;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  19. use Symfony\Component\HttpFoundation\RedirectResponse;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  24. use Symfony\Component\Mime\FileinfoMimeTypeGuesser;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. use Symfony\Component\HttpClient\HttpClient;
  27. use App\Service\Mailer;
  28. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  29. use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
  30. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  31. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  32. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  33. use Symfony\Contracts\HttpClient\ResponseInterface;
  34. class FrontController extends AbstractController
  35. {
  36.     /**
  37.      * Home
  38.      * @Route("/", name="home", methods={"GET"})
  39.      * @param Tools $tools
  40.      * @return Response
  41.      * @throws ClientExceptionInterface
  42.      * @throws DecodingExceptionInterface
  43.      * @throws RedirectionExceptionInterface
  44.      * @throws ServerExceptionInterface
  45.      * @throws TransportExceptionInterface
  46.      */
  47.     public function listCatalogs(Tools $tools)
  48.     {
  49.         $localities = ['saint-denis' => 'Saint-Denis''saint-pierre' => 'Saint-Pierre''saint-benoit' => 'Saint-Benoit''les-avirons' => 'Les Avirons''bras-panon' => 'Bras-Panon''cilaos' => 'Cilaos''entre-deux' => 'Entre-Deux''etang-salé' => 'L\'Etang-Salé''petite-ile' => 'Petite Ile''le-port' => 'Le Port''plaine-des-palmistes' => 'La Plaine des Palmistes''la-possession' => 'La Possession''saint-andré' => 'Saint-Andre''sainte-marie' => 'Sainte-Marie''sainte-rose' => 'Sainte-Rose''sainte-suzanne' => 'Sainte-Suzanne''saint-joseph' => 'Saint-Joseph''saint-leu' => 'Saint-Leu''saint-louis' => 'Saint-Louis''saint-paul' => 'Saint-Paul''saint-philippe' => 'Saint-Philippe''salazie' => 'Salazie''le-tampon' => 'Le Tampon''trois-bassins' => 'Les Trois-Bassins'];
  50.         $home = [
  51.             'brands' => [
  52.                 'brands' => []
  53.             ],
  54.             'catalogue' => [
  55.                 'title' => '',
  56.                 'localities' => []
  57.             ],
  58.             'information' => [
  59.                 'title' => '',
  60.                 'information' => ''
  61.             ],
  62.             'footer' => [
  63.                 'copyright' => [
  64.                     'text' => '',
  65.                     'tagline' => [
  66.                         'button_text' => '',
  67.                         'button_link' => ''
  68.                     ]
  69.                 ]
  70.             ]
  71.         ];
  72.         try {
  73.             $client HttpClient::create();
  74.             $response $client->request('GET'$this->getParameter('api2_url').'/home',[
  75.                 'headers' => [
  76.                     'Accept' => 'application/json',
  77.                     // 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
  78.                 ],
  79.             ]);
  80.             if ($response->getStatusCode() == 404) {
  81.                 throw $this->createNotFoundException();
  82.             }
  83.             $homes $response->toArray();
  84.             if( count($homes) ) {
  85.                 $home['catalogue'] = [
  86.                     'localities' => $localities
  87.                 ];
  88.                 $home['brands'] = $homes['Brands'];
  89.                 $home['information'] = $homes['Information'];
  90.                 $home['footer'] = [
  91.                     'copyright' => $homes['Copyright']
  92.                 ];
  93.             }
  94.         }catch(\Exception $e) {
  95.         }
  96.         $sliders $this->getDoctrine()->getRepository(Slider::class)->findBy(array(
  97.             'enabled' => true,
  98.             'page' => 'home'
  99.         ), array(
  100.             'priority' => 'ASC',
  101.             'priorityUpdatedAt' => 'DESC'
  102.         ));
  103.         foreach ($sliders as $slider) {
  104.             $url $slider->getUrl();
  105.             if(!(strpos($url"http") !== false)){
  106.                 $url "https://" $_SERVER['SERVER_NAME'] . "/" $url;
  107.                 $slider->setUrl($url);
  108.             }
  109.         }
  110.         $headerVideo $this->getDoctrine()->getRepository(Video::class)->findOneBy(array(
  111.             'enabled' => true
  112.         ), array(
  113.             'priority' => 'DESC',
  114.             'priorityUpdatedAt' => 'DESC'
  115.         ));
  116.         $logos $this->getDoctrine()->getRepository(Logo::class)->findBy(array(
  117.             'enabled' => true
  118.         ), array(
  119.             'priority' => 'ASC',
  120.             'priorityUpdatedAt' => 'DESC'
  121.         ));
  122.         $videos $this->getDoctrine()->getRepository(Video::class)->findBy(array(
  123.             'enabled' => true
  124.         ), array(
  125.             'priority' => 'ASC',
  126.             'priorityUpdatedAt' => 'DESC'
  127.         ));
  128.         /* pour brand */
  129.         $brands = [];
  130.         try {
  131.             $client HttpClient::create();
  132.             $response $client->request('GET'$this->getParameter('api2_url').'/brands');
  133.             if ($response->getStatusCode() == 404) {
  134.                 throw $this->createNotFoundException();
  135.             }
  136.             $marks $response->toArray();
  137.             foreach ($marks as $mark) {
  138.                 $brands[$mark['id']] = $mark['brand_name'];
  139.             }
  140.         }catch(\Exception $e) {
  141.         }
  142.         /* pour catalog */
  143.         $catalogs = [];
  144.         try {
  145.             $client HttpClient::create();
  146.             $response $client->request('GET'$this->getParameter('api2_url').'/catalogs/actual', [
  147.                 'headers' => [
  148.                     'Accept' => 'application/json',
  149.                     // 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
  150.                 ],
  151.             ]);
  152.             if ($response->getStatusCode() == 404) {
  153.                 throw $this->createNotFoundException();
  154.             }
  155.             $catalogs $response->toArray();  
  156.             foreach ($catalogs as $idx => $catalog) {
  157.                 $endDate date('d-m'strtotime($catalog['date_end']));
  158.                 $catalogs[$idx]['slug'] = $tools->slugify($catalog['brand_name'].'-'.$endDate.'-'.$catalog['id']);
  159.             }
  160.         }catch(\Exception $e) {
  161.         }
  162.         return $this->render('front/catalog/list.html.twig', array(
  163.             'home' => $home,
  164.             'isProdURI' => $tools->isProdURI(),
  165.             'headerVideo' => $headerVideo,
  166.             'sliders' => $sliders,
  167.             'catalogs' => $catalogs,
  168.             'catalogsJson' => json_encode($catalogs),
  169.             'logos' => $logos,
  170.             'videos' => $videos,
  171.             'localities' => $localities
  172.         ));
  173.     }
  174.     /**
  175.      * List catalogs by locality
  176.      * @Route("/commune/{locality}", name="catalogs_by_locality", methods={"GET"})
  177.      * @param $locality
  178.      * @param Tools $tools
  179.      * @return Response
  180.      * @throws ClientExceptionInterface
  181.      * @throws DecodingExceptionInterface
  182.      * @throws RedirectionExceptionInterface
  183.      * @throws ServerExceptionInterface
  184.      * @throws TransportExceptionInterface
  185.      */
  186.     public function listCatalogsByLocality($localityTools $tools)
  187.     {
  188.         $localities = ['saint-denis' => 'Saint-Denis''saint-pierre' => 'Saint-Pierre''saint-benoit' => 'Saint-Benoit''les-avirons' => 'Les Avirons''bras-panon' => 'Bras-Panon''cilaos' => 'Cilaos''entre-deux' => 'Entre-Deux''etang-salé' => 'Etang Salé''petite-ile' => 'Petite Ile''le-port' => 'Le Port''plaine-des-palmistes' => 'La Plaine des Palmistes''la-possession' => 'La Possession''saint-andré' => 'Saint-Andre''sainte-marie' => 'Sainte-Marie''sainte-rose' => 'Sainte-Rose''sainte-suzanne' => 'Sainte-Suzanne''saint-joseph' => 'Saint-Joseph''saint-leu' => 'Saint-Leu''saint-louis' => 'Saint-Louis''saint-paul' => 'Saint-Paul''saint-philippe' => 'Saint-Philippe''salazie' => 'Salazie''le-tampon' => 'Le Tampon''trois-bassins' => 'Les Trois-Bassins'];
  189.         /* pour brand */
  190.         $brands = [];
  191.         try {
  192.             $client HttpClient::create();
  193.             $response $client->request('GET'$this->getParameter('api2_url').'/brands');
  194.             if ($response->getStatusCode() == 404) {
  195.                 throw $this->createNotFoundException();
  196.             }
  197.             $marks $response->toArray();
  198.             foreach ($marks as $mark) {
  199.                 $brands[$mark['id']] = $mark['brand_name'];
  200.             }
  201.         }catch(\Exception $e) {
  202.         }
  203.         // getByIdLocation
  204.         $filteredCatalogs = [];
  205.         try {
  206.             $client HttpClient::create();
  207.             $response $client->request('GET'$this->getParameter('api2_url').'/catalogs/' $localities[$locality] . '/city', [
  208.                 'headers' => [
  209.                     'Accept' => 'application/json',
  210.                     // 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
  211.                 ],
  212.             ]);
  213.             if ($response->getStatusCode() == 404) {
  214.                 throw $this->createNotFoundException();
  215.             }
  216.             $filteredCatalogs $response->toArray();
  217.             foreach ($filteredCatalogs as $idx => $catalog) {
  218.                 $endDate date('d-m'strtotime($catalog['date_end']));
  219.                 $filteredCatalogs[$idx]['slug'] = $tools->slugify($catalog['brand_name'].'-'.$endDate.'-'.$catalog['id']);
  220.             }
  221.         }catch(\Exception $e){
  222.             // perhaps a message
  223.         }
  224.         return $this->render('front/catalog/catalog-by-locality.html.twig', array(
  225.             'isProdURI' => $tools->isProdURI(),
  226.             'catalogs' => $filteredCatalogs,
  227.             'catalogsJson' => json_encode($filteredCatalogs),
  228.             'locality' => $locality,
  229.             'localities' => $localities
  230.         ));
  231. //        $pageResponse->setSharedMaxAge($this->getParameter('cache_expiration'));
  232. //        $pageResponse->headers->addCacheControlDirective('must-revalidate', true);
  233. //        return $pageResponse;
  234.     }
  235.     /**
  236.      * List catalogs
  237.      * @Route("/catalogue", name="catalog", methods={"GET"})
  238.      * @return RedirectResponse
  239.      */
  240.     public function OldListCatalog()
  241.     {
  242.         return $this->redirectToRoute('home');
  243.     }
  244.     /**
  245.      * View catalog
  246.      * @Route("/catalogue/{id}", name="catalog_view", methods={"GET"})
  247.      * @param Request $request
  248.      * @param $id
  249.      * @param Tools $tools
  250.      * @return Response
  251.      * @throws ClientExceptionInterface
  252.      * @throws DecodingExceptionInterface
  253.      * @throws RedirectionExceptionInterface
  254.      * @throws ServerExceptionInterface
  255.      * @throws TransportExceptionInterface
  256.      */
  257.     public function viewCatalog(Request $request$idTools $tools)
  258.     {
  259.         $localities = ['saint-denis' => 'Saint-Denis''saint-pierre' => 'Saint-Pierre''saint-benoit' => 'Saint-Benoit''les-avirons' => 'Les Avirons''bras-panon' => 'Bras-Panon''cilaos' => 'Cilaos''entre-deux' => 'Entre-Deux''etang-salé' => 'L\'Etang-Salé''petite-ile' => 'Petite Ile''le-port' => 'Le Port''plaine-des-palmistes' => 'La Plaine des Palmistes''la-possession' => 'La Possession''saint-andré' => 'Saint-Andre''sainte-marie' => 'Sainte-Marie''sainte-rose' => 'Sainte-Rose''sainte-suzanne' => 'Sainte-Suzanne''saint-joseph' => 'Saint-Joseph''saint-leu' => 'Saint-Leu''saint-louis' => 'Saint-Louis''saint-paul' => 'Saint-Paul''saint-philippe' => 'Saint-Philippe''salazie' => 'Salazie''le-tampon' => 'Le Tampon''trois-bassins' => 'Les Trois-Bassins'];
  260.         $offers $this->getDoctrine()->getRepository(Offer::class)->findBy(array(
  261.             'enabled' => true
  262.         ), array(
  263.             'priority' => 'ASC',
  264.             'priorityUpdatedAt' => 'DESC'
  265.         ));
  266.         $videos $this->getDoctrine()->getRepository(Video::class)->findBy(array(
  267.             'enabled' => true
  268.         ), array(
  269.             'priority' => 'ASC',
  270.             'priorityUpdatedAt' => 'DESC'
  271.         ));
  272.         /* pour brand */
  273.         $brands = [];
  274.         try {
  275.             $client HttpClient::create();
  276.             $response $client->request('GET'$this->getParameter('api2_url').'/brands');
  277.             if ($response->getStatusCode() == 404) {
  278.                 throw $this->createNotFoundException();
  279.             }
  280.             $marks $response->toArray();
  281.             foreach ($marks as $mark) {
  282.                 $brands[$mark['id']] = [
  283.                     'brand_name' => $mark['brand_name'],
  284.                     'brand_logo' => $mark['logo']
  285.                 ];
  286.             }
  287.         }catch(\Exception $e) {
  288.         }
  289.         //Get catalog ID from slug
  290.         $pathID explode('-'$id);
  291.         $cid $pathID[count($pathID) - 1];
  292.         $client HttpClient::create();
  293.         $response $client->request('GET'$this->getParameter('api2_url').'/catalogs/'.$cid.'/file', [
  294.             'headers' => [
  295.                 'Accept' => 'application/json',
  296.                 // 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
  297.             ],
  298.         ]);
  299.         if ($response->getStatusCode() == 404) {
  300.             throw $this->createNotFoundException();
  301.         }
  302.         if ($response->getStatusCode() == 500) {
  303.             throw $this->createNotFoundException();
  304.         }
  305.         $catalog $response->toArray();
  306.         $page $request->query->get('page'1);
  307.         // sector
  308.         $sectors strtolower(str_replace([' ','et'], ['',','], $catalog['brand']['category_name']));
  309.         $sectors explode(','$sectors);
  310.         $sectors array_map(function($value) use($tools) {
  311.             $value strtolower($value);
  312.             $value $tools->slugify($value);
  313.             return "secteur=$value";
  314.         }, $sectors);
  315.         return $this->render('front/catalog/detail.html.twig', array(
  316.             'isProdURI' => $tools->isProdURI(),
  317.             'catalogID' => $cid,
  318.             'catalogTitle' => $catalog['title'],
  319.             'catalogSubTitle' => '',
  320.             'catalogImage' => '',
  321.             'catalogAddresses' => $catalog['addresses'],
  322.             'catalog' => [$catalog], //$tools->sortArray($catalog, 'pageNumber'),
  323.             'catalogSlug' => $id,
  324.             'offers' => $offers,
  325.             'videos' => $videos,
  326.             'page' => $page,
  327.             'currentBreadcrumb' => ucwords($tools->slugify($catalog['title'])),
  328.             'thumbnail' => $this->getParameter('api2_url').$catalog['pages'][0]['image']['image_url'],
  329.             'announcer' => strtolower($tools->slugify($catalog['brand']['name'])),
  330.             'sector' => implode(';'$sectors)
  331.         ));
  332. //        $pageResponse->setSharedMaxAge($this->getParameter('cache_expiration'));
  333. //        $pageResponse->headers->addCacheControlDirective('must-revalidate', true);
  334. //        return $pageResponse;
  335.     }
  336.     /**
  337.      * About
  338.      * @Route("/a-propos", name="about", methods={"GET"})
  339.      * @param Tools $tools
  340.      * @return Response
  341.      * @throws ClientExceptionInterface
  342.      * @throws DecodingExceptionInterface
  343.      * @throws RedirectionExceptionInterface
  344.      * @throws ServerExceptionInterface
  345.      * @throws TransportExceptionInterface
  346.      */
  347.     public function about(Tools $tools)
  348.     {
  349.         $headerType $tools->getConfig('header-type');
  350.         $sliders = array();
  351.         $headerVideo null;
  352.         if ($headerType == 'image') {
  353.             $sliders $this->getDoctrine()->getRepository(Slider::class)->findBy(array(
  354.                 'enabled' => true
  355.             ), array(
  356.                 'priority' => 'ASC',
  357.                 'priorityUpdatedAt' => 'DESC'
  358.             ));
  359.         } else {
  360.             $headerVideo $this->getDoctrine()->getRepository(Video::class)->findOneBy(array(
  361.                 'enabled' => true
  362.             ), array(
  363.                 'priority' => 'DESC',
  364.                 'priorityUpdatedAt' => 'DESC'
  365.             ));
  366.         }
  367.         $offers $this->getDoctrine()->getRepository(Offer::class)->findBy(array(
  368.             'enabled' => true
  369.         ), array(
  370.             'priority' => 'ASC',
  371.             'priorityUpdatedAt' => 'DESC'
  372.         ));
  373.         $catalogs = [];
  374.         try {
  375.             $client HttpClient::create();
  376.             $response $client->request('GET'$this->getParameter('api2_url').'/api/catalogs');
  377.             if ($response->getStatusCode() == 404) {
  378.                 throw $this->createNotFoundException();
  379.             }
  380.             $catalogs $response->toArray();
  381.         }catch(\Exception $e){
  382.             // perhaps a message
  383.         }
  384.         $logos $this->getDoctrine()->getRepository(Logo::class)->findBy(array(
  385.             'enabled' => true
  386.         ), array(
  387.             'priority' => 'ASC',
  388.             'priorityUpdatedAt' => 'DESC'
  389.         ));
  390.         $videos $this->getDoctrine()->getRepository(Video::class)->findBy(array(
  391.             'enabled' => true
  392.         ), array(
  393.             'priority' => 'ASC',
  394.             'priorityUpdatedAt' => 'DESC'
  395.         ));
  396.         $videos600 = (count($videos) > 2) ? count($videos);
  397.         $videos1000 = (count($videos) > 3) ? count($videos);
  398.         return $this->render('front/about.html.twig', array(
  399.             'isProdURI' => $tools->isProdURI(),
  400.             'headerVideo' => $headerVideo,
  401.             'sliders' => $sliders,
  402.             'offers' => $offers,
  403.             'catalogs' => $catalogs,
  404.             'logos' => $logos,
  405.             'videos' => $videos,
  406.             'videos600' => $videos600,
  407.             'videos1000' => $videos1000
  408.         ));
  409. //        $pageResponse->setSharedMaxAge($this->getParameter('cache_expiration'));
  410. //        $pageResponse->headers->addCacheControlDirective('must-revalidate', true);
  411. //        return $pageResponse;
  412.     }
  413.     /**
  414.      * Download pdf
  415.      * @Route("/pdf/{filename}", name="download_pdf", methods={"GET"})
  416.      * @param $filename
  417.      * @return BinaryFileResponse
  418.      */
  419.     public function pdf($filename)
  420.     {
  421.         $file $this->getParameter('uploads_pdf_dir').$filename;
  422.         $response = new BinaryFileResponse($file);
  423.         $mimeTypeGuesser = new FileinfoMimeTypeGuesser();
  424.         if ($mimeTypeGuesser->isGuesserSupported()) {
  425.             $response->headers->set('Content-Type'$mimeTypeGuesser->guessMimeType($file));
  426.         } else {
  427.             $response->headers->set('Content-Type''text/plain');
  428.         }
  429.         $response->setContentDisposition(
  430.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  431.             $filename
  432.         );
  433.         return $response;
  434.     }
  435.     /**
  436.      * Download android app
  437.      * @Route("/android.html", name="download_android_app", methods={"GET"})
  438.      * @return Response
  439.      */
  440.     public function android()
  441.     {
  442.         return $this->render('android.html.twig');
  443.     }
  444.     /**
  445.      * Download ios app
  446.      * @Route("/ios.html", name="download_ios_app", methods={"GET"})
  447.      * @return Response
  448.      */
  449.     public function ios()
  450.     {
  451.         return $this->render('ios.html.twig');
  452.     }
  453.     /**
  454.      * SiteMap
  455.      * @Route("/sitemap.xml", name="sitemap", defaults={"_format"="xml"})
  456.      * @param Request $request
  457.      * @param Tools $tools
  458.      * @return Response|ResponseInterface
  459.      * @throws ClientExceptionInterface
  460.      * @throws DecodingExceptionInterface
  461.      * @throws RedirectionExceptionInterface
  462.      * @throws ServerExceptionInterface
  463.      * @throws TransportExceptionInterface
  464.      */
  465.     public function siteMap(Request $requestTools $tools)
  466.     {
  467.         $hostname $request->getSchemeAndHttpHost();
  468.         $urls = [];
  469.         //Static urls
  470.         $urls[] = ['loc' => $this->generateUrl('home'), 'changefreq' => 'daily''priority' => '1.0'];
  471.         $urls[] = ['loc' => $this->generateUrl('about'), 'changefreq' => 'weekly''priority' => '1.0'];
  472.         $urls[] = ['loc' => $this->generateUrl('faq'), 'changefreq' => 'monthly''priority' => '1.0'];
  473.         $urls[] = ['loc' => $this->generateUrl('covid-19'), 'changefreq' => 'daily''priority' => '1.0'];
  474.         $urls[] = ['loc' => $this->generateUrl('download_pdf', ['filename' => 'ml-rodzafer.pdf']), 'changefreq' => 'monthly''priority' => '0.80'];
  475.         $urls[] = ['loc' => $this->generateUrl('download_pdf', ['filename' => 'charte-utilisation-ar.pdf']), 'changefreq' => 'monthly''priority' => '0.80'];
  476.         $urls[] = ['loc' => $this->generateUrl('download_pdf', ['filename' => 'charte-donnee-rodzafer.pdf']), 'changefreq' => 'monthly''priority' => '0.80'];
  477.         $client HttpClient::create();
  478.         $response $client->request('GET'$this->getParameter('api2_url').'/api/catalogs');
  479.         if ($response->getStatusCode() == 200) {
  480.             $catalogs $response->toArray()['hits'];
  481.             foreach ($catalogs as $idx => $catalog) {
  482.                 $name $catalog['company']['name'];
  483.                 $endDate date('d-m'strtotime($catalog['dateEnd']));
  484.                 $urls[] = ['loc' => $this->generateUrl('catalog_view', ['id' => $tools->slugify($name.'-'.$endDate.'-'.$catalog['_id'])]), 'changefreq' => 'daily''priority' => '0.80'];
  485.             }
  486.         }
  487.         $response $this->render('sitemap.html.twig', [
  488.             'urls' => $urls,
  489.             'hostname' => $hostname
  490.         ]);
  491.         $response->headers->set('Content-Type''text/xml');
  492.         return $response;
  493.     }
  494.     /**
  495.      * SiteMap
  496.      * @Route("/contactez-nous.json", name="contact_nous", defaults={"_format"="json"}, methods={"POST"})
  497.      * @param Request $request
  498.      * @param Mailer $mailer
  499.      * @return Response
  500.      * @throws ClientExceptionInterface
  501.      * @throws DecodingExceptionInterface
  502.      * @throws RedirectionExceptionInterface
  503.      * @throws ServerExceptionInterface
  504.      * @throws TransportExceptionInterface
  505.      */
  506.     public function contactNous(Request $requestMailer $mailer)
  507.     {
  508.         $projectRoot Kernel::getProjectDir();
  509.         date_default_timezone_set("Indian/Reunion");
  510.         // data item
  511.         $item = [
  512.             'civ'                   => $request->request->get('civ'),
  513.             'nom'                   => $request->request->get('nom'),
  514.             'prenom'                => $request->request->get('prenom'),
  515.             'email'                 => $request->request->get('email'),
  516.             'phone'                 => $request->request->get('phone'),
  517.             'activite'              => $request->request->get('activite'),
  518.             'entreprise'            => $request->request->get('entreprise'),
  519.             'fonction'              => $request->request->get('fonction'),
  520.             'internet'              => $request->request->get('internet'),
  521.             'option_tv'             => $request->request->get('option_tv'),
  522.             'option_partenaire'     => $request->request->get('option_partenaire'),
  523.             'comment'               => $request->request->get('comment'),
  524.             'ip_address'            => $request->request->get('ip_address')
  525.         ];
  526.         // retour
  527.         $return = [
  528.             'error' => false,
  529.             'message' => ''
  530.         ];
  531.         $blockMail $this->blockMail($item['email'], $projectRoot);
  532.         // test si l'adresse email est sur la liste noire
  533.         if ($blockMail) {
  534.             $return = [
  535.                 'error' => true,
  536.                 'message' => "Votre adresse email est bloquée"
  537.             ];
  538.         } else {
  539.             // check google captcha
  540.             $client HttpClient::create();
  541.             $response $client->request(
  542.                 'POST',
  543.                 'https://www.google.com/recaptcha/api/siteverify',
  544.                 [
  545.                     'body' => [
  546.                         'secret' => '6LfaeuQUAAAAABAOWavgf6FnQ5ijlRIL8njokb9i',
  547.                         'response' => $_POST['g-recaptcha-response'],
  548.                         'remoteip' => $_SERVER['REMOTE_ADDR']
  549.                     ]
  550.                 ]
  551.             );
  552.             // test si captcha valid
  553.             $google $response->toArray();
  554.             if( !$google['success'] )
  555.             {
  556.                 $return = [
  557.                     'error' => true,
  558.                     'message' => 'Temps de validation dépassé ou donnée captcha erroné. veuillez réessayer'
  559.                 ];
  560.             }
  561.             else
  562.             {
  563.                 // Send email
  564.                 $mailer->setFrom($this->getParameter('mailer_from'));
  565.                 $mailer->setFromName($this->getParameter('mailer_from_name'));
  566.                 $mailer->setTo('[email protected]');
  567.                 $mailer->setBcc(array('[email protected]','[email protected]','[email protected]'));
  568.                 $mailer->setSubject('Contact RodZafer');
  569.                 $mailer->setTemplate($this->renderView('email/contactez-nous.html.twig', array(
  570.                     'item' => $item
  571.                 )));
  572.                 $mailer->send();
  573.                 $return = [
  574.                     'error' => false,
  575.                     'message' => 'Message envoyé'
  576.                 ];
  577.                 $arr = array(
  578.                     "email" => $item['email'],
  579.                     "date" => date("j-n-Y H:i:s"),
  580.                     "ip_infos" => $item['ip_address']
  581.                 );
  582.                 file_put_contents($projectRoot.'/public/log_formulaire/log.log'json_encode($arr), FILE_APPEND);
  583.             }
  584.         }
  585.         return new JsonResponse($return);
  586.     }
  587.     /**
  588.      * Universal link for IOS
  589.      * @Route("/product", name="universal_link_ios", methods={"GET"})
  590.      * @return Response
  591.      */
  592.     public function universalLinkIOS()
  593.     {
  594.         return new Response('Veuillez cliquer sur le bouton open');
  595.     }
  596.     /**
  597.      * Generate signboards data
  598.      * @Route("/data/enseignes.json", name="signboards_data", methods={"GET"})
  599.      * @param APIRequestService $requestService
  600.      * @return JsonResponse
  601.      * @throws ClientExceptionInterface
  602.      * @throws DecodingExceptionInterface
  603.      * @throws RedirectionExceptionInterface
  604.      * @throws ServerExceptionInterface
  605.      * @throws TransportExceptionInterface
  606.      */
  607.     public function signboardData(APIRequestService $requestService)
  608.     {
  609.         $signboards $requestService->get($this->getParameter('api_url').'/point_of_sales?order[signboard]=asc');
  610.         foreach ($signboards as $idx => $signboard) {
  611.             $signboards[$idx]['id'] = $signboards[$idx]['externalId'];
  612.             unset($signboards[$idx]['externalId']);
  613.         }
  614.         $response = new JsonResponse($signboards);
  615.         $response->setEncodingOptions(JSON_UNESCAPED_UNICODE);
  616.         return $response;
  617.     }
  618.     /**
  619.      * @Route("/catalogs", methods={"GET"})
  620.      * @return RedirectResponse
  621.      */
  622.     public function listCatalogsOldUrl()
  623.     {
  624.         return $this->redirectToRoute('home');
  625.     }
  626.     /**
  627.      * @Route("/catalog", methods={"GET"})
  628.      * @return RedirectResponse
  629.      */
  630.     public function listCatalogsOldUrl2()
  631.     {
  632.         return $this->redirectToRoute('home');
  633.     }
  634.     /**
  635.      * @Route("/catalog/{id}", methods={"GET"})
  636.      * @param $id
  637.      * @return RedirectResponse
  638.      */
  639.     public function viewCatalogOldUrl($id)
  640.     {
  641.         return $this->redirectToRoute('catalog_view', ['id' => $id]);
  642.     }
  643.     /**
  644.      * Compress catalog's image
  645.      * @Route("/image/{filename}/{id}", name="compress_image", methods={"GET"}, requirements={"filename":"[a-zA-Z0-9-_\/.]+"})
  646.      * @param Request $request
  647.      * @param $filename
  648.      * @return Response
  649.      */
  650.     public function compressImage(Request $request$filename$id)
  651.     {
  652.         $imageUrl $this->getParameter('api2_url').$filename;
  653.         $pathParts pathinfo($imageUrl);
  654.         $directory $this->getParameter('uploads_catalog_dir').$id;
  655.         $file $directory.'/'.str_replace('/''_'$filename);
  656.         if (!file_exists($this->getParameter('uploads_catalog_dir')))
  657.             mkdir($this->getParameter('uploads_catalog_dir'));
  658.         if (!file_exists($directory))
  659.             mkdir($directory);
  660.         if (!file_exists($file)) {
  661.             try {
  662.                 \Tinify\setKey($this->getParameter('tiny_png_key'));
  663.                 $source = \Tinify\fromUrl($imageUrl);
  664.                 $source->toFile($file);
  665.             } catch (\Tinify\AccountException $e) {
  666.                 file_put_contents($filefile_get_contents($imageUrl));
  667.             } catch(\Tinify\Exception $e) {
  668.                 file_put_contents($filefile_get_contents($imageUrl));
  669.             }
  670.         }
  671.         //if (strpos($file, 'p-1.jpg')) {
  672.         //    $this->resize_crop_image(600, 315, $file, str_replace('p-1.jpg', 'thumbnail.jpg', $file));
  673.         //}
  674.         return new Response('OK');
  675.     }
  676.     function resize_crop_image($max_width$max_height$source_file$dst_dir$quality 80){
  677.         $imgsize getimagesize($source_file);
  678.         $width $imgsize[0];
  679.         $height $imgsize[1];
  680.         $mime $imgsize['mime'];
  681.         switch($mime){
  682.             case 'image/gif':
  683.                 $image_create "imagecreatefromgif";
  684.                 $image "imagegif";
  685.                 break;
  686.             case 'image/png':
  687.                 $image_create "imagecreatefrompng";
  688.                 $image "imagepng";
  689.                 $quality 7;
  690.                 break;
  691.             case 'image/jpeg':
  692.                 $image_create "imagecreatefromjpeg";
  693.                 $image "imagejpeg";
  694.                 $quality 80;
  695.                 break;
  696.             default:
  697.                 return false;
  698.                 break;
  699.         }
  700.         $dst_img imagecreatetruecolor($max_width$max_height);
  701.         $src_img $image_create($source_file);
  702.         $width_new $height $max_width $max_height;
  703.         $height_new $width $max_height $max_width;
  704.         //if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
  705.         if($width_new $width) {
  706.             //cut point by height
  707.             $h_point = (($height $height_new) / 2);
  708.             //copy image
  709.             imagecopyresampled($dst_img$src_img000$h_point$max_width$max_height$width$height_new);
  710.         } else {
  711.             //cut point by width
  712.             $w_point = (($width $width_new) / 2);
  713.             imagecopyresampled($dst_img$src_img00$w_point0$max_width$max_height$width_new$height);
  714.         }
  715.         $image($dst_img$dst_dir$quality);
  716.         if ($dst_imgimagedestroy($dst_img);
  717.         if ($src_imgimagedestroy($src_img);
  718.     }
  719.     private function getConfiguration($configName)
  720.     {
  721.         $_CONFIGURATION = [];
  722.         
  723.         $user       $this->getParameter('api_user');
  724.         $password   $this->getParameter('api_pwd');
  725.         // ancien système de token
  726.         // $_CONFIGURATION['api2_token'] = $this->getParameter('api2_token');
  727.         
  728.         // nouveau système de récupération de token
  729.         $_CONFIGURATION['api2_token'] = $this->getJwt($user$password);
  730.         return $_CONFIGURATION[$configName];
  731.     }
  732.     private function getJwt($user$password)
  733.     {
  734.         $auth_route $this->getParameter('api2_url').'/auth/local';
  735.         $payload json_encode([
  736.             'identifier' => $user,
  737.             'password' => $password
  738.         ]);
  739.         $header = ['Content-Type' => 'application/json'];
  740.         $client HttpClient::create();
  741.         $response $client->request('POST'$auth_route,[
  742.             'headers' => $header,
  743.             'body' => $payload
  744.         ]);
  745.         if ($response->getStatusCode() == 200){
  746.             $responseArray $response->toArray();
  747.             if ($responseArray['jwt'])
  748.                 return $responseArray['jwt'];
  749.         }
  750.         return null;
  751.     }
  752.     private function blockMail($mail$root) {
  753.         $data file_get_contents($root "/public/log_formulaire/mail.txt");
  754.         if (!empty($data)) {
  755.             $arr_mails explode("|"$data);
  756.             if (in_array($mail$arr_mails)) {
  757.                 return true;
  758.             } else {
  759.                 return false;
  760.             }
  761.         } else {
  762.             return false;
  763.         }
  764.     }
  765. }