<?php
/**
 * Created by PhpStorm.
 * User: sdaoudi
 * Date: 04/06/14
 * Time: 12:32
 */

namespace Ayaline\Bundle\EzSitBundle\Utils;


use eZ\Bundle\EzPublishCoreBundle\Controller;
use eZ\Publish\Core\Repository\Values\Content\Location;
use eZ\Publish\API\Repository\Values\Content\Content;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion;
use eZ\Publish\API\Repository\Values\Content\Query;


class SitUtils
{
    /**
     * @var \eZ\Bundle\EzPublishCoreBundle\Controller
     */
    protected $controller;

    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;

    /**
     * @var array
     */
    protected $viewParameters;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @var \Symfony\Component\HttpFoundation\Request
     */
    protected $request;

    /**
     * @var \Symfony\Bundle\FrameworkBundle\Translation\Translator
     */
    protected $translator;

    /**
     * @param Controller $controller
     * @param ContainerInterface $container
     * @param array $viewParameters
     * @param LoggerInterface $logger
     * @param Request $request
     * @param Translator $translator
     */
    public function __construct(Controller $controller, ContainerInterface $container, array $viewParameters, LoggerInterface $logger, Request $request, Translator $translator)
    {
        $this->controller = $controller;
        $this->container = $container;
        $this->viewParameters = $viewParameters;
        $this->logger = $logger;
        $this->request = $request;
        $this->translator = $translator;
    }

