bb-legacy/app/Tools.php line 1568

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