bb-legacy/app/Tools.php line 1568

Open in your IDE?
  1.         if ($output == false) {
  2.             $output curl_error($ch);
  3.         }
  4.         // DEVOLVEMOS EL CODIGO HTTP (404, 500, 200...)
  5.         if ($return_http_code) {
  6.             $output curl_getinfo($chCURLINFO_HTTP_CODE);
  7.         }
  8.         curl_close($ch);
  9.         return $output;
  10.     }
  11.     /**
  12.      * Truncate strings
  13.      *
  14.      * @param string $str
  15.      * @param int $max_length Max length
  16.      * @param string $suffix Suffix optional
  17.      *
  18.      * @return string $str truncated
  19.      */
  20.     /* CAUTION : Use it only on module hookEvents.
  21.      * * For other purposes use the smarty function instead */
  22.     public static function truncate($str$max_length$suffix '...')
  23.     {
  24.         if (Tools::strlen($str) <= $max_length) {
  25.             return $str;
  26.         }
  27.         $str utf8_decode($str);
  28.         return utf8_encode(substr($str0$max_length Tools::strlen($suffix)).$suffix);
  29.     }
  30.     public static function isMobile()
  31.     {// return true;
  32.         if (defined('IS_MOBILE')) {
  33.             return IS_MOBILE;
  34.         }
  35.         return false;
  36.     }
  37.     public static function calculateDaysTransit($days$productId null$extern false)
  38.     {
  39.         $syncronisedException = ($extern) ? Product::isSincronisedSendException($productId) : false;
  40.         if ($days <= 2) {
  41.             return [
  42.                 'days' => 1,
  43.                 'text_product' => self::l('%s uds.''Tools'),
  44.                 'text_cart' => (!$syncronisedException) ? self::l('Envío inmediato''Tools') : self::l('24/48h''Tools'),
  45.             ];
  46.         }
  47.         $tmpDays = (int)ceil($days 5);
  48.         switch ($tmpDays) {
  49.             case 0:
  50.             case 1:
  51.                 $days_range '2/5';
  52.                 $tmpDays 1;
  53.                 break;
  54.             case 2:
  55.                 $days_range '5/10';
  56.                 break;
  57.             case 3:
  58.                 $days_range '10/15';
  59.                 break;
  60.             case 4:
  61.                 $days_range '15/20';
  62.                 break;
  63.             default:
  64.                 $days_range '20/30';
  65.         }
  66.         return [
  67.             'days' => $tmpDays 5,
  68.             'text_product' => sprintf(self::l('%s uds. envío %s días''Tools'), '%s'$days_range),
  69.             'text_cart' => sprintf(self::l('%s días''Tools'), $days_range),
  70.         ];
  71.     }
  72.     public static function divideString($name$separador '<br />'$num_lines 2)
  73.     {
  74.         $blank_spaces ceil(substr_count($name' ') / $num_lines);
  75.         $nameEnd '';
  76.         $count_spaces 0;
  77.         $nameTmp str_split($name);
  78.         $br false;
  79.         foreach ($nameTmp as $c) {
  80.             if ($c == ' ') {
  81.                 $count_spaces++;
  82.             }
  83.             if ($count_spaces == $blank_spaces && $blank_spaces && !$br) {
  84.                 $nameEnd .= $separador;
  85.                 $br true;
  86.             } else {
  87.                 $nameEnd .= $c;
  88.             }
  89.         }
  90.         return $nameEnd;
  91.     }
  92.     /**
  93.      * Añadimos la cookie de la secure Key del carriro
  94.      */
  95.     public static function processCookieSecureKey()
  96.     {
  97.         if (empty($_COOKIE['secure_key'])) {
  98.             $secureKey uniqid(rand(09).rand(09).rand(09), true);
  99.             setcookie('secure_key'$secureKeytime() + (60 60 24 7), '/');
  100.             Session::set('secure_key'$secureKey);
  101.         }
  102.     }
  103.     /**
  104.      * @param $timestamp
  105.      * @param $supplierId
  106.      *
  107.      * @return int
  108.      */
  109.     public static function getClosestNonHolidayTimestampInFuture($timestamp$supplierId$additionalDaysToSkip 0): int
  110.     {
  111.         $dateTimeHelper = new DatetimeHelper();
  112.         $dateTime $dateTimeHelper->getDatetimeFromTimestamp($timestamp);
  113.         $weekendDays = [DatetimeHelper::SATURDAYDatetimeHelper::SUNDAY];
  114.         $dateHolidays Tools::jsonDecode(Configuration::get('HOLIDAYS'true), true);
  115.         if ($supplierId) {
  116.             /** @var SupplierHolidaysManager $supplierHolidayManager */
  117.             $supplierHolidayManager Tools::getSfService(SupplierHolidaysManager::class);
  118.             $supplierHoliday $supplierHolidayManager->findOneById((int)$supplierId);
  119.             $dateSupplierHolidays = ($supplierHoliday) ? json_decode($supplierHoliday->getHolidays(), true) : [];
  120.         }
  121.         while (true) {
  122.             $isHoliday = isset($dateHolidays[$dateTime->format('Y-m-d')]);
  123.             $isWeekend in_array($dateTime->format('w'), $weekendDays);
  124.             if ($supplierId) {
  125.                 $isHolidaySuplier in_array($dateTime->format('Y-m-d'), $dateSupplierHolidays);
  126.                 if (!$isHoliday && !$isWeekend && !$isHolidaySuplier) {
  127.                     if ($additionalDaysToSkip === 0) {
  128.                         return $dateTime->getTimestamp();
  129.                     } else {
  130.                         $additionalDaysToSkip--;
  131.                     }
  132.                 }
  133.             } else {
  134.                 if (!$isHoliday && !$isWeekend) {
  135.                     if ($additionalDaysToSkip === 0) {
  136.                         return $dateTime->getTimestamp();
  137.                     } else {
  138.                         $additionalDaysToSkip--;
  139.                     }
  140.                 }
  141.             }
  142.             $dateTime->modify('+1 day');
  143.         }
  144.     }
  145.     /**
  146.      * @return int
  147.      *
  148.      * @throws Exception
  149.      *
  150.      * @var
  151.      */
  152.     public static function getExpeditionTimestampByDefault(?int $customerId$supplierId): int
  153.     {
  154.         return self::calculateExpeditionTimestamp($customerIdShippingDateService::DEFAULT_EXPEDITION_MESSAGE_TIME$supplierId00false);
  155.     }
  156.     /**
  157.      * @param int $idSupplier
  158.      * @param int|null $timestampToCompare
  159.      *
  160.      * @return int
  161.      *
  162.      * @throws Exception
  163.      */
  164.     public static function getExpeditionTimestampBySupplier(?int $customerIdint $idSupplier, ?int $timestampToComparebool $stock_3_5): int
  165.     {
  166.         $supplierExpeditionConfig plazo_aprovisionamiento_proveedor::getExpeditionInformation($idSupplier);
  167.         $cutTimeString $supplierExpeditionConfig['expedition_message_time'];
  168.         $expeditionAdditionalDaysDelay = (int)$supplierExpeditionConfig['expedition_days'];
  169.         if ($stock_3_5) {
  170.             $expeditionAdditionalDaysDelay = (int)$supplierExpeditionConfig['expedition_days_3_5'];
  171.         }
  172.         return self::calculateExpeditionTimestamp($customerId$cutTimeString$idSupplier$expeditionAdditionalDaysDelay$timestampToComparetrue);
  173.     }
  174.     /**
  175.      * @param array $product
  176.      *
  177.      * @return int
  178.      *
  179.      * @throws Exception
  180.      */
  181.     public static function getExpeditionTimestampForFutureStock(array $product): int
  182.     {
  183.         $daysUntilStockWillBeHere = \stock_venideros::calculateDaysTransit($product['id_product'], $product['id_product_attribute']);
  184.         if (!$daysUntilStockWillBeHere) {
  185.             $daysUntilStockWillBeHere = (int)self::jsonDecode(Configuration::get('STOCK_VENIDERO_DIAS_CORTESIA'), true);
  186.         }
  187.         $transitDaysData self::calculateDaysTransit($daysUntilStockWillBeHere$product['id_product']);
  188.         $datetimeHelper = new DatetimeHelper();
  189.         $tmpExpeditionTimestamp $datetimeHelper->getCurrentTimestamp();
  190.         // Add
  191.         $tmpExpeditionTimestamp += $transitDaysData['days'] * DatetimeHelper::SECONDS_A_DAY;
  192.         return self::getClosestNonHolidayTimestampInFuture($tmpExpeditionTimestampnull);
  193.     }
  194.     /**
  195.      * @param string $cutTimeString
  196.      * @param int $supplierId
  197.      * @param int $supplierAdditionalDaysDelay
  198.      * @param int|null $timestampToCompare
  199.      *
  200.      * @return int
  201.      *
  202.      * @throws Exception Calculates expedition timestamp taking into account:
  203.      *                   1. Customer specific delays (Ex: Workhuman 3 hour delay)
  204.      *                   2. Whether cut time has passed or not
  205.      *                   3. Supplier specific delays
  206.      *                   4. Skip holidays and weekends
  207.      *
  208.      * Accepts a $timestampToCompare argument that will be returned if its greater than the value calculated by the function
  209.      */
  210.     private static function calculateExpeditionTimestamp(
  211.         ?int $customerId,
  212.         string $cutTimeString,
  213.         int $supplierId,
  214.         int $supplierAdditionalDaysDelay,
  215.         ?int $timestampToCompare,
  216.         bool $includeSupplierHolidays
  217.     ): int {
  218.         $datetimeHelper = new DatetimeHelper();
  219.         $currentTimestamp $datetimeHelper->getCurrentTimestamp();
  220.         // Init to current timestamp
  221.         $tmpExpeditionTimestamp $currentTimestamp;
  222.         // Apply customer-defined delay
  223.         if (!empty($customerId)) {
  224.             $tmpExpeditionTimestamp self::addCustomerSpecificDelay($tmpExpeditionTimestamp$customerId);
  225.         }
  226.         // If the temporary expedition timestamp exceeds the cut time, add a day
  227.         if (self::timestampExceedsCutTime($tmpExpeditionTimestamp$cutTimeString)) {
  228.             $tmpExpeditionTimestamp $tmpExpeditionTimestamp DatetimeHelper::SECONDS_A_DAY;
  229.         }
  230.         // if $tmpExpeditionTimestamp is not a working day, get closest one
  231.         $closestNonHolidayTimestampInFuture Tools::getClosestNonHolidayTimestampInFuture($tmpExpeditionTimestamp$includeSupplierHolidays $supplierId null0);
  232.         // Add as many more days as 'expedition_days' value and get closest working day again
  233.         if ($supplierAdditionalDaysDelay 0) {
  234.             $closestNonHolidayTimestampInFuture Tools::getClosestNonHolidayTimestampInFuture($tmpExpeditionTimestamp$includeSupplierHolidays $supplierId null$supplierAdditionalDaysDelay);
  235.         }
  236.         if ($timestampToCompare $closestNonHolidayTimestampInFuture) {
  237.             return $timestampToCompare;
  238.         }
  239.         return $closestNonHolidayTimestampInFuture;
  240.     }
  241.     public static function replaceByAbsoluteURL($matches)
  242.     {
  243.         if (array_key_exists(1$matches) && array_key_exists(2$matches)) {
  244.             if (!preg_match('/^(?:https?:)?\/\//iUs'$matches[2])) {
  245.                 return $matches[1].BASE_URL.'public/css/'.$matches[2];
  246.             }
  247.             return $matches[0];
  248.         }
  249.         return false;
  250.     }
  251.     /**
  252.      * @param int $tmpExpeditionTimestamp
  253.      * @param string $cutTimeString
  254.      *
  255.      * @return bool
  256.      */
  257.     private static function timestampExceedsCutTime(int $tmpExpeditionTimestampstring $cutTimeString): bool
  258.     {
  259.         $datetimeHelper = new DatetimeHelper();
  260.         $tmpDatetime $datetimeHelper->getDatetimeFromTimestamp($tmpExpeditionTimestamp);
  261.         $cutTimeComponents explode(':'$cutTimeString);
  262.         $cutTimeHours = (int)trim($cutTimeComponents[0]);
  263.         $cutTimeMinutes = (int)trim($cutTimeComponents[1]);
  264.         $cutTimeSeconds = (int)trim($cutTimeComponents[2]);
  265.         $cutDatetime $datetimeHelper->getCurrentDateTime()->setTime($cutTimeHours$cutTimeMinutes$cutTimeSeconds);
  266.         return $tmpDatetime $cutDatetime;
  267.     }
  268.     /**
  269.      * Retornamos un array con la lista de todos los productos tienda disponibles
  270.      *
  271.      * @return array Listado de productos tienda
  272.      */
  273.     public static function getProductShopListArray()
  274.     {
  275.         $prestashopList explode(','Configuration::get('ID_SHOPS'));
  276.         return array_merge(\App\Entity\System\Product::SHOPIFY_PRODUCTS_IDS$prestashopList);
  277.     }
  278.     public static function getPackName($packName$subscriptionName '')
  279.     {
  280.         if ($packName == $subscriptionName) {
  281.             return $subscriptionName;
  282.         }
  283.         return $packName.' '.$subscriptionName;
  284.     }
  285.     public static function getGenericServerError($errorCode)
  286.     {
  287.         return sprintf(
  288.             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'),
  289.             '<a href="'.Link::getFrontLink('contact#tabpanel3').'" class="link color-blue">',
  290.             '</a>',
  291.             $errorCode
  292.         );
  293.     }
  294.     /**
  295.      * Clean Url of <script> tags
  296.      * This method use HTMLPurifier lib from composer
  297.      *
  298.      * @param string $url
  299.      */
  300.     public static function htmlPurifier($url): string
  301.     {
  302.         $config HTMLPurifier_Config::createDefault();
  303.         $config->set('Cache.DefinitionImpl'null);
  304.         $purifier = new HTMLPurifier($config);
  305.         $newParam $purifier->purify($url); // this convert
  306.         $searchParams = ['&lt;script&gt;''&lt;/script&gt;'];
  307.         $replaceParams '';
  308.         $newParam str_ireplace($searchParams$replaceParams$newParam);
  309.         $newParam trim($newParam);
  310.         return $newParam;
  311.     }
  312.     /**
  313.      * @template T
  314.      *
  315.      * @param class-string<T> $serviceFqn
  316.      *
  317.      * @return T
  318.      */
  319.     public static function getSfService(string $serviceFqn)
  320.     {
  321.         /** @var ContainerInterface $container */
  322.         $container $GLOBALS['kernel']->getContainer();
  323.         return $container->get($serviceFqn);
  324.     }
  325.     public static function getSfParameter(string $parameterName)
  326.     {
  327.         /** @var ContainerInterface $container */
  328.         $container $GLOBALS['kernel']->getContainer();
  329.         return $container->getParameter($parameterName);
  330.     }
  331.     /**
  332.      * @throws Exception
  333.      */
  334.     public static function getExpeditionDateTextForAvailableStock(?int $customerId$supplierId$languageId): string
  335.     {
  336.         $expeditionTimestamp self::getExpeditionTimestampByDefault($customerId$supplierId);
  337.         /** @var \App\Application\Service\Helper\ShippingDateService $shippingDateService */
  338.         $shippingDateService self::getSfService(ShippingDateService::class);
  339.         return $shippingDateService->getBuyItNowAndWeSendItOnDateText($expeditionTimestampfalse$languageId);
  340.     }
  341.     /**
  342.      * @throws Exception
  343.      */
  344.     public static function getExpeditionDateTextForSupplierStock($customerId$idSupplier$dateToCompare$stockSupplier_3_5$languageId): string
  345.     {
  346.         $expeditionTimestamp self::getExpeditionTimestampBySupplier($customerId$idSupplier$dateToCompare$stockSupplier_3_5);
  347.         $shippingDateService self::getSfService(ShippingDateService::class);
  348.         return $shippingDateService->getBuyItNowAndWeSendItOnDateText($expeditionTimestampfalse$languageId);
  349.     }
  350.     /**
  351.      * @param string $data
  352.      *
  353.      * @return string|null
  354.      */
  355.     public static function cleanNonPrintableCharacters(string $data): ?string
  356.     {
  357.         return preg_replace('/[[:^print:]]/'''$data);
  358.     }
  359.     /**
  360.      * @deprecated use Symfony translator instead
  361.      */
  362.     public static function trans(string $key, ?array $parameters = [], ?string $domain 'messages'): ?string
  363.     {
  364.         return Tools::getSfService('translator')->trans($key$parameters$domain);
  365.     }
  366.     public static function displayIban(string $iban)
  367.     {
  368.         return self::substr($iban04).' ****** '.self::substr($iban, -44);
  369.     }
  370.     /**
  371.      * @param int $tmpExpeditionTimestamp
  372.      * @param int $customerId
  373.      * @return float|int
  374.      */
  375.     protected static function addCustomerSpecificDelay(int $tmpExpeditionTimestampint $customerId): int
  376.     {
  377.         // If customer order confirmation delay exists, add to the timestamp
  378.         $customerManager self::getSfService(CustomerManager::class);
  379.         $customer $customerManager->findOneById($customerId);
  380.         if (!empty($customer->getOrderConfirmationDelay())) {
  381.             $tmpExpeditionTimestamp $tmpExpeditionTimestamp + ($customer->getOrderConfirmationDelay() * DatetimeHelper::SECONDS_AN_HOUR);
  382.         }
  383.         return $tmpExpeditionTimestamp;
  384.     }
  385. }