src/Service/BootService.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\CfgBlocs;
  4. use App\Entity\CfgClient;
  5. use App\Entity\CfgClientAddresses;
  6. use App\Entity\CfgConstants;
  7. use App\Entity\CfgLangues;
  8. use App\Entity\CfgSite;
  9. use App\Entity\CfgTranslations;
  10. use App\Form\RappelsType;
  11. use App\Kernel;
  12. use App\Modules\Pages\Entity\Pages;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\DependencyInjection\ContainerBuilder;
  16. use Symfony\Component\Form\FormFactoryInterface;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\RouterInterface;
  19. use Twig\Environment;
  20. class BootService extends AbstractController
  21. {
  22.     public EntityManagerInterface $entityManager;
  23.     public $container;
  24.     public FormFactoryInterface $formFactory;
  25.     public RouterInterface $router;
  26.     public Environment $twig;
  27.     private static array $params = [
  28.         "modules"=>[],
  29.         "lang_dir"=>"/languages/"
  30.     ];
  31.     public static array $ressources = [];
  32.     protected array $css = [];
  33.     protected array $js = [];
  34.     public static array $bc = [];
  35.     public function __construct(Kernel $kernelFormFactoryInterface $formFactoryEntityManagerInterface $entityManagerEnvironment $twigRouterInterface $router)
  36.     {
  37.         /*if(defined("API_IS_ACTIVE") && API_IS_ACTIVE === true){
  38.             $response = new Response();
  39.             $response->setContent('Accès non autorisé');
  40.             $response->setStatusCode(401);
  41.             $response->send();
  42.         }*/
  43.         $this->formFactory $formFactory;
  44.         $this->container $kernel->getContainer();
  45.         $this->twig $twig;
  46.         $this->entityManager $entityManager;
  47.         $this->router $router;
  48.         $informations=$this->getConfigurationSite();
  49.         if($informations->site instanceof CfgSite && PROTOCOL."://".$_SERVER['HTTP_HOST']<>$informations->site->getUrl() && LOCALHOST === false){
  50.             header("Status: 301 Moved Permanently"false301);
  51.             header("location:".$informations->site->getUrl());
  52.         }
  53.         if($this->getPageTemporaire($informations->site) === false){
  54.             echo $this->twig->render('templates/offline/index.html.twig', [
  55.                 "site_offline"=>$informations
  56.             ]);exit;
  57.         }
  58.         $this->setContentCfgConstants();
  59.         $this->setContentCfgTranslations();
  60.         $this->loadTwigVars();
  61.         $this->setContentLangues();
  62.         $this->getParamMod();
  63.         if(defined('TARTEAUCITRON_ACTIVE') && TARTEAUCITRON_ACTIVE===true && TARTEAUCITRON_SERVICES['recaptcha']===true){
  64.             $this->AddJS("https://www.google.com/recaptcha/api.js");
  65.         }
  66.         if(defined("TARTEAUCITRON_ACTIVE") && TARTEAUCITRON_ACTIVE===true){
  67.             $this->AddJS("/lib/tarteaucitron.js-1.9.0/tarteaucitron.js");
  68.         }
  69.         $this->loadTwigVars("scripts");
  70.         $this->loadTwigVars("styles");
  71.     }
  72.     public function getPageTemporaire(CfgSite $cfgSite):bool
  73.     {
  74.         if(str_contains($cfgSite->getIpsAuth(), $_SERVER["REMOTE_ADDR"])){
  75.             return true;
  76.         }
  77.         if($cfgSite->isIsActive() === true){
  78.             return true;
  79.         }
  80.         return false;
  81.     }
  82.     public static function getParamMod()
  83.     {
  84.         $containerBuilder = new ContainerBuilder();
  85.         $containerBuilder->register('boot''App\Service\BootService');
  86.     }
  87.     public static function returnMessage(array|string $data,int $status=200,bool $errorCode=true):array
  88.     {
  89.         if($errorCode === true){
  90.             return [
  91.                 "status"=>$status,
  92.                 "data"=>[
  93.                     "error"=>$data
  94.                 ]
  95.             ];
  96.         }
  97.         return [
  98.             "status"=>$status,
  99.             "data"=>$data
  100.         ];
  101.     }
  102.     public function getRessourceCoreTwig(string $ressource, array $params=[]):string
  103.     {
  104.         if($ressource === "content_all"){
  105.             if(CONTROLEUR_DEFAUT === "pages"){
  106.                 return $this->forward("App\Modules\Pages\Controller\PagesController::indexPagesRoot")->getContent();
  107.             }
  108.         }
  109.         return $this->renderView("/templates/core/".$ressource.".html.twig"$params);
  110.     }
  111.     public static function getParamsRoot(string $hookstring $sshook=null):string
  112.     {
  113.         if($sshook !== null){
  114.             return "src/Modules/".ucfirst($hook)."/Hooks/".ucfirst($sshook)."/";
  115.         }
  116.         return "src/Modules/".ucfirst($hook)."/Templates/";
  117.     }
  118.     /*public static function getParamsEntity(string $module=null, string $hook=null):string
  119.     {
  120.         if($hook !== null){
  121.             return "App\Modules\\".ucfirst($module)."\\Hooks\\".ucfirst($hook)."\\Entity\\";
  122.         } elseif($module !== null){
  123.             return "App\Modules\\".ucfirst($module)."\\Entity\\";
  124.         }
  125.         return "App\Entity\\";
  126.     }*/
  127.     public function getConfigurationSite():object
  128.     {
  129.         $data = (object)[
  130.             "site"=>[
  131.                 "fetch"=>$this->entityManager->getRepository(CfgSite::class)->find(1),
  132.                 "instance"=>CfgSite::class
  133.             ],
  134.             "client"=>[
  135.                 "fetch"=>$this->entityManager->getRepository(CfgClient::class)->find(1),
  136.                 "instance"=>CfgClient::class
  137.             ],
  138.             "addresses"=>[
  139.                 "fetch"=>$this->entityManager->getRepository(CfgClientAddresses::class)->findBy(["isActive"=>true]),
  140.             ]
  141.         ];
  142.         foreach($data as $config=>$params){
  143.             if(isset($params["instance"]) && !$params["fetch"] instanceof $params["instance"]){
  144.                 echo "<h1>Une erreur est parvenue lors de la configuration du {$config}.</h1>";exit;
  145.             }
  146.             $data->{$config} = $params["fetch"];
  147.         }
  148.         return $data;
  149.     }
  150.     public function loadTwigVars(string $reloadRessource null):void
  151.     {
  152.         switch($reloadRessource){
  153.             case "styles":
  154.                 $this->assign($reloadRessource$this->css);
  155.             break;
  156.             case "scripts":
  157.                 $this->assign($reloadRessource$this->js);
  158.             break;
  159.             default:
  160.                 if(!defined("LANGUE_DEFAULT")){
  161.                     $this->assign('langue'"fr");
  162.                 } else{
  163.                     $this->assign('langue'LANGUE_DEFAUT);
  164.                 }
  165.                 $this->assign('styles'$this->css);
  166.                 $this->assign('scripts'$this->js);
  167.                 $configSite $this->getConfigurationSite();
  168.                 $this->assign('config'$configSite);
  169.                 $this->assign("device"MobileDetectService::getDevice(["twig"=>$this->twig,"site"=>$configSite]));
  170.                 $this->assign("rappelForm"$this->formFactory->create(RappelsType::class)->createView());
  171.                 $this->assign("sentences"$this->entityManager->getRepository(CfgBlocs::class)->findBy(["isActive"=>true],["rank"=>"ASC"]));
  172.                 $this->assign("pag_contact"$this->entityManager->getRepository(Pages::class)->findOneBy(["id"=>$_ENV["pag_contact"],"isActive"=>1]));
  173.                 $this->assign("pag_avis"$this->entityManager->getRepository(Pages::class)->findOneBy(["id"=>$_ENV["pag_avis"],"isActive"=>1]));
  174.                 $this->loadDefaultModules();
  175.             break;
  176.         }
  177.     }
  178.     private function loadDefaultModules():void
  179.     {
  180.         $this->assign('mod_social'$this->getModule("Socials"));
  181.         $this->assign('mod_shortcuts'$this->getModule("Shortcuts"));
  182.         $this->assign('mod_shortcuts_projects'$this->getModule("Shortcuts""ShortcutsProjects"));
  183.         $this->assign('mod_shortcuts_facts'$this->getModule("Shortcuts""ShortcutsFacts"));
  184.         $this->assign('mod_newsletter'$this->getModule("Newsletter"null, ["id"=>1]));
  185.         if(MODE_INTRANET === false){
  186.             $this->assign('menu_haut'$this->getModule("CfgMenus","Menus", ["tag"=>"menu_haut""origin"=>"includeContentDynamicalMenu"]));
  187.             $this->assign('menu_bas'$this->getModule("CfgMenus","Menus", [
  188.                 "menus"=>[
  189.                     "menu_bas_gauche",
  190.                     "menu_bas_milieu",
  191.                     "menu_bas_droite",
  192.                     "menu_copyrights"
  193.                 ]
  194.             ], "loadMenuFooter"));
  195.         }
  196.     }
  197.     private function setContentCfgConstants():bool
  198.     {
  199.         $constants $this->entityManager->getRepository(CfgConstants::class)->findBy(["isActive"=>true]);
  200.         if(empty($constants)){
  201.             return false;
  202.         }
  203.         foreach($constants as $constant){
  204.             if(!defined($constant->getName())){
  205.                 define($constant->getName(),$constant->getValue());
  206.             }
  207.         }
  208.         return true;
  209.     }
  210.     private function setContentCfgTranslations():bool
  211.     {
  212.         $translations $this->entityManager->getRepository(CfgTranslations::class)->findAll();
  213.         if(empty($translations)){
  214.             return false;
  215.         }
  216.         foreach($translations as $translation){
  217.             if(!defined($translation->getName())){
  218.                 define($translation->getName(),$translation->getValue());
  219.             }
  220.         }
  221.         return true;
  222.     }
  223.     private function setContentLangues():void
  224.     {
  225.         try{
  226.             // On récupère les valeurs des fichiers de langue
  227.             $langueDirectory scandir(ROOT.self::$params["lang_dir"]);
  228.             foreach($langueDirectory as $valeur){
  229.                 if($valeur !== "." && $valeur !== ".." && strpos($valeur"json")){
  230.                     $lang_file json_decode(file_get_contents(ROOT.self::$params["lang_dir"].$valeur),true);
  231.                     foreach($lang_file as $key=>$tab){
  232.                         $this->assign($key,$tab[LANGUE]);
  233.                     }
  234.                 }
  235.             }
  236.         }
  237.         catch(\Exception $e){
  238.             echo $e->getMessage();
  239.         }
  240.     }
  241.     public function assign(string $var$value):void
  242.     {
  243.         if (!array_key_exists($var$this->twig->getGlobals())) {
  244.             $this->twig->addGlobal($var$value);
  245.             self::$ressources[$var] = $value;
  246.         }
  247.     }
  248.     public function checkURL(string $ctstring $itemTitleint $itemIdstring $requestUristring $itemUrlRwbool $champs_redirection=false):string
  249.     {
  250.         $langDefault $this->entityManager->getRepository(CfgLangues::class)->findOneBy(["isDefault"=>1,"isActive"=>1]);
  251.         if(!$langDefault instanceof CfgLangues){
  252.             $ct LANGUE_DEFAUT."/".$ct;
  253.         }
  254.         $urlReceived $requestUri;
  255.         $urlValid URL."/".$ct."/".ReecritureService::reecrire($itemTitle)."-".$itemId.".html";
  256.         if($itemUrlRw){
  257.             $urlValid URL."/".$ct."/".ReecritureService::reecrire($itemUrlRw)."-".$itemId.".html";
  258.         }
  259.         if($urlValid !== $urlReceived){
  260.             header("HTTP/1.1 301 Moved Permanently");
  261.             header("location:".$urlValid);
  262.             header("Connection: close");exit;
  263.         }
  264.         return $urlValid;
  265.     }
  266.     public function getBBCode(string $content):string
  267.     {
  268.         preg_match_all('#\[\[(.*)\]\]#',$content,$modules); 
  269.         if(!empty($modules[1])){
  270.             foreach($modules[1] as $module){
  271.                 $param = [];
  272.                 $ss_module null;
  273.                 $explode explode("|",$module);
  274.                 $explode explode("-",$explode[0]);
  275.                 if(!empty($explode[1])){
  276.                     $param = ["id"=>$explode[1]];
  277.                 }
  278.                 $explode explode("/",$explode[0]);
  279.                 if(!empty($explode[1])){
  280.                     $ss_module $explode[1];
  281.                 }
  282.                 $lemodule $explode[0];
  283.                 $module_preg preg_quote($module'/');
  284.                 $content preg_replace('#\[\['.$module_preg.'\]\]#',$this->getModule($lemodule,$ss_module,$param),$content,1);
  285.             }
  286.         }
  287.         return $content;
  288.     }
  289.     private function getModuleFormsConfig(array $data):array
  290.     {
  291.         return array_merge([
  292.             "bootService"=>$this
  293.         ], $data);
  294.     }
  295.     private function getModuleNewsletterConfig(array $data):array
  296.     {
  297.         return array_merge([
  298.             "formFactory"=>$this->formFactory
  299.         ], $data);
  300.     }
  301.     private function getModuleJobsConfig(array $data):array
  302.     {
  303.         return array_merge([
  304.             "formFactory"=>$this->formFactory
  305.         ], $data);
  306.     }
  307.     public function loadConfigurationHook(array $data=[]):array
  308.     {
  309.         return array_merge([
  310.             "container"=>$this->container,
  311.             "twig"=>$this->twig,
  312.             "router"=>$this->router,
  313.             "entityManager"=>$this->entityManager,
  314.         ], $data);
  315.     }
  316.     private static function checkRegisteredModule($mod):bool
  317.     {
  318.         if(array_key_exists($modself::$params["modules"])){
  319.             return false;
  320.         }
  321.         return true;
  322.     }
  323.     // Chargement d'un module
  324.     public function getModule(string $module,string $ss_module=null,array $param=[],string $action="loadConfigHook"):string|array
  325.     {
  326.         $modLoad base64_encode($module.$ss_module.json_encode($param).$action);
  327.         if(self::checkRegisteredModule($modLoad) === false){
  328.             return self::$params["modules"][$modLoad];
  329.         }
  330.         if($ss_module===null){
  331.             $ss_module ucfirst($module);
  332.         } else{
  333.             $ss_module ucfirst($ss_module);
  334.         }
  335.         $module ucfirst($module);
  336.         $servicesMod "App\Modules\\".$module."\Hooks\\".$ss_module."\\".$ss_module."Hook";
  337.         if(!class_exists($servicesMod)) {
  338.             return '<div class="alert alert-danger">Erreur de chargement de la classe '.$servicesMod.'</div>';
  339.         }
  340.         if(!method_exists($servicesMod,$action)) {
  341.             return '<div class="alert alert-danger">Erreur de chargement de la méthode '.$servicesMod.'\\'.$action.'</div>';
  342.         }
  343.         if(isset($param["default"])){
  344.             $data $param["default"];
  345.         } else{
  346.             $data = [
  347.                 "param"=>$param,
  348.                 "hookRep"=>"src/Modules/".$module."/Hooks/"
  349.             ];
  350.         }
  351.         if(method_exists("App\Service\BootService""getModule".$module."Config")){
  352.             $data $this->{"getModule".$module."Config"}($data);
  353.         }
  354.         $modServiceInst = new $servicesMod($this->loadConfigurationHook($data));
  355.         $contentHook $modServiceInst->$action();
  356.         if(!is_string($contentHook) && !is_array($contentHook)) {
  357.             switch ($contentHook->getStatusCode()) {
  358.                 case 500:
  359.                     $content '<div class="alert alert-danger">Le module n\'a pas pu être récupéré : Erreur ' $contentHook->getStatusCode() . '</div>';
  360.                     break;
  361.                 default:
  362.                     $content $contentHook->getContent();
  363.                     break;
  364.             }
  365.         } else{
  366.             $content $contentHook;
  367.         }
  368.         self::$params["modules"][$modLoad] = $content;
  369.         return $content;
  370.     }
  371.     public static function addBC($name,$url):void
  372.     {
  373.         self::$bc[]=array(
  374.             "name"=>$name,
  375.             "url"=>$url
  376.         );
  377.     }
  378.     public function Error($description="Page introuvable",$code=404):Response
  379.     {
  380.         return $this->render('/templates/error.html.twig', ['error' => [
  381.             'code'=>$code,
  382.             'description'=>$description
  383.         ]]);
  384.     }
  385.     public function AddJS($url$index=null):void
  386.     {
  387.         if(!in_array($url$this->js)){
  388.             if(is_null($index) || $index===false){
  389.                 $k 100 count($this->js);
  390.             }
  391.             else{
  392.                 $k $index;
  393.             }
  394.             while(array_key_exists($k$this->js)){
  395.                 $k++;
  396.             }
  397.             $this->js[$k]=$url;
  398.             ksort($this->js);
  399.         }
  400.     }
  401.     public function AddCSS($url$index=null):void
  402.     {
  403.         if(!in_array($url$this->css)){
  404.             if(is_null($index) || $index===false){
  405.                 $k 100 count($this->css);
  406.             }
  407.             else{
  408.                 $k $index;
  409.             }
  410.             while(array_key_exists($k$this->css)){
  411.                 $k++;
  412.             }
  413.             $this->css[$k]=$url;
  414.             ksort($this->css);
  415.         }
  416.     }
  417.     public static function sendCurlBasic(string $endpoint, array $endpointConfig=[], string $endpointType="GET"):string|array
  418.     {
  419.         $ch curl_init($endpoint);
  420.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  421.         if(!empty($endpointConfig)){
  422.             if(isset($endpointConfig["auth"]) && isset($endpointConfig["auth"]["type"]) && !empty($endpointConfig["auth"]["type"])){
  423.                 switch($endpointConfig["auth"]["type"]){
  424.                     case "bearer":
  425.                         curl_setopt($chCURLOPT_HTTPHEADER,  [
  426.                             'Authorization: Bearer '.$endpointConfig["auth"]["token"]
  427.                         ]);
  428.                     break;
  429.                 }
  430.             }
  431.             if(isset($endpointConfig["data"])){
  432.                 curl_setopt($chCURLOPT_POSTtrue);
  433.                 curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($endpointConfig["data"]));
  434.             }
  435.         }
  436.         curl_setopt($chCURLOPT_USERAGENT'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
  437.         $result curl_exec($ch);
  438.         //dd($ch);
  439.         if(mb_strtoupper($endpointType) === "GET"){
  440.             // 3 try si timeout dépassé
  441.             $retry 0;
  442.             while(curl_errno($ch) == 28 && $retry 3){
  443.                 $result curl_exec($ch);
  444.                 $retry++;
  445.             }
  446.             // Dernier try avec timeout plus long
  447.             if(curl_errno($ch) == 28){
  448.                 curl_setopt($chCURLOPT_TIMEOUT10);
  449.                 $result curl_exec($ch);
  450.             }
  451.         }
  452.         curl_close($ch);
  453.         return json_decode($resulttrue);
  454.     }
  455. }