<?php
/**
* Created by PhpStorm.
* User: MohamedAli
* Date: 21/04/2020
* Time: 06:38
*/
namespace App\Service;
use App\Entity\LogCache;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface as Session;
use Symfony\Component\Security\Core\Security;
class Generale
{
/**
* GeneraleExtension constructor.
*/
public function __construct(EntityManagerInterface $em, Session $session, RequestStack $requestStack, Security $security)
{
$this->em = $em;
$this->security = $security;
$this->session = $session;
$this->requestStack = $requestStack;
}
public function WebService($produit, $service, $param = array(), $cache = false, $headers = [], $endpoint = null)
{
if (!$endpoint)
$endpoint = $this->domaineBack();
$login = $_SERVER['LOGIN_XML'];
$pwd = $_SERVER['PWD_XML'];
$urlSHT = "$endpoint/api/hotel/";
$urlOldSHT = "$endpoint/api-sht/";
$urlVO = "$endpoint/api-vo/";
$urlBE = "$endpoint/api-be/";
$urlLV = "$endpoint/api-lv/";
$urlTASK = "$endpoint/api-task/";
$urlCHAT = "$endpoint/api-chat/";
$urlCMS = "$endpoint/api-cms/";
$urlTransfert = "$endpoint/api-t/";
$urlAUTH = "$endpoint/api-auth/";
$urlAFFILIE = "$endpoint/api-espace-affilie/";
$urlVOL = "$endpoint/api-vol/";
$urlM = "$endpoint/api-m/";
if (is_null($param))
$param = [];
//if($container->getParameter('kernel.debug'));
$request = $this->requestStack->getCurrentRequest();
$sub_dir = array_search($endpoint, $_SERVER, true);
$sub_dir = str_replace('DOMAINE_BACK', '', $sub_dir);
if ($sub_dir == '')
$sub_dir = "data";
$DIR_SEP = DIRECTORY_SEPARATOR;
$folder_json_file = "cache-webservices{$DIR_SEP}{$service}{$DIR_SEP}{$sub_dir}";
$path_json_file = "{$folder_json_file}{$DIR_SEP}$cache.json";
if ($cache and !$request->get('not-cache'))
if ($_SERVER['VERSION_CACHE'] == 1 and file_exists($path_json_file))
return json_decode(file_get_contents($path_json_file), true);
$connexion = [
'login' => $login,
'pwd' => $pwd
];
if (in_array($service, ['Subscribe', 'check-credential']))
$connexion = [
'WSlogin' => $login,
'WSpwd' => $pwd
];
if ($produit == "SHT")
$connexion = array(
'Credential' => [
'Login' => $login,
'Password' => $pwd
]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ${"url$produit"} . $service);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$headers [] = "ClientIp:{$request->getClientIp()}";
$headers [] = "Language:{$request->getLocale()}";
$clientHost = (isset($_SERVER['DOMAINE_FRONT']) and $_SERVER['DOMAINE_FRONT'] != "" and $_SERVER['CHECK_CLIENT_BY_HOST'] == 'false') ? $_SERVER['DOMAINE_FRONT'] : $request->getSchemeAndHttpHost();
//$_clientHost = self::domain($clientHost);
if (isset($_SERVER['PREFIXE_ROUTE']))
$clientHost .= "/{$_SERVER['PREFIXE_ROUTE']}";
$headers [] = "Content-Type: application/json";
$headers [] = "ClientHost:$clientHost";
$headers [] = "ClientHost2:{$request->getSchemeAndHttpHost()}";
$clientId = null;
if (isset($this->session->get('client', [])['id'])) {
$clientId = $this->session->get('client')['id'];
$headers [] = "ClientId:$clientId";
} elseif (isset($this->session->get('amicale', [])['clients'][0])) {
$clientId = $this->session->get('amicale')['clients'][0];
$headers [] = "ClientId:$clientId";
$headers [] = "ClientAnonyme: True";
}
$param['B2B'] = (in_array($_SERVER['APP_ACCESS_CONTROL'], ['ROLE_CLIENT_B2B', 'ROLE_CLIENT_B2B_OR_AMICALE']) or
in_array($_SERVER['APP_SECOND_ACCESS_CONTROL'], ['ROLE_CLIENT_B2B', 'ROLE_CLIENT_B2B_OR_AMICALE']));
if ($service != 'Subscribe' and !in_array($produit, ['AUTH', 'CMS']) and $param['B2B'] and !$clientId)
throw new \Exception("Votre session a expiré ou les informations nécessaires sont manquantes. Veuillez vous reconnecter pour continuer.");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array_merge($connexion, $param)));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
// Décompresser la réponse si elle est compressée
$output = $this->decompressOutput($output);
$info = curl_getinfo($ch);
$curl_error = curl_error($ch);
curl_close($ch);
#===============================================================================================================
#............. SAVE LOG WEBSERVICE IN SESSION ...............................................
#===============================================================================================================
$headers [] = "Accept-Encoding: identity";
$LOG_WEB_SERVICES = $this->session->get('LOG_WEB_SERVICES', []);
$LOG_WEB_SERVICES[$service][date('d/m/Y H:i:s')]['request'] = "curl --location --request POST " . ${"url$produit"} . $service . implode("", array_map(function ($item) {
return "\n--header '$item'";
}, $headers)) . "\n--data-raw '" . json_encode(array_merge($connexion, $param), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "'";
$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);
$this->session->set('LOG_WEB_SERVICES', $LOG_WEB_SERVICES);
#===============================================================================================================
try {
if ($cache and self::isJson($output)) {
if ($_SERVER['VERSION_CACHE'] == 1) {
if (!is_dir($folder_json_file))
if (PHP_OS_FAMILY === "Linux")
exec("mkdir -p -m 777 $folder_json_file");
elseif (PHP_OS_FAMILY === "Windows")
exec("mkdir $folder_json_file");
//array_map('unlink', array_filter((array)glob("$folder_json_file/*")));
$_folder_json_file = realpath($folder_json_file);
exec("find $_folder_json_file -type f -mtime +1 -exec rm -rf {} \;");
file_put_contents($path_json_file, $output);
// Ajout du log de sauvegarde du cache avec data
$logMsg = sprintf(
"[%s] SAVE | file: %s | data: %s\n",
date('Y-m-d H:i:s'),
$path_json_file,
base64_encode($output)
);
file_put_contents(__DIR__ . '/../../var/cache-webservices.log', $logMsg, FILE_APPEND);
}
if ($_SERVER['VERSION_CACHE'] == 2) {
}
}
} catch (\Exception $exception) {
}
$response = json_decode($output, true);
if (isset($response["ErrorMessage"]["Description"]))
return array("Erreur" => $response["ErrorMessage"]["Description"]); //throw new \Exception()
if (isset($response["error_message"]))
return array("Error" => $response["error_message"]); //throw new \Exception()
if (isset($response["Erreur"]))
return array("Error" => $response["Erreur"]);
return $response;
}
function isJson($string)
{
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
/**
* Décompresse la sortie si elle est compressée (gzip ou deflate)
*/
private function decompressOutput($data)
{
if (!is_string($data) || empty($data)) {
return $data;
}
// Vérifier si les données sont compressées en gzip
if (strpos($data, "\x1f\x8b") === 0) {
return gzdecode($data);
}
// Vérifier si les données sont compressées en deflate
if (extension_loaded('zlib')) {
$decompressed = @gzuncompress($data);
if ($decompressed !== false) {
return $decompressed;
}
}
// Si les données ne sont pas compressées, retourner tel quel
return $data;
}
public function checkCustomTemplate($template, $template_commun = null)
{
if ($this->session->has('force-templates-front-commun'))
return "FrontCommun/$template";
if (file_exists("../templates/$template"))
return $template;
if (!$template_commun)
$template_commun = $template;
return "FrontCommun/$template_commun";
}
public function saveTiming($operation, $step = "begin")
{
$timing = $this->session->get('timing', []);
$timing[$operation][$step] = microtime(true);
$this->session->set('timing', $timing);
}
public function getTiming($operation)
{
try {
if (is_array($operation))
return (int)number_format($operation['end'] - $operation['begin'], 3, '', '') . " ms";
$timing = $this->session->get('timing', []);
if (isset($timing[$operation]))
return (int)number_format($timing[$operation]['end'] - $timing[$operation]['begin'], 3, '', '') . " ms";
} catch (\Exception $exception) {
return "";
}
}
private $ciphering = 'AES-128-CTR';// Store the cipher method
private $encryption_iv = '0734221652719037';// Non-NULL Initialization Vector for encryption
public function encryption($string, $key)
{
return openssl_encrypt($string, $this->ciphering,
$key, 0, $this->encryption_iv);
}
public function decryption($string, $key)
{
return openssl_decrypt($string, $this->ciphering,
$key, 0, $this->encryption_iv);
}
public function getErrorsForm($errors)
{
$msgErrors = [];
foreach ($errors as $error) {
$err = "";
if (method_exists($error, 'getOrigin'))
$err .= "{$error->getOrigin()->getName()} : ";
if (method_exists($error, 'getMessage'))
$err .= "{$error->getMessage()}";
if ($err != "")
$msgErrors[] = $err;
}
return $msgErrors;
}
public function hasModule($module)
{
$agence = $this->session->get('agence');
$client = $this->session->get('client');
$amicale = $this->session->get('amicale');
if (
(!isset($agence['Agence']['modules'][$module]) || $agence['Agence']['modules'][$module]) &&
(!isset($amicale['modules'][$module]) || $amicale['modules'][$module]) &&
(!isset($client['amicale']['modules'][$module]) || $client['amicale']['modules'][$module])
)
return true;
return false;
}
public function domain($domainb)
{
$_domainb = $domainb;
$bits = explode('/', $domainb);
if ($bits[0] == 'http:' || $bits[0] == 'https:') {
$domainb = $bits[2];
} else {
$domainb = $bits[0];
}
unset($bits);
$bits = explode('.', $domainb);
$idz = 0;
while (isset($bits[$idz])) {
$idz += 1;
}
$idz -= 3;
$idy = 0;
while ($idy < $idz) {
unset($bits[$idy]);
$idy += 1;
}
$part = array();
foreach ($bits as $bit) {
$part[] = $bit;
}
unset($bit);
unset($bits);
unset($domainb);
$domainb = '';
if (strlen($part[1]) > 3) {
unset($part[0]);
}
foreach ($part as $bit) {
$domainb .= $bit . '.';
}
unset($bit);
$domainb = preg_replace('/(.*)\./', '$1', $domainb);
$domainb = strpos($_domainb, 'www') !== false ? "www.$domainb" : $domainb;
$domainb = strpos($_domainb, 'https:') !== false ? "https://$domainb" : $domainb;
$domainb = strpos($_domainb, 'http:') !== false ? "http://$domainb" : $domainb;
return $domainb;
}
public function domaineBack($domaine_back = null)
{
if ($domaine_back)
return $_SERVER[$domaine_back];
return $_SERVER[$this->session->get('DOMAINE_BACK', 'DOMAINE_BACK')];
}
function array_group_by($key, $array)
{
return array_reduce($array, function (array $accumulator, array $element) use ($key) {
$accumulator[$element[$key]][] = $element;
return $accumulator;
}, []);
}
}