src/Controller/Front/FrontPageController.php line 123

Open in your IDE?
  1. <?php
  2. namespace Acme\SudcmsBundle\Controller\Front;
  3. use Acme\SudcmsBundle\Entity\AnnuaireCategs;
  4. use Acme\SudcmsBundle\Entity\ContactHistorique;
  5. use Acme\SudcmsBundle\Entity\FormElements;
  6. use Acme\SudcmsBundle\Entity\FormSite;
  7. use Acme\SudcmsBundle\Entity\Pages;
  8. use Acme\SudcmsBundle\Entity\PagesBlocs;
  9. use Acme\SudcmsBundle\Form\FrontContactType;
  10. use Acme\SudcmsBundle\Repository\AddressBookCategoryRepository;
  11. use Acme\SudcmsBundle\Repository\FormAdressesRepository;
  12. use Acme\SudcmsBundle\Repository\FormSiteRepository;
  13. use Acme\SudcmsBundle\Repository\PagesRepository;
  14. use Acme\SudcmsBundle\Service\FormBuilderService;
  15. use Acme\SudcmsBundle\Service\MailerService;
  16. use Acme\SudcmsBundle\Service\OtideaUtils;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\Filesystem\Exception\FileNotFoundException;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\RequestStack;
  21. use Symfony\Component\HttpFoundation\Session\Session;
  22. use Symfony\Component\HttpKernel\KernelInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Twig\Environment;
  25. class FrontPageController extends AbstractController
  26. {
  27.     private $appKernel;
  28.     private $otideaUtils;
  29.     private $mailerService;
  30.     private $session;
  31.     private $twig null;
  32.     private $formSiteRepo;
  33.     private $formAdressesRepo;
  34.     private $requestStack;
  35.     private $formService;
  36.     private $popupFront null;
  37.     private $currentPage null;
  38.     private $fileAriane = array();
  39.     private $isThereSlider = array();
  40.     private $isThereGalerie = array();
  41.     private $tabVerifCarte = array();
  42.     private $pageWithForm false;
  43.     public function __construct(KernelInterface $appKernelMailerService $mailerServiceFormSiteRepository $formSiteRepoFormAdressesRepository $formAdressesRepoRequestStack $requestStackOtideaUtils $otideaUtilsFormBuilderService $formService)
  44.     {
  45.         $this->session = new Session();
  46.         $this->appKernel $appKernel;
  47.         $this->requestStack $requestStack;
  48.         $this->otideaUtils $otideaUtils;
  49.         $this->mailerService $mailerService;
  50.         $this->formSiteRepo $formSiteRepo;
  51.         $this->formAdressesRepo $formAdressesRepo;
  52.         $this->formService $formService;
  53.     }
  54.     #[Route(path'/change_locale/{locale}'name'front_change_locale'defaults: ['locale' => ''])]
  55.     public function changeLocale($localeRequest $request)
  56.     {
  57.         // On stocke la langue dans la session
  58.         $request->getSession()->set('_locale'$locale);
  59.         $request->getSession()->remove('_localeMenu');
  60.         // On revient sur la page précédente
  61. //        return $this->redirect($request->headers->get('referer'));
  62.         return $this->redirectToRoute("front_home");
  63.     }
  64.     #[Route(path'/change_locale_menu/{localMenu}'name'front_change_locale_menu'defaults: ['localMenu' => ''])]
  65.     public function changeLocaleMenu($localMenuRequest $request)
  66.     {
  67.         // On stocke la langue dans la session
  68.         $request->getSession()->set('_locale'"fr");
  69.         $request->getSession()->set('_localeMenu'$localMenu);
  70.         // On revient sur la page précédente
  71. //        return $this->redirect($request->headers->get('referer'));
  72.         return $this->redirectToRoute("front_home");
  73.     }
  74.     /*     * *********************************************************************** */
  75.     /*     * ************ FONCTION APPELEE AUTOMATIQUEMENT PAR UN BLOC HTML ******** */
  76.     /*     * *********************************************************************** */
  77.     private function fichier_exemple()
  78.     {
  79.         //@TODO -- le fichier template doit étendre de bloc-html.html.twig
  80.         return array(
  81.             'var1' => 'value1',
  82.             'var2' => 'value2',
  83.         );
  84.     }
  85.     #[Route(path: ['fr' => '/page/{name}''en' => '/page-en/{name}''es' => '/pagina/{name}''it' => '/pagina/{name}''de' => '/seite/{name}''pt' => '/pagina/{name}''pl' => '/strona/{name}''ru' => '/stranitsa/{name}''zh' => '/ye/{name}''tr' => '/sayfa/{name}'], name'front_page'defaults: ['name' => ''])]
  86.     public function page($nameRequest $requestPagesRepository $repoAddressBookCategoryRepository $anCatRepoEnvironment $twig$marker_id 0)
  87.     {
  88.         $this->twig $twig;
  89.         $this->currentPage $repo->findOneBy(['permalien' => $name'psite' => CURRENT_SITE_ID]);
  90.         if ($this->currentPage == null)
  91.             throw $this->createNotFoundException();
  92.         $this->getRubriquePrincipal($this->currentPage);
  93.         //Soumission d'un formulaire administrable
  94.         if ($request->get('formulaire_id') && $request->get('captcha')) {
  95.             if (trim($request->get('captcha')) == $request->get('captcha_resp')) {
  96.                 $this->sendForm($request$request->get('formulaire_id'));
  97.             } else {
  98.                 $this->otideaUtils->createPopup(["title" => 'Vérification'"message" => 'Vous avez échoué au test de vérification, veuillez essayer de nouveau.'"btn2" => null]);
  99.             }
  100.         }
  101.         $page_content $this->getPageBlocs($request);
  102.         $page_content_mediasForCanonical $this->getPageMediasForCanon();
  103.         $page_descriptionRef $this->getDescriptionRef();
  104.         $annuaireCategs $anCatRepo->findBy(['abcSiteUid' => CURRENT_SITE_ID], ['abcOrder' => 'ASC']);
  105.         $annuaire $anCatRepo->findByFicheWithCategories(['site_uid' => CURRENT_SITE_ID'site_lang' => 'fr']);
  106.         return $this->render('front/front_page/page.html.twig', [
  107.             "page_content" => $page_content,
  108.             "pageContentMediasForCanonical" => $page_content_mediasForCanonical,
  109.             "descriptionRef" => $page_descriptionRef,
  110.             "page" => $this->currentPage,
  111.             "isThereSlider" => $this->isThereSlider,
  112.             "isThereGalerie" => $this->isThereGalerie,
  113.             "tabVerifCarte" => $this->tabVerifCarte,
  114.             "fileAriane" => array_reverse($this->fileAriane),
  115.             'markerSelect' => $marker_id,
  116. //                    'geojsonLayers' => $this->getGeoJsonCarteTerritoire(),
  117.             'annuaireCategs' => $annuaireCategs,
  118.             'annuaire' => $annuaire,
  119.             'pageWithForm' => $this->pageWithForm,
  120.         ]);
  121.     }
  122.     /**
  123.      * Soumission d'un formulaire administrable
  124.      * @param int $formulaire_id
  125.      */
  126.     private function sendForm($request$formulaire_id)
  127.     {
  128.         $htmlContent '';
  129.         $entityManager $this->getDoctrine()->getManager();
  130.         $form $entityManager->getRepository(FormSite::class)->find($formulaire_id);
  131.         $elements $entityManager->getRepository(FormElements::class)->findBy(['form_id' => $formulaire_id]);
  132.         $htmlContent .= '<h2>Détail du formulaire :</h2>';
  133.         $htmlContent .= '<p>Ce mail vous est envoyé depuis le formulaire "' $form->getSubject() . '" du site internet.</p>';
  134.         $emailForm '';
  135.         $nomForm '';
  136.         $prenomForm '';
  137.         //Préparation du contenu HTML
  138.         $htmlContent .= '<ul>';
  139.         if (is_array($_POST) && sizeof($_POST) > 0) {
  140.             foreach ($_POST as $key => $post) {
  141.                 $keyExplode explode('=='$key);
  142.                 if ($keyExplode !== false && sizeof($keyExplode) > 1) {
  143.                     if ($keyExplode[1] == 'E-mail') {
  144.                         $emailForm $post;
  145.                     }
  146.                     if ($keyExplode[1] == 'Nom') {
  147.                         $nomForm $post;
  148.                     }
  149.                     if ($keyExplode[1] == 'Prenom') {
  150.                         $prenomForm $post;
  151.                     }
  152.                     //Cas du RGPD
  153.                     if ($keyExplode[1] == 'rgpd') {
  154.                         $labelElmt '';
  155.                         foreach ($elements as $element) {
  156.                             if ($element->getElementType() == 'rgpd') {
  157.                                 $labelElmt $element->getElementLabel();
  158.                             }
  159.                         }
  160.                         $htmlContent .= "<li>Le " date('d/m/Y H:i:s') . " " $labelElmt ".</li>";
  161.                         //Autres champs
  162.                     } else {
  163.                         foreach ($elements as $element) {
  164.                             if ($element->getId() == $keyExplode[0]) {
  165.                                 if (is_array($request->get($key))) {
  166.                                     $htmlContent .= "<li><strong>" $element->getElementLabel() . " : </strong>" implode(', '$request->get($key)) . "</li>";
  167.                                 } else {
  168.                                     $htmlContent .= "<li><strong>" $element->getElementLabel() . " : </strong>" $request->get($key) . "</li>";
  169.                                 }
  170.                             }
  171.                         }
  172.                     }
  173.                 }
  174.             }
  175.         }
  176.         $htmlContent .= '</ul>';
  177.         $allRecipients = array();
  178.         $allRecipients[] = [
  179.             "nom" => $nomForm,
  180.             "prenom" => $prenomForm,
  181.             "email" => $emailForm,
  182.             "type" => "to"
  183.         ];
  184.         //Envoi du mail
  185.         $this->mailerService->fromName SITE_NAME;
  186.         $this->mailerService->subject "Formulaire - " $form->getSubject();
  187.         $this->mailerService->sendMail($allRecipients$htmlContent$attachments = array(), $form->getName());
  188.         //Affichage de la popup de confirmation
  189.         $this->otideaUtils->createPopup(["title" => 'Confirmation'"message" => 'Soumission du formulaire avec succès'"btn2" => null]);
  190. //        echo '<pre>';
  191. //        print_r($htmlContent);
  192. //        echo '</pre>';
  193. //        
  194. //        exit();
  195.     }
  196.     private function getGeoJsonCarteTerritoire()
  197.     {
  198.         $layersMap = array();
  199.         //eurocampus problème avec le fichier
  200.         $layers = ['arsenal''cappyrenees''centrekennedy''cognac''creaminnov''ecoparc''gabas''garounere''gave''mayelane''monge''poleadourpyrenees''poleartisanaleechez''pyreneaeropole''saux''seguelongue'];
  201.         foreach ($layers as $layer) {
  202.             $layersMap[$layer] = file_get_contents($this->appKernel->getProjectDir() . '/public/import/geojson/' $layer '.geojson');
  203.         }
  204.         return $layersMap;
  205.     }
  206.     private function getPageBlocs(Request $request)
  207.     {
  208.         $content '';
  209.         $entityManager $this->getDoctrine()->getManager();
  210.         $blocs $entityManager->getRepository(PagesBlocs::class)->findByListeBlocsWithMedia($this->currentPage->getPageId(), "page");
  211.         if (is_array($blocs) && sizeof($blocs) > 0) {
  212.             foreach ($blocs as $bloc) {
  213.                 $annuaireCategs = array();
  214.                 $annuaire = array();
  215.                 $tabVerif = array();
  216.                 if ($bloc['bloc_type'] == 'formulaire') {
  217.                     $this->pageWithForm true;
  218.                     $form $entityManager->getRepository(FormSite::class)->findOneBy(['id' => $bloc['bloc_formulaire_id']]);
  219. //                    if($form != null){
  220. //                        $content .= $this->formService->create($bloc['bloc_formulaire_id'], 
  221. //                            ['editingMode' => false, 'method' => 'post', 'action' => '', 'captchaMode' => true],
  222. //                            ['id' => $form->getName(), 'class' => $form->getName(), 'name' => 'front_formulaire']
  223. //                        );
  224. //                    }
  225.                     if ($form != null) {
  226.                         $contentTemp $this->formService->create(
  227.                             ['editingMode' => false'method' => 'post''action' => '''captchaMode' => true],
  228.                             ['id' => $form->getName(), 'class' => $form->getName() . ' mbr-form''name' => 'front_formulaire'],
  229.                             $bloc['bloc_formulaire_id'],
  230.                             $request
  231.                         );
  232.                         $content .= $this->renderView("front/front_page/bloc-" $bloc['bloc_type'] . ".html.twig", ['bloc' => $bloc'result' => $contentTemp]);
  233.                     }
  234.                     //...
  235.                 } else if ($bloc['bloc_type'] == 'html') {
  236.                     $content .= $this->htmlfile($bloc);
  237.                 } else {
  238.                     if ($bloc['bloc_type'] == 'texte_slider') {
  239.                         $this->isThereSlider[] = $bloc['bloc_id'];
  240.                     }
  241.                     if ($bloc['bloc_type'] == 'galerie') {
  242.                         $this->isThereGalerie[] = $bloc['bloc_id'];
  243.                     }
  244.                     if ($bloc['bloc_type'] == 'carte') {
  245.                         $this->tabVerifCarte explode(","$bloc['bloc_texte']);
  246.                         $annuaireCategs $entityManager->getRepository(AnnuaireCategs::class)->findBy(['site_uid' => 1], ['an_cat_order' => 'ASC']);
  247.                         $annuaire $entityManager->getRepository(AnnuaireCategs::class)->findByFicheWithCategories(1'fr');
  248.                     }
  249.                     $MediasBlocs $entityManager->getRepository(Pages::class)->getAllMediasByBloc($blocs);
  250.                     $currentBlocMedias = array();
  251.                     foreach ($MediasBlocs as $media) {
  252.                         if ($bloc['bloc_id'] == $media["id_bloc"]) {
  253.                             $currentBlocMedias[] = $media;
  254.                         }
  255.                     }
  256.                     if ($bloc['bloc_type'] == 'texte_image' && empty($currentBlocMedias)) {
  257.                         $bloc['bloc_type'] = 'texte';
  258.                     }
  259.                     if ($bloc['bloc_type'] == 'texte_slider' && empty($currentBlocMedias)) {
  260.                         $bloc['bloc_type'] = 'texte';
  261.                     }
  262. //                    dd($currentBlocMedias[0]);
  263.                     $content .= $this->renderView("front/front_blocks/bloc-" $bloc['bloc_type'] . ".html.twig", [
  264.                         'medias' => $currentBlocMedias,
  265.                         'module' => "pages",
  266.                         'bloc' => $bloc,
  267.                         "uniqId" => uniqid(),
  268.                         'annuaireCategs' => $annuaireCategs,
  269.                         'annuaire' => $annuaire,
  270.                         'page' => $this->currentPage
  271.                     ]);
  272.                 }
  273.             }
  274.         }
  275.         return $content;
  276.     }
  277.     private function getPageMediasForCanon()
  278.     {
  279.         $contentMedForCannon = array();
  280.         $entityManager $this->getDoctrine()->getManager();
  281.         $blocs $entityManager->getRepository(PagesBlocs::class)->findByListeBlocsWithMedia($this->currentPage->getPageId(), "page");
  282.         if (is_array($blocs) && sizeof($blocs) > 0) {
  283.             foreach ($blocs as $bloc) {
  284.                 $MediasBlocs $entityManager->getRepository(Pages::class)->getAllMediasByBloc($blocs);
  285.                 foreach ($MediasBlocs as $media) {
  286.                     if ($bloc['bloc_id'] == $media["id_bloc"]) {
  287.                         $contentMedForCannon[] = $media;
  288.                     }
  289.                 }
  290.             }
  291.         }
  292.         return $contentMedForCannon;
  293.     }
  294.     private function getDescriptionRef()
  295.     {
  296.         $entityManager $this->getDoctrine()->getManager();
  297.         $blocs $entityManager->getRepository(PagesBlocs::class)->findByListeBlocsWithMedia($this->currentPage->getPageId(), "page");
  298.         $descriptionRef "";
  299.         $contentDescrRefOk 0;
  300.         if (is_array($blocs) && sizeof($blocs) > 0) {
  301.             foreach ($blocs as $bloc) {
  302.                 if (($bloc['bloc_type'] == 'texte' || $bloc['bloc_type'] == 'texte_image') && $contentDescrRefOk == 0) {
  303.                     if ($bloc['bloc_titre'] != "" && $bloc['bloc_titre'] != " ") {
  304.                         $descriptionRef $bloc['bloc_titre'];
  305.                     }
  306.                     if ($bloc['bloc_sstitre'] != "" && $bloc['bloc_sstitre'] != " ") {
  307.                         $descriptionRef .= " - " $bloc['bloc_sstitre'];
  308.                     }
  309.                     if ($bloc['bloc_texte'] != "" && $bloc['bloc_texte'] != " ") {
  310.                         $descriptionRef .= " : " strip_tags($bloc['bloc_texte']);
  311.                     }
  312.                 }
  313.             }
  314.         }
  315.         return $descriptionRef;
  316.     }
  317.     //Dans le cas d'une page statique on charge le contenu du fichier HTML
  318.     private function htmlfile($bloc)
  319.     {
  320.         $blocHTML '';
  321.         $result '';
  322.         //Execution de la fonction correspondant à la page statique si besoin
  323.         $filename $this->getFonctionParFichier($bloc['bloc_htmlfile']);
  324.         $rc = new \ReflectionClass('Acme\\SudcmsBundle\\Controller\\Front\\FrontPageController');
  325.         if (substr($filename07) == "contact" && $rc->hasMethod("contact")) {
  326.             $result $this->contact();
  327.         } elseif ($rc->hasMethod($filename)) {
  328.             $result $this->$filename();
  329.         }
  330.         $originFile $this->appKernel->getProjectDir() . "/templates/front/front_page/bloc-" $bloc['bloc_type'] . ".html.twig";
  331.         if (file_exists($originFile)) {
  332.             $blocHTML $this->renderView("front/front_page/bloc-" $bloc['bloc_type'] . ".html.twig", [
  333.                 'bloc' => $bloc,
  334.                 'result' => $result,
  335.                 'page' => $this->currentPage,
  336.             ]);
  337.         } else {
  338.             throw new FileNotFoundException("Le fichier " $bloc['bloc_htmlfile'] . " n'existe pas."0null$originFile);
  339.         }
  340.         return $blocHTML;
  341.     }
  342.     /**
  343.      * Retourne le nom de la fonction à appeler en fonction du nom du fichier .html
  344.      * @param string $fichier
  345.      * @return string
  346.      */
  347.     private function getFonctionParFichier($fichier)
  348.     {
  349.         $fichier str_replace(array('-'), '_'$fichier);
  350.         $fichier str_replace(array('.html''.twig'), ''$fichier);
  351.         return $fichier;
  352.     }
  353.     /**
  354.      * Retournee l'id de la rubrique principale d'une page
  355.      * @param array $page
  356.      */
  357.     private function getRubriquePrincipal($page)
  358.     {
  359.         $pparent $page->getPparent();
  360.         while ($pparent 0) {
  361.             $repo $this->getDoctrine()->getManager()->getRepository(Pages::class);
  362.             $page $repo->findOneBy(["pageId" => $pparent]);
  363.             $this->fileAriane[] = $page;
  364.             $pparent $page->getPparent();
  365.         }
  366.     }
  367.     private function socialwall()
  368.     {
  369.         $originFile $this->appKernel->getProjectDir() . '/templates/front_page/pages_statiques/socialwall.html.twig';
  370.         if (file_exists($originFile)) {
  371.             return $this->renderView("front_page/pages_statiques/socialwall.html.twig", [
  372.             ]);
  373.         } else {
  374.             throw new FileNotFoundException("Le fichier socialwall.html.twig n'existe pas."0null$originFile);
  375.         }
  376.     }
  377.     public function contact()
  378.     {
  379.         $contact = new ContactHistorique;
  380.         $form $this->createForm(FrontContactType::class, $contact);
  381.         $form->handleRequest($this->requestStack->getCurrentRequest());
  382.         if ($form->isSubmitted() && $form->isValid()) {
  383.             // cleaning inputs + setting additionnals fields
  384.             $contact->setNom(htmlspecialchars($form->get('nom')->getData(), ENT_QUOTES"UTF-8"));
  385.             $contact->setPrenom(htmlspecialchars($form->get('prenom')->getData(), ENT_QUOTES"UTF-8"));
  386.             $contact->setSociete(null);
  387.             $contact->setVille(htmlspecialchars($form->get('ville')->getData(), ENT_QUOTES"UTF-8"));
  388.             $contact->setTel(htmlspecialchars($form->get('tel')->getData(), ENT_QUOTES"UTF-8"));
  389.             $contact->setEmail(htmlspecialchars($form->get('email')->getData(), ENT_QUOTES"UTF-8"));
  390.             $contact->setMessage(htmlspecialchars($form->get('message')->getData(), ENT_QUOTES"UTF-8"));
  391.             $contact->setCreationDatetime(new \DateTime());
  392.             $contact->setSiteLang($this->requestStack->getCurrentRequest()->getLocale());
  393.             $contact->setSiteUid(CURRENT_SITE_ID);
  394.             $contact->setSource($this->formSiteRepo->findOneBy(["name" => "contact"]));
  395.             $entityManager $this->getDoctrine()->getManager();
  396.             if ($this->requestStack->getCurrentRequest()->getLocale() == "fr") {
  397.                 $titleOK SITE_NAME " | confirmation d'envoi";
  398.                 $msgOK "Le message a bien été enregistré. Nous vous répondrons dans les plus brefs délais.";
  399.                 $titleKO SITE_NAME " | Echec de l'envoi.";
  400.                 $msgKO "Le message n'a pas été enregistré.";
  401.             } else {
  402.                 $titleOK SITE_NAME " | your message has been send.";
  403.                 $msgOK "The message has been saved. We will respond as soon as possible.";
  404.                 $titleKO SITE_NAME " | Failed to send the message.";
  405.                 $msgKO "The message was not saved.";
  406.             }
  407.             try {
  408.                 $entityManager->persist($contact);
  409.                 $result $entityManager->flush();
  410.                 $this->otideaUtils->createPopup(["title" => $titleOK"message" => $msgOK"btn2" => null]);
  411.                 $this->mailerService->sendEmailFromForm(["form" => $form"formName" => "contact"]);
  412.                 $affOverlayCenter true;
  413.             } catch (Exception $e) {
  414.                 $this->otideaUtils->createPopup(["title" => $titleKO"message" => $msgKO"btn2" => null]);
  415.                 $affOverlayCenter true;
  416. //                    throw $e;
  417.             }
  418.         }
  419.         $originFile $this->appKernel->getProjectDir() . '/templates/front_page/pages_statiques/form-contact.html.twig';
  420.         if (file_exists($originFile)) {
  421.             return $this->renderView("front_page/pages_statiques/form-contact.html.twig", [
  422.                 'formContact' => $form->createView(),
  423.             ]);
  424.         } else {
  425.             throw new FileNotFoundException("Le fichier form-contact.html.twig n'existe pas."0null$originFile);
  426.         }
  427.     }
  428. }