<?php
/** @noinspection PhpUndefinedFieldInspection */
use App\Application\Service\Customer\CustomerExpeditionTimeService;
use App\Application\Service\Helper\DatetimeHelper;
use App\Application\Service\Helper\ShippingDateService;
use App\Application\Service\Session\SessionService;
use App\Service\Search\Adapter\ProductRepositoryAdapter;
use App\ViewManager\Landing\ViewService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Manager\System\SupplierHolidaysManager;
use App\Service\TaxService;
class Tools extends AllowTranslation
{
public const COOKIE_TAPFILIATE = 'ref_tapfiliate';
public const KEY_TAPFILIATE = 'tapfiliate';
public const COOKIE_ID_CUSTOMER_STASH = 'bbidm';
public const HOST_BIGBUY = 'bigbuy.eu';
public const ERROR_LIST = [
'SUBS01' => 'SUBS01', // No se ha podido crear el pedido.
'SUBS02' => 'SUBS02', // No se ha podido crear carrito de pack
'SUBS03' => 'SUBS03', // No se ha podido crear carrito de servicios
'ORD01' => 'ORD01', // No se ha podido recuperar el carrito asociado al pedido
'ORD02' => 'ORD02', // No se han podido recuperar los costes de envío
'ORD03' => 'ORD03', // No se ha podido guardar el pedido
'ORD04' => 'ORD04', // Cache de carrito bloqueada
];
public const MAX_LIST_PRODUCTS = 9984;
public const SECONDS_BY_DAY = 86400;
public static function getValue($key, $default_value = false, $stripSlashes = true)
{
if (!isset($key) || empty($key) || !is_string($key)) {
return false;
}
$ret = (isset($_POST[$key]) ? $_POST[$key] : (isset($_GET[$key]) ? $_GET[$key] : $default_value));
if (is_string($ret) === true) {
$ret = urldecode(preg_replace('/((\%5C0+)|(\%00+))/i', '', urlencode($ret)));
}
if (!is_string($ret)) {
return $ret;
} else {
return $stripSlashes ? stripslashes($ret) : $ret;
}
}
/**
* Sanitize data which will be injected into SQL query
*
* @param string $string SQL data which will be injected into SQL query
* @param bool $htmlOK Does data contain HTML code ? (optional)
*
* @return string Sanitized data
*/
public static function pSQL($string, $htmlOK = false)
{
return self::escape($string, $htmlOK);
}
/**
* Sanitize data which will be injected into SQL query
*
* @param string $string SQL data which will be injected into SQL query
* @param bool $html_ok Does data contain HTML code ? (optional)
*
* @return string Sanitized data
*/
public static function escape($string, $html_ok = false)
{
$string = addslashes($string);
if (!is_numeric($string)) {
if (!$html_ok) {
$string = strip_tags(Tools::nl2br($string));
}
}
return $string;
}
/**
* Convert \n and \r\n and \r to <br />
*
* @param string $string String to transform
*
* @return string New string
*/
public static function nl2br($str)
{
return str_replace(["\r\n", "\r", "\n"], '<br />', $str);
}
/**
* Delete unicode class from regular expression patterns
*
* @param string $pattern
*
* @return pattern
*/
public static function cleanNonUnicodeSupport($pattern)
{
if (!defined('PREG_BAD_UTF8_OFFSET')) {
return $pattern;
}
return preg_replace('/\\\[px]\{[a-z]\}{1,2}|(\/[a-z]*)u([a-z]*)$/i', '$1$2', $pattern);
}
/**
* Redirect user to another page
*
* @param string $url Desired URL
* @param string $baseUri Base URI (optional)
* @param string|array $headers A list of headers to send before redirection
*/
public static function redirect($url, $base_uri = BASE_URL, $redirect_301 = false)
{
if (strpos($url, 'http://') === false && strpos($url, 'https://') === false) {
if (strpos($url, $base_uri) === 0) {
$url = substr($url, strlen($base_uri));
}
// SE CONCATENA LA URI BASE JUNTO CON LA URL SOLICITADA
$url = $base_uri.$url;
}
ob_clean();
if ($redirect_301) {
header('HTTP/1.1 301 Moved Permanently');
}
header('Location: '.$url);
exit;
}
public static function addError($message)
{
Session::add('error', $message);
}
public static function addNamedError($name_input, $message)
{
Session::add_flashdata_byId('error', $name_input, $message);
}
public static function getError()
{
return Session::get('error', false, true);
}
public static function hasError()
{
return Session::get('error');
}
public static function getErrors()
{
$errors = false;
if (Tools::hasError()) {
$errors = Tools::getError();
}
return $errors;
}
public static function addNamedNotice($name_input, $message)
{
Session::add_flashdata_byId('notice', $name_input, $message);
}
public static function hasNotice()
{
return Session::get('notice');
}
public static function getNotice()
{
return Session::get('notice', false, true);
}
public static function getNotices()
{
$notices = false;
if (Tools::hasNotice()) {
$notices = Tools::getNotice();
}
return $notices;
}
public static function strlen($str, $encoding = 'UTF-8')
{
if (is_array($str)) {
return false;
}
$str = html_entity_decode($str, ENT_COMPAT, 'UTF-8');
if (function_exists('mb_strlen')) {
return mb_strlen($str, $encoding);
}
return strlen($str);
}
/**
* Encrypt password
*
* @param string $passwd String to encrypt
*/
public static function encrypt($passwd)
{
return md5($passwd);
}
/**
* jsonDecode convert json string to php array / object
*
* @param string $json
* @param bool $assoc (since 1.4.2.4) if true, convert to associativ array
*
* @return array
*
* @deprecated use json_decode instead
*/
public static function jsonDecode($json, $assoc = false)
{
return json_decode($json, $assoc);
}
/**
* Convert an array to json string
*
* @param array $data
*
* @return string json
* @deprecated use json_encode instead
*
*/
public static function jsonEncode($data, $unescape = false)
{
if (!$unescape) {
return json_encode($data);
}
return json_encode($data, JSON_UNESCAPED_SLASHES);
}
/**
* Retorna una fecha según las preferencias del lenguaje
*
* @param string $date La fecha a convertir
* @param bool $full Si el formato de la fecha debe retornar horas o no
* @param string $format Formato de la fecha personalizado
*
* @return string La fecha convertida
*/
public static function displayDate($date, $full = false, $date_format = false, $plus_gmt_offset = true)
{
if (!$date || !($time = strtotime($date))) {
return $date;
}
if ($date == '0000-00-00 00:00:00' || $date == '0000-00-00') {
return '';
}
if (!Validate::isDate($date) || !Validate::isBool($full)) {
Tools::addError('Invalid date');
}
if (!$date_format) {
$date_format = ($full ? Session::get('date_format_full') : Session::get('date_format_lite'));
}
if ($plus_gmt_offset) {
return date($date_format, $time + Session::get('gmt_offset'));
} else {
return date($date_format, $time);
}
}
/**
* Retorna una fecha con formato compatible con Mysql
*
* @param type $date Fecha a convertir
* @param type $dateFormat Formato para Mysql
*
* @return type Fecha formateada
*/
public static function displayDateMysql($date, $dateFormat = 'Y-m-d H:i:s')
{
$date = str_replace('/', '.', $date);
$dateMysql = date($dateFormat, strtotime($date));
return $dateMysql;
}
public static function getWeekDays()
{
return [
self::l('Domingo', 'Tools'),
self::l('Lunes', 'Tools'),
self::l('Martes', 'Tools'),
self::l('Miércoles', 'Tools'),
self::l('Jueves', 'Tools'),
self::l('Viernes', 'Tools'),
self::l('Sábado', 'Tools'),
];
}
public static function getMonths()
{
return [
self::l('Enero', 'Tools'),
self::l('Febrero', 'Tools'),
self::l('Marzo', 'Tools'),
self::l('Abril', 'Tools'),
self::l('Mayo', 'Tools'),
self::l('Junio', 'Tools'),
self::l('Julio', 'Tools'),
self::l('Agosto', 'Tools'),
self::l('Septiembre', 'Tools'),
self::l('Octubre', 'Tools'),
self::l('Noviembre', 'Tools'),
self::l('Diciembre', 'Tools'),
];
}
public static function displayTextDate($date)
{
$year = date('Y', $date);
$month = (int)date('m', $date);
$day = date('d', $date);
$week_day = date('w', $date);
$week_days = Tools::getWeekDays();
$months = Tools::getMonths();
return $week_days[$week_day].', '.$day.' de '.$months[$month].' de '.$year;
}
public static function displayTextMonth($monthsNumber)
{
$months = Tools::getMonths();
return $months[$monthsNumber - 1];
}
/**
* Return price with currency sign for a given product
*
* @param float $price Product price
*
* @return string Price correctly formated (sign, decimal separator...)
*/
public static function displayPrice($price, $show_currency = true, $decimal = 2, $no_utf8 = false)
{
if (!is_numeric($price)) {
return $price;
}
$c_char = '';
$blank = '';
if ($show_currency) {
$c_char = '€';
$blank = ' ';
}
$c_format = Session::get('currency_format');
$c_decimals = $decimal;
$ret = 0;
if ($is_negative = ($price < 0)) {
$price *= -1;
}
$price = Tools::ps_round($price, $c_decimals);
switch ($c_format) {
/* 0.000,00 X */
case 1:
$ret = number_format($price, $c_decimals, ',', '.').$blank.$c_char;
break;
/* X 0,000.00 X */
case 2:
$ret = $c_char.number_format($price, $c_decimals, '.', ',');
break;
}
if ($is_negative) {
$ret = '-'.$ret;
}
if ($no_utf8) {
return str_replace('€', chr(128), $ret);
}
return $ret;
}
/**
* Return price with currency sign for a given product
*
* @param float $price Product price
*
* @return string Price correctly formated (sign, decimal separator...)
*/
public static function displayNumber($number, $decimal = 2)
{
if (!is_numeric($number)) {
return $number;
}
$c_format = Session::get('currency_format');
$c_decimals = $decimal;
$ret = 0;
if ($is_negative = ($number < 0)) {
$number *= -1;
}
$number = Tools::ps_round($number, $c_decimals);
switch ($c_format) {
/* 0.000,00 */
case 1:
$ret = number_format($number, $c_decimals, ',', '.');
break;
/* 0,000.00 */
case 2:
$ret = number_format($number, $c_decimals, '.', ',');
break;
}
if ($is_negative) {
$ret = '-'.$ret;
}
return $ret;
}
public static function strtolower($str)
{
if (is_array($str)) {
return false;
}
if (function_exists('mb_strtolower')) {
return mb_strtolower($str, 'utf-8');
}
return strtolower($str);
}
public static function substr($str, $start, $length = false, $encoding = 'utf-8')
{
if (is_array($str)) {
return false;
}
if (function_exists('mb_substr')) {
return mb_substr($str, (int)$start, $length === false ? Tools::strlen($str) : (int)$length, $encoding);
}
return substr($str, $start, $length === false ? Tools::strlen($str) : (int)$length);
}
/**
* Comprobamos un VAT Number
*
* @param string $vatid VAT Number a validar
* @param string $cc codigo ISO del pais
* @param int $idCustomer Identificador del usuario
*
* @return bool
* @deprecated use TaxService::isValidVies() instead
*/
public static function checkVATNumber($vatid, $cc, $idCustomer)
{
if (!$vatid || !$cc) {
return false;
}
$taxService = self::getSfService(TaxService::class);
return $taxService->isValidVies($idCustomer, $vatid, $cc);
}
/**
* returns the rounded value of $value to specified precision, according to your configuration;
*
* @note : PHP 5.3.0 introduce a 3rd parameter mode in round function
*
* @param float $value
* @param int $precision
*
* @return float
*
* @deprecated use round() instead
*/
public static function ps_round($value, $precision = 0)
{
return round($value, $precision);
}
public static function getBreadcrumbData($taxonomyId, $addSections = [], $idLang = null)
{
if (!$idLang) {
$idLang = Session::get('id_lang');
}
$parentTaxonomies = Taxonomy::getParentsTaxonomy($taxonomyId, $idLang);
if (!$parentTaxonomies) {
return [];
}
$sections = [];
$taxonomy = array_shift($parentTaxonomies);
$link = Link::getTaxonomyLink($taxonomy->getId(), $idLang); // str_replace(".html", "/", $taxonomy->getLink());
$name = Taxonomy::getTaxonomyName($taxonomy->getId(), $idLang);
$sections[] = ['link' => $link, 'name' => $name];
foreach ($parentTaxonomies as $parentTaxonomy) {
$link = Link::getTaxonomyLink($parentTaxonomy->getId(), $idLang);
$name = Taxonomy::getTaxonomyName($parentTaxonomy->getId(), $idLang);
$sections[] = ['link' => $link, 'name' => $name];
}
if (count($addSections) > 0) {
foreach ($addSections as $section) {
$sections[] = $section;
}
}
return $sections;
}
public static function getRealIP()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
}
// TODO quitar este if y descomentar las líneas
if (!empty($_SERVER['REMOTE_ADDR'])) {
return $_SERVER['REMOTE_ADDR'];
}
// if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
return $_SERVER['HTTP_X_FORWARDED_FOR'];
// return $_SERVER['REMOTE_ADDR'];
}
public static function getCoordsIP()
{
// Obtenemos localización del usuario por su ip
$ip = Tools::getRealIP();
// $ip = '88.0.57.88';
$url = 'http://www.geoplugin.net/php.gp?ip='.$ip; // echo $url;
$datos = @unserialize(file_get_contents($url));
$resp = [];
if ($datos) {
// $iso_code = $datos['geoplugin_countryCode'];
// $city = $datos['geoplugin_city'];
$resp['latitud'] = (isset($datos['geoplugin_latitude'])) ? $datos['geoplugin_latitude'] : '';
$resp['longitud'] = (isset($datos['geoplugin_longitude'])) ? $datos['geoplugin_longitude'] : '';
$resp['country_code'] = (isset($datos['geoplugin_countryCode'])) ? $datos['geoplugin_countryCode'] : '';
$resp['geoplugin_request'] = (isset($datos['geoplugin_request'])) ? $datos['geoplugin_request'] : '';
} else {
$resp['latitud'] = '';
$resp['longitud'] = '';
$resp['country_code'] = '';
$resp['geoplugin_request'] = '';
}
return $resp;
}
/**
* Modifies a string to remove all non ASCII characters and spaces.
*/
public static function slugify($text)
{
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
if (function_exists('iconv')) {
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
public static function httpPost($url, $params, $return_http_code = false, $follow = false, $sslVerification = true)
{
$postData = '';
if (!empty($params)) {
$postData = http_build_query($params);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
// NO VERIFICAR SSL SI ESTAMOS EN MODO DESARROLLO
if (Tools::getSfService(\App\Service\EnvironmentService::class)->isDev() || !$sslVerification) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
if (!empty($params)) {
curl_setopt($ch, CURLOPT_POST, is_array($postData) && count($postData) ? true : false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
if ($follow) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
}
// DESCOMENTAR PARA DEPURAR LLAMADAS CURL DESDE NETBEANS
// curl_setopt($ch, CURLOPT_COOKIE,"XDEBUG_SESSION=netbeans-xdebug");
$output = curl_exec($ch);
if ($output == false) {
$output = curl_error($ch);
}
// DEVOLVEMOS EL CODIGO HTTP (404, 500, 200...)
if ($return_http_code) {
$output = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch);
return $output;
}
/**
* Truncate strings
*
* @param string $str
* @param int $max_length Max length
* @param string $suffix Suffix optional
*
* @return string $str truncated
*/
/* CAUTION : Use it only on module hookEvents.
* * For other purposes use the smarty function instead */
public static function truncate($str, $max_length, $suffix = '...')
{
if (Tools::strlen($str) <= $max_length) {
return $str;
}
$str = utf8_decode($str);
return utf8_encode(substr($str, 0, $max_length - Tools::strlen($suffix)).$suffix);
}
public static function getDefaultIndexContent()
{
return '<?php
/*
* BLOQUEAR ACCESO A LAS CARPETAS
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;
';
}
public static function isMobile()
{// return true;
if (defined('IS_MOBILE')) {
return IS_MOBILE;
}
return false;
}
public static function getPassword()
{
// Se define una cadena de caractares. Te recomiendo que uses esta.
$cadena = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
// Obtenemos la longitud de la cadena de caracteres
$longitudCadena = strlen($cadena);
// Se define la variable que va a contener la contraseña
$pass = '';
// Se define la longitud de la contraseña, en mi caso 10, pero puedes poner la longitud que quieras
$longitudPass = 10;
// Creamos la contraseña
for ($i = 1; $i <= $longitudPass; $i++) {
// Definimos numero aleatorio entre 0 y la longitud de la cadena de caracteres-1
$pos = rand(0, $longitudCadena - 1);
// Vamos formando la contraseña en cada iteraccion del bucle, añadiendo a la cadena $pass la letra correspondiente a la posicion $pos en la cadena de caracteres definida.
$pass .= substr($cadena, $pos, 1);
}
return $pass;
}
public static function getNombreMes($mes)
{
setlocale(LC_TIME, Session::get('lang'));
$nombre = strftime('%B', mktime(0, 0, 0, $mes, 1, 2000));
return strtoupper(substr($nombre, 0, 3));
}
public static function generarCodigo($longitud)
{
$key = '';
$pattern = '1234567890abcdefghijklmnopqrstuvwxyz';
$max = strlen($pattern) - 1;
for ($i = 0; $i < $longitud; $i++) {
$key .= $pattern[mt_rand(0, $max)];
}
return $key;
}
public static function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = [];
foreach ($data as $key => $row) {
$tmp[$key] = $row[$field];
}
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
public static function dropAccents($incoming_string)
{
$tofind = 'ÀÁÂÄÅàáâäÒÓÔÖòóôöÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ';
$replac = 'AAAAAaaaaOOOOooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn';
return utf8_encode(strtr(utf8_decode($incoming_string), utf8_decode($tofind), $replac));
}
public static function addPeriodToDate($frecuency, $time, $period)
{
$date = new DateTime($time);
$monthOld = $date->format('m');
$date->modify('+'.$frecuency.' '.$period);
$monthActually = $date->format('m');
if ($monthActually < $monthOld) {
$monthActually += 12;
}
if ($monthActually - $monthOld > $frecuency) {
$date->modify('last day of -1 Month');
}
return $date->format('Y-m-d');
}
public static function calculateDaysTransit($days, $productId = null, $extern = false)
{
$syncronisedException = ($extern) ? Product::isSincronisedSendException($productId) : false;
if ($days <= 2) {
return [
'days' => 1,
'text_product' => self::l('%s uds.', 'Tools'),
'text_cart' => (!$syncronisedException) ? self::l('Envío inmediato', 'Tools') : self::l('24/48h', 'Tools'),
];
}
$tmpDays = (int)ceil($days / 5);
switch ($tmpDays) {
case 0:
case 1:
$days_range = '2/5';
$tmpDays = 1;
break;
case 2:
$days_range = '5/10';
break;
case 3:
$days_range = '10/15';
break;
case 4:
$days_range = '15/20';
break;
default:
$days_range = '20/30';
}
return [
'days' => $tmpDays * 5,
'text_product' => sprintf(self::l('%s uds. envío %s días', 'Tools'), '%s', $days_range),
'text_cart' => sprintf(self::l('%s días', 'Tools'), $days_range),
];
}
public static function divideString($name, $separador = '<br />', $num_lines = 2)
{
$blank_spaces = ceil(substr_count($name, ' ') / $num_lines);
$nameEnd = '';
$count_spaces = 0;
$nameTmp = str_split($name);
$br = false;
foreach ($nameTmp as $c) {
if ($c == ' ') {
$count_spaces++;
}
if ($count_spaces == $blank_spaces && $blank_spaces > 0 && !$br) {
$nameEnd .= $separador;
$br = true;
} else {
$nameEnd .= $c;
}
}
return $nameEnd;
}
public static function replaceAutomatedLinks($string_to_replace)
{
return preg_replace_callback('/##(CMS|CAT|TAXONOMY)\_(.[0-9]*)##/', function ($matches) {
switch ($matches[1]) {
case 'CMS':
$cms = new Cms($matches[2]);
// RECUPERAMOS LOS DATOS QUE NECESITAMOS PARA EL LINK
$link_rewrite = (!empty($cms->link_rewrite[Session::get('id_lang')])) ? $cms->link_rewrite[Session::get('id_lang')] : '';
return Link::getActionLink($link_rewrite);
break;
case 'CAT':
return Link::getCategoryLink($matches[2]);
case 'TAXONOMY':
return Link::getTaxonomyLink($matches[2]);
break;
}
}, $string_to_replace);
}
public static function convertTable($txt, $titulo = '')
{
$_convertTable = [
'&' => 'and', '@' => 'at', '©' => 'c', '®' => 'r', 'À' => 'a', 'Á' => 'a', 'Â' => 'a', 'Ä' => 'a', 'Å' => 'a', 'Æ' => 'ae', 'Ç' => 'c', 'È' => 'e', 'É' => 'e', 'Ë' => 'e', 'Ì' => 'i', 'Í' => 'i', 'Î' => 'i', 'Ï' => 'i', 'Ò' => 'o', 'Ó' => 'o', 'Ô' => 'o', 'Õ' => 'o', 'Ö' => 'o', 'Ø' => 'o', 'Ù' => 'u', 'Ú' => 'u', 'Û' => 'u', 'Ü' => 'u', 'Ý' => 'y', 'ß' => 'ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ý' => 'y', 'þ' => 'p', 'ÿ' => 'y', 'Ā' => 'a', 'ā' => 'a', 'Ă' => 'a', 'ă' => 'a', 'Ą' => 'a', 'ą' => 'a', 'Ć' => 'c', 'ć' => 'c', 'Ĉ' => 'c', 'ĉ' => 'c', 'Ċ' => 'c', 'ċ' => 'c', 'Č' => 'c', 'č' => 'c', 'Ď' => 'd', 'ď' => 'd', 'Đ' => 'd', 'đ' => 'd', 'Ē' => 'e', 'ē' => 'e', 'Ĕ' => 'e', 'ĕ' => 'e', 'Ė' => 'e', 'ė' => 'e', 'Ę' => 'e', 'ę' => 'e', 'Ě' => 'e', 'ě' => 'e', 'Ĝ' => 'g', 'ĝ' => 'g', 'Ğ' => 'g', 'ğ' => 'g', 'Ġ' => 'g', 'ġ' => 'g', 'Ģ' => 'g', 'ģ' => 'g', 'Ĥ' => 'h', 'ĥ' => 'h', 'Ħ' => 'h', 'ħ' => 'h', 'Ĩ' => 'i', 'ĩ' => 'i', 'Ī' => 'i', 'ī' => 'i', 'Ĭ' => 'i', 'ĭ' => 'i', 'Į' => 'i', 'į' => 'i', 'İ' => 'i', 'ı' => 'i', 'IJ' => 'ij', 'ij' => 'ij', 'Ĵ' => 'j', 'ĵ' => 'j', 'Ķ' => 'k', 'ķ' => 'k', 'ĸ' => 'k', 'Ĺ' => 'l', 'ĺ' => 'l', 'Ļ' => 'l', 'ļ' => 'l', 'Ľ' => 'l', 'ľ' => 'l', 'Ŀ' => 'l', 'ŀ' => 'l', 'Ł' => 'l', 'ł' => 'l', 'Ń' => 'n', 'ń' => 'n', 'Ņ' => 'n', 'ņ' => 'n', 'Ň' => 'n', 'ň' => 'n', 'ʼn' => 'n', 'Ŋ' => 'n', 'ŋ' => 'n', 'Ō' => 'o', 'ō' => 'o', 'Ŏ' => 'o', 'ŏ' => 'o', 'Ő' => 'o', 'ő' => 'o', 'Œ' => 'oe', 'œ' => 'oe', 'Ŕ' => 'r', 'ŕ' => 'r', 'Ŗ' => 'r', 'ŗ' => 'r', 'Ř' => 'r', 'ř' => 'r', 'Ś' => 's', 'ś' => 's', 'Ŝ' => 's', 'ŝ' => 's', 'Ş' => 's', 'ş' => 's', 'Š' => 's', 'š' => 's', 'Ţ' => 't', 'ţ' => 't', 'Ť' => 't', 'ť' => 't', 'Ŧ' => 't', 'ŧ' => 't', 'Ũ' => 'u', 'ũ' => 'u', 'Ū' => 'u', 'ū' => 'u', 'Ŭ' => 'u', 'ŭ' => 'u', 'Ů' => 'u', 'ů' => 'u', 'Ű' => 'u', 'ű' => 'u', 'Ų' => 'u', 'ų' => 'u', 'Ŵ' => 'w', 'ŵ' => 'w', 'Ŷ' => 'y', 'ŷ' => 'y', 'Ÿ' => 'y', 'Ź' => 'z', 'ź' => 'z', 'Ż' => 'z', 'ż' => 'z', 'Ž' => 'z', 'ž' => 'z', 'ſ' => 'z', 'Ə' => 'e', 'ƒ' => 'f', 'Ơ' => 'o', 'ơ' => 'o', 'Ư' => 'u', 'ư' => 'u', 'Ǎ' => 'a', 'ǎ' => 'a', 'Ǐ' => 'i', 'ǐ' => 'i', 'Ǒ' => 'o', 'ǒ' => 'o', 'Ǔ' => 'u', 'ǔ' => 'u', 'Ǖ' => 'u', 'ǖ' => 'u', 'Ǘ' => 'u', 'ǘ' => 'u', 'Ǚ' => 'u', 'ǚ' => 'u', 'Ǜ' => 'u', 'ǜ' => 'u', 'Ǻ' => 'a', 'ǻ' => 'a', 'Ǽ' => 'ae', 'ǽ' => 'ae', 'Ǿ' => 'o', 'ǿ' => 'o', 'ə' => 'e', 'Ё' => 'jo', 'Є' => 'e', 'І' => 'i', 'Ї' => 'i', 'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'g', 'Д' => 'd', 'Е' => 'e', 'Ж' => 'zh', 'З' => 'z', 'И' => 'i', 'Й' => 'j', 'К' => 'k', 'Л' => 'l', 'М' => 'm', 'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r', 'С' => 's', 'Т' => 't', 'У' => 'u', 'Ф' => 'f', 'Х' => 'h', 'Ц' => 'c', 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'sch', 'Ъ' => '-', 'Ы' => 'y', 'Ь' => '-', 'Э' => 'je', 'Ю' => 'ju', 'Я' => 'ja', 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ъ' => '-', 'ы' => 'y', 'ь' => '-', 'э' => 'je', 'ю' => 'ju', 'я' => 'ja', 'ё' => 'jo', 'є' => 'e', 'і' => 'i', 'ї' => 'i', 'Ґ' => 'g', 'ґ' => 'g', 'א' => 'a', 'ב' => 'b', 'ג' => 'g', 'ד' => 'd', 'ה' => 'h', 'ו' => 'v', 'ז' => 'z', 'ח' => 'h', 'ט' => 't', 'י' => 'i', 'ך' => 'k', 'כ' => 'k', 'ל' => 'l', 'ם' => 'm', 'מ' => 'm', 'ן' => 'n', 'נ' => 'n', 'ס' => 's', 'ע' => 'e', 'ף' => 'p', 'פ' => 'p', 'ץ' => 'C', 'צ' => 'c', 'ק' => 'q', 'ר' => 'r', 'ש' => 'w', 'ת' => 't', '™' => 'tm', 'Α' => 'a', 'α' => 'a', 'Β' => 'v', 'β' => 'v', 'Γ' => 'g', 'γ' => 'g', 'Δ' => 'd', 'δ' => 'd', 'Ε' => 'e', 'ε' => 'e', 'Ζ' => 'z', 'ζ' => 'z', 'Η' => 'i', 'η' => 'i', 'Θ' => 'th', 'θ' => 'th', 'Ι' => 'i', 'ι' => 'i', 'Κ' => 'k', 'κ' => 'k', 'Λ' => 'l', 'λ' => 'l', 'Μ' => 'm', 'μ' => 'm', 'Ν' => 'n', 'ν' => 'n', 'Ξ' => 'ks', 'ξ' => 'ks', 'Ο' => 'o', 'ο' => 'o', 'Π' => 'p', 'π' => 'p', 'Ρ' => 'r', 'ρ' => 'r', 'Σ' => 's', 'σ' => 's', 'ς' => 's', 'Τ' => 't', 'τ' => 't', 'Υ' => 'u', 'υ' => 'u', 'Φ' => 'ph', 'φ' => 'ph', 'Χ' => 'x', 'χ' => 'x', 'Ψ' => 'ps', 'ψ' => 'ps', 'Ω' => 'o', 'ω' => 'o', 'Ά' => 'a', 'ά' => 'a', 'Έ' => 'e', 'έ' => 'e', 'Ή' => 'i', 'ή' => 'i', 'Ί' => 'i', 'ί' => 'i', 'Ό' => 'o', 'ό' => 'o', 'Ώ' => 'o', 'ώ' => 'o', 'Ύ' => 'u', 'ύ' => 'u', ];
if ($txt == '') {
$txt = $titulo;
}
$temp = strtr($txt, $_convertTable);
$urlKey = preg_replace('#[^0-9a-z]+#i', '-', $temp);
$urlKey = strtolower($urlKey);
$urlKey = trim($urlKey, '-');
return $urlKey;
}
// Recibimos los parámetros que debemos aplicar para definir los filtros Javascript de las categorías
public static function createCategoryFilters($params)
{
/*
* Estructura
* key => array(valor predeterminado, is_string)
*/
$filters = [
'categoryId' => ['', true],
'entityId' => [0, false],
'categoryOffset' => [ViewService::MAX_CATEGORY_PRODUCTS],
'categoryLimit' => [ViewService::MAX_CATEGORY_PRODUCTS],
'categoryMaxPrice' => [0, false],
'categoryMaxStock' => [0, false],
'categoryMinStock' => [0, false],
'catLink' => ['', true],
'filterMobile' => [0, false],
'sliderFilterInit' => [0, false],
'sliderFilterEnd' => [0, false],
'sliderFilterStockInit' => [0, false],
'sliderFilterStockEnd' => [0, false],
'urlListProducts' => ['', true],
];
$jsCode = '';
foreach ($filters as $key => $value) {
$valorFinal = (empty($params[$key])) ? $value[0] : $params[$key];
if (!isset($value[1]) || $value[1] == true) {
$jsCode .= 'var '.$key."='".$valorFinal."';";
} else {
$jsCode .= 'var '.$key.'='.$valorFinal.';';
}
}
return $jsCode;
}
/*
* ELIMINAMOS LOS FILTROS PARA MOVIL
*/
public static function remove_filters()
{
Session::delete('filters');
}
public static function convertDateToEpoch($date)
{
$tmp = explode(' ', $date);
$dateArray = explode('-', $tmp[0]);
$hourArray = explode(':', $tmp[1]);
if (empty($dateArray[1]) || empty($hourArray[2]) || empty($hourArray[1]) || empty($hourArray[2])) {
return 0;
}
$epoch = mktime($hourArray[0], $hourArray[1], $hourArray[2], $dateArray[1], $dateArray[2], $dateArray[0]);
return $epoch;
}
public static function addShowRecentProduct($id_product)
{
$maxNumProductsViews = Configuration::get('MAX_NUM_PRODUCTS_VIEWS', true);
$recentProductList = Session::get('view_recent_products');
if (!$recentProductList) {
$recentProductList = [];
$recentProductList[$id_product] = date('Y-m-d H:i:s');
Session::set('view_recent_products', $recentProductList);
return;
}
$recentProductList[$id_product] = date('Y-m-d H:i:s');
if (count($recentProductList) > $maxNumProductsViews) {
arsort($recentProductList);
array_pop($recentProductList);
}
Session::set('view_recent_products', $recentProductList);
}
/**
* Comprobamos si el usuario tiene precio de coste para los productos
*
* @param $idCustomer Identificador del cliente
*
* @return bool|mixed Retornamos el porcentaje de descuento al precio de coste o false
*/
public static function getCustomerCostPrice($customerId)
{
//TODO no borrar esta función. Aunque Nine tenga un 0% debemos aplicar ese porcentaje al precio
$customerCostList = Tools::jsonDecode(Configuration::get('CUSTOMER_COST_PRICE', true), true);
if (!$customerCostList) {
return null;
}
if (!isset($customerCostList[$customerId])) {
return null;
}
return $customerCostList[$customerId];
}
/**
* Añadimos la cookie de la secure Key del carriro
*/
public static function processCookieSecureKey()
{
if (empty($_COOKIE['secure_key'])) {
$secureKey = uniqid(rand(0, 9).rand(0, 9).rand(0, 9), true);
setcookie('secure_key', $secureKey, time() + (60 * 60 * 24 * 7), '/');
Session::set('secure_key', $secureKey);
}
}
/**
* @deprecated migrated to App\Service\FiscalPositionService
*
* Comprobamos si se produce una excepción para determinados paises de la UE
*/
public static function reviewExceptions(string $isoCode, string $postCode): bool
{
return self::getSfService(\App\Service\FiscalPositionService::class)->reviewExceptions($isoCode, $postCode);
}
public static function getCustomerName($idCustomer)
{
$customer = new Account($idCustomer);
if (!$customer->getId()) {
return '';
}
return $customer->getName().' '.$customer->getSurnames();
}
public static function getLinkAcademy($type)
{
switch ($type) {
case 'invoice':
$text = Tools::getLinkAcademyInvoice();
break;
case 'lock_refuse':
$text = Tools::getLinkLockRefuse();
break;
default:
$text = '';
break;
}
return $text;
}
public static function getLinkAcademyInvoice()
{
switch (Session::get('lang')) {
case 'es':
$link = 'http://www.bigbuy.eu/academy/es/crear-una-factura-exportaciones-la-union-europea/';
break;
case 'fr':
$link = 'http://www.bigbuy.eu/academy/fr/comment-creer-facture-exportations-dehors-lunion-europeenne/';
break;
case 'de':
$link = 'http://www.bigbuy.eu/academy/de/so-erstellen-rechnung-exporte-ausserhalb-europaeischen-union/';
break;
case 'it':
$link = 'http://www.bigbuy.eu/academy/it/come-emettere-fattura-esportazioni-fuori-unione-europea/';
break;
default:
$link = 'http://www.bigbuy.eu/academy/en/how-create-invoice-exports-outside-european-union/';
break;
}
return $link;
}
public static function getLinkLockRefuse()
{
switch (Session::get('lang')) {
case 'es':
$link = 'http://www.bigbuy.eu/academy/es/bloqueo-stock-bigbuy-como-funciona/';
break;
case 'fr':
$link = 'http://www.bigbuy.eu/academy/fr/blocage-stock-ce-cest-et-comment-cela-fonctionne/';
break;
case 'de':
$link = 'http://www.bigbuy.eu/academy/de/lagerbestandssperre-was-ist-und-wie-funktioniert/';
break;
case 'it':
$link = 'http://www.bigbuy.eu/academy/it/bloccaggio-dello-stock-bigbuy-cose-e-come-funziona/';
break;
default:
$link = 'http://www.bigbuy.eu/academy/en/stock-blocking-what-it-is-and-how-it-works/';
break;
}
return $link;
}
/**
* @param $timestamp
* @param $supplierId
*
* @return int
*/
public static function getClosestNonHolidayTimestampInFuture($timestamp, $supplierId, $additionalDaysToSkip = 0): int
{
$dateTimeHelper = new DatetimeHelper();
$dateTime = $dateTimeHelper->getDatetimeFromTimestamp($timestamp);
$weekendDays = [DatetimeHelper::SATURDAY, DatetimeHelper::SUNDAY];
$dateHolidays = Tools::jsonDecode(Configuration::get('HOLIDAYS', true), true);
if ($supplierId) {
/** @var SupplierHolidaysManager $supplierHolidayManager */
$supplierHolidayManager = Tools::getSfService(SupplierHolidaysManager::class);
$supplierHoliday = $supplierHolidayManager->findOneById((int)$supplierId);
$dateSupplierHolidays = ($supplierHoliday) ? json_decode($supplierHoliday->getHolidays(), true) : [];
}
while (true) {
$isHoliday = isset($dateHolidays[$dateTime->format('Y-m-d')]);
$isWeekend = in_array($dateTime->format('w'), $weekendDays);
if ($supplierId) {
$isHolidaySuplier = in_array($dateTime->format('Y-m-d'), $dateSupplierHolidays);
if (!$isHoliday && !$isWeekend && !$isHolidaySuplier) {
if ($additionalDaysToSkip === 0) {
return $dateTime->getTimestamp();
} else {
$additionalDaysToSkip--;
}
}
} else {
if (!$isHoliday && !$isWeekend) {
if ($additionalDaysToSkip === 0) {
return $dateTime->getTimestamp();
} else {
$additionalDaysToSkip--;
}
}
}
$dateTime->modify('+1 day');
}
}
public static function removeTimeToStrtotime($date, $time, $period)
{
$newDate = strtotime('-'.$time.' '.$period, $date);
return $newDate;
}
/**
* @return int
*
* @throws Exception
*
* @var
*/
public static function getExpeditionTimestampByDefault($supplierId): int
{
$availableStockExpeditionConfig = self::jsonDecode(Configuration::get('EXPEDITION_DEFAULT_DATA', true), true);
$cutTimeString = $availableStockExpeditionConfig['expedition_message_time'];
return self::calculateExpeditionTimestamp($cutTimeString, $supplierId, 0, 0, false);
}
/**
* @param int $idSupplier
* @param int|null $timestampToCompare
*
* @return int
*
* @throws Exception
*/
public static function getExpeditionTimestampBySupplier(int $idSupplier, ?int $timestampToCompare, bool $stock_3_5): int
{
$supplierExpeditionConfig = plazo_aprovisionamiento_proveedor::getExpeditionInformation($idSupplier);
$cutTimeString = $supplierExpeditionConfig['expedition_message_time'];
$expeditionAdditionalDaysDelay = (int)$supplierExpeditionConfig['expedition_days'];
if ($stock_3_5) {
$expeditionAdditionalDaysDelay = (int)$supplierExpeditionConfig['expedition_days_3_5'];
}
return self::calculateExpeditionTimestamp($cutTimeString, $idSupplier, $expeditionAdditionalDaysDelay, $timestampToCompare, true);
}
/**
* @param array $product
*
* @return int
*
* @throws Exception
*/
public static function getExpeditionTimestampForFutureStock(array $product): int
{
$daysUntilStockWillBeHere = \stock_venideros::calculateDaysTransit($product['id_product'], $product['id_product_attribute']);
if (!$daysUntilStockWillBeHere) {
$daysUntilStockWillBeHere = (int)self::jsonDecode(Configuration::get('STOCK_VENIDERO_DIAS_CORTESIA'), true);
}
$transitDaysData = self::calculateDaysTransit($daysUntilStockWillBeHere, $product['id_product']);
$datetimeHelper = new DatetimeHelper();
$tmpExpeditionTimestamp = $datetimeHelper->getCurrentTimestamp();
// Add
$tmpExpeditionTimestamp += $transitDaysData['days'] * DatetimeHelper::SECONDS_A_DAY;
return self::getClosestNonHolidayTimestampInFuture($tmpExpeditionTimestamp, null);
}
/**
* @param string $cutTimeString
* @param int $supplierId
* @param int $supplierAdditionalDaysDelay
* @param int|null $timestampToCompare
*
* @return int
*
* @throws Exception Calculates expedition timestamp taking into account:
* 1. Customer specific delays (Ex: Workhuman 3 hour delay)
* 2. Whether cut time has passed or not
* 3. Supplier specific delays
* 4. Skip holidays and weekends
*
* Accepts a $timestampToCompare argument that will be returned if its greater than the value calculated by the function
*/
private static function calculateExpeditionTimestamp(
string $cutTimeString,
int $supplierId,
int $supplierAdditionalDaysDelay,
?int $timestampToCompare,
bool $includeSupplierHolidays
): int {
$datetimeHelper = new DatetimeHelper();
$currentTimestamp = $datetimeHelper->getCurrentTimestamp();
// Init to current timestamp
$tmpExpeditionTimestamp = $currentTimestamp;
// If customer specific delay exists, add to the timestamp (Ex: 3 hours for Workhuman)
/** @var CustomerExpeditionTimeService */
$customerExpeditionTimeService = self::getSfService(CustomerExpeditionTimeService::class);
$customerExpeditionDelayInHours = $customerExpeditionTimeService->getCustomCustomerExpeditionTimeDelayInHours(Session::get('id_customer'));
if ($customerExpeditionDelayInHours > 0) {
$tmpExpeditionTimestamp = $tmpExpeditionTimestamp + ($customerExpeditionDelayInHours * DatetimeHelper::SECONDS_AN_HOUR);
}
// If the temporary expedition timestamp exceeds the cut time, add a day
if (self::timestampExceedsCutTime($tmpExpeditionTimestamp, $cutTimeString)) {
$tmpExpeditionTimestamp = $tmpExpeditionTimestamp + DatetimeHelper::SECONDS_A_DAY;
}
// if $tmpExpeditionTimestamp is not a working day, get closest one
$closestNonHolidayTimestampInFuture = Tools::getClosestNonHolidayTimestampInFuture($tmpExpeditionTimestamp, $includeSupplierHolidays ? $supplierId : null, 0);
// Add as many more days as 'expedition_days' value and get closest working day again
if ($supplierAdditionalDaysDelay > 0) {
$closestNonHolidayTimestampInFuture = Tools::getClosestNonHolidayTimestampInFuture($tmpExpeditionTimestamp, $includeSupplierHolidays ? $supplierId : null, $supplierAdditionalDaysDelay);
}
if ($timestampToCompare > $closestNonHolidayTimestampInFuture) {
return $timestampToCompare;
}
return $closestNonHolidayTimestampInFuture;
}
public static function replaceByAbsoluteURL($matches)
{
if (array_key_exists(1, $matches) && array_key_exists(2, $matches)) {
if (!preg_match('/^(?:https?:)?\/\//iUs', $matches[2])) {
return $matches[1].BASE_URL.'public/css/'.$matches[2];
}
return $matches[0];
}
return false;
}
/**
* @param int $tmpExpeditionTimestamp
* @param string $cutTimeString
*
* @return bool
*/
private static function timestampExceedsCutTime(int $tmpExpeditionTimestamp, string $cutTimeString): bool
{
$datetimeHelper = new DatetimeHelper();
$tmpDatetime = $datetimeHelper->getDatetimeFromTimestamp($tmpExpeditionTimestamp);
$cutTimeComponents = explode(':', $cutTimeString);
$cutTimeHours = (int)trim($cutTimeComponents[0]);
$cutTimeMinutes = (int)trim($cutTimeComponents[1]);
$cutTimeSeconds = (int)trim($cutTimeComponents[2]);
$cutDatetime = $datetimeHelper->getCurrentDateTime()->setTime($cutTimeHours, $cutTimeMinutes, $cutTimeSeconds);
return $tmpDatetime > $cutDatetime;
}
/**
* Recuperamos los indentificadores de las tiendas disponibles para contratar
*
* @return array Listado de tiendas de servicios
*/
public static function getProductsShopsList()
{
$shops360 = Tools::jsonDecode(Configuration::get('SHOP_360_LIST', true), true);
$shopsShopify = Tools::jsonDecode(Configuration::get('SHOPIFY_360_LIST', true), true);
return array_merge($shops360, $shopsShopify);
}
/**
* Retorna la lista de identificadores de los conectores
*
* @return array Listado de identificadores conectores
*/
public static function getProductsConectorsList()
{
$serviceIds = [];
$availableServices = \App\Entity\System\ServiceProduct::MIP_ADDITIONAL_SERVICE_DATA_INDEXED_BY_NAME;
foreach ($availableServices as $availableService) {
$serviceIds[] = $availableService['id'];
}
return $serviceIds;
}
/**
* Retornamos un array con la lista de todos los productos tienda disponibles
*
* @return array Listado de productos tienda
*/
public static function getProductShopListArray()
{
$shopifyList = Tools::jsonDecode(Configuration::get('SHOPIFY_360_LIST'), true);
$prestashopList = explode(',', Configuration::get('ID_SHOPS'));
return array_merge($shopifyList, $prestashopList);
}
public static function getPayPalSpecificError($idPayPalError, ?bool $urlPassVirtual)
{
$url = Link::getFrontLink('cart/checkout');
if ($urlPassVirtual) {
$url = Link::getFrontLink('subscription/checkout');
}
$defaultMessage = sprintf(
self::l('Ha habido un fallo en la transacción. Inténtelo de nuevo haciendo clic %saquí%s o bien elija un método de pago alternativo.', 'Tools'),
'<a href="'.$url.'" class="link color-blue">',
'</a>'
).'<br><br>'.
self::l('Si el fallo persiste, no dude en contactarnos para que podamos ayudarle.', 'Tools');
$messageErrorTmp = [
'10417' => self::l('Ha habido un fallo de pago. A continuación, le indicamos posibles soluciones, revíselas:', 'Tools').
'<ul class="orderMsg-text">'.
'<li>'.self::l('Si tiene asociada una tarjeta de crédito a PayPal como fuente de financiación, revise si ha caducado. Si es el caso, renuévela.', 'Tools').'</li>'.
'<li>'.self::l('El cargo que intenta realizar con PayPal es posible que supere el límite de su tarjeta de crédito. Si es así, amplíe ese límite.', 'Tools').'</li>'.
'<li>'.self::l('Si está realizando la compra de un pack más servicios adicionales, intente realizar la compra en 2 pasos. Primero active el pack y una vez tenga el pack activo vuelva a comprar los servicios adicionales.', 'Tools').'</li>'.
'<li>'.self::l('Para evitar problemas con su tarjeta de crédito, puede asociar una cuenta bancaria como fuente de financiación de PayPal.', 'Tools').'</li>'.
'<li>'.sprintf(self::l('Si tiene problemas con su tarjeta de crédito o para asociar un nuevo método de pago, contacte con PayPal aquí.', 'Tools'), '<a href="http://www.paypal.com/contactus" target="_blank" class="link color-blue">', '</a>').'</li>'.
'<li>'.self::l('Si no ha conseguido solucionar los problemas con su cuenta de PayPal, puede utilizar un método de pago alternativo. Vuelva a hacer la compra.', 'Tools').'</li>'.
'<li>'.self::l('Si con estas indicaciones sigue teniendo problemas para realizar el pago, no dude en contactarnos para que podamos ayudarle.', 'Tools').'</li>'.
'</ul>',
'10474' => self::l('El método de pago PayPal no está disponible en el país de envío. Elija un método de pago alternativo para finalizar la compra.', 'Tools'),
'10486' => self::l('Ha habido un fallo de pago. A continuación, le indicamos posibles soluciones, revíselas:', 'Tools').
'<ul class="orderMsg-text">'.
'<li>'.self::l('Si tiene asociada una tarjeta de crédito a PayPal como fuente de financiación, revise si ha caducado. Si es el caso, renuévela.', 'Tools').'</li>'.
'<li>'.self::l('El cargo que intenta realizar con PayPal es posible que supere el límite de su tarjeta de crédito. Si es así, amplíe ese límite.', 'Tools').'</li>'.
'<li>'.self::l('Si está realizando la compra de un pack más servicios adicionales, intente realizar la compra en 2 pasos. Primero active el pack y una vez tenga el pack activo vuelva a comprar los servicios adicionales.', 'Tools').'</li>'.
'<li>'.self::l('Para evitar problemas con su tarjeta de crédito, puede asociar una cuenta bancaria como fuente de financiación de PayPal.', 'Tools').'</li>'.
'<li>'.sprintf(self::l('Si tiene problemas con su tarjeta de crédito o para asociar un nuevo método de pago, contacte con PayPal aquí.', 'Tools'), '<a href="http://www.paypal.com/contactus" target="_blank" class="link color-blue">', '</a>').'</li>'.
'<li>'.self::l('Si no ha conseguido solucionar los problemas con su cuenta de PayPal, puede utilizar un método de pago alternativo. Vuelva a hacer la compra.', 'Tools').'</li>'.
'<li>'.self::l('Si con estas indicaciones sigue teniendo problemas para realizar el pago, no dude en contactarnos para que podamos ayudarle.', 'Tools').'</li>'.
'</ul>',
'10411' => self::l('La sesión ha expirado. Haga de nuevo la compra haciendo clic aquí.', 'Tools'),
];
$msgIdPayPalError = '<p class="orderMsg-text"><strong>Id PayPal error: </strong>'.$idPayPalError.'</p>';
if (empty($messageErrorTmp[$idPayPalError])) {
return $defaultMessage.$msgIdPayPalError;
}
return $messageErrorTmp[$idPayPalError].$msgIdPayPalError;
}
public static function getPackName($packName, $subscriptionName = '')
{
if ($packName == $subscriptionName) {
return $subscriptionName;
}
return $packName.' '.$subscriptionName;
}
public static function getDateExpeditionTime($productList)
{
$dateTmp = 0;
foreach ($productList as $product) {
$dateExpeditionTmp = Tools::getExpeditionTimestampBySupplier($product['id_supplier'], $dateTmp, (int)$product['quantity_stock_supplier_3_5'] === 1);
if ($dateExpeditionTmp > $dateTmp) {
$dateTmp = $dateExpeditionTmp;
}
}
return $dateTmp;
}
public static function getGenericServerError($errorCode)
{
return sprintf(
self::l('Ha habido una incidencia y no ha podido completarse su pedido. Vaya a la sección %sContacto > Soporte técnico%s, seleccione Web BigBuy e indíquenos el código de la incidencia %s para poder ayudarle.', 'subscriptionController'),
'<a href="'.Link::getFrontLink('contact#tabpanel3').'" class="link color-blue">',
'</a>',
$errorCode
);
}
/**
* Clean Url of <script> tags
* This method use HTMLPurifier lib from composer
*
* @param string $url
*/
public static function htmlPurifier($url): string
{
$config = HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null);
$purifier = new HTMLPurifier($config);
$newParam = $purifier->purify($url); // this convert
$searchParams = ['<script>', '</script>'];
$replaceParams = '';
$newParam = str_ireplace($searchParams, $replaceParams, $newParam);
$newParam = trim($newParam);
return $newParam;
}
public static function getPriceToCheckout($productId)
{
$product = new Product($productId);
return (int)$product->getWholesale_price();
}
/**
* @param $resOrderSync
*
* @return string|string[]
*/
public static function formatResOrderSync($resOrderSync)
{
/**
* TODO Aparece el caracter ZWNBSP y rompe la codificación
* Al pasarle esa cadena a pack() da error
* Warning: pack(): Type H: illegal hex digit Z
*/
// Remove BOM special chars
$bom = pack('H*', 'EFBBBF');
$resOrderSync = preg_replace("/^$bom/", '', $resOrderSync);
// $resOrderSync = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $resOrderSync);
$resOrderSync = str_replace('<\\/', '</', $resOrderSync);
return $resOrderSync;
}
public static function getResultsElasticSearch($lang, $init, $limit, $ajax, $filters, $isWholeSaler, $searchText = null)
{
$customerId = Session::get('id_customer');
$filters['catalogs'] = Session::get(SessionService::ALLOWED_CATALOGS_KEY);
if (empty($customerId)) {
$customerId = null;
}
if (isset($filters['rangeStock']) && is_array($filters['rangeStock'])) {
$minStock = $filters['rangeStock'][0] ?? 0;
if (!\is_numeric($minStock)) {
$minStock = 0;
}
$maxStock = $filters['rangeStock'][1] ?? $minStock + 1000;
if (!\is_numeric($maxStock)) {
$maxStock = $minStock + 1000;
}
$filters['minStock'] = $minStock;
$filters['maxStock'] = $maxStock;
}
if (isset($filters['category']) && is_array($filters['category'])) {
$filters['taxonomy'] = [];
foreach ($filters['category'] as $categoryId) {
$filters['taxonomy'][] = $categoryId;
}
unset($filters['category']);
}
// TODO comprobar si esta definida la sesion
if (empty(Session::get('list_products_rand_seed'))) {
$randSeed = rand(1, MAX_RANDOM_SEED);
Session::set('list_products_rand_seed', $randSeed);
}
$randOrderingSeed = null;
if (isset($filters['order'])) {
if ((\is_array($filters['order']) && (int)$filters['order'][0] === 6)
|| (int)$filters['order'] === 6) {
if (!isset($filters['randOrderingSeed'])) {
// If user selected "Selección BigBuy" we use a fixed seed so pagination won't repeat results
$randOrderingSeed = Session::get('list_products_rand_seed');
} else {
// True randomness
$randOrderingSeed = $filters['randOrderingSeed'];
}
}
}
$factory = self::getSfService(\App\Factory\Search\FindProductsRequestFactory::class);
$findProductsRequest = $factory->buildFromWebProductListsCriteria(
$customerId,
$lang,
$init,
$limit,
$ajax,
$filters,
(bool)$isWholeSaler,
self::getRealIP(),
$searchText,
$randOrderingSeed
);
$productRepositoryAdapter = self::getSfService(ProductRepositoryAdapter::class);
return $productRepositoryAdapter->search($findProductsRequest);
}
/**
* @template T
*
* @param class-string<T> $serviceFqn
*
* @return T
*/
public static function getSfService(string $serviceFqn)
{
/** @var ContainerInterface $container */
$container = $GLOBALS['kernel']->getContainer();
return $container->get($serviceFqn);
}
public static function getSfParameter(string $parameterName)
{
/** @var ContainerInterface $container */
$container = $GLOBALS['kernel']->getContainer();
return $container->getParameter($parameterName);
}
/**
* @param $supplierId
*
* @return string
*
* @throws Exception
*/
public static function getExpeditionDateTextForAvailableStock($supplierId): string
{
$expeditionTimestamp = self::getExpeditionTimestampByDefault($supplierId);
/** @var \App\Application\Service\Helper\ShippingDateService $shippingDateService */
$shippingDateService = self::getSfService(ShippingDateService::class);
return $shippingDateService->getBuyItNowAndWeSendItOnDateText($expeditionTimestamp);
}
/**
* @param $idSupplier
*
* @return string
*
* @throws Exception
*/
public static function getExpeditionDateTextForSupplierStock($idSupplier, $dateToCompare, $stockSupplier_3_5): string
{
$expeditionTimestamp = self::getExpeditionTimestampBySupplier($idSupplier, $dateToCompare, $stockSupplier_3_5);
$shippingDateService = self::getSfService(ShippingDateService::class);
return $shippingDateService->getBuyItNowAndWeSendItOnDateText($expeditionTimestamp);
}
/**
* @param string $data
*
* @return string|null
*/
public static function cleanNonPrintableCharacters(string $data): ?string
{
return preg_replace('/[[:^print:]]/', '', $data);
}
/**
* @deprecated use Symfony translator instead
*/
public static function trans(string $key, ?array $parameters = [], ?string $domain = 'messages'): ?string
{
return Tools::getSfService('translator')->trans($key, $parameters, $domain);
}
public static function getDaysBetweenTwoDates(?string $initialDateString, string $finalDateString): int
{
$initialDate = date($initialDateString);
$finalDate = date($finalDateString);
$initialSeconds = strtotime($initialDate);
$finalSeconds = strtotime($finalDate);
return ($finalSeconds - $initialSeconds) / self::SECONDS_BY_DAY;
}
public static function displayIban(string $iban)
{
return self::substr($iban, 0, 4).' ****** '.self::substr($iban, -4, 4);
}
}