    /**
     * @param $currentLocationId
     * @param Location $sitListLocation
     * @param Content $sitListContent
     * @param $idFicheEnCours
     * @param $xslFile
     * @return mixed|string
     */
    public function getSitListeHtml($currentLocationId, Location $sitListLocation, Content $sitListContent, $idFicheEnCours, $xslFile)
    {
        $session = $this->container->get('session');
        $query = $this->request->query;

        $rootLocation = $this->controller->getRootLocation();

        $lienCourant = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $currentLocationId)
        );
        $cheminRacineSite = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $rootLocation->id)
        );
        $cheminRacineSite = $cheminRacineSite == "/" ? "" : $cheminRacineSite;

        $lienCourant = preg_replace("{^/layout/set/[^/]+(/.*)}", "$1", $lienCourant);
        $langue = "fr";

        $saisonId = null;
        if ($session != null && $session->has('saison')) {
            $saisonId = $session->get('saison');
        }

        $sitListeUrlAlias = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $sitListLocation->id)
        );

        $sitListeUrlAlias = substr_replace($sitListeUrlAlias, '', 0, 1);

        $cheminImagesDesign = $this->container->getParameter('ImagesDesign.CheminRoot');
        $cheminImages = $this->container->getParameter('ImagesDesign.CheminBundle');

        $rootSitUrl = null;
        if ($this->container->hasParameter("GlobalSitParameters.RootSitUrl")) {
            $rootSitUrl = $this->container->getParameter('GlobalSitParameters.RootSitUrl');
        }

        $cheminCacheXml = "";
        if ($this->container->hasParameter("GlobalSitParameters.XmlCachePath")) {
            $cheminCacheXml = $this->container->getParameter('GlobalSitParameters.XmlCachePath');
        }

        if (!file_exists($cheminCacheXml)) {
            mkdir($cheminCacheXml, 0777, true);
        }

        $cheminXsl = "";
        if ($this->container->hasParameter("GlobalSitParameters.XslPath")) {
            $cheminXsl = $this->container->getParameter('GlobalSitParameters.XslPath');
        }

        if (!file_exists($cheminXsl)) {
            mkdir($cheminXsl, 0777, true);
        }

        $traductionsStatiques = array();

        if ($this->container->hasParameter("SitTranslations.StaticSitTranslations")) {
            $traductionsStatiques = $this->container->getParameter('SitTranslations.StaticSitTranslations');
        }

        $categories = $sitListContent->getFieldValue("categorie")->selection;

        if (count($categories) == 1) {
            $categories = $categories[0];
        } elseif (count($categories)) {
            $tempoCategories = "";
            foreach ($categories as $cle => $categorie) {
                $tempoCategories .= $categorie;
                if (($cle + 1) < count($categories)) {
                    $tempoCategories .= '|';
                }
            }
            $categories = $tempoCategories;
        }

        $idCritereTarif = "";
        $idCritereModalite = "";
        if ($this->container->hasParameter("GlobalSitParameters.CriteresTarisPourCateg")) {
            $criteresTarisPourCateg = $this->container->getParameter('GlobalSitParameters.CriteresTarisPourCateg');
            if (array_key_exists($categories, $criteresTarisPourCateg)) {
                $criteresTarisPourCateg = explode('|', $criteresTarisPourCateg[$categories]);
                $idCritereTarif = $criteresTarisPourCateg[0];
                $idCritereModalite = $criteresTarisPourCateg[1];
            }
        }

        $nbItemsParPage = $sitListContent->getFieldValue('nb_items_par_page')->value;
        $dureeVieCache = $sitListContent->getFieldValue('duree_vie_cache')->value * 60;

        $triEnCours = "";
        if (array_key_exists('tri', $this->viewParameters) && $this->viewParameters['tri']) {
            $triEnCours = $this->viewParameters['tri'];
        }

        $rechercheEnCours = "non";
        if (array_key_exists('recherche', $this->viewParameters) && $this->viewParameters['recherche']) {
            $rechercheEnCours = $this->viewParameters['recherche'];
        }

        $pageCourante = "1";
        if (array_key_exists('page', $this->viewParameters) && $this->viewParameters['page']) {
            $pageCourante = $this->viewParameters['page'];
        }

        $sitParams = array();
        $sitParams['dwimg'] = "1";
        $sitParams['dwadd'] = "111";
        $sitParams['dwdate'] = "111";
        $sitParams['dwcom'] = "11111";
        $sitParams['dwlien'] = "1";
        $sitParams['dwref'] = "1";

        if ($langue) {
            $sitParams['lang'] = $langue;
        }

        $entites = $sitListContent->getFieldValue('entites')->selection;
        foreach ($entites as $entite) {
            if ($entite) {
                if (array_key_exists('ide', $sitParams)) {
                    $sitParams['ide'] .= "," . $entite;
                } else {
                    $sitParams['ide'] = $entite;
                }
            }
        }

        $paysEpci = $sitListContent->getFieldValue('pays_epci')->selection;
        foreach ($paysEpci as $unPaysEpci) {
            if ($unPaysEpci) {
                if (array_key_exists('idp', $sitParams)) {
                    $sitParams['idp'] .= "," . $unPaysEpci;
                } else {
                    $sitParams['idp'] = $unPaysEpci;
                }
            }
        }

        $criteresAffiches = $sitListContent->getFieldValue('criteres_affiches')->categories;
        foreach ($criteresAffiches as $idCritere) {
            if ($idCritere) {
                if (!array_key_exists('dwcrit', $sitParams) || !preg_match("/(^|\\|)" . substr($idCritere, 0, 9) . "/", $sitParams['dwcrit'])) {
                    if (array_key_exists('dwcrit', $sitParams)) {
                        $sitParams['dwcrit'] .= "|" . substr($idCritere, 0, 9);
                    } else {
                        $sitParams['dwcrit'] = substr($idCritere, 0, 9);
                    }
                }
            }
        }

        $criteresTriPrincipaux = $sitListContent->getFieldValue('criteres_tri_principaux')->categories;

        $sitParams['sort'] = "pho";
        $sitParams['order'] = "desc";
        foreach ($criteresTriPrincipaux as $critereTri) {
            $idCritereTri = substr($critereTri, 1);
            $sensCritereTri = substr($critereTri, 0, 1);

            if ($idCritereTri == '1') {
                $sitParams['sort'] .= ",com";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri == '2') {
                $sitParams['sort'] .= ",ran";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri == '3') {
                $sitParams['sort'] .= ",nco";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri == '4') {
                $sitParams['sort'] .= ",douv";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri) {
                $sitParams['sort'] .= "," . (strlen($idCritereTri) > 9 ? "m" : (preg_match("/^\\d+$/", $idCritereTri) ? "c" : "")) . $idCritereTri;
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            }
        }

        if (array_key_exists('tri', $this->viewParameters) && $this->viewParameters['tri']) {
            $tri = explode('~', $this->viewParameters['tri']);
            $sitParams['sort'] = $tri[0];
            $sitParams['order'] = (count($tri) >= 2 && $tri[1] ? $tri[1] : "asc");
        }

        $sitModalitesRapides = array();
        $sitModalitesTexte = "";
        $sitModalitesNum = "";
        $codesInsee = null;
        $motsCles = null;
        $debutDispo = null;
        $dureeDispo = null;
        $ouvAnnee = null;
        $debutOuv = null;
        $finOuv = null;

        if ($query->has("search_sit")) {
            $rechercheEnCours = "oui";

            if ($query->has("sit_mr")) {
                $sitModalitesRapides = $query->get("sit_mr");
            }

            foreach ($sitModalitesRapides as $idCritere => $sitModaliteRapide) {
                $sitModalitesRapides[$idCritere] = preg_replace("/(^,|,$)/", "", preg_replace("/,+/", ",", implode(",", $sitModaliteRapide)));
            }

            $sitModalitesRapides = preg_replace("/(^\\||\\|$)/", "", preg_replace("/\\|+/", "|", implode("|", $sitModalitesRapides)));
            $session->set("sit_mr_" . sha1($lienCourant), $sitModalitesRapides);

            $sitModalitesTexteNum = array();
            if ($query->has("sit_nrtr")) {
                $sitModalitesTexteNum = $query->get("sit_nrtr");
            }

            foreach ($sitModalitesTexteNum as $idCritere => $sitModaliteTexteNum) {
                if (trim($sitModaliteTexteNum['val']) != "") {
                    if (array_key_exists('ope', $sitModaliteTexteNum)) {
                        $sitModalitesNum[$idCritere] = $idCritere . utf8_decode('Â§') . $sitModaliteTexteNum['val'] . utf8_decode('Â§') . $sitModaliteTexteNum['ope'];
                    } else {
                        //echo "toto";
                        $sitModalitesTexte[$idCritere] = $idCritere . utf8_decode('Â§') . $sitModaliteTexteNum['val'];
                    }
                }
            }

            $sitModalitesTexte = preg_replace("/(^\\||\\|$)/", "", preg_replace("/\\|+/", "|", implode("|", $sitModalitesTexte)));
            $sitModalitesNum = preg_replace("/(^\\||\\|$)/", "", preg_replace("/\\|+/", "|", implode("|", $sitModalitesNum)));
            $session->set("sit_tr_" . sha1($lienCourant), $sitModalitesTexte);
            $session->set("sit_nr_" . sha1($lienCourant), $sitModalitesNum);

            if ($query->has("sit_cinsee")) {
                $codesInsee = join("|", $query->get("sit_cinsee"));
            }
            $session->set("sit_cinsee_" . sha1($lienCourant), $codesInsee);

            if ($query->has("sit_mc")) {
                $motsCles = $query->get("sit_mc");
                if ($motsCles == "Mots-clés") {
                    $motsCles = '';
                }
            }
            $session->set("sit_mc_" . sha1($lienCourant), $motsCles);

            if ($query->has("sit_ouvert_annee")) {
                $ouvAnnee = $query->get("sit_ouvert_annee");
            }
            $session->set("sit_ouv_annee_" . sha1($lienCourant), $ouvAnnee);

            if ($query->has("sit_debut_ouv")) {
                if (preg_match("/^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((19|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$|^$/", $query->get("sit_debut_ouv"))) {
                    $debutOuv = $query->get("sit_debut_ouv");
                }
            }

            if (!$ouvAnnee) {
                $session->set("sit_debut_ouv_" . sha1($lienCourant), $debutOuv);
            } elseif ($session->has("sit_debut_ouv_" . sha1($lienCourant))) {
                $debutOuv = $session->get("sit_debut_ouv_" . sha1($lienCourant));
            }

            if ($query->has("sit_fin_ouv")) {
                if (preg_match("/^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((19|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$|^$/", $query->get("sit_fin_ouv"))) {
                    $finOuv = $query->get("sit_fin_ouv");
                }
            }

            if (!$ouvAnnee) {
                $session->set("sit_fin_ouv_" . sha1($lienCourant), $finOuv);
            } elseif ($session->has("sit_fin_ouv_" . sha1($lienCourant))) {
                $finOuv = $session->get("sit_fin_ouv_" . sha1($lienCourant));
            }

            if ($query->has("sit_debut_dispo")) {
                if (preg_match("/^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((19|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$|^$/", $query->get("sit_debut_dispo"))) {
                    $debutDispo = $query->get("sit_debut_dispo");
                }
            }
            $session->set("sit_debut_dispo_" . sha1($lienCourant), $debutDispo);

            if ($query->has("sit_duree_dispo")) {
                if (preg_match("/^[0-9]+$|^$/", $query->get("sit_duree_dispo")) && $query->get("sit_duree_dispo") > 0) {
                    $dureeDispo = $query->get("sit_duree_dispo");
                }
            }
            $session->set("sit_duree_dispo_" . sha1($lienCourant), $dureeDispo);

            if ($query->has("villes")) {
                $vil = $query->get("villes");
                $session->set("villes_" . sha1($lienCourant), $vil);
            }

        } else if ($rechercheEnCours == "oui") {
            if ($session->has("sit_mr_" . sha1($lienCourant))) {
                $sitModalitesRapides = $session->get("sit_mr_" . sha1($lienCourant));
            }
            if ($session->has("sit_tr_" . sha1($lienCourant))) {
                $sitModalitesTexte = $session->get("sit_tr_" . sha1($lienCourant));
            }
            if ($session->has("sit_nr_" . sha1($lienCourant))) {
                $sitModalitesNum = $session->get("sit_nr_" . sha1($lienCourant));
            }
            if ($session->has("sit_cinsee_" . sha1($lienCourant))) {
                $codesInsee = $session->get("sit_cinsee_" . sha1($lienCourant));
            }
            if ($session->has("sit_mc_" . sha1($lienCourant))) {
                $motsCles = $session->get("sit_mc_" . sha1($lienCourant));
            }
            if ($session->has("sit_ouv_annee_" . sha1($lienCourant))) {
                $ouvAnnee = $session->get("sit_ouv_annee_" . sha1($lienCourant));
            }
            if ($session->has("sit_debut_ouv_" . sha1($lienCourant))) {
                $debutOuv = $session->get("sit_debut_ouv_" . sha1($lienCourant));
            }
            if ($session->has("sit_fin_ouv_" . sha1($lienCourant))) {
                $finOuv = $session->get("sit_fin_ouv_" . sha1($lienCourant));
            }
            if ($session->has("sit_debut_dispo_" . sha1($lienCourant))) {
                $debutDispo = $session->get("sit_debut_dispo_" . sha1($lienCourant));
            }
            if ($session->has("sit_duree_dispo_" . sha1($lienCourant))) {
                $dureeDispo = $session->get("sit_duree_dispo_" . sha1($lienCourant));
            }

        }

        if ($saisonId !== null && ($debutOuv == '' || $ouvAnnee)) {
            if ($this->container->hasParameter("Saisons.Printemps") && $saisonId == $this->container->getParameter("Saisons.Printemps")) {
                if ($this->container->hasParameter("Saisons.DebutPrintemps")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutPrintemps") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinPrintemps")) {
                    $finOuv = $this->container->getParameter("Saisons.FinPrintemps") . '/' . date('Y');
                }

            }
            if ($this->container->hasParameter("Saisons.Ete") && $saisonId == $this->container->getParameter("Saisons.Ete")) {
                if ($this->container->hasParameter("Saisons.DebutEte")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutEte") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinEte")) {
                    $finOuv = $this->container->getParameter("Saisons.FinEte") . '/' . date('Y');
                }

            }
            if ($this->container->hasParameter("Saisons.Automne") && $saisonId == $this->container->getParameter("Saisons.Automne")) {
                if ($this->container->hasParameter("Saisons.DebutAutomne")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutAutomne") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinAutomne")) {
                    $finOuv = $this->container->getParameter("Saisons.FinAutomne") . '/' . date('Y');
                }
            }
            if ($this->container->hasParameter("Saisons.Hiver") && $saisonId == $this->container->getParameter("Saisons.Hiver")) {
                if ($this->container->hasParameter("Saisons.DebutHiver")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutHiver") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinHiver")) {
                    $finOuv = $this->container->getParameter("Saisons.FinHiver") . '/' . date('Y');
                }

            }
            if ($debutOuv && $finOuv) {
                $now = time();
                $dateDebutOuv = explode('/', $debutOuv);
                $dateDebutOuv = mktime(0, 0, 0, $dateDebutOuv[1], $dateDebutOuv[0], $dateDebutOuv[2]);
                $dateFinOuv = explode('/', $finOuv);
                $dateFinOuv = mktime(0, 0, 0, $dateFinOuv[1], $dateFinOuv[0], $dateFinOuv[2]);
                if ($now >= $dateDebutOuv && $now <= $dateFinOuv) {
                    $debutOuv = date("d/m/Y", $now);
                }
            }
            $session->set("sit_debut_ouv_" . sha1($lienCourant), $debutOuv);
            $session->set("sit_fin_ouv_" . sha1($lienCourant), $finOuv);
        }

        if ($sitModalitesRapides) {
            if (array_key_exists('mr2', $sitParams)) {
                $sitParams['mr2'] .= "|" . $sitModalitesRapides;
            } else {
                $sitParams['mr2'] = $sitModalitesRapides;
            }
        }

        if ($sitModalitesTexte) {
            if (array_key_exists('tr', $sitParams)) {
                $sitParams['tr'] .= "|" . $sitModalitesTexte;
            } else {
                $sitParams['tr'] = $sitModalitesTexte;
            }
        }

        if ($sitModalitesNum) {
            if (array_key_exists('nr', $sitParams)) {
                $sitParams['nr'] .= "|" . $sitModalitesNum;
            } else {
                $sitParams['nr'] = $sitModalitesNum;
            }
        }

        if ($codesInsee) {
            $sitParams['cinsee'] = utf8_decode($codesInsee);
        }
        if ($motsCles) {
            $sitParams['mc'] = utf8_decode($motsCles);
        }
        if (!$ouvAnnee) {
            if ($debutOuv) {
                $dateDebutOuv = explode('/', $debutOuv);
                $sitParams['jdd'] = $dateDebutOuv[0];
                $sitParams['mdd'] = $dateDebutOuv[1];
                $sitParams['add'] = $dateDebutOuv[2];
            }
            if ($finOuv) {
                $dateFinOuv = explode('/', $finOuv);
                $sitParams['jfd'] = $dateFinOuv[0];
                $sitParams['mfd'] = $dateFinOuv[1];
                $sitParams['afd'] = $dateFinOuv[2];
                if ($query->has('td')) {
                    $sitParams['td'] = 1;
                }
            }
        }
        if ($debutDispo && $dureeDispo) {
            $dateDebutDispo = explode('/', $debutDispo);
            $sitParams['jdd'] = $dateDebutDispo[0];
            $sitParams['mdd'] = $dateDebutDispo[1];
            $sitParams['add'] = $dateDebutDispo[2];
            $dateFinDispo = explode('/', date("d/m/Y", mktime(0, 0, 0, $dateDebutDispo[1], $dateDebutDispo[0], $dateDebutDispo[2]) + $dureeDispo * 24 * 60 * 60));
            $sitParams['jfd'] = $dateFinDispo[0];
            $sitParams['mfd'] = $dateFinDispo[1];
            $sitParams['afd'] = $dateFinDispo[2];
        }

        $parametresDiffusionSupplementaires = $sitListContent->getFieldValue('parametres_diffusion_supplementaires')->matrix;
        $parametresDiffusionSupplementaires = simplexml_load_string($parametresDiffusionSupplementaires);;

        if (isset($parametresDiffusionSupplementaires->rows) && isset($parametresDiffusionSupplementaires->c)) {
            for ($i = 0; $i < count($parametresDiffusionSupplementaires->c); $i += 2) {
                $sitParamName = '' . $parametresDiffusionSupplementaires->c[$i];
                $sitParamValue = '' . $parametresDiffusionSupplementaires->c[$i + 1];
                if ($sitParamName && $sitParamValue) {
                    if (array_key_exists($sitParamName, $sitParams)) {
                        $sitParams[$sitParamName] .= (preg_match("{^dwcrit|mr2$}", $sitParamName) ? "|" : (preg_match("{^mc$}", $sitParamName) ? " " : ",")) . $sitParamValue;
                    } else {
                        $sitParams['' . $sitParamName] = $sitParamValue;
                    }
                    if ($sitParamName == 'dwcrit') {
                        $criteresAffiches = array_merge($criteresAffiches, explode("|", $sitParamValue));
                    }
                }
            }
        }

        $sitParamsString = "";
        $sitParamsEncodedString = "";
        foreach ($sitParams as $sitParamName => $sitParamValue) {
            $sitParamsString .= "&" . $sitParamName . "=" . $sitParamValue;
            $sitParamsEncodedString .= "&" . urlencode($sitParamName) . "=" . urlencode($sitParamValue);
        }


        $sitParamsString .= $categories ? "&idc=" . $categories : "";
        $sitParamsEncodedString .= $categories ? "&idc=" . $categories : "";

        $sitParamsStringCrypte = sha1("Recherche__" . substr($sitParamsString, 1));

        $cheminFichierCacheXml = $cheminCacheXml . $sitParamsStringCrypte . ".xml";

        $cacheExpire = true;
        if (file_exists($cheminFichierCacheXml)) {
            $maintenant = time();
            $dateExpirationCache = filemtime($cheminFichierCacheXml) + $dureeVieCache;
            if ($dateExpirationCache > $maintenant) {
                $cacheExpire = false;
            }
        }
        $contenuXmlDistant = "";
        if ($cacheExpire) {
            $contenuXmlDistant = \SitUtils::urlGetContentsCurl(urldecode($rootSitUrl . "Recherche" . $sitParamsEncodedString), 120);
            if ($contenuXmlDistant) {
                $contenuXmlCache = utf8_encode(preg_replace("/&([\\w\\d]+|\\#\\d+);/si", "_dw_entity__$1__", $contenuXmlDistant));
                file_put_contents($cheminFichierCacheXml, $contenuXmlCache, LOCK_EX);
            }
        }

        $this->logger->info($rootSitUrl . "Recherche" . $sitParamsString);

        $sitParamsString .= "&num=1";
        $sitParamsEncodedString .= "&num=1";
        $sitParamsStringCrypte = sha1("Recherche__" . substr($sitParamsString, 1));
        $cheminFichierCacheXmlNbProduits = $cheminCacheXml . $sitParamsStringCrypte . ".xml";

        $cacheExpire = true;
        if (file_exists($cheminFichierCacheXmlNbProduits)) {
            $maintenant = time();
            $dateExpirationCache = filemtime($cheminFichierCacheXmlNbProduits) + $dureeVieCache;
            if ($dateExpirationCache > $maintenant) {
                $cacheExpire = false;
            }
        }
        $contenuXmlDistant = "";
        if ($cacheExpire) {
            $contenuXmlDistant = \SitUtils::urlGetContentsCurl($rootSitUrl . "Recherche" . $sitParamsEncodedString);
            if ($contenuXmlDistant) {
                $contenuXmlCache = utf8_encode($contenuXmlDistant);
                file_put_contents($cheminFichierCacheXmlNbProduits, $contenuXmlCache, LOCK_EX);
            }
        }

        $cheminFichierXsl = $cheminXsl . "sit_nb_produits.xsl";

        $xsltParameters = array();
        $xsltParameters['nbPages'] = "1";
        $nbResultatsTotal = "0";
        if (file_exists($cheminFichierCacheXmlNbProduits) && file_exists($cheminFichierXsl)) {
            $nbResultatsTotal = trim(\SitUtils::getHtmlResult($cheminFichierCacheXmlNbProduits, $cheminFichierXsl));
            $xsltParameters['nbPages'] = ceil($nbItemsParPage > 0 ? $nbResultatsTotal / $nbItemsParPage : 1);
        }

        //$xsltParameters['saisonId'] = $saisonId;
        $xsltParameters['cheminImages'] = $cheminImagesDesign ? $cheminImagesDesign : $cheminImagesDesign;
        $xsltParameters['cheminImagesDesign'] = $cheminImages;
        $xsltParameters['lienCourant'] = $lienCourant;
        $xsltParameters['cheminRacineSite'] = $cheminRacineSite;
        $xsltParameters['rootSitUrl'] = $rootSitUrl;
        $xsltParameters['sitListeUrlAlias'] = str_replace("/", "~", $sitListeUrlAlias);
        $xsltParameters['sitListeLien'] = $sitListeUrlAlias;

        $xsltParameters['idFicheEnCours'] = $idFicheEnCours;

        $xsltParameters['nbItemsParPage'] = $nbItemsParPage;
        $xsltParameters['nbResultatsTotal'] = $nbResultatsTotal;
        $xsltParameters['pageCourante'] = $pageCourante;

        $xsltParameters['triEnCours'] = $triEnCours;
        $xsltParameters['rechercheEnCours'] = $rechercheEnCours;
        $xsltParameters['criteresAffiches'] = "|" . implode("|", $criteresAffiches) . "|";

        $xsltParameters['caracteresKo'] = utf8_encode("Å Å’Å½Å¸Â¥ÂµÃ€ÃÃ‚ÃƒÃ„Ã…Ã†Ã‡ÃˆÃ‰ÃŠÃ‹ÃŒÃÃŽÃÃÃ‘Ã’Ã“Ã”Ã•Ã–Ã˜Ã™ÃšÃ›ÃœÃÃŸ");
        $xsltParameters['caracteresOk'] = utf8_encode("Å¡Å“Å¾Ã¿Â¥ÂµÃ Ã¡Ã¢Ã£Ã¤Ã¥Ã¦Ã§Ã¨Ã©ÃªÃ«Ã¬Ã­Ã®Ã¯Ã°Ã±Ã²Ã³Ã´ÃµÃ¶Ã¸Ã¹ÃºÃ»Ã¼Ã½ÃŸ");

        $xsltParameters['langue'] = $langue;

        $xsltParameters['idCritereTarif'] = $idCritereTarif;
        $xsltParameters['idCritereModalite'] = $idCritereModalite;
        $xsltParameters['queryString'] = "";

        if (is_array($categories)) {
            $cheminFichierXsl = $cheminXsl . $xslFile . ".xsl";
        } else {
            $cheminFichierXsl = $cheminXsl . $xslFile . "_" . $categories . ".xsl";
        }

        // A revoir

        foreach ($traductionsStatiques as $traductionStatique) {
            $xsltParameters['terme' . $traductionStatique] = utf8_encode($this->translator->trans($traductionStatique));
        }

        if (!file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . $xslFile . ".xsl";
        }
        if (!file_exists($cheminFichierXsl) && !is_array($categories)) {
            $cheminFichierXsl = $cheminXsl . "sit_liste_" . $categories . ".xsl";
        }
        if (!file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . "sit_liste.xsl";
        }

        $contenuBloc = "";
        if (file_exists($cheminFichierCacheXml) && file_exists($cheminFichierXsl)) {
            $contenuBloc = \SitUtils::getHtmlResult($cheminFichierCacheXml, $cheminFichierXsl, $xsltParameters);
        }
        $contenuBloc = preg_replace("/_dw_entity__#13__\n/si", " ", $contenuBloc);
        $contenuBloc = utf8_decode(preg_replace("/_dw_entity__([^_]+)__/si", "&$1;", $contenuBloc));
        $contenuBloc = preg_replace("/&amp;([\\w\\d]+|\\#\\d+);/si", "&$1;", html_entity_decode($contenuBloc));
        $contenuBloc = "\n" . preg_replace("/(http:\\/\\/[^\\/]+):\\d+/si", "$1", $contenuBloc) . "\n";

        return $contenuBloc;
    }

    public function getSitRechercheHtml($currentLocationId, $sitListLocation, Content $sitListContent, $xslFile)
    {
        $request = Request::createFromGlobals();

        $session = $this->container->get('session');
        $query = $request->query;

        $rootLocation = $this->controller->getRootLocation();

        // Récupération du lien courant
        $lienCourant = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $currentLocationId)
        );
        $cheminRacineSite = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $rootLocation->id)
        );

        $cheminRacineSite = $cheminRacineSite == "/" ? "" : $cheminRacineSite;

        $lienCourant = preg_replace("{^/layout/set/[^/]+(/.*)}", "$1", $lienCourant);

        $langue = "fr";

        $saisonId = null;

        if ($session != null && $session->has('saison')) {
            $saisonId = $session->get('saison');
        }

        $sitListeUrlAlias = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $sitListLocation->id)
        );

        $cheminImagesDesign = $this->container->getParameter('ImagesDesign.CheminRoot');
        $cheminImages = $this->container->getParameter('ImagesDesign.CheminBundle');

        $rootSitUrl = null;
        if ($this->container->hasParameter("GlobalSitParameters.RootSitUrl")) {
            $rootSitUrl = $this->container->getParameter('GlobalSitParameters.RootSitUrl');
        }

        $cheminCacheXml = "";
        if ($this->container->hasParameter("GlobalSitParameters.XmlCachePath")) {
            $cheminCacheXml = $this->container->getParameter('GlobalSitParameters.XmlCachePath');
        }

        if (!file_exists($cheminCacheXml)) {
            mkdir($cheminCacheXml, 0777, true);
        }

        $cheminXsl = "";
        if ($this->container->hasParameter("GlobalSitParameters.XslPath")) {
            $cheminXsl = $this->container->getParameter('GlobalSitParameters.XslPath');
        }

        if (!file_exists($cheminXsl)) {
            mkdir($cheminXsl, 0777, true);
        }

        $traductionsStatiques = array();
        if ($this->container->hasParameter("SitTranslations.StaticSitTranslations")) {
            $traductionsStatiques = $this->container->getParameter('SitTranslations.StaticSitTranslations');
        }

        $villes = array();
        if ($this->container->hasParameter("GlobalSitParameters.ListeVilles")) {
            $villes = $this->container->getParameter('GlobalSitParameters.ListeVilles');
        }
        $villes = join("#", $villes);

        $triEnCours = "";
        if (array_key_exists('tri', $this->viewParameters) && $this->viewParameters['tri']) {
            $triEnCours = $this->viewParameters['tri'];
        }

        $rechercheEnCours = "non";
        if (array_key_exists('recherche', $this->viewParameters) && $this->viewParameters['recherche']) {
            $rechercheEnCours = $this->viewParameters['recherche'];
        }

        $pageCourante = "1";
        if (array_key_exists('page', $this->viewParameters) && $this->viewParameters['page']) {
            $pageCourante = $this->viewParameters['page'];
        }

        /*** Ajout gestion param affichage commune et date dans la recherche ***/
        $search_commune = false;
        $search_date_ouverture = false;
        if (isset($sitListContent->fields['recherche_commune'])) {
            $search_commune = $sitListContent->getFieldValue('recherche_commune')->bool;
        }

        if (isset($sitListContent->fields['recherche_date_ouverture'])) {
            $search_date_ouverture = $sitListContent->getFieldValue('recherche_date_ouverture')->bool;
        }

        $categorie = array();
        if (isset($sitListContent->fields['categorie'])) {
            $categorie = $sitListContent->getFieldValue('categorie')->selection;
        }

        if (count($categorie) == 1) {
            $categorie = $categorie[0];
        } elseif (count($categorie)) {
            $tempoCategories = "";
            foreach ($categorie as $cle => $cat) {
                $tempoCategories .= $cat;
                if ($cle + 1 < count($categorie)) {
                    $tempoCategories .= '|';
                }
            }
            $categorie = $tempoCategories;
        }
        /*** Fin ***/

        $idCritereTarif = '';
        $idCritereModalite = '';

        if ($this->container->hasParameter("GlobalSitParameters.CriteresTarisPourCateg")) {
            $criteresTarisPourCateg = $this->container->getParameter('GlobalSitParameters.CriteresTarisPourCateg');
            if (array_key_exists($categorie, $criteresTarisPourCateg)) {
                $criteresTarisPourCateg = explode('|', $criteresTarisPourCateg[$categorie]);
                $idCritereTarif = $criteresTarisPourCateg[0];
                $idCritereModalite = $criteresTarisPourCateg[1];
            }
        }

        $dureeVieCache = 0;
        if (isset($sitListContent->fields['categorie'])) {
            $dureeVieCache = $sitListContent->getFieldValue('duree_vie_cache')->value * 60;
        }

        $criteresTri = array();
        if (isset($sitListContent->fields['criteres_tri'])) {
            $criteresTri = $sitListContent->getFieldValue('criteres_tri')->categories;
        }

        $criteresRecherche = array();
        if (isset($sitListContent->fields['criteres_recherche'])) {
            $criteresRecherche = $sitListContent->getFieldValue('criteres_recherche')->categories;
        }

        $sitModalitesRapides = "";
        $sitModalitesTexte = "";
        $sitModalitesNum = "";
        $codesInsee = null;
        $motsCles = null;
        $debutDispo = null;
        $dureeDispo = null;
        $ouvAnnee = null;
        $debutOuv = null;
        $finOuv = null;
        $bornes = '';
        $checkCriteres = '';

        if ($query->has("search_sit")) {


            $rechercheEnCours = "oui";

            if ($query->has("sit_mr")) {
                $sitModalitesRapides = $query->get("sit_mr");
            }

            foreach ($sitModalitesRapides as $idCritere => $sitModaliteRapide) {
                $sitModalitesRapides[$idCritere] = preg_replace("/(^,|,$)/", "", preg_replace("/,+/", ",", implode(",", $sitModaliteRapide)));
            }

            $sitModalitesRapides = preg_replace("/(^\\||\\|$)/", "", preg_replace("/\\|+/", "|", implode("|", $sitModalitesRapides)));

            $session->set("sit_mr_" . sha1($lienCourant), $sitModalitesRapides);

            $sitModalitesTexteNum = array();
            if ($query->has("sit_nrtr")) {
                $sitModalitesTexteNum = $query->get("sit_nrtr");
            }

            foreach ($sitModalitesTexteNum as $idCritere => $sitModaliteTexteNum) {
                if (trim($sitModaliteTexteNum['val']) != "") {
                    if (array_key_exists('ope', $sitModaliteTexteNum)) {
                        $sitModalitesNum[$idCritere] = $idCritere . utf8_decode('Â§') . $sitModaliteTexteNum['val'] . utf8_decode('Â§') . $sitModaliteTexteNum['ope'];
                    } else {
                        $sitModalitesTexte[$idCritere] = $idCritere . utf8_decode('Â§') . $sitModaliteTexteNum['val'];
                    }
                }
            }

            $sitModalitesTexte = preg_replace("/(^\\||\\|$)/", "", preg_replace("/\\|+/", "|", implode("|", $sitModalitesTexte)));
            $sitModalitesNum = preg_replace("/(^\\||\\|$)/", "", preg_replace("/\\|+/", "|", implode("|", $sitModalitesNum)));

            $session->set("sit_tr_" . sha1($lienCourant), $sitModalitesTexte);
            $session->set("sit_nr_" . sha1($lienCourant), $sitModalitesNum);

            if ($query->has("sit_cinsee")) {
                $codesInsee = join("|", $query->get("sit_cinsee"));
            }

            $session->set("sit_cinsee_" . sha1($lienCourant), $codesInsee);

            if ($query->has("sit_mc")) {
                $motsCles = $query->get("sit_mc");
            }

            $session->set("sit_mc_" . sha1($lienCourant), $motsCles);

            if ($query->has("sit_ouvert_annee")) {
                $ouvAnnee = $query->get("sit_ouvert_annee");
            }

            $session->set("sit_ouv_annee_" . sha1($lienCourant), $ouvAnnee);

            if ($query->has("sit_debut_ouv")) {
                if (preg_match("/^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((19|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$|^$/", $query->get("sit_debut_ouv"))) {
                    $debutOuv = $query->get("sit_debut_ouv");
                }
            }

            if (!$ouvAnnee) {
                $session->set("sit_debut_ouv_" . sha1($lienCourant), $debutOuv);
            } else {
                if ($query->has("sit_debut_ouv_" . sha1($lienCourant))) {
                    $debutOuv = $session->get("sit_debut_ouv_" . sha1($lienCourant));
                }
            }

            if ($query->has("sit_fin_ouv")) {
                if (preg_match("/^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((19|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$|^$/", $query->get("sit_fin_ouv"))) {
                    $finOuv = $query->get("sit_fin_ouv");
                }
            }

            if (!$ouvAnnee) {
                $session->set("sit_fin_ouv_" . sha1($lienCourant), $finOuv);
            } else {
                if ($query->has("sit_fin_ouv_" . sha1($lienCourant))) {
                    $finOuv = $session->get("sit_fin_ouv_" . sha1($lienCourant));
                }
            }

            if ($query->has("sit_debut_dispo")) {
                if (preg_match("/^(((0[1-9]|[12]\\d|3[01])\\/(0[13578]|1[02])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|[12]\\d|30)\\/(0[13456789]|1[012])\\/((19|[2-9]\\d)\\d{2}))|((0[1-9]|1\\d|2[0-8])\\/02\\/((19|[2-9]\\d)\\d{2}))|(29\\/02\\/((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$|^$/", $query->get("sit_debut_dispo"))) {
                    $debutDispo = $query->get("sit_debut_dispo");
                }
            }

            $session->set("sit_debut_dispo_" . sha1($lienCourant), $debutDispo);

            if ($query->has("sit_duree_dispo")) {
                if (preg_match("/^[0-9]+$|^$/", $query->get("sit_duree_dispo")) && $query->get("sit_duree_dispo") > 0) {
                    $dureeDispo = $query->get("sit_duree_dispo");
                }
            }

            $session->set("sit_duree_dispo_" . sha1($lienCourant), $dureeDispo);

            if ($query->has("bornes")) {
                $bornesValues = $query->get("bornes");
                $bornes = '';
                foreach ($bornesValues as $key => $borne) {
                    $bornes .= '|' . $key . '|' . $borne . '|';
                }
                $session->set("bornes_" . sha1($lienCourant), $bornes);
            }
            if ($query->has("critere-check")) {
                $checkCriteresValues = $query->get("critere-check");
                $checkCriteres = '';
                foreach ($checkCriteresValues as $key => $checkValue) {
                    $checkCriteres .= '|' . $key . '|' . $checkValue . '|';
                }
                $session->set("check_criteres_" . sha1($lienCourant), $checkCriteres);
            }

        } else if ($rechercheEnCours == "oui") {
            if ($session->has("sit_mr_" . sha1($lienCourant))) {
                $sitModalitesRapides = $session->get("sit_mr_" . sha1($lienCourant));
            }
            if ($session->has("sit_tr_" . sha1($lienCourant))) {
                $sitModalitesTexte = $session->get("sit_tr_" . sha1($lienCourant));
            }
            if ($session->has("sit_nr_" . sha1($lienCourant))) {
                $sitModalitesNum = $session->get("sit_nr_" . sha1($lienCourant));
            }
            if ($session->has("sit_cinsee_" . sha1($lienCourant))) {
                $codesInsee = $session->get("sit_cinsee_" . sha1($lienCourant));
            }
            if ($session->has("sit_mc_" . sha1($lienCourant))) {
                $motsCles = $session->get("sit_mc_" . sha1($lienCourant));
            }
            if ($session->has("sit_ouv_annee_" . sha1($lienCourant))) {
                $ouvAnnee = $session->get("sit_ouv_annee_" . sha1($lienCourant));
            }
            if ($session->has("sit_debut_ouv_" . sha1($lienCourant))) {
                $debutOuv = $session->get("sit_debut_ouv_" . sha1($lienCourant));
            }
            if ($session->has("sit_fin_ouv_" . sha1($lienCourant))) {
                $finOuv = $session->get("sit_fin_ouv_" . sha1($lienCourant));
            }
            if ($session->has("sit_debut_dispo_" . sha1($lienCourant))) {
                $debutDispo = $session->get("sit_debut_dispo_" . sha1($lienCourant));
            }
            if ($session->has("sit_duree_dispo_" . sha1($lienCourant))) {
                $dureeDispo = $session->get("sit_duree_dispo_" . sha1($lienCourant));
            }
            if ($session->has("bornes_" . sha1($lienCourant))) {
                $bornes = $session->get("bornes_" . sha1($lienCourant));
            }
            if ($session->has("check_criteres_" . sha1($lienCourant))) {
                $checkCriteres = $session->get("check_criteres_" . sha1($lienCourant));
            }
        }

        if ($saisonId !== null && ($debutOuv == '' || $ouvAnnee)) {
            if ($this->container->hasParameter("Saisons.Printemps") && $saisonId == $this->container->getParameter("Saisons.Printemps")) {
                if ($this->container->hasParameter("Saisons.DebutPrintemps")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutPrintemps") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinPrintemps")) {
                    $finOuv = $this->container->getParameter("Saisons.FinPrintemps") . '/' . date('Y');
                }

            }
            if ($this->container->hasParameter("Saisons.Ete") && $saisonId == $this->container->getParameter("Saisons.Ete")) {
                if ($this->container->hasParameter("Saisons.DebutEte")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutEte") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinEte")) {
                    $finOuv = $this->container->getParameter("Saisons.FinEte") . '/' . date('Y');
                }

            }
            if ($this->container->hasParameter("Saisons.Automne") && $saisonId == $this->container->getParameter("Saisons.Automne")) {
                if ($this->container->hasParameter("Saisons.DebutAutomne")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutAutomne") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinAutomne")) {
                    $finOuv = $this->container->getParameter("Saisons.FinAutomne") . '/' . date('Y');
                }
            }
            if ($this->container->hasParameter("Saisons.Hiver") && $saisonId == $this->container->getParameter("Saisons.Hiver")) {
                if ($this->container->hasParameter("Saisons.DebutHiver")) {
                    $debutOuv = $this->container->getParameter("Saisons.DebutHiver") . '/' . date('Y');
                }
                if ($this->container->hasParameter("Saisons.FinHiver")) {
                    $finOuv = $this->container->getParameter("Saisons.FinHiver") . '/' . date('Y');
                }

            }
            if ($debutOuv && $finOuv) {
                $now = time();
                $dateDebutOuv = explode('/', $debutOuv);
                $dateDebutOuv = mktime(0, 0, 0, $dateDebutOuv[1], $dateDebutOuv[0], $dateDebutOuv[2]);
                $dateFinOuv = explode('/', $finOuv);
                $dateFinOuv = mktime(0, 0, 0, $dateFinOuv[1], $dateFinOuv[0], $dateFinOuv[2]);
                if ($now >= $dateDebutOuv && $now <= $dateFinOuv) {
                    $debutOuv = date("d/m/Y", $now);
                }
            }
            $session->set("sit_debut_ouv_" . sha1($lienCourant), $debutOuv);
            $session->set("sit_fin_ouv_" . sha1($lienCourant), $finOuv);
        }

        $sitParamsString = $categorie ? "&idC=" . $categorie : "";
        $sitParamsString .= $langue ? "&lang=" . $langue : "";

        $sitParamsStringCrypte = sha1("Criteres__" . substr($sitParamsString, 1));

        $cheminFichierCacheXml = $cheminCacheXml . $sitParamsStringCrypte . ".xml";

        $cacheExpire = true;
        if (file_exists($cheminFichierCacheXml)) {
            $maintenant = time();
            $dateExpirationCache = filemtime($cheminFichierCacheXml) + $dureeVieCache;
            if ($dateExpirationCache > $maintenant) {
                $cacheExpire = false;
            }
        }

        $contenuXmlDistant = "";
        //var_dump($rootSitUrl."Criteres".$sitParamsString);exit;
        if ($cacheExpire) {
            $contenuXmlDistant = \SitUtils::urlGetContentsCurl($rootSitUrl . "Criteres" . $sitParamsString);
            if ($contenuXmlDistant) {
                $contenuXmlCache = utf8_encode(preg_replace("/&([\\w\\d]+|\\#\\d+);/si", "_dw_entity__$1__", $contenuXmlDistant));
                file_put_contents($cheminFichierCacheXml, $contenuXmlCache, LOCK_EX);
            }
        }
        $this->logger->info($rootSitUrl . "Criteres" . $sitParamsString);
        $xsltParameters = array();

        /*** Ajout gestion param affichage commune et date dans la recherche ***/
        $xsltParameters['search_commune'] = $search_commune;
        $xsltParameters['search_date_ouverture'] = $search_date_ouverture;
        /*** Fin ***/

        $xsltParameters['saisonId'] = $saisonId;
        $xsltParameters['cheminImages'] = $cheminImagesDesign ? $cheminImagesDesign : $cheminImagesDesign;
        $xsltParameters['cheminImagesDesign'] = $cheminImages;
        $xsltParameters['lienCourant'] = $lienCourant;
        $xsltParameters['cheminRacineSite'] = $cheminRacineSite;
        $xsltParameters['rootSitUrl'] = $rootSitUrl;

        $xsltParameters['pageCourante'] = $pageCourante;

        $xsltParameters['villes'] = utf8_encode($villes);

        $xsltParameters['triEnCours'] = $triEnCours;
        $xsltParameters['rechercheEnCours'] = $rechercheEnCours;
        $xsltParameters['criteresTri'] = "|" . implode("|", $criteresTri) . "|";
        $xsltParameters['criteresRecherche'] = "|" . implode("|", $criteresRecherche) . "|";

        $xsltParameters['modalitesRapides'] = "|" . str_replace(",", "|", $sitModalitesRapides) . "|";
        $xsltParameters['modalitesTexte'] = str_replace(utf8_encode("Â§"), "#", utf8_encode(utf8_encode("|" . urldecode($sitModalitesTexte) . "|")));
        $xsltParameters['modalitesNum'] = str_replace(utf8_encode("Â§"), "#", utf8_encode(utf8_encode("|" . urldecode($sitModalitesNum) . "|")));

        $xsltParameters['codesInsee'] = utf8_encode($codesInsee);
        $xsltParameters['motsCles'] = utf8_encode($motsCles);
        $xsltParameters['ouvAnnee'] = utf8_encode($ouvAnnee);
        $xsltParameters['debutOuv'] = utf8_encode($debutOuv);
        $xsltParameters['finOuv'] = utf8_encode($finOuv);
        $xsltParameters['debutDispo'] = utf8_encode($debutDispo);
        $xsltParameters['dureeDispo'] = utf8_encode($dureeDispo);

        $xsltParameters['idCritereTarif'] = $idCritereTarif;
        $xsltParameters['idCritereModalite'] = $idCritereModalite;
        $xsltParameters['bornes'] = utf8_encode($bornes);
        $xsltParameters['checkCriteres'] = utf8_encode($checkCriteres);

        foreach ($traductionsStatiques as $traductionStatique) {
            $xsltParameters['terme' . $traductionStatique] = utf8_encode($this->translator->trans($traductionStatique));
        }

        $cheminFichierXsl = $cheminXsl . $xslFile . "_" . $categorie . ".xsl";
        if (!file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . $xslFile . ".xsl";
        }
        if (!file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . "sit_recherche_" . $categorie . ".xsl";
        }
        if (!file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . "sit_recherche.xsl";
        }

        $contenuBloc = "";

        /*commune*/
        $communeViewParameters = $this->viewParameters;

        unset($communeViewParameters['recherche']);

        $idFicheEnCours = null;
        $communeHtml = $this->getSitListeHtml($currentLocationId, $sitListLocation, $sitListContent, $idFicheEnCours, 'sit_recherche_communes');
        $xsltParameters['liste_communes'] = utf8_encode($communeHtml);
        $xsltParameters['liste_communes'] = preg_replace("/(\\n)|( )+/", ' ', $xsltParameters['liste_communes']);
        /*commune*/

        if (file_exists($cheminFichierCacheXml) && file_exists($cheminFichierXsl)) {
            $contenuBloc = \SitUtils::getHtmlResult($cheminFichierCacheXml, $cheminFichierXsl, $xsltParameters);
        }

        $contenuBloc = preg_replace("/&([\\w\\d]+|\\#\\d+);/si", "_dw_entity__$1__", html_entity_decode($contenuBloc));
        $contenuBloc = preg_replace("/&/si", "&amp;", $contenuBloc);
        $contenuBloc = utf8_decode(preg_replace("/_dw_entity__([^_]+)__/si", "&$1;", $contenuBloc));
        $contenuBloc = "\n" . preg_replace("/(http:\\/\\/[^\\/]+):\\d+/si", "$1", $contenuBloc) . "\n";

        return $contenuBloc;
    }

    public function getSitMiseEnAvantHtml(Location $sitMeaLocation, Content $sitMeaContent, $categorie, $sitMiseEnAvantUrlAlias, $xslFile)
    {
        $rootLocation = $this->controller->getRootLocation();

        // Récupération du lien courant
        $lienCourant = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $sitMeaLocation->id)
        );
        $cheminRacineSite = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $rootLocation->id)
        );

        $lien = "";

        $cheminRacineSite = $cheminRacineSite == "/" ? "" : $cheminRacineSite;

        $lienCourant = preg_replace("{^/layout/set/[^/]+(/.*)}", "$1", $lienCourant);

        $langue = "fr";

        $cheminImagesDesign = $this->container->getParameter('ImagesDesign.CheminRoot');
        $cheminImages = $this->container->getParameter('ImagesDesign.CheminBundle');

        $rootSitUrl = null;
        if ($this->container->hasParameter("GlobalSitParameters.RootSitUrl")) {
            $rootSitUrl = $this->container->getParameter('GlobalSitParameters.RootSitUrl');
        }

        $cheminCacheXml = "";
        if ($this->container->hasParameter("GlobalSitParameters.XmlCachePath")) {
            $cheminCacheXml = $this->container->getParameter('GlobalSitParameters.XmlCachePath');
        }

        if (!file_exists($cheminCacheXml)) {
            mkdir($cheminCacheXml, 0777, true);
        }

        $cheminXsl = "";
        if ($this->container->hasParameter("GlobalSitParameters.XslPath")) {
            $cheminXsl = $this->container->getParameter('GlobalSitParameters.XslPath');
        }

        if (!file_exists($cheminXsl)) {
            mkdir($cheminXsl, 0777, true);
        }

        $traductionsStatiques = array();
        if ($this->container->hasParameter("SitTranslations.StaticSitTranslations")) {
            $traductionsStatiques = $this->container->getParameter('SitTranslations.StaticSitTranslations');
        }

        $titreMEA = $sitMeaContent->getFieldValue('title')->text;

        $modeAffichage = $sitMeaContent->getFieldValue('mode_affichage')->selection;
        $modeAffichage = $modeAffichage[0];

        $titreMiseEnAvant = $sitMeaContent->getFieldValue('title')->text;
        $nbItems = $sitMeaContent->getFieldValue('nb_items')->value;
        $dureeVieCache = $sitMeaContent->getFieldValue('duree_vie_cache')->value * 60;

        $sitParams = array();

        $sitParams['dwimg'] = "1";
        $sitParams['dwadd'] = "111";
        $sitParams['dwdate'] = "111";
        $sitParams['dwcom'] = "11111";
        $sitParams['dwlien'] = "1";
        $sitParams['dwref'] = "1";

        if ($langue) {
            $sitParams['lang'] = $langue;
        }

        $entites = $sitMeaContent->getFieldValue('entites')->selection;
        foreach ($entites as $entite) {
            if ($entite) {
                if (array_key_exists('ide', $sitParams)) {
                    $sitParams['ide'] .= "," . $entite;
                } else {
                    $sitParams['ide'] = $entite;
                }
            }
        }

        $paysEpci = $sitMeaContent->getFieldValue('pays_epci')->selection;
        foreach ($paysEpci as $unPaysEpci) {
            if ($unPaysEpci) {
                if (array_key_exists('idp', $sitParams)) {
                    $sitParams['idp'] .= "," . $unPaysEpci;
                } else {
                    $sitParams['idp'] = $unPaysEpci;
                }
            }
        }

        $criteresAffiches = $sitMeaContent->getFieldValue('criteres_affiches')->categories;
        foreach ($criteresAffiches as $idCritere) {
            if ($idCritere) {
                if (!array_key_exists('dwcrit', $sitParams) || !preg_match("/(^|\\|)" . substr($idCritere, 0, 9) . "/", $sitParams['dwcrit'])) {
                    if (array_key_exists('dwcrit', $sitParams)) {
                        $sitParams['dwcrit'] .= "|" . substr($idCritere, 0, 9);
                    } else {
                        $sitParams['dwcrit'] = substr($idCritere, 0, 9);
                    }
                }
            }
        }

        $criteresTriPrincipaux = $sitMeaContent->getFieldValue('criteres_tri_principaux')->categories;

        $sitParams['sort'] = "pho";
        $sitParams['order'] = "desc";
        foreach ($criteresTriPrincipaux as $critereTri) {
            $idCritereTri = substr($critereTri, 1);
            $sensCritereTri = substr($critereTri, 0, 1);

            if ($idCritereTri == '1') {
                $sitParams['sort'] .= ",com";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri == '2') {
                $sitParams['sort'] .= ",ran";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri == '3') {
                $sitParams['sort'] .= ",nco";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri == '4') {
                $sitParams['sort'] .= ",douv";
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            } else if ($idCritereTri) {
                $sitParams['sort'] .= "," . (strlen($idCritereTri) > 9 ? "m" : (preg_match("/^\\d+$/", $idCritereTri) ? "c" : "")) . $idCritereTri;
                $sitParams['order'] .= "," . ($sensCritereTri == 'd' ? "desc" : "asc");
            }
        }

        $parametresDiffusionSupplementaires = $sitMeaContent->getFieldValue('parametres_diffusion_supplementaires')->matrix;
        $parametresDiffusionSupplementaires = simplexml_load_string($parametresDiffusionSupplementaires);;

        if (isset($parametresDiffusionSupplementaires->rows) && isset($parametresDiffusionSupplementaires->c)) {
            for ($i = 0; $i < count($parametresDiffusionSupplementaires->c); $i += 2) {
                $sitParamName = '' . $parametresDiffusionSupplementaires->c[$i];
                $sitParamValue = '' . $parametresDiffusionSupplementaires->c[$i + 1];
                if ($sitParamName && $sitParamValue) {
                    if (array_key_exists($sitParamName, $sitParams)) {
                        $sitParams[$sitParamName] .= (preg_match("{^dwcrit|mr2$}", $sitParamName) ? "|" : (preg_match("{^mc$}", $sitParamName) ? " " : ",")) . $sitParamValue;
                    } else {
                        $sitParams['' . $sitParamName] = $sitParamValue;
                    }
                    if ($sitParamName == 'dwcrit') {
                        $criteresAffiches = array_merge($criteresAffiches, explode("|", $sitParamValue));
                    }
                }
            }
        }

        $sitParams['nbr'] = $nbItems;
        $sitParams['ofs'] = '0';

        $sitParamsString = "";
        $sitParamsEncodedString = "";
        foreach ($sitParams as $sitParamName => $sitParamValue) {
            $sitParamsString .= "&" . $sitParamName . "=" . $sitParamValue;
            $sitParamsEncodedString .= "&" . urlencode($sitParamName) . "=" . urlencode($sitParamValue);
        }

        $sitParamsString .= $categorie ? "&idc=" . $categorie : "";
        $sitParamsEncodedString .= $categorie ? "&idc=" . $categorie : "";

        $sitParamsStringCrypte = sha1("Recherche__" . substr($sitParamsString, 1));

        $cheminFichierCacheXml = $cheminCacheXml . $sitParamsStringCrypte . ".xml";

        $cacheExpire = true;
        if (file_exists($cheminFichierCacheXml)) {
            $maintenant = time();
            $dateExpirationCache = filemtime($cheminFichierCacheXml) + $dureeVieCache;
            if ($dateExpirationCache > $maintenant) {
                $cacheExpire = false;
            }
        }
        $contenuXmlDistant = "";
        //var_dump($rootSitUrl."Recherche".$sitParamsEncodedString);
        if ($cacheExpire) {
            $contenuXmlDistant = \SitUtils::urlGetContentsCurl($rootSitUrl . "Recherche" . $sitParamsEncodedString, 120);
            if ($contenuXmlDistant) {
                $contenuXmlCache = utf8_encode(preg_replace("/&([\\w\\d]+|\\#\\d+);/si", "_dw_entity__$1__", $contenuXmlDistant));
                file_put_contents($cheminFichierCacheXml, $contenuXmlCache, LOCK_EX);
            }
        }

        $this->logger->info($rootSitUrl . "Recherche" . $sitParamsString);

        $idCritereTarif = "";
        $idCritereModalite = "";
        if ($this->container->hasParameter("GlobalSitParameters.CriteresTarisPourCateg")) {
            $criteresTarisPourCateg = $this->container->getParameter('GlobalSitParameters.CriteresTarisPourCateg');
            if (array_key_exists($categorie, $criteresTarisPourCateg)) {
                $criteresTarisPourCateg = explode('|', $criteresTarisPourCateg[$categorie]);
                $idCritereTarif = $criteresTarisPourCateg[0];
                $idCritereModalite = $criteresTarisPourCateg[1];
            }
        }

        $xsltParameters = array();
        $xsltParameters['titreMEA'] = utf8_encode($titreMEA);
        $xsltParameters['lienCourant'] = $lienCourant;
        $xsltParameters['titreMiseEnAvant'] = utf8_encode($titreMiseEnAvant);
        $xsltParameters['couleursThemes'] = "";
        $xsltParameters['cheminImages'] = $cheminImagesDesign ? $cheminImagesDesign : $cheminImagesDesign;
        $xsltParameters['cheminImagesDesign'] = $cheminImages;
        $xsltParameters['cheminRacineSite'] = $cheminRacineSite;
        $xsltParameters['rootSitUrl'] = $rootSitUrl;
        $xsltParameters['sitListeUrlAlias'] = $sitMiseEnAvantUrlAlias;
        $sitMiseEnAvantUrlAlias = substr_replace($sitMiseEnAvantUrlAlias, '', 0, 1);
        $xsltParameters['sitMiseEnAvantUrlAlias'] = str_replace("/", "~", $sitMiseEnAvantUrlAlias);

        $pageCourante = "1";
        if (array_key_exists('page', $this->viewParameters) && $this->viewParameters['page']) {
            $pageCourante = $this->viewParameters['page'];
        }
        $xsltParameters['pageCourante'] = $pageCourante;

        $triEnCours = "";
        if (array_key_exists('tri', $this->viewParameters) && $this->viewParameters['tri']) {
            $triEnCours = $this->viewParameters['tri'];
        }
        $xsltParameters['triEnCours'] = $triEnCours;

        $rechercheEnCours = "non";
        if (array_key_exists('recherche', $this->viewParameters) && $this->viewParameters['recherche']) {
            $rechercheEnCours = $this->viewParameters['recherche'];
        }
        $xsltParameters['rechercheEnCours'] = $rechercheEnCours;

        $xsltParameters['criteresAffiches'] = "|" . implode("|", $criteresAffiches) . "|";

        $xsltParameters['caracteresKo'] = utf8_encode("Å Å’Å½Å¸Â¥ÂµÃ€ÃÃ‚ÃƒÃ„Ã…Ã†Ã‡ÃˆÃ‰ÃŠÃ‹ÃŒÃÃŽÃÃÃ‘Ã’Ã“Ã”Ã•Ã–Ã˜Ã™ÃšÃ›ÃœÃÃŸ");
        $xsltParameters['caracteresOk'] = utf8_encode("Å¡Å“Å¾Ã¿Â¥ÂµÃ Ã¡Ã¢Ã£Ã¤Ã¥Ã¦Ã§Ã¨Ã©ÃªÃ«Ã¬Ã­Ã®Ã¯Ã°Ã±Ã²Ã³Ã´ÃµÃ¶Ã¸Ã¹ÃºÃ»Ã¼Ã½ÃŸ");

        $xsltParameters['langue'] = $langue;

        $xsltParameters['idCritereTarif'] = $idCritereTarif;
        $xsltParameters['idCritereModalite'] = $idCritereModalite;
        $xsltParameters['lien'] = $lien;

        foreach ($traductionsStatiques as $traductionStatique) {
            $xsltParameters['terme' . $traductionStatique] = utf8_encode($this->translator->trans($traductionStatique));
        }
        $cheminFichierXsl = "";


        if ((!$cheminFichierXsl || !file_exists($cheminFichierXsl)) && $modeAffichage) {
            $cheminFichierXsl = $cheminXsl . "sit_mise_en_avant_mode" . $modeAffichage . "_" . $categorie . ".xsl";
        }
        if ((!$cheminFichierXsl || !file_exists($cheminFichierXsl)) && $modeAffichage) {
            $cheminFichierXsl = $cheminXsl . "sit_mise_en_avant_mode" . $modeAffichage . ".xsl";
        }
        if (!$cheminFichierXsl || !file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . "sit_mise_en_avant_" . $categorie . ".xsl";
        }
        if (!$cheminFichierXsl || !file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . "sit_mise_en_avant.xsl";
        }

        /*$pageURL = 'http';
        $pageURL .= "://";
        $pageURL .= eZSys::serverVariable("SERVER_NAME");*/
        //$siteUrl = $siteIni->variable('SiteSettings','SiteURL');
        $xsltParameters['siteUrl'] = "";

        $contenuBloc = "";
        if (file_exists($cheminFichierCacheXml) && file_exists($cheminFichierXsl)) {
            $contenuBloc = \SitUtils::getHtmlResult($cheminFichierCacheXml, $cheminFichierXsl, $xsltParameters);
        }

        $contenuBloc = preg_replace("/_dw_entity__#13__\n/si", " ", $contenuBloc);
        $contenuBloc = utf8_decode(preg_replace("/_dw_entity__([^_]+)__/si", "&$1;", $contenuBloc));
        $contenuBloc = preg_replace("/&amp;([\\w\\d]+|\\#\\d+);/si", "&$1;", html_entity_decode($contenuBloc));
        $contenuBloc = "\n" . preg_replace("/(http:\\/\\/[^\\/]+):\\d+/si", "$1", $contenuBloc) . "\n";

        return $contenuBloc;
    }

    public function getFicheDetail($idFiche, $cheminCategorie, $ficheTitle)
    {
        $repository = $this->controller->getRepository();
        $connection = $this->controller->getDoctrine()->getConnection();
        $helperContent = $this->controller->get('ayaline_tools.tools.content');

        $rootLocation = $this->controller->getRootLocation();
        $rootSitUrl = null;
        if ($this->container->hasParameter("GlobalSitParameters.RootSitUrl")) {
            $rootSitUrl = $this->container->getParameter('GlobalSitParameters.RootSitUrl');
        }

        $cheminCacheXml = "";
        if ($this->container->hasParameter("GlobalSitParameters.XmlCachePath")) {
            $cheminCacheXml = $this->container->getParameter('GlobalSitParameters.XmlCachePath');
        }

        if (!file_exists($cheminCacheXml)) {
            mkdir($cheminCacheXml, 0777, true);
        }

        $cheminXsl = "";
        if ($this->container->hasParameter("GlobalSitParameters.XslPath")) {
            $cheminXsl = $this->container->getParameter('GlobalSitParameters.XslPath');
        }

        if (!file_exists($cheminXsl)) {
            mkdir($cheminXsl, 0777, true);
        }

        $traductionsStatiques = array();

        if ($this->container->hasParameter("SitTranslations.StaticSitTranslations")) {
            $traductionsStatiques = $this->container->getParameter('SitTranslations.StaticSitTranslations');
        }

        $dureeVieCache = $this->container->hasParameter("GlobalSitParameters.DureeVieCacheFiche") ? $this->container->getParameter("GlobalSitParameters.DureeVieCacheFiche") : 0;
        $dureeVieCache = $dureeVieCache * 60;

        $xslFile = null;
        if (!$xslFile || !trim($xslFile)) {
            $xslFile = "sit_fiche";
        }

        $triEnCours = "";
        if (array_key_exists('tri', $this->viewParameters)) {
            $triEnCours = $this->viewParameters['tri'];
        }

        $rechercheEnCours = "non";
        if (array_key_exists('recherche', $this->viewParameters)) {
            $rechercheEnCours = $this->viewParameters['recherche'];
        }

        $pageCourante = "";
        if (array_key_exists('page', $this->viewParameters)) {
            $pageCourante = $this->viewParameters['page'];
        }

        $langue = "fr";

        $sitParamsString = $idFiche ? "&idP=" . $idFiche : "";
        $sitParamsString .= $langue ? "&lang=" . $langue : "";

        $sitParamsStringCrypte = sha1("Produit__" . substr($sitParamsString, 1));

        $cheminFichierCacheXml = $cheminCacheXml . $sitParamsStringCrypte . ".xml";

        $cacheExpire = true;
        if (file_exists($cheminFichierCacheXml)) {
            $maintenant = time();
            $dateExpirationCache = filemtime($cheminFichierCacheXml) + $dureeVieCache;
            if ($dateExpirationCache > $maintenant) {
                $cacheExpire = false;
            }
        }
        $contenuXmlDistant = "";
        if ($cacheExpire) {
            $contenuXmlDistant = \SitUtils::urlGetContentsCurl($rootSitUrl . "Produit" . $sitParamsString, 100);

            if ($contenuXmlDistant && substr(trim($contenuXmlDistant), 0, 5) === "<?xml") {
                $contenuXmlCache = utf8_encode(preg_replace("/&([\\w\\d]+|\\#\\d+);/si", "_dw_entity__$1__", $contenuXmlDistant));
                file_put_contents($cheminFichierCacheXml, $contenuXmlCache, LOCK_EX);
            }
        }

        /*
         * Ajout de infos de Proximites (addProximiteToFicheXML)
         */
        if (file_exists($cheminFichierCacheXml)) {
            $_cacheXmlContents = file_get_contents($cheminFichierCacheXml);
            if (strlen(trim($_cacheXmlContents)) > 0 && substr(trim($_cacheXmlContents), 0, 5) === "<?xml") {
                // A revoir
                //\SitProximitesUtils::addProximiteToFicheXML($cheminFichierCacheXml);
            }
        }

        $this->logger->info($rootSitUrl . "Produit" . $sitParamsString);

        $cheminRacineSite = $this->controller->generateUrl(
            'ez_urlalias',
            array('locationId' => $rootLocation->id)
        );
        $cheminRacineSite = $cheminRacineSite == "/" ? "" : $cheminRacineSite;

        $cheminImagesDesign = $this->container->getParameter('ImagesDesign.CheminRoot');
        $cheminImages = $this->container->getParameter('ImagesDesign.CheminBundle');

        $xsltParameters = array();

        $xsltParameters['cheminRacineSite'] = $cheminRacineSite;
        $xsltParameters['rootSitUrl'] = $rootSitUrl;
        
        $xsltParameters['triEnCours'] = $triEnCours;
        $xsltParameters['rechercheEnCours'] = $rechercheEnCours;
        $xsltParameters['pageCourante'] = $pageCourante;

        $xsltParameters['langue'] = $langue;

        $xsltParameters['cheminImages'] = $cheminImagesDesign ? $cheminImagesDesign : $cheminImagesDesign;
        $xsltParameters['cheminImagesDesign'] = $cheminImages;

        $currentCheminCategorie = "";
        $locationExist = false;
        $previousLocationId = null;
        $previousContent = null;
        if ($cheminCategorie) {
            $cheminCategorie = explode("~", $cheminCategorie);
            foreach ($cheminCategorie as $cheminCategoriePart) {
                $currentCheminCategorie .= ($currentCheminCategorie ? "/" : "") . $cheminCategoriePart;
                $currentLocationId = $helperContent->loadLocationIdByNodePath($currentCheminCategorie, $connection);
                if ($currentLocationId) {
                    $previousLocationId = $currentLocationId;
                    $locationExist = true;
                }
            }
        }

        if (!$locationExist && array_key_exists('HTTP_REFERER', $_SERVER)) {
            $httpReferer = preg_replace("{^" . $cheminRacineSite . "/(.*?)(/\\([^\\)]*\\)/[^/]*)*$}", "$1", $_SERVER['HTTP_REFERER']);
            $httpReferer = $httpReferer ? $httpReferer : "/";
            $previousLocationId = $helperContent->loadLocationIdByNodePath($httpReferer, $connection);
            /*
            if ($previousLocationId) {

            }*/
        }

        $lienPrecedent = "";
        if ($previousLocationId) {
            $lienPrecedent = $this->controller->generateUrl(
                'ez_urlalias',
                array('locationId' => $previousLocationId)
            );
        }

        $xsltParameters['lienPrecedent'] = $lienPrecedent;
        $xsltParameters['anneeCourante'] = date("Y");

        $categorie = null;
        $intituleFiche = "Fiche inconnue";
        if (file_exists($cheminFichierCacheXml)) {
            $xmlFiche = simplexml_load_file($cheminFichierCacheXml);
            if ($xmlFiche) {
                $categorieNode = $xmlFiche->xpath("/produit/categorie[string-length(@id) > 0]");
                if ($categorieNode && count($categorieNode) > 0) {
                    $categorie = $categorieNode[0]->attributes()->id;
                }

                $intituleFicheNode = $xmlFiche->xpath('/produit/intitule');
                if ($intituleFicheNode && count($intituleFicheNode) > 0) {
                    $intituleFiche = utf8_decode("" . $intituleFicheNode[0]);
                }
            }
        }

        $criteresAffiches = array();
        $criteresNonAffiches = array();
        $modeAffichageCriteres = array('0');
        if ($categorie && $previousLocationId) {
            $previousLocation = $repository->getLocationService()->loadLocation($previousLocationId);
            $previousContent = $repository->getContentService()->loadContent($previousLocation->contentInfo->id);
            $categorieSelection = $previousContent->getFieldValue('categorie')->selection;
            $query = new Query();
            $query->criterion = new Criterion\LogicalAnd(
                array(
                    new Criterion\Subtree($previousLocation->pathString),
                    new Criterion\Field("categorie", Criterion\Operator::IN, $categorieSelection),
                    new Criterion\ContentTypeIdentifier("sit_fiche"),
                )
            );
            $sitFicheContent = null;
            $searchResults = $repository->getSearchService()->findContent($query);
            if (count($searchResults->searchHits)) {
                $sitFicheContent = $searchResults->searchHits;
            }
            if ($sitFicheContent && count($sitFicheContent)) {
                $sitFicheContent = $sitFicheContent[0]->valueObject;
            } else {
                $sitFicheContent = null;
            }
            if ($sitFicheContent) {
                $modeAffichageCriteres = $sitFicheContent->getFieldValue('mode_affichage_criteres')->selection;
                $criteresAffiches = $sitFicheContent->getFieldValue('criteres_affiches')->categories;
                $criteresNonAffiches = $sitFicheContent->getFieldValue('criteres_non_affiches')->categories;
            }

        }
        $xsltParameters['modeAffichageCriteres'] = $modeAffichageCriteres[0] == '1' ? "afficher" : ($modeAffichageCriteres[0] == '2' ? "pas_afficher" : "afficher_tout");
        $xsltParameters['criteresAffiches'] = "|" . implode("|", $criteresAffiches) . "|";
        $xsltParameters['criteresNonAffiches'] = "|" . implode("|", $criteresNonAffiches) . "|";

        foreach ($traductionsStatiques as $traductionStatique) {
            $xsltParameters['terme' . $traductionStatique] = utf8_encode($this->translator->trans($traductionStatique));
        }

        $sitListeContent = null;
        if ($previousContent && $helperContent->getClassIdentifier($previousContent->contentInfo->mainLocationId)) {
            $sitListeContent = $previousContent;
        }
        if (!$categorie && $sitListeContent) {
            $sitListeContent = $previousContent;
            if ($sitListeContent && $helperContent->getClassIdentifier($sitListeContent->contentInfo->mainLocationId) != 'sit_liste') {
                $categorie = $previousContent->getFieldValue('categorie')->selection;
                $categorie = $categorie[0];
            }
        }

        $cheminFichierXsl = null;
        if ($categorie) {
            $cheminFichierXsl = $cheminXsl . $xslFile . "_" . $categorie . ".xsl";
        }
        if (!$cheminFichierXsl || !file_exists($cheminFichierXsl)) {
            $cheminFichierXsl = $cheminXsl . $xslFile . ".xsl";
        }


        /* Déb : Test de la validité de la fiche */
        if (file_exists($cheminFichierCacheXml)) {
            $fichierCacheSimpleXml = simplexml_load_file($cheminFichierCacheXml);
            $ficheDateValiditeDebut = $fichierCacheSimpleXml->xpath("/produit/dateValidite/dateValiditeDebut");
            $ficheDateValiditeFin = $fichierCacheSimpleXml->xpath("/produit/dateValidite/dateValiditeFin");
            $_ficheProduitIsValid = true;
            if (is_array($ficheDateValiditeDebut) && count($ficheDateValiditeDebut) > 0) {
                $ficheDateValiditeDebut = (string)$ficheDateValiditeDebut[0];
            }
            if (is_array($ficheDateValiditeFin) && count($ficheDateValiditeFin) > 0) {
                $ficheDateValiditeFin = (string)$ficheDateValiditeFin[0];
            }

            /* Redirect si les date de den et fin de validité ne sont pas renseignées */
            if (!is_string($ficheDateValiditeDebut) || strlen(trim($ficheDateValiditeDebut)) == 0) {
                $_ficheProduitIsValid = false;
            }
            if (!is_string($ficheDateValiditeFin) || strlen(trim($ficheDateValiditeDebut)) == 0) {
                $_ficheProduitIsValid = false;
            }

            //$ficheDateValiditeDebutTS = strtotime(trim($ficheDateValiditeDebut));
            //$ficheDateValiditeFinTS = strtotime(trim($ficheDateValiditeFin)) + (24*60*60);//+1j pour inclure ledernier jour de date de fin


            /* Normaliser le format date (yyyy-dd-mm) */
            $ficheDateValiditeDebut = preg_replace("/\\//", "-", $ficheDateValiditeDebut);
            $ficheDateValiditeFin = preg_replace("/\\//", "-", $ficheDateValiditeFin);

            $ficheDateValiditeDebutArr = explode("-", $ficheDateValiditeDebut);
            $ficheDateValiditeFinArr = explode("-", $ficheDateValiditeFin);

            $ficheDateValiditeDebutInt = (int)preg_replace("/-/", "", $ficheDateValiditeDebut);
            $ficheDateValiditeFinInt = (int)preg_replace("/-/", "", $ficheDateValiditeFin);
            $currentDateInt = (int)date('Ymd');

            /* Hack pour timestamp false (date > 2038 ) */
            if (is_array($ficheDateValiditeDebutArr) && is_array($ficheDateValiditeFinArr)) {
                /* Valide pour le format yyyy-mm-dd */
                foreach ($ficheDateValiditeDebutArr as $dateKey => $dateVal) {
                    if ((int)$dateVal > 9) {
                        $dateVal = '0' . ((int)$dateVal);
                    }
                    $ficheDateValiditeDebutArr[$dateKey] = (int)$dateVal;
                }
                foreach ($ficheDateValiditeFinArr as $dateKey => $dateVal) {
                    if ((int)$dateVal > 9) {
                        $dateVal = '0' . ((int)$dateVal);
                    }
                    $ficheDateValiditeFinArr[$dateKey] = $dateVal;
                }
                $ficheDateValiditeDebutInt = (int)implode("", $ficheDateValiditeDebutArr);
                $ficheDateValiditeFinInt = (int)implode("", $ficheDateValiditeFinArr) + 1;
            }

            if (!$_ficheProduitIsValid || $ficheDateValiditeDebutInt > $currentDateInt || $currentDateInt > $ficheDateValiditeFinInt) {
                /* Redirection vers la page sit liste */
                echo "<pre>Redirection vers la page sit liste</pre>";
            }
        }
        /* Fin : Test de la validité de la fiche */

        $idCritereTarif = "";
        $idCritereModalite = "";
        if ($this->container->hasParameter("GlobalSitParameters.CriteresTarisPourCateg")) {
            $criteresTarisPourCateg = $this->container->getParameter('GlobalSitParameters.CriteresTarisPourCateg');
            if (array_key_exists((int)$categorie, $criteresTarisPourCateg)) {
                $criteresTarisPourCateg = explode('|', $criteresTarisPourCateg[(int)$categorie]);
                $idCritereTarif = $criteresTarisPourCateg[0];
                $idCritereModalite = $criteresTarisPourCateg[1];
            }
        }

        $xsltParameters['idCritereTarif'] = $idCritereTarif;
        $xsltParameters['idCritereModalite'] = $idCritereModalite;


        /*
        if (!is_null($sitListeNode)) {
            $tpl->setVariable('node', $sitListeNode);
        }

        /*récupération du bloc sit liste aléatoire*/
        /*
        $xsltParemters['randomSitListeContent'] = $tpl->fetch('design:fiche_detail/random_sit_liste.tpl');
        $xsltParemters['randomSitListeContent'] = preg_replace("/(\\n)|( )+/", ' ', $xsltParemters['randomSitListeContent']);
        */

        $descriptionFiche = "";
        if (file_exists($cheminFichierCacheXml)) {
            $xmlFiche = simplexml_load_file($cheminFichierCacheXml);
            if ($xmlFiche) {
                $descriptionFicheNode = $xmlFiche->xpath("/produit/commentaires/commentaire1");
                if ($descriptionFicheNode && count($descriptionFicheNode) > 0) {
                    $descriptionFiche = utf8_decode("" . $descriptionFicheNode[0]);
                }
                if (strlen($descriptionFiche) > 250) {
                    $descriptionFiche = substr($descriptionFiche, 0, 250) . '...';
                }
            }
        }

        $contenuBloc = "";
        if (file_exists($cheminFichierCacheXml) && file_exists($cheminFichierXsl)) {
            $contenuBloc = \SitUtils::getHtmlResult($cheminFichierCacheXml, $cheminFichierXsl, $xsltParameters);
        }

        $contenuBloc = preg_replace("/_dw_entity__#13__\n/si", " ", $contenuBloc);
        $contenuBloc = utf8_decode(preg_replace("/_dw_entity__([^_]+)__/si", "&$1;", $contenuBloc));
        $contenuBloc = preg_replace("/&amp;([\\w\\d]+|\\#\\d+);/si", "&$1;", html_entity_decode($contenuBloc));
        $contenuBloc = "\n" . preg_replace("/(http:\\/\\/[^\\/]+):\\d+/si", "$1", $contenuBloc) . "\n";

        $intituleFiche = preg_replace("/&([\\w\\d]+|\\#\\d+);/si", "_dw_entity__$1__", html_entity_decode($intituleFiche));
        $intituleFiche = utf8_decode(preg_replace("/_dw_entity__([^_]+)__/si", "&$1;", $intituleFiche));
        $intituleFiche = html_entity_decode($intituleFiche);

        $templateParameters = array();
        $templateParameters['contenuBloc'] = $contenuBloc;
        $templateParameters['intituleFiche'] = utf8_encode($intituleFiche);
        $templateParameters['parentLocationId'] = $previousLocationId ? $previousLocationId : false;
        $templateParameters['pagelayoutTemplate'] = $this->container->getParameter('SitFiche.Pagelayout.Template');
        $templateParameters['sitFicheTemplate'] = $this->container->getParameter('SitFiche.Detail.Template');
        $templateParameters['descriptionFiche'] = $descriptionFiche;
        $templateParameters['idFiche'] = $idFiche;

        return $templateParameters;
    }
}