src/EventSubscriber/ControllerSubscriber.php line 235

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Psr\Log\LoggerInterface;
  4. use App\Helper\Utils;
  5. use App\Services\CustomLogger;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Session\Session;
  10. use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
  11. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use App\Entity\Utilisateur;
  16. use Symfony\Component\Security\Core\Security;
  17. use Symfony\Component\HttpKernel\Event\RequestEvent;
  18. class ControllerSubscriber implements EventSubscriberInterface {
  19.     /**
  20.      * @var \Psr\Log\LoggerInterface
  21.      */
  22.     private $logger;
  23.     private $urlRedis;
  24.     /**
  25.      * @var ParameterBagInterface
  26.      */
  27.     private ParameterBagInterface $params;
  28.     /**
  29.      * @var \Doctrine\ORM\EntityManagerInterface
  30.      */
  31.     private $em;
  32.     private $security;
  33.     public function __construct(ParameterBagInterface $paramsstring $urlRedisEntityManagerInterface $emSecurity $securityLoggerInterface $logger) {
  34.         $this->params $params;
  35.         $this->urlRedis $urlRedis;
  36.         $this->em $em;
  37.         $this->security $security;
  38.         $this->logger $logger;
  39.     }
  40.     public static function getSubscribedEvents() {
  41.         /* return [
  42.           KernelEvents::CONTROLLER => [
  43.           ['processRedirectionInternational', 10]
  44.           ],
  45.           ]; */
  46.         return [KernelEvents::REQUEST => ['onRequest'0]];
  47.     }
  48.     public function onRequest(RequestEvent $event) {
  49.         $request $event->getRequest();
  50.         $session $request->getSession(); // utilise la session Symfony
  51.         $url $request->getPathInfo();
  52.         $requestUri $request->getUri();
  53.         // Ajout de la logique spécifique pour les URLs de Buzz
  54.         if (preg_match('/^\/buzz\/([a-z]{2})$/'$url$matches) || preg_match('/^\/buzz$/'$url)) {
  55.             $codeUrl $matches[1] ?? 'fr';
  56.             $session->set("codePays"$codeUrl);
  57.             $_SESSION["codePays"] = $codeUrl;
  58.             setcookie("codePays"strtoupper($codeUrl), time() + 3600 24 365"/");
  59.             return;
  60.         }
  61.         $user $this->security->getUser();
  62.         if (!empty($user)) {
  63.             $session->set("token", (array) $user); // $_SESSION EST BIEN CHARGÉ MAINTENANT
  64.             $session->set('user'$user);
  65.         }
  66.         // l url sera modifié si elle n'est pas validé reg_match par la liste static
  67.         if (!$this->istUrlToIgnore($url)) {
  68.             $requestUri explode("?"$requestUri);
  69.             $listeCodePaysActive = array("be""ca"'fr''ch');
  70.             if (!empty($request->server->get('HTTP_CLIENT_IP'))) {
  71.                 $ipClient $request->server->get('HTTP_CLIENT_IP');
  72.             } else if (!empty($request->server->get('HTTP_X_FORWARDED_FOR'))) {
  73.                 $ipClient $request->server->get('HTTP_X_FORWARDED_FOR');
  74.             } else {
  75.                 $ipClient $request->server->get('REMOTE_ADDR');
  76.             }
  77.             $_SESSION['ipClient'] = $ipClient;
  78.             $session->set("ipClient"$ipClient);
  79.             $botRegexPattern 'googlebot|bingbot|slurp|duckduckbot|baiduspider|yandex|sogou|exabot|facebot|ia_archiver|twitterbot|tweetmemebot|rogerbot|linkedinbot|embedly|quora link preview|outbrain|pinterest|slackbot|vkshare|w3c_validator|redditbot|tumblr|xenuforobot|ahrefsbot|semrushbot|adsbot-google|feedfetcher-google|mediapartners-google|google-structured-data-testing-tool|google-read-aloud|google-speakr|google-podcast|google-page-experience|google-page-speed-insights|google-search-console|google-site-verification|google-web-light|google-weblight|google-webmaster-tools|google-webmaster-central|google-webmaster-central-api|google-webmaster-central-api-v3|googlebot\/|Googlebot-Mobile|Googlebot-Image|Google favicon|Mediapartners-Google|java|wget|curl|Commons-HttpClient|Python-urllib|libwww|httpunit|nutch|phpcrawl|jyxobot|FAST-WebCrawler|FAST Enterprise Crawler|biglotron|teoma|convera|seekbot|gigablast|ngbot|GingerCrawler|webmon|httrack|webcrawler|grub\.org|UsineNouvelleCrawler|antibot|netresearchserver|speedy|fluffy|bibnum\.bnf|findlink|msrbot|panscient|yacybot|AISearchBot|IOI|ips-agent|tagoobot|MJ12bot|woriobot|yanga|buzzbot|mlbot|purebot|Linguee Bot|Voyager|CyberPatrol|voilabot|citeseerxbot|spbot|twengabot|postrank|turnitinbot|scribdbot|page2rss|sitebot|linkdex|Adidxbot|blekkobot|ezooms|Mail\.RU_Bot|discobot|heritrix|findthatfile|europarchive\.org|NerdByNature\.Bot|sistrix crawler|Aboundex|domaincrawler|wbsearchbot|summify|ccbot|edisterbot|seznambot|ec2linkfinder|gslfbot|aihitbot|intelium_bot|yeti|RetrevoPageAnalyzer|lb-spider|lssbot|careerbot|wotbox|wocbot|ichiro|lssrocketcrawler|drupact|webcompanycrawler|acoonbot|openindexspider|gnam gnam spider|web-archive-net\.com\.bot|backlinkcrawler|coccoc|integromedb|content crawler spider|toplistbot|seokicks-robot|it2media-domain-crawler|ip-web-crawler\.com|siteexplorer\.info|elisabot|proximic|changedetection|blexbot|arabot|WeSEE:Search|niki-bot|CrystalSemanticsBot|360Spider|psbot|InterfaxScanBot|Lipperhey SEO Service|CC Metadata Scaper|g00g1e\.net|GrapeshotCrawler|urlappendbot|brainobot|fr-crawler|binlar|SimpleCrawler|Livelapbot|cXensebot|smtbot|bnf\.fr_bot|A6-Indexer|ADmantX|OrangeBot|memorybot|AdvBot|MegaIndex|SemanticScholarBot|ltx71|nerdybot|xovibot|BUbiNG|Qwantify|archive\.org_bot|Applebot|crawler4j|findxbot|SemrushBot|yoozBot|y!j-asr|Domain Re-Animator Bot|AddThis|YisouSpider|BLEXBot|YandexBot|SurdotlyBot|AwarioRssBot|FeedlyBot|Barkrowler|Gluten Free Crawler|Cliqzbot';
  80.             $isbot preg_match("/{$botRegexPattern}/"$request->server->get('HTTP_USER_AGENT'));
  81.             $ua $request->headers->get('User-Agent''');
  82.             $accept $request->headers->get('Accept''');
  83.             $secFetchSite $request->headers->get('Sec-Fetch-Site');
  84.             $secFetchMode $request->headers->get('Sec-Fetch-Mode');
  85.             $looksLikeBrowser =
  86.             $ua !== '' &&
  87.             (strpos($accept'text/html') !== false || strpos($accept'application/json') !== false) &&
  88.             $secFetchSite !== null &&
  89.             $secFetchMode !== null;
  90.             
  91.             
  92.             //nouveau façson redirection##################################################################################
  93.             /* $codeUrl = "";
  94.               $codePaysFinal = "";
  95.               $codeToSee = "";
  96.               $urlRetour = "";
  97.               $cookieCountry = strtolower((string) $request->cookies->get("codePays", ''));
  98.               $sessionCountry = strtolower((string) ($session->get('codePays') ?? ''));
  99.               if (!empty($cookieCountry)) {
  100.               $session->set("codePays", $cookieCountry);
  101.               $codeToSee = $cookieCountry;
  102.               $_SESSION["codePays"] = $cookieCountry;
  103.               }
  104.               if (!empty($sessionCountry)) {
  105.               $codeToSee = $sessionCountry;
  106.               }
  107.               if (preg_match("/\_[a-z]+\_/", $url)) {
  108.               $codeUrl = substr($url, -3, 2);
  109.               $urlRetour = substr($url, 0, -4);
  110.               }
  111.               elseif ($url == "/" || (preg_match("/\/[a-z][a-z]/", $url) && strlen($url) == 3)) {
  112.               $codeUrl = substr($url, -2, 2);
  113.               $urlRetour = "/";
  114.               }
  115.               else{
  116.               $urlRetour = $url;
  117.               }
  118.               if (!in_array(strtolower($codeUrl), $listeCodePaysActive)) {
  119.               if (!empty($codeToSee)&&in_array(strtolower($codeToSee), $listeCodePaysActive)) {
  120.               $codePaysFinal = $codeToSee;
  121.               }
  122.               else{
  123.               if (!$isbot &&empty($user)&&$looksLikeBrowser){
  124.               $infoPays = $this->getInfoPaysIp($ipClient);
  125.               if (!empty($infoPays["country_code"])&&in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
  126.               $session->set("codePays", strtolower($infoPays["country_code"]));
  127.               $_SESSION["codePays"] = strtolower($infoPays["country_code"]);
  128.               $codePaysFinal = strtolower($infoPays["country_code"]);
  129.               } else {
  130.               $session->set("codePays", "fr");
  131.               $_SESSION["codePays"] = "fr";
  132.               $codePaysFinal = "fr";
  133.               }
  134.               }
  135.               else{
  136.               $session->set("codePays", "fr");
  137.               $_SESSION["codePays"] = "fr";
  138.               $codePaysFinal = "fr";
  139.               }
  140.               }
  141.               if ($urlRetour=="/") {
  142.               $urlRetour = "/" . strtolower($codePaysFinal) ;
  143.               }
  144.               else{
  145.               $urlRetour .= "_" . strtolower($codePaysFinal) . "_";
  146.               }
  147.               if (isset($requestUri[1])) {
  148.               $urlRetour .= "?" . $requestUri[1];
  149.               }
  150.               $session->set("codePays", $codePaysFinal);
  151.               $_SESSION["codePays"] =$codePaysFinal;
  152.               if ($codePaysFinal!=$cookieCountry) {
  153.               setcookie("codePays", strtoupper($codeUrl), time() + 60 * 60 * 24 * 365);
  154.               }
  155.               $event->setResponse(new RedirectResponse($urlRetour));
  156.               }
  157.               else{
  158.               $codePaysFinal = $codeUrl;
  159.               $session->set("codePays", $codePaysFinal);
  160.               $_SESSION["codePays"] =$codePaysFinal;
  161.               if ($codePaysFinal!=$cookieCountry) {
  162.               setcookie("codePays", strtoupper($codeUrl), time() + 60 * 60 * 24 * 365);
  163.               }
  164.               return;
  165.               } */
  166.             //nouveau façson redirection##################################################################################
  167.             //ancien façson redirection##################################################################################
  168.             $okCookie false;
  169.             if (isset($_COOKIE["codePays"]) && $_COOKIE["codePays"] != "") {
  170.                 if (!in_array(strtolower($_COOKIE["codePays"]), $listeCodePaysActive)) {
  171.                     $okCookie false;
  172.                 } else {
  173.                     $okCookie true;
  174.                 }
  175.             }
  176.             if (preg_match("/\_[a-z]+\_/"$url)) {
  177.                 $codeUrl substr($url, -32);
  178.                 if (!in_array(strtolower($codeUrl), $listeCodePaysActive)) {
  179.                     if ($okCookie) {
  180.                         $urlRetour substr($url0, -4);
  181.                         $urlRetour .= "_" strtolower($_COOKIE["codePays"]) . "_";
  182.                         if (isset($requestUri[1])) {
  183.                             $urlRetour .= "?" $requestUri[1];
  184.                         }
  185.                         $session->set("codePays"$_COOKIE["codePays"]);
  186.                         $_SESSION["codePays"] = $_COOKIE["codePays"];
  187.                     } else {
  188.                         $codeRe "fr";
  189.                         if (!$isbot && empty($_SESSION["codePays"]) && empty($session->get("codePays")) && empty($user) && empty($_COOKIE["codePays"]) && $looksLikeBrowser) {
  190.                             $infoPays $this->getInfoPaysIp($ipClient);
  191.                             if (!empty($infoPays["country_code"]) && in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
  192.                                 $session->set("codePays"$infoPays["country_code"]);
  193.                                 $_SESSION["codePays"] = $infoPays["country_code"];
  194.                                 $codeRe strtolower($infoPays["country_code"]);
  195.                             } else {
  196.                                 $session->set("codePays""FR");
  197.                                 $_SESSION["codePays"] = "FR";
  198.                             }
  199.                         } elseif (!$isbot && empty($_SESSION["codePays"]) && !empty($session->get("codePays"))) {
  200.                             $_SESSION["codePays"] = $session->get("codePays");
  201.                             if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
  202.                                 $codeRe strtolower($session->get("codePays"));
  203.                             }
  204.                         } elseif (!$isbot && !empty($_SESSION["codePays"]) && empty($session->get("codePays"))) {
  205.                             $session->set("codePays"$_SESSION["codePays"]);
  206.                             if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
  207.                                 $codeRe strtolower($session->get("codePays"));
  208.                             }
  209.                         } else {
  210.                             $session->set("codePays""FR");
  211.                             $_SESSION["codePays"] = "FR";
  212.                         }
  213.                         $urlRetour substr($url0, -4);
  214.                         $urlRetour .= "_" strtolower($codeRe) . "_";
  215.                         if (isset($requestUri[1])) {
  216.                             $urlRetour .= "?" $requestUri[1];
  217.                         }
  218.                         setcookie("codePays"strtoupper($codeRe), time() + 60 60 24 365);
  219.                     }
  220.                     $event->setResponse(new RedirectResponse($urlRetour));
  221.                 } else {
  222.                     $session->set("codePays"$codeUrl);
  223.                     $_SESSION["codePays"] = $codeUrl;
  224.                     setcookie("codePays"strtoupper($codeUrl), time() + 60 60 24 365);
  225.                 }
  226.             } elseif ($url == "/" || (preg_match("/\/[a-z][a-z]/"$url) && strlen($url) == 3)) {
  227.                 $codeUrl "";
  228.                 if ((preg_match("/\/[a-z][a-z]/"$url) && strlen($url) == 3)) {
  229.                     $codeUrl substr($url, -22);
  230.                 }
  231.                 if ($url == "/" || !in_array(strtolower($codeUrl), $listeCodePaysActive)) {
  232.                     if ($okCookie) {
  233.                         if ((preg_match("/\/[a-z][a-z]/"$url) && strlen($url) == 3)||$url == "/" ) {
  234.                             $urlRetour "/";
  235.                         }
  236.                         else {
  237.                             $urlRetour $url."/";
  238.                         }
  239.                         $urlRetour .= strtolower($_COOKIE["codePays"]);
  240.                         if (isset($requestUri[1])) {
  241.                             $urlRetour .= "?" $requestUri[1];
  242.                         }
  243.                         $session->set("codePays"$_COOKIE["codePays"]);
  244.                         $_SESSION["codePays"] = $_COOKIE["codePays"];
  245.                     } else {
  246.                         $codeRe "fr";
  247.                         if (!$isbot && empty($_SESSION["codePays"]) && empty($session->get("codePays")) && empty($user) && empty($_COOKIE["codePays"]) && $looksLikeBrowser) {
  248.                             $infoPays $this->getInfoPaysIp($ipClient);
  249.                             if (!empty($infoPays["country_code"]) && in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
  250.                                 $session->set("codePays"$infoPays["country_code"]);
  251.                                 $_SESSION["codePays"] = $infoPays["country_code"];
  252.                                 $codeRe strtolower($infoPays["country_code"]);
  253.                             } else {
  254.                                 $session->set("codePays""FR");
  255.                                 $_SESSION["codePays"] = "FR";
  256.                             }
  257.                         } elseif (!$isbot && empty($_SESSION["codePays"]) && !empty($session->get("codePays"))) {
  258.                             $_SESSION["codePays"] = $session->get("codePays");
  259.                             if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
  260.                                 $codeRe strtolower($session->get("codePays"));
  261.                             }
  262.                         } elseif (!$isbot && !empty($_SESSION["codePays"]) && empty($session->get("codePays"))) {
  263.                             $session->set("codePays"$_SESSION["codePays"]);
  264.                             if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
  265.                                 $codeRe strtolower($session->get("codePays"));
  266.                             }
  267.                         } else {
  268.                             $session->set("codePays""FR");
  269.                             $_SESSION["codePays"] = "FR";
  270.                         }
  271.                         if ((preg_match("/\/[a-z][a-z]/"$url) && strlen($url) == 3)||$url == "/" ) {
  272.                             $urlRetour "/";
  273.                         }
  274.                         else {
  275.                             $urlRetour $url."/";
  276.                         }
  277.                         $urlRetour .= strtolower($codeRe);
  278.                         if (isset($requestUri[1])) {
  279.                             $urlRetour .= "?" $requestUri[1];
  280.                         }
  281.                         setcookie("codePays"strtoupper($codeRe), time() + 60 60 24 365);
  282.                     }
  283.                     $event->setResponse(new RedirectResponse($urlRetour));
  284.                 } else {
  285.                     $session->set("codePays"$codeUrl);
  286.                     $_SESSION["codePays"] = $codeUrl;
  287.                     setcookie("codePays"strtoupper($codeUrl), time() + 60 60 24 365);
  288.                 }
  289.             } else {
  290.                 if ($okCookie) {
  291.                     $urlRetour $url "_" strtolower($_COOKIE["codePays"]) . "_";
  292.                     if (isset($requestUri[1])) {
  293.                         $urlRetour .= "?" $requestUri[1];
  294.                     }
  295.                     $session->set("codePays"$_COOKIE["codePays"]);
  296.                     $_SESSION["codePays"] = $_COOKIE["codePays"];
  297.                 } else {
  298.                     $codeRe "fr";
  299.                     if (!$isbot && empty($_SESSION["codePays"]) && empty($session->get("codePays")) && empty($user) && empty($_COOKIE["codePays"]) && $looksLikeBrowser) {
  300.                         $infoPays $this->getInfoPaysIp($ipClient);
  301.                         if (!empty($infoPays["country_code"]) && in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
  302.                             $session->set("codePays"$infoPays["country_code"]);
  303.                             $_SESSION["codePays"] = $infoPays["country_code"];
  304.                             $codeRe strtolower($infoPays["country_code"]);
  305.                         } else {
  306.                             $session->set("codePays""FR");
  307.                             $_SESSION["codePays"] = "FR";
  308.                         }
  309.                     } elseif (!$isbot && empty($_SESSION["codePays"]) && !empty($session->get("codePays"))) {
  310.                         $_SESSION["codePays"] = $session->get("codePays");
  311.                         if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
  312.                             $codeRe strtolower($session->get("codePays"));
  313.                         }
  314.                     } elseif (!$isbot && !empty($_SESSION["codePays"]) && empty($session->get("codePays"))) {
  315.                         $session->set("codePays"$_SESSION["codePays"]);
  316.                         if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
  317.                             $codeRe strtolower($session->get("codePays"));
  318.                         }
  319.                     } else {
  320.                         $session->set("codePays""FR");
  321.                         $_SESSION["codePays"] = "FR";
  322.                     }
  323.                     $urlRetour $url "_" strtolower($codeRe) . "_";
  324.                     if (isset($requestUri[1])) {
  325.                         $urlRetour .= "?" $requestUri[1];
  326.                     }
  327.                     setcookie("codePays"strtoupper($codeRe), time() + 60 60 24 365);
  328.                 }
  329.                 $event->setResponse(new RedirectResponse($urlRetour));
  330.             }
  331.             //ancien façson redirection##################################################################################
  332.         }
  333.     }
  334.     /**
  335.      * @Description function to detect url if dynamique, debug , img, assets etc..
  336.      *
  337.      * @param $url
  338.      * @return bool
  339.      */
  340.     private function istUrlToIgnore($url): bool {
  341.         $beginWith $this->params->get('app.url_begin_with_to_ignore');
  342.         $endWith $this->params->get('app.url_end_with_to_ignore');
  343.         foreach ($beginWith as $item) {
  344.             if (Utils::startsWith($item$url)) {
  345.                 return true;
  346.             }
  347.         }
  348.         foreach ($endWith as $item) {
  349.             if (Utils::endsWith($item$url)) {
  350.                 return true;
  351.             }
  352.         }
  353.         return false;
  354.     }
  355.     private function getInfoPaysIp($ipClient) {
  356. //        // Initialize cURL.
  357.         $ch curl_init();
  358. //        // Set the URL that you want to GET by using the CURLOPT_URL option.
  359.         curl_setopt($chCURLOPT_URL'https://ipgeolocation.abstractapi.com/v1/?api_key=b44e74c0ae384b3aaf982ee8382768cc&ip_address=' $ipClient);
  360. //        // Set CURLOPT_RETURNTRANSFER so that the content is returned as a variable.
  361.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  362. //        // Set CURLOPT_FOLLOWLOCATION to true to follow redirects.
  363.         curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
  364. //        // Execute the request.
  365.         $data curl_exec($ch);
  366. //        // Close the cURL handle.
  367.         curl_close($ch);
  368. //        // Print the data out onto the page.
  369.         $array json_decode($datatrue);
  370.         return $array;
  371.     }
  372.     private function getInfoPaysIpFake($ipClient) {
  373.         $array = array("country_code" => "FR");
  374.         return $array;
  375.     }
  376. }