src/Service/Generale.php line 335

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 Doctrine\ORM\EntityManagerInterface;
  10. use Symfony\Component\HttpFoundation\RequestStack;
  11. use Symfony\Component\HttpFoundation\Session\SessionInterface as Session;
  12. use Symfony\Component\Security\Core\Security;
  13. class Generale
  14. {
  15.     /**
  16.      * GeneraleExtension constructor.
  17.      */
  18.     public function __construct(EntityManagerInterface $em, Session $session, RequestStack $requestStack, Security $security)
  19.     {
  20.         $this->em = $em;
  21.         $this->security = $security;
  22.         $this->session = $session;
  23.         $this->requestStack = $requestStack;
  24.     }
  25.     public function WebService($produit, $service, $param = array(), $cache = false, $headers = [], $endpoint = null)
  26.     {
  27.         if (!$endpoint)
  28.             $endpoint = $this->domaineBack();
  29.         $login = $_SERVER['LOGIN_XML'];
  30.         $pwd = $_SERVER['PWD_XML'];
  31.         $urlSHT = "$endpoint/api/hotel/";
  32.         $urlOldSHT = "$endpoint/api-sht/";
  33.         $urlVO = "$endpoint/api-vo/";
  34.         $urlBE = "$endpoint/api-be/";
  35.         $urlLV = "$endpoint/api-lv/";
  36.         $urlTASK = "$endpoint/api-task/";
  37.         $urlCHAT = "$endpoint/api-chat/";
  38.         $urlCMS = "$endpoint/api-cms/";
  39.         $urlTransfert = "$endpoint/api-t/";
  40.         $urlAUTH = "$endpoint/api-auth/";
  41.         $urlAFFILIE = "$endpoint/api-espace-affilie/";
  42.         $urlVOL = "$endpoint/api-vol/";
  43.         $urlM = "$endpoint/api-m/";
  44.         $urlTRAIN = "$endpoint/api-train/";
  45.         if (is_null($param))
  46.             $param = [];
  47.         //if($container->getParameter('kernel.debug'));
  48.         $request = $this->requestStack->getCurrentRequest();
  49.         $sub_dir = array_search($endpoint, $_SERVER, true);
  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 (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($ch, CURLOPT_URL, ${"url$produit"} . $service);
  77.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  78.         curl_setopt($ch, CURLOPT_ENCODING, '');
  79.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  80.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  81.         $headers [] = "ClientIp:{$request->getClientIp()}";
  82.         $headers [] = "Language:{$request->getLocale()}";
  83.         $clientHost = (!empty($_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($ch, CURLOPT_POSTFIELDS, json_encode(array_merge($connexion, $param)));
  104.         curl_setopt($ch, CURLOPT_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($output, true), 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 (!is_dir($folder_json_file))
  125.                     if (PHP_OS_FAMILY === "Linux")
  126.                         exec("mkdir -p -m 777 $folder_json_file");
  127.                     elseif (PHP_OS_FAMILY === "Windows")
  128.                         exec("mkdir $folder_json_file");
  129.                 //array_map('unlink', array_filter((array)glob("$folder_json_file/*")));
  130.                 $_folder_json_file = realpath($folder_json_file);
  131.                 exec("find $_folder_json_file -type f -mtime +1 -exec rm -rf {} \;");
  132.                 file_put_contents($path_json_file, $output);
  133.             }
  134.         } catch (\Exception $exception) {
  135.         }
  136.         $response = json_decode($output, true);
  137.         if (isset($response["ErrorMessage"]["Description"]))
  138.             return array("Erreur" => $response["ErrorMessage"]["Description"]); //throw new \Exception()
  139.         if (isset($response["error_message"]))
  140.             return array("Error" => $response["error_message"]); //throw new \Exception()
  141.         if (isset($response["Erreur"]))
  142.             return array("Error" => $response["Erreur"]);
  143.         return $response;
  144.     }
  145.     function isJson($string)
  146.     {
  147.         json_decode($string);
  148.         return json_last_error() === JSON_ERROR_NONE;
  149.     }
  150.     /**
  151.      * Décompresse la sortie si elle est compressée (gzip ou deflate)
  152.      */
  153.     private function decompressOutput($data)
  154.     {
  155.         if (!is_string($data) || empty($data)) {
  156.             return $data;
  157.         }
  158.         // Vérifier si les données sont compressées en gzip
  159.         if (strpos($data, "\x1f\x8b") === 0) {
  160.             return gzdecode($data);
  161.         }
  162.         // Vérifier si les données sont compressées en deflate
  163.         if (extension_loaded('zlib')) {
  164.             $decompressed = @gzuncompress($data);
  165.             if ($decompressed !== false) {
  166.                 return $decompressed;
  167.             }
  168.         }
  169.         // Si les données ne sont pas compressées, retourner tel quel
  170.         return $data;
  171.     }
  172.     public function checkCustomTemplate($template, $template_commun = null)
  173.     {
  174.         if ($this->session->has('force-templates-front-commun'))
  175.             return "FrontCommun/$template";
  176.         if (file_exists("../templates/$template"))
  177.             return $template;
  178.         if (!$template_commun)
  179.             $template_commun = $template;
  180.         return "FrontCommun/$template_commun";
  181.     }
  182.     public function saveTiming($operation, $step = "begin")
  183.     {
  184.         $timing = $this->session->get('timing', []);
  185.         $timing[$operation][$step] = microtime(true);
  186.         $this->session->set('timing', $timing);
  187.     }
  188.     public function getTiming($operation)
  189.     {
  190.         try {
  191.             if (is_array($operation))
  192.                 return (int)number_format($operation['end'] - $operation['begin'], 3, '', '') . " ms";
  193.             $timing = $this->session->get('timing', []);
  194.             if (isset($timing[$operation]))
  195.                 return (int)number_format($timing[$operation]['end'] - $timing[$operation]['begin'], 3, '', '') . " ms";
  196.         } catch (\Exception $exception) {
  197.             return "";
  198.         }
  199.     }
  200.     private $ciphering = 'AES-128-CTR';// Store the cipher method
  201.     private $encryption_iv = '0734221652719037';// Non-NULL Initialization Vector for encryption
  202.     public function encryption($string, $key)
  203.     {
  204.         return openssl_encrypt($string, $this->ciphering,
  205.             $key, 0, $this->encryption_iv);
  206.     }
  207.     public function decryption($string, $key)
  208.     {
  209.         return openssl_decrypt($string, $this->ciphering,
  210.             $key, 0, $this->encryption_iv);
  211.     }
  212.     public function getErrorsForm($errors)
  213.     {
  214.         $msgErrors = [];
  215.         foreach ($errors as $error) {
  216.             $err = "";
  217.             if (method_exists($error, 'getOrigin'))
  218.                 $err .= "{$error->getOrigin()->getName()} : ";
  219.             if (method_exists($error, 'getMessage'))
  220.                 $err .= "{$error->getMessage()}";
  221.             if ($err != "")
  222.                 $msgErrors[] = $err;
  223.         }
  224.         return $msgErrors;
  225.     }
  226.     public function hasModule($module)
  227.     {
  228.         $agence = $this->session->get('agence');
  229.         $client = $this->session->get('client');
  230.         $amicale = $this->session->get('amicale');
  231.         if (
  232.             (!isset($agence['Agence']['modules'][$module]) || $agence['Agence']['modules'][$module]) &&
  233.             (!isset($amicale['modules'][$module]) || $amicale['modules'][$module]) &&
  234.             (!isset($client['amicale']['modules'][$module]) || $client['amicale']['modules'][$module])
  235.         )
  236.             return true;
  237.         return false;
  238.     }
  239.     public function domain($domainb)
  240.     {
  241.         $_domainb = $domainb;
  242.         $bits = explode('/', $domainb);
  243.         if ($bits[0] == 'http:' || $bits[0] == 'https:') {
  244.             $domainb = $bits[2];
  245.         } else {
  246.             $domainb = $bits[0];
  247.         }
  248.         unset($bits);
  249.         $bits = explode('.', $domainb);
  250.         $idz = 0;
  251.         while (isset($bits[$idz])) {
  252.             $idz += 1;
  253.         }
  254.         $idz -= 3;
  255.         $idy = 0;
  256.         while ($idy < $idz) {
  257.             unset($bits[$idy]);
  258.             $idy += 1;
  259.         }
  260.         $part = array();
  261.         foreach ($bits as $bit) {
  262.             $part[] = $bit;
  263.         }
  264.         unset($bit);
  265.         unset($bits);
  266.         unset($domainb);
  267.         $domainb = '';
  268.         if (strlen($part[1]) > 3) {
  269.             unset($part[0]);
  270.         }
  271.         foreach ($part as $bit) {
  272.             $domainb .= $bit . '.';
  273.         }
  274.         unset($bit);
  275.         $domainb = preg_replace('/(.*)\./', '$1', $domainb);
  276.         $domainb = strpos($_domainb, 'www') !== false ? "www.$domainb" : $domainb;
  277.         $domainb = strpos($_domainb, 'https:') !== false ? "https://$domainb" : $domainb;
  278.         $domainb = strpos($_domainb, 'http:') !== false ? "http://$domainb" : $domainb;
  279.         return $domainb;
  280.     }
  281.     public function domaineBack($domaine_back = null)
  282.     {
  283.         if ($domaine_back)
  284.             return $_SERVER[$domaine_back];
  285.         return $_SERVER[$this->session->get('DOMAINE_BACK', 'DOMAINE_BACK')];
  286.     }
  287.     function array_group_by($key, $array)
  288.     {
  289.         return array_reduce($array, function (array $accumulator, array $element) use ($key) {
  290.             $accumulator[$element[$key]][] = $element;
  291.             return $accumulator;
  292.         }, []);
  293.     }
  294. }