<?php
namespace App\EventSubscriber;
use Psr\Log\LoggerInterface;
use App\Helper\Utils;
use App\Services\CustomLogger;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Utilisateur;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class ControllerSubscriber implements EventSubscriberInterface {
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
private $urlRedis;
/**
* @var ParameterBagInterface
*/
private ParameterBagInterface $params;
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
private $em;
private $security;
public function __construct(ParameterBagInterface $params, string $urlRedis, EntityManagerInterface $em, Security $security, LoggerInterface $logger) {
$this->params = $params;
$this->urlRedis = $urlRedis;
$this->em = $em;
$this->security = $security;
$this->logger = $logger;
}
public static function getSubscribedEvents() {
/* return [
KernelEvents::CONTROLLER => [
['processRedirectionInternational', 10]
],
]; */
return [KernelEvents::REQUEST => ['onRequest', 0]];
}
public function onRequest(RequestEvent $event) {
$request = $event->getRequest();
$session = $request->getSession(); // utilise la session Symfony
$url = $request->getPathInfo();
$requestUri = $request->getUri();
// Ajout de la logique spécifique pour les URLs de Buzz
if (preg_match('/^\/buzz\/([a-z]{2})$/', $url, $matches) || preg_match('/^\/buzz$/', $url)) {
$codeUrl = $matches[1] ?? 'fr';
$session->set("codePays", $codeUrl);
$_SESSION["codePays"] = $codeUrl;
setcookie("codePays", strtoupper($codeUrl), time() + 3600 * 24 * 365, "/");
return;
}
$user = $this->security->getUser();
if (!empty($user)) {
$session->set("token", (array) $user); // $_SESSION EST BIEN CHARGÉ MAINTENANT
$session->set('user', $user);
}
// l url sera modifié si elle n'est pas validé reg_match par la liste static
if (!$this->istUrlToIgnore($url)) {
$requestUri = explode("?", $requestUri);
$listeCodePaysActive = array("be", "ca", 'fr', 'ch');
if (!empty($request->server->get('HTTP_CLIENT_IP'))) {
$ipClient = $request->server->get('HTTP_CLIENT_IP');
} else if (!empty($request->server->get('HTTP_X_FORWARDED_FOR'))) {
$ipClient = $request->server->get('HTTP_X_FORWARDED_FOR');
} else {
$ipClient = $request->server->get('REMOTE_ADDR');
}
$_SESSION['ipClient'] = $ipClient;
$session->set("ipClient", $ipClient);
$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';
$isbot = preg_match("/{$botRegexPattern}/", $request->server->get('HTTP_USER_AGENT'));
$ua = $request->headers->get('User-Agent', '');
$accept = $request->headers->get('Accept', '');
$secFetchSite = $request->headers->get('Sec-Fetch-Site');
$secFetchMode = $request->headers->get('Sec-Fetch-Mode');
$looksLikeBrowser =
$ua !== '' &&
(strpos($accept, 'text/html') !== false || strpos($accept, 'application/json') !== false) &&
$secFetchSite !== null &&
$secFetchMode !== null;
//nouveau façson redirection##################################################################################
/* $codeUrl = "";
$codePaysFinal = "";
$codeToSee = "";
$urlRetour = "";
$cookieCountry = strtolower((string) $request->cookies->get("codePays", ''));
$sessionCountry = strtolower((string) ($session->get('codePays') ?? ''));
if (!empty($cookieCountry)) {
$session->set("codePays", $cookieCountry);
$codeToSee = $cookieCountry;
$_SESSION["codePays"] = $cookieCountry;
}
if (!empty($sessionCountry)) {
$codeToSee = $sessionCountry;
}
if (preg_match("/\_[a-z]+\_/", $url)) {
$codeUrl = substr($url, -3, 2);
$urlRetour = substr($url, 0, -4);
}
elseif ($url == "/" || (preg_match("/\/[a-z][a-z]/", $url) && strlen($url) == 3)) {
$codeUrl = substr($url, -2, 2);
$urlRetour = "/";
}
else{
$urlRetour = $url;
}
if (!in_array(strtolower($codeUrl), $listeCodePaysActive)) {
if (!empty($codeToSee)&&in_array(strtolower($codeToSee), $listeCodePaysActive)) {
$codePaysFinal = $codeToSee;
}
else{
if (!$isbot &&empty($user)&&$looksLikeBrowser){
$infoPays = $this->getInfoPaysIp($ipClient);
if (!empty($infoPays["country_code"])&&in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
$session->set("codePays", strtolower($infoPays["country_code"]));
$_SESSION["codePays"] = strtolower($infoPays["country_code"]);
$codePaysFinal = strtolower($infoPays["country_code"]);
} else {
$session->set("codePays", "fr");
$_SESSION["codePays"] = "fr";
$codePaysFinal = "fr";
}
}
else{
$session->set("codePays", "fr");
$_SESSION["codePays"] = "fr";
$codePaysFinal = "fr";
}
}
if ($urlRetour=="/") {
$urlRetour = "/" . strtolower($codePaysFinal) ;
}
else{
$urlRetour .= "_" . strtolower($codePaysFinal) . "_";
}
if (isset($requestUri[1])) {
$urlRetour .= "?" . $requestUri[1];
}
$session->set("codePays", $codePaysFinal);
$_SESSION["codePays"] =$codePaysFinal;
if ($codePaysFinal!=$cookieCountry) {
setcookie("codePays", strtoupper($codeUrl), time() + 60 * 60 * 24 * 365);
}
$event->setResponse(new RedirectResponse($urlRetour));
}
else{
$codePaysFinal = $codeUrl;
$session->set("codePays", $codePaysFinal);
$_SESSION["codePays"] =$codePaysFinal;
if ($codePaysFinal!=$cookieCountry) {
setcookie("codePays", strtoupper($codeUrl), time() + 60 * 60 * 24 * 365);
}
return;
} */
//nouveau façson redirection##################################################################################
//ancien façson redirection##################################################################################
$okCookie = false;
if (isset($_COOKIE["codePays"]) && $_COOKIE["codePays"] != "") {
if (!in_array(strtolower($_COOKIE["codePays"]), $listeCodePaysActive)) {
$okCookie = false;
} else {
$okCookie = true;
}
}
if (preg_match("/\_[a-z]+\_/", $url)) {
$codeUrl = substr($url, -3, 2);
if (!in_array(strtolower($codeUrl), $listeCodePaysActive)) {
if ($okCookie) {
$urlRetour = substr($url, 0, -4);
$urlRetour .= "_" . strtolower($_COOKIE["codePays"]) . "_";
if (isset($requestUri[1])) {
$urlRetour .= "?" . $requestUri[1];
}
$session->set("codePays", $_COOKIE["codePays"]);
$_SESSION["codePays"] = $_COOKIE["codePays"];
} else {
$codeRe = "fr";
if (!$isbot && empty($_SESSION["codePays"]) && empty($session->get("codePays")) && empty($user) && empty($_COOKIE["codePays"]) && $looksLikeBrowser) {
$infoPays = $this->getInfoPaysIp($ipClient);
if (!empty($infoPays["country_code"]) && in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
$session->set("codePays", $infoPays["country_code"]);
$_SESSION["codePays"] = $infoPays["country_code"];
$codeRe = strtolower($infoPays["country_code"]);
} else {
$session->set("codePays", "FR");
$_SESSION["codePays"] = "FR";
}
} elseif (!$isbot && empty($_SESSION["codePays"]) && !empty($session->get("codePays"))) {
$_SESSION["codePays"] = $session->get("codePays");
if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
$codeRe = strtolower($session->get("codePays"));
}
} elseif (!$isbot && !empty($_SESSION["codePays"]) && empty($session->get("codePays"))) {
$session->set("codePays", $_SESSION["codePays"]);
if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
$codeRe = strtolower($session->get("codePays"));
}
} else {
$session->set("codePays", "FR");
$_SESSION["codePays"] = "FR";
}
$urlRetour = substr($url, 0, -4);
$urlRetour .= "_" . strtolower($codeRe) . "_";
if (isset($requestUri[1])) {
$urlRetour .= "?" . $requestUri[1];
}
setcookie("codePays", strtoupper($codeRe), time() + 60 * 60 * 24 * 365);
}
$event->setResponse(new RedirectResponse($urlRetour));
} else {
$session->set("codePays", $codeUrl);
$_SESSION["codePays"] = $codeUrl;
setcookie("codePays", strtoupper($codeUrl), time() + 60 * 60 * 24 * 365);
}
} elseif ($url == "/" || (preg_match("/\/[a-z][a-z]/", $url) && strlen($url) == 3)) {
$codeUrl = "";
if ((preg_match("/\/[a-z][a-z]/", $url) && strlen($url) == 3)) {
$codeUrl = substr($url, -2, 2);
}
if ($url == "/" || !in_array(strtolower($codeUrl), $listeCodePaysActive)) {
if ($okCookie) {
if ((preg_match("/\/[a-z][a-z]/", $url) && strlen($url) == 3)||$url == "/" ) {
$urlRetour = "/";
}
else {
$urlRetour = $url."/";
}
$urlRetour .= strtolower($_COOKIE["codePays"]);
if (isset($requestUri[1])) {
$urlRetour .= "?" . $requestUri[1];
}
$session->set("codePays", $_COOKIE["codePays"]);
$_SESSION["codePays"] = $_COOKIE["codePays"];
} else {
$codeRe = "fr";
if (!$isbot && empty($_SESSION["codePays"]) && empty($session->get("codePays")) && empty($user) && empty($_COOKIE["codePays"]) && $looksLikeBrowser) {
$infoPays = $this->getInfoPaysIp($ipClient);
if (!empty($infoPays["country_code"]) && in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
$session->set("codePays", $infoPays["country_code"]);
$_SESSION["codePays"] = $infoPays["country_code"];
$codeRe = strtolower($infoPays["country_code"]);
} else {
$session->set("codePays", "FR");
$_SESSION["codePays"] = "FR";
}
} elseif (!$isbot && empty($_SESSION["codePays"]) && !empty($session->get("codePays"))) {
$_SESSION["codePays"] = $session->get("codePays");
if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
$codeRe = strtolower($session->get("codePays"));
}
} elseif (!$isbot && !empty($_SESSION["codePays"]) && empty($session->get("codePays"))) {
$session->set("codePays", $_SESSION["codePays"]);
if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
$codeRe = strtolower($session->get("codePays"));
}
} else {
$session->set("codePays", "FR");
$_SESSION["codePays"] = "FR";
}
if ((preg_match("/\/[a-z][a-z]/", $url) && strlen($url) == 3)||$url == "/" ) {
$urlRetour = "/";
}
else {
$urlRetour = $url."/";
}
$urlRetour .= strtolower($codeRe);
if (isset($requestUri[1])) {
$urlRetour .= "?" . $requestUri[1];
}
setcookie("codePays", strtoupper($codeRe), time() + 60 * 60 * 24 * 365);
}
$event->setResponse(new RedirectResponse($urlRetour));
} else {
$session->set("codePays", $codeUrl);
$_SESSION["codePays"] = $codeUrl;
setcookie("codePays", strtoupper($codeUrl), time() + 60 * 60 * 24 * 365);
}
} else {
if ($okCookie) {
$urlRetour = $url . "_" . strtolower($_COOKIE["codePays"]) . "_";
if (isset($requestUri[1])) {
$urlRetour .= "?" . $requestUri[1];
}
$session->set("codePays", $_COOKIE["codePays"]);
$_SESSION["codePays"] = $_COOKIE["codePays"];
} else {
$codeRe = "fr";
if (!$isbot && empty($_SESSION["codePays"]) && empty($session->get("codePays")) && empty($user) && empty($_COOKIE["codePays"]) && $looksLikeBrowser) {
$infoPays = $this->getInfoPaysIp($ipClient);
if (!empty($infoPays["country_code"]) && in_array(strtolower($infoPays["country_code"]), $listeCodePaysActive)) {
$session->set("codePays", $infoPays["country_code"]);
$_SESSION["codePays"] = $infoPays["country_code"];
$codeRe = strtolower($infoPays["country_code"]);
} else {
$session->set("codePays", "FR");
$_SESSION["codePays"] = "FR";
}
} elseif (!$isbot && empty($_SESSION["codePays"]) && !empty($session->get("codePays"))) {
$_SESSION["codePays"] = $session->get("codePays");
if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
$codeRe = strtolower($session->get("codePays"));
}
} elseif (!$isbot && !empty($_SESSION["codePays"]) && empty($session->get("codePays"))) {
$session->set("codePays", $_SESSION["codePays"]);
if (in_array(strtolower($session->get("codePays")), $listeCodePaysActive)) {
$codeRe = strtolower($session->get("codePays"));
}
} else {
$session->set("codePays", "FR");
$_SESSION["codePays"] = "FR";
}
$urlRetour = $url . "_" . strtolower($codeRe) . "_";
if (isset($requestUri[1])) {
$urlRetour .= "?" . $requestUri[1];
}
setcookie("codePays", strtoupper($codeRe), time() + 60 * 60 * 24 * 365);
}
$event->setResponse(new RedirectResponse($urlRetour));
}
//ancien façson redirection##################################################################################
}
}
/**
* @Description function to detect url if dynamique, debug , img, assets etc..
*
* @param $url
* @return bool
*/
private function istUrlToIgnore($url): bool {
$beginWith = $this->params->get('app.url_begin_with_to_ignore');
$endWith = $this->params->get('app.url_end_with_to_ignore');
foreach ($beginWith as $item) {
if (Utils::startsWith($item, $url)) {
return true;
}
}
foreach ($endWith as $item) {
if (Utils::endsWith($item, $url)) {
return true;
}
}
return false;
}
private function getInfoPaysIp($ipClient) {
// // Initialize cURL.
$ch = curl_init();
// // Set the URL that you want to GET by using the CURLOPT_URL option.
curl_setopt($ch, CURLOPT_URL, 'https://ipgeolocation.abstractapi.com/v1/?api_key=b44e74c0ae384b3aaf982ee8382768cc&ip_address=' . $ipClient);
// // Set CURLOPT_RETURNTRANSFER so that the content is returned as a variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// // Set CURLOPT_FOLLOWLOCATION to true to follow redirects.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// // Execute the request.
$data = curl_exec($ch);
// // Close the cURL handle.
curl_close($ch);
// // Print the data out onto the page.
$array = json_decode($data, true);
return $array;
}
private function getInfoPaysIpFake($ipClient) {
$array = array("country_code" => "FR");
return $array;
}
}