src/Service/Generale.php line 143

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: MohamedAli
  5.  * Date: 21/04/2020
  6.  * Time: 06:38
  7.  */
  8. namespace App\Service;
  9. use App\Entity\LogCache;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Component\HttpFoundation\RequestStack;
  12. use Symfony\Component\HttpFoundation\Session\SessionInterface as Session;
  13. use Symfony\Component\Security\Core\Security;
  14. class Generale
  15. {
  16.     /**
  17.      * GeneraleExtension constructor.
  18.      */
  19.     public function __construct(EntityManagerInterface $emSession $sessionRequestStack $requestStackSecurity $security)
  20.     {
  21.         $this->em $em;
  22.         $this->security $security;
  23.         $this->session $session;
  24.         $this->requestStack $requestStack;
  25.     }
  26.     public function WebService($produit$service$param = array(), $cache false$headers = [], $endpoint null)
  27.     {
  28.         if (!$endpoint)
  29.             $endpoint $this->domaineBack();
  30.         $login $_SERVER['LOGIN_XML'];
  31.         $pwd $_SERVER['PWD_XML'];
  32.         $urlSHT "$endpoint/api/hotel/";
  33.         $urlOldSHT "$endpoint/api-sht/";
  34.         $urlVO "$endpoint/api-vo/";
  35.         $urlBE "$endpoint/api-be/";
  36.         $urlLV "$endpoint/api-lv/";
  37.         $urlTASK "$endpoint/api-task/";
  38.         $urlCHAT "$endpoint/api-chat/";
  39.         $urlCMS "$endpoint/api-cms/";
  40.         $urlTransfert "$endpoint/api-t/";
  41.         $urlAUTH "$endpoint/api-auth/";
  42.         $urlAFFILIE "$endpoint/api-espace-affilie/";
  43.         $urlVOL "$endpoint/api-vol/";
  44.         $urlM "$endpoint/api-m/";
  45.         if (is_null($param))
  46.             $param = [];
  47.         //if($container->getParameter('kernel.debug'));
  48.         $request $this->requestStack->getCurrentRequest();
  49.         $sub_dir array_search($endpoint$_SERVERtrue);
  50.         $sub_dir str_replace('DOMAINE_BACK'''$sub_dir);
  51.         if ($sub_dir == '')
  52.             $sub_dir "data";
  53.         $DIR_SEP DIRECTORY_SEPARATOR;
  54.         $folder_json_file "cache-webservices{$DIR_SEP}{$service}{$DIR_SEP}{$sub_dir}";
  55.         $path_json_file "{$folder_json_file}{$DIR_SEP}$cache.json";
  56.         if ($cache and !$request->get('not-cache'))
  57.             if ($_SERVER['VERSION_CACHE'] == and file_exists($path_json_file))
  58.                 return json_decode(file_get_contents($path_json_file), true);
  59.         $connexion = [
  60.             'login' => $login,
  61.             'pwd' => $pwd
  62.         ];
  63.         if (in_array($service, ['Subscribe''check-credential']))
  64.             $connexion = [
  65.                 'WSlogin' => $login,
  66.                 'WSpwd' => $pwd
  67.             ];
  68.         if ($produit == "SHT")
  69.             $connexion = array(
  70.                 'Credential' => [
  71.                     'Login' => $login,
  72.                     'Password' => $pwd
  73.                 ]
  74.             );
  75.         $ch curl_init();
  76.         curl_setopt($chCURLOPT_URL, ${"url$produit"} . $service);
  77.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  78.         curl_setopt($chCURLOPT_ENCODING'');
  79.         curl_setopt($chCURLOPT_SSL_VERIFYHOST0);
  80.         curl_setopt($chCURLOPT_SSL_VERIFYPEER0);
  81.         $headers [] = "ClientIp:{$request->getClientIp()}";
  82.         $headers [] = "Language:{$request->getLocale()}";
  83.         $clientHost = (isset($_SERVER['DOMAINE_FRONT']) and $_SERVER['DOMAINE_FRONT'] != "" and $_SERVER['CHECK_CLIENT_BY_HOST'] == 'false') ? $_SERVER['DOMAINE_FRONT'] : $request->getSchemeAndHttpHost();
  84.         //$_clientHost = self::domain($clientHost);
  85.         if (isset($_SERVER['PREFIXE_ROUTE']))
  86.             $clientHost .= "/{$_SERVER['PREFIXE_ROUTE']}";
  87.         $headers [] = "Content-Type: application/json";
  88.         $headers [] = "ClientHost:$clientHost";
  89.         $headers [] = "ClientHost2:{$request->getSchemeAndHttpHost()}";
  90.         $clientId null;
  91.         if (isset($this->session->get('client', [])['id'])) {
  92.             $clientId $this->session->get('client')['id'];
  93.             $headers [] = "ClientId:$clientId";
  94.         } elseif (isset($this->session->get('amicale', [])['clients'][0])) {
  95.             $clientId $this->session->get('amicale')['clients'][0];
  96.             $headers [] = "ClientId:$clientId";
  97.             $headers [] = "ClientAnonyme: True";
  98.         }
  99.         $param['B2B'] = (in_array($_SERVER['APP_ACCESS_CONTROL'], ['ROLE_CLIENT_B2B''ROLE_CLIENT_B2B_OR_AMICALE']) or
  100.             in_array($_SERVER['APP_SECOND_ACCESS_CONTROL'], ['ROLE_CLIENT_B2B''ROLE_CLIENT_B2B_OR_AMICALE']));
  101.         if ($service != 'Subscribe' and !in_array($produit, ['AUTH''CMS']) and $param['B2B'] and !$clientId)
  102.             throw new \Exception("Votre session a expiré ou les informations nécessaires sont manquantes. Veuillez vous reconnecter pour continuer.");
  103.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode(array_merge($connexion$param)));
  104.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  105.         $output curl_exec($ch);
  106.         // Décompresser la réponse si elle est compressée
  107.         $output $this->decompressOutput($output);
  108.         $info curl_getinfo($ch);
  109.         $curl_error curl_error($ch);
  110.         curl_close($ch);
  111.         #===============================================================================================================
  112.         #.............   SAVE LOG WEBSERVICE IN SESSION                  ...............................................
  113.         #===============================================================================================================
  114.         $headers [] = "Accept-Encoding: identity";
  115.         $LOG_WEB_SERVICES $this->session->get('LOG_WEB_SERVICES', []);
  116.         $LOG_WEB_SERVICES[$service][date('d/m/Y H:i:s')]['request'] = "curl --location --request POST " . ${"url$produit"} . $service implode(""array_map(function ($item) {
  117.                 return "\n--header '$item'";
  118.             }, $headers)) . "\n--data-raw '" json_encode(array_merge($connexion$param), JSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE JSON_UNESCAPED_SLASHES) . "'";
  119.         $LOG_WEB_SERVICES[$service][date('d/m/Y H:i:s')]['response'] = json_encode(json_decode($outputtrue), JSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE JSON_UNESCAPED_SLASHES);
  120.         $this->session->set('LOG_WEB_SERVICES'$LOG_WEB_SERVICES);
  121.         #===============================================================================================================
  122.         try {
  123.             if ($cache and self::isJson($output)) {
  124.                 if ($_SERVER['VERSION_CACHE'] == 1) {
  125.                     if (!is_dir($folder_json_file))
  126.                         if (PHP_OS_FAMILY === "Linux")
  127.                             exec("mkdir -p -m 777 $folder_json_file");
  128.                         elseif (PHP_OS_FAMILY === "Windows")
  129.                             exec("mkdir $folder_json_file");
  130.                     //array_map('unlink', array_filter((array)glob("$folder_json_file/*")));
  131.                     $_folder_json_file realpath($folder_json_file);
  132.                     exec("find $_folder_json_file -type f -mtime +1 -exec rm -rf {} \;");
  133.                     file_put_contents($path_json_file$output);
  134.                     // Ajout du log de sauvegarde du cache avec data
  135.                     $logMsg sprintf(
  136.                         "[%s] SAVE | file: %s | data: %s\n",
  137.                         date('Y-m-d H:i:s'),
  138.                         $path_json_file,
  139.                         base64_encode($output)
  140.                     );
  141.                     file_put_contents(__DIR__ '/../../var/cache-webservices.log'$logMsgFILE_APPEND);
  142.                 }
  143.                 if ($_SERVER['VERSION_CACHE'] == 2) {
  144.                 }
  145.             }
  146.         } catch (\Exception $exception) {
  147.         }
  148.         $response json_decode($outputtrue);
  149.         if (isset($response["ErrorMessage"]["Description"]))
  150.             return array("Erreur" => $response["ErrorMessage"]["Description"]); //throw new \Exception()
  151.         if (isset($response["error_message"]))
  152.             return array("Error" => $response["error_message"]); //throw new \Exception()
  153.         if (isset($response["Erreur"]))
  154.             return array("Error" => $response["Erreur"]);
  155.         return $response;
  156.     }
  157.     function isJson($string)
  158.     {
  159.         json_decode($string);
  160.         return json_last_error() === JSON_ERROR_NONE;
  161.     }
  162.     /**
  163.      * Décompresse la sortie si elle est compressée (gzip ou deflate)
  164.      */
  165.     private function decompressOutput($data)
  166.     {
  167.         if (!is_string($data) || empty($data)) {
  168.             return $data;
  169.         }
  170.         // Vérifier si les données sont compressées en gzip
  171.         if (strpos($data"\x1f\x8b") === 0) {
  172.             return gzdecode($data);
  173.         }
  174.         // Vérifier si les données sont compressées en deflate
  175.         if (extension_loaded('zlib')) {
  176.             $decompressed = @gzuncompress($data);
  177.             if ($decompressed !== false) {
  178.                 return $decompressed;
  179.             }
  180.         }
  181.         // Si les données ne sont pas compressées, retourner tel quel
  182.         return $data;
  183.     }
  184.     public function checkCustomTemplate($template$template_commun null)
  185.     {
  186.         if ($this->session->has('force-templates-front-commun'))
  187.             return "FrontCommun/$template";
  188.         if (file_exists("../templates/$template"))
  189.             return $template;
  190.         if (!$template_commun)
  191.             $template_commun $template;
  192.         return "FrontCommun/$template_commun";
  193.     }
  194.     public function saveTiming($operation$step "begin")
  195.     {
  196.         $timing $this->session->get('timing', []);
  197.         $timing[$operation][$step] = microtime(true);
  198.         $this->session->set('timing'$timing);
  199.     }
  200.     public function getTiming($operation)
  201.     {
  202.         try {
  203.             if (is_array($operation))
  204.                 return (int)number_format($operation['end'] - $operation['begin'], 3'''') . " ms";
  205.             $timing $this->session->get('timing', []);
  206.             if (isset($timing[$operation]))
  207.                 return (int)number_format($timing[$operation]['end'] - $timing[$operation]['begin'], 3'''') . " ms";
  208.         } catch (\Exception $exception) {
  209.             return "";
  210.         }
  211.     }
  212.     private $ciphering 'AES-128-CTR';// Store the cipher method
  213.     private $encryption_iv '0734221652719037';// Non-NULL Initialization Vector for encryption
  214.     public function encryption($string$key)
  215.     {
  216.         return openssl_encrypt($string$this->ciphering,
  217.             $key0$this->encryption_iv);
  218.     }
  219.     public function decryption($string$key)
  220.     {
  221.         return openssl_decrypt($string$this->ciphering,
  222.             $key0$this->encryption_iv);
  223.     }
  224.     public function getErrorsForm($errors)
  225.     {
  226.         $msgErrors = [];
  227.         foreach ($errors as $error) {
  228.             $err "";
  229.             if (method_exists($error'getOrigin'))
  230.                 $err .= "{$error->getOrigin()->getName()} : ";
  231.             if (method_exists($error'getMessage'))
  232.                 $err .= "{$error->getMessage()}";
  233.             if ($err != "")
  234.                 $msgErrors[] = $err;
  235.         }
  236.         return $msgErrors;
  237.     }
  238.     public function hasModule($module)
  239.     {
  240.         $agence $this->session->get('agence');
  241.         $client $this->session->get('client');
  242.         $amicale $this->session->get('amicale');
  243.         if (
  244.             (!isset($agence['Agence']['modules'][$module]) || $agence['Agence']['modules'][$module]) &&
  245.             (!isset($amicale['modules'][$module]) || $amicale['modules'][$module]) &&
  246.             (!isset($client['amicale']['modules'][$module]) || $client['amicale']['modules'][$module])
  247.         )
  248.             return true;
  249.         return false;
  250.     }
  251.     public function domain($domainb)
  252.     {
  253.         $_domainb $domainb;
  254.         $bits explode('/'$domainb);
  255.         if ($bits[0] == 'http:' || $bits[0] == 'https:') {
  256.             $domainb $bits[2];
  257.         } else {
  258.             $domainb $bits[0];
  259.         }
  260.         unset($bits);
  261.         $bits explode('.'$domainb);
  262.         $idz 0;
  263.         while (isset($bits[$idz])) {
  264.             $idz += 1;
  265.         }
  266.         $idz -= 3;
  267.         $idy 0;
  268.         while ($idy $idz) {
  269.             unset($bits[$idy]);
  270.             $idy += 1;
  271.         }
  272.         $part = array();
  273.         foreach ($bits as $bit) {
  274.             $part[] = $bit;
  275.         }
  276.         unset($bit);
  277.         unset($bits);
  278.         unset($domainb);
  279.         $domainb '';
  280.         if (strlen($part[1]) > 3) {
  281.             unset($part[0]);
  282.         }
  283.         foreach ($part as $bit) {
  284.             $domainb .= $bit '.';
  285.         }
  286.         unset($bit);
  287.         $domainb preg_replace('/(.*)\./''$1'$domainb);
  288.         $domainb strpos($_domainb'www') !== false "www.$domainb$domainb;
  289.         $domainb strpos($_domainb'https:') !== false "https://$domainb$domainb;
  290.         $domainb strpos($_domainb'http:') !== false "http://$domainb$domainb;
  291.         return $domainb;
  292.     }
  293.     public function domaineBack($domaine_back null)
  294.     {
  295.         if ($domaine_back)
  296.             return $_SERVER[$domaine_back];
  297.         return $_SERVER[$this->session->get('DOMAINE_BACK''DOMAINE_BACK')];
  298.     }
  299.     function array_group_by($key$array)
  300.     {
  301.         return array_reduce($array, function (array $accumulator, array $element) use ($key) {
  302.             $accumulator[$element[$key]][] = $element;
  303.             return $accumulator;
  304.         }, []);
  305.     }
  306. }