<?php
namespace App\Util;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Twig\Extension\ExtensionInterface;
use App\Entity\Idioma;
class Util extends AbstractController
{
private $em;
// Definir un array amb les planes a comprovar per canviar de domini
public $aValors = [
'escola_esqui_alpi_snowboard',
'escuela_esqui_alpino_snowboard',
'ski_snowboard_school',
'ecole_ski_snowboard',
'escola_esqui_snowboard',
'preus_escola',
'precios_escuela',
'rates_school',
'tarifs',
'precos_escola',
'consells-per-als-mes-petits',
'consejos-para-los-mas-pequenos',
'advice-for-children',
'conseils-pour-les-enfants',
'conselhos-para-os-mais-pequenos',
'grups_escolars',
'grupos_escolares',
'school_groups',
'groupes_scolaires',
'grupos_escolares'
];
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function checkDateBetweenPeriod($dDate, $iPediod = '-99')
{
//$dDateFormat = date('Y-m-d');
//$dDateFormat = date('Y-m-d', strtotime($dDate));
$dDateFormat = $dDate;
if (strpos($dDate,'/') !== false) {
$aData = explode('/', $dDate);
$dDateFormat = $aData[2] . '-' . $aData[1] . '-' . $aData[0];
}
$dDateBegin = date('Y-m-d', strtotime($iPediod . ' year'));
$dDateEnd = date('Y-m-d', strtotime('-1 year'));
if (($dDateFormat >= $dDateBegin)
&& ($dDateFormat <= $dDateEnd))
{
return true;
} else {
return false;
}
}
public function getIdiomes()
{
$entities = $this->em->getRepository(Idioma::class)->findAll();
return $entities;
}
public function logAction($request, $user)
{
ini_set('max_execution_time', 300);
$sDataHora = date("Y_m_d");
$sNameLog = "userLog_" . $sDataHora . ".txt";
switch ($_SERVER['SERVER_NAME']) {
case 'www.masella.com':
case 'beta.masella.com':
$sBase = '/var/www/vhosts/masella.com/httpdocs/';
break;
case 'dev22.masella.com':
$sBase = '/var/www/vhosts/dev22.masella.com/httpdocs/';
break;
case 'dev23.masella.com':
$sBase = '/var/www/vhosts/dev23.masella.com/httpdocs/';
break;
case 'masella015.developer.entorno.es':
$sBase = '/home/jramon/projects/masella2015/';
break;
default:
$sBase = '/var/www/vhosts/' . $_SERVER['HTTP_HOST'] . '/httpdocs/';
break;
}
$sDir = $sBase . 'userLog/';
$aUserLog = fopen($sDir . $sNameLog, 'a');
$antigua = umask(0);
umask($antigua);
fputs($aUserLog, preg_replace("/\r|\n/", "", $this->processLogInfo($request, $user)) . PHP_EOL);
fclose($aUserLog);
return true;
}
private function processLogInfo($request, $user)
{
$module = 'Módulo: ' . $request->attributes->get('_controller');
$action = 'Action: ' . $request->get('_route');
$sLinea = '->' . date('Y-m-d H:i:s') . ', ' . $module . ', ' . $action;
$session_params = (array)$user;
if ($session_params)
$sLinea .= ", sesión: ";
//dump ($session_params);
$allowed_keys = array('id','nom','email');
$sComa = '';
foreach ($session_params as $key => $value)
{
$key = trim(str_replace('App\Entity\Usuari','',$key));
if (in_array($key, $allowed_keys))
{
if ($key == 'en_culture')
$key = 'idioma';
$sLinea .= $sComa . ' ' . $key . '="' . strip_tags(substr($value, 0, 50)) . '"';
$sComa = ',';
}
}
$param = '';
//dump ($request);
//die();
$request_params = array_merge((array)$request->query->all(), (array)$request->request->all(), (array)$request->attributes->all());
//dump ($request->request->all());
//dump ($request_params);
//die();
if ($request_params)
{
$sLinea .= ", parámetros: ";
}
$not_allowed_keys = array( 'input_x',
'input_y',
'PHPSESSID',
'input',
'pagina',
'user',
'__utmc',
'__utma',
'__utmz',
'__utmb',
'password',
'Usuario',
'Clave',
'locale',
'psaContext',
'BarExpanded',
'phpMyAdmin');
foreach ($request_params as $key => $value)
{
//echo '-' . $key . '-';
// dump($value);
// die();
if (!in_array($key, $not_allowed_keys)
&& $value)
{
if ($key == 'en_culture')
$key = 'idioma';
if (is_array($value))
{
$sLinea .= ' ' . $key . '=(';
foreach ($value as $key => $val)
{
if (is_array($val)) $val = implode(",", $val);
$sLinea .= ' ' . $key . '="' . strip_tags(substr($val, 0, 50)) . '" , ';
}
$sLinea .= ')';
} else {
$sLinea .= ' ' . $key . '="' . strip_tags(substr($value, 0, 50)) . '" , ';
}
//$param .= ' ' . $key . '="' . $value . '" , ';
}
}
//if (!$param)
// $sLinea .= ' sin parámetros, sólo acceso a la página ';
//else
// $sLinea .= $param;
return $sLinea;
}
public function encrypt($string, $key)
{
// $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
// $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_URANDOM );
// mcrypt_generic_init($td, $key, $iv);
// $encrypted_data_bin = mcrypt_generic($td, $string);
// mcrypt_generic_deinit($td);
// mcrypt_module_close($td);
// $encrypted_data_hex = bin2hex($iv).bin2hex($encrypted_data_bin);
// return $encrypted_data_hex;
//$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$secret_iv = '5fgf5HJ5g27';
$iv = substr(hash('sha256', $secret_iv), 0, 16);
$encrypted = openssl_encrypt($string, 'aes-256-cbc', $key, 0, $iv);
return urlencode(str_replace('/', '**', base64_encode($encrypted . '::' . $iv)));
}
public function decrypt($encrypted_data_hex, $key)
{
// $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
// $iv_size_hex = mcrypt_enc_get_iv_size($td)*2;
// $iv = pack("H*", substr($encrypted_data_hex, 0, $iv_size_hex));
// $encrypted_data_bin = pack("H*", substr($encrypted_data_hex, $iv_size_hex));
// mcrypt_generic_init($td, $key, $iv);
// $decrypted = mdecrypt_generic($td, $encrypted_data_bin);
// mcrypt_generic_deinit($td);
// mcrypt_module_close($td);
// return $decrypted;
$string = str_replace('**', '/', urldecode($encrypted_data_hex));
list($encrypted_data, $iv) = explode('::', base64_decode($string), 2);
return rtrim(openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv), "\0");
}
public function createLocalitzador($id)
{
return 'ED' . date('ym') . $id;
}
public function createLocalitzadorBaixadaTorxes($id)
{
return 'BT' . date('ym') . str_pad($id, 4, '0', STR_PAD_LEFT);
}
public function getNegativeNumber($iNumber)
{
if (!is_null($iNumber))
{
$iNumber = $iNumber * (-1);
}
return $iNumber;
}
/**
* Funció per substituir les lletres o els dígits per -
*
* @param $text
* @return unknown_type slugified $text
*/
public function slugifyFile($text, $cReplace = "-")
{
if (empty($text)
|| is_null($text)
|| $text == '')
{
return '';
}
$text = strtolower($text.'');
$text = preg_replace("/[^a-z0-9.\s-]/", $cReplace, $text);
$text = trim(preg_replace("/\s+/", "", $text));
$text = preg_replace("/\s/", $cReplace, $text);
return $text;
}
public function texto_aleatorio ($long = 8, $letras_min = true, $letras_max = true, $num = true)
{
$salt = $letras_min?'abchefghknpqrstuvwxyz':'';
$salt .= $letras_max?'ACDEFHKNPRSTUVWXYZ':'';
$salt .= $num?(strlen($salt)?'2345679':'0123456789'):'';
if (strlen($salt) == 0)
{
return '';
}
$i = 0;
$str = '';
srand((double)microtime()*1000000);
while ($i < $long)
{
$num = rand(0, strlen($salt)-1);
$str .= substr($salt, $num, 1);
$i++;
}
return $str;
}
public function separarCognoms ($sCognoms)
{
$aCognom = explode(' ', $sCognoms);
$sCognom = $aCognom[0];
unset($aCognom[0]);
$sCognom2 = implode(' ',$aCognom);
$aResposta = array( 'cognom1' => $sCognom,
'cognom2' => $sCognom2);
return new JsonResponse($aResposta);
}
public function giraData($sData, $sSeparado = '/')
{
return implode($sSeparado, array_reverse(explode($sSeparado, $sData)));
}
/**
* Guardem una imatge base64 a un arxiu
* @param type $sPath
* @param type $sBase64
* @return boolean
*/
public function guardaImatge($sPath, $sBase64)
{
$f = fopen($sPath, "wb") or die("Unable to open file!");
//////////////////////////////////////////////////////////////
// Guardem en l'arxiu el contenido que hi ha despés de la coma
//////////////////////////////////////////////////////////////
//fwrite($f, base64_decode(explode(",", $sBase64, 2)[1]));
fwrite($f, base64_decode($sBase64));
fclose($f);
return true;
}
/**
* Whether ip is from share internet
*
* @return mixed
*/
public function getIpConsumer()
{
$ip_address = '';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
///////////////////////////
// Whether ip is from proxy
///////////////////////////
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
////////////////////////////////////
// Whether ip is from remote address
////////////////////////////////////
$ip_address = $_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
public function dataFormatYYYYMMDD($data, $sSeparador = '/')
{
$aData = explode($sSeparador, $data);
return $aData[2] . '-' . $aData[1] . '-' . $aData[0];
}
public function getPDO()
{
$conn = new \PDO('sqlsrv:Server=192.168.20.179;Database=TT_AXESS_MAS_Integracions;Encrypt = false;', 'Entorno', 'Etn@2537');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
return $conn;
}
}