*/
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
*
* @deprecated use displayNumber from ToolsService instead
*
* @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 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'];
}
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
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;
}
/**
* @deprecated use guzzle instead
*/
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 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 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 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 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;
}
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;
}
/**
* 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);
}
}
/**
* @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');
}
}
/**
* @return int
*
* @throws Exception
*
* @var
*/
public static function getExpeditionTimestampByDefault(?int $customerId, $supplierId): int
{
return self::calculateExpeditionTimestamp($customerId, ShippingDateService::DEFAULT_EXPEDITION_MESSAGE_TIME, $supplierId, 0, 0, false);
}
/**
* @param int $idSupplier
* @param int|null $timestampToCompare
*
* @return int
*
* @throws Exception
*/
public static function getExpeditionTimestampBySupplier(?int $customerId, 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($customerId, $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(
?int $customerId,
string $cutTimeString,
int $supplierId,
int $supplierAdditionalDaysDelay,
?int $timestampToCompare,
bool $includeSupplierHolidays
): int {
$datetimeHelper = new DatetimeHelper();
$currentTimestamp = $datetimeHelper->getCurrentTimestamp();
// Init to current timestamp
$tmpExpeditionTimestamp = $currentTimestamp;
// Apply customer-defined delay
if (!empty($customerId)) {
$tmpExpeditionTimestamp = self::addCustomerSpecificDelay($tmpExpeditionTimestamp, $customerId);
}
// 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;
}
/**
* Retornamos un array con la lista de todos los productos tienda disponibles
*
* @return array Listado de productos tienda
*/
public static function getProductShopListArray()
{
$prestashopList = explode(',', Configuration::get('ID_SHOPS'));
return array_merge(\App\Entity\System\Product::SHOPIFY_PRODUCTS_IDS, $prestashopList);
}
public static function getPackName($packName, $subscriptionName = '')
{
if ($packName == $subscriptionName) {
return $subscriptionName;
}
return $packName.' '.$subscriptionName;
}
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 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);
}
/**
* @throws Exception
*/
public static function getExpeditionDateTextForAvailableStock(?int $customerId, $supplierId, $languageId): string
{
$expeditionTimestamp = self::getExpeditionTimestampByDefault($customerId, $supplierId);
/** @var \App\Application\Service\Helper\ShippingDateService $shippingDateService */
$shippingDateService = self::getSfService(ShippingDateService::class);
return $shippingDateService->getBuyItNowAndWeSendItOnDateText($expeditionTimestamp, false, $languageId);
}
/**
* @throws Exception
*/
public static function getExpeditionDateTextForSupplierStock($customerId, $idSupplier, $dateToCompare, $stockSupplier_3_5, $languageId): string
{
$expeditionTimestamp = self::getExpeditionTimestampBySupplier($customerId, $idSupplier, $dateToCompare, $stockSupplier_3_5);
$shippingDateService = self::getSfService(ShippingDateService::class);
return $shippingDateService->getBuyItNowAndWeSendItOnDateText($expeditionTimestamp, false, $languageId);
}
/**
* @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 displayIban(string $iban)
{
return self::substr($iban, 0, 4).' ****** '.self::substr($iban, -4, 4);
}
/**
* @param int $tmpExpeditionTimestamp
* @param int $customerId
* @return float|int
*/
protected static function addCustomerSpecificDelay(int $tmpExpeditionTimestamp, int $customerId): int
{
// If customer order confirmation delay exists, add to the timestamp
$customerManager = self::getSfService(CustomerManager::class);
$customer = $customerManager->findOneById($customerId);
if (!empty($customer->getOrderConfirmationDelay())) {
$tmpExpeditionTimestamp = $tmpExpeditionTimestamp + ($customer->getOrderConfirmationDelay() * DatetimeHelper::SECONDS_AN_HOUR);
}
return $tmpExpeditionTimestamp;
}
}