PageRenderTime 39ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/classes/Tools.php

https://gitlab.com/mtellezgalindo/PrestaShop
PHP | 3335 lines | 2441 code | 313 blank | 581 comment | 461 complexity | 9c817d8a1bc923d233ad9f4b718dda70 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-3.0
  1. <?php
  2. /*
  3. * 2007-2014 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2014 PrestaShop SA
  23. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. class ToolsCore
  27. {
  28. protected static $file_exists_cache = array();
  29. protected static $_forceCompile;
  30. protected static $_caching;
  31. protected static $_user_plateform;
  32. protected static $_user_browser;
  33. public static $round_mode = null;
  34. /**
  35. * Random password generator
  36. *
  37. * @param integer $length Desired length (optional)
  38. * @param string $flag Output type (NUMERIC, ALPHANUMERIC, NO_NUMERIC)
  39. * @return string Password
  40. */
  41. public static function passwdGen($length = 8, $flag = 'ALPHANUMERIC')
  42. {
  43. switch ($flag)
  44. {
  45. case 'NUMERIC':
  46. $str = '0123456789';
  47. break;
  48. case 'NO_NUMERIC':
  49. $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  50. break;
  51. default:
  52. $str = 'abcdefghijkmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  53. break;
  54. }
  55. for ($i = 0, $passwd = ''; $i < $length; $i++)
  56. $passwd .= Tools::substr($str, mt_rand(0, Tools::strlen($str) - 1), 1);
  57. return $passwd;
  58. }
  59. public static function strReplaceFirst($search, $replace, $subject, $cur = 0)
  60. {
  61. return (strpos($subject, $search, $cur))?substr_replace($subject, $replace, (int)strpos($subject, $search, $cur), strlen($search)):$subject;
  62. }
  63. /**
  64. * Redirect user to another page
  65. *
  66. * @param string $url Desired URL
  67. * @param string $baseUri Base URI (optional)
  68. * @param Link $link
  69. * @param string|array $headers A list of headers to send before redirection
  70. */
  71. public static function redirect($url, $base_uri = __PS_BASE_URI__, Link $link = null, $headers = null)
  72. {
  73. if (!$link)
  74. $link = Context::getContext()->link;
  75. if (strpos($url, 'http://') === false && strpos($url, 'https://') === false && $link)
  76. {
  77. if (strpos($url, $base_uri) === 0)
  78. $url = substr($url, strlen($base_uri));
  79. if (strpos($url, 'index.php?controller=') !== false && strpos($url, 'index.php/') == 0)
  80. {
  81. $url = substr($url, strlen('index.php?controller='));
  82. if (Configuration::get('PS_REWRITING_SETTINGS'))
  83. $url = Tools::strReplaceFirst('&', '?', $url);
  84. }
  85. $explode = explode('?', $url);
  86. // don't use ssl if url is home page
  87. // used when logout for example
  88. $use_ssl = !empty($url);
  89. $url = $link->getPageLink($explode[0], $use_ssl);
  90. if (isset($explode[1]))
  91. $url .= '?'.$explode[1];
  92. }
  93. // Send additional headers
  94. if ($headers)
  95. {
  96. if (!is_array($headers))
  97. $headers = array($headers);
  98. foreach ($headers as $header)
  99. header($header);
  100. }
  101. header('Location: '.$url);
  102. exit;
  103. }
  104. /**
  105. * Redirect URLs already containing PS_BASE_URI
  106. *
  107. * @param string $url Desired URL
  108. */
  109. public static function redirectLink($url)
  110. {
  111. if (!preg_match('@^https?://@i', $url))
  112. {
  113. if (strpos($url, __PS_BASE_URI__) !== false && strpos($url, __PS_BASE_URI__) == 0)
  114. $url = substr($url, strlen(__PS_BASE_URI__));
  115. if (strpos($url, 'index.php?controller=') !== false && strpos($url, 'index.php/') == 0)
  116. $url = substr($url, strlen('index.php?controller='));
  117. $explode = explode('?', $url);
  118. $url = Context::getContext()->link->getPageLink($explode[0]);
  119. if (isset($explode[1]))
  120. $url .= '?'.$explode[1];
  121. }
  122. header('Location: '.$url);
  123. exit;
  124. }
  125. /**
  126. * Redirect user to another admin page
  127. *
  128. * @param string $url Desired URL
  129. */
  130. public static function redirectAdmin($url)
  131. {
  132. header('Location: '.$url);
  133. exit;
  134. }
  135. /**
  136. * getShopProtocol return the available protocol for the current shop in use
  137. * SSL if Configuration is set on and available for the server
  138. * @static
  139. * @return String
  140. */
  141. public static function getShopProtocol()
  142. {
  143. $protocol = (Configuration::get('PS_SSL_ENABLED') || (!empty($_SERVER['HTTPS'])
  144. && Tools::strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
  145. return $protocol;
  146. }
  147. /**
  148. * getProtocol return the set protocol according to configuration (http[s])
  149. * @param bool $use_ssl true if require ssl
  150. * @return String (http|https)
  151. */
  152. public static function getProtocol($use_ssl = null)
  153. {
  154. return (!is_null($use_ssl) && $use_ssl ? 'https://' : 'http://');
  155. }
  156. /**
  157. * getHttpHost return the <b>current</b> host used, with the protocol (http or https) if $http is true
  158. * This function should not be used to choose http or https domain name.
  159. * Use Tools::getShopDomain() or Tools::getShopDomainSsl instead
  160. *
  161. * @param boolean $http
  162. * @param boolean $entities
  163. * @return string host
  164. */
  165. public static function getHttpHost($http = false, $entities = false, $ignore_port = false)
  166. {
  167. $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST']);
  168. if ($ignore_port && $pos = strpos($host, ':'))
  169. $host = substr($host, 0, $pos);
  170. if ($entities)
  171. $host = htmlspecialchars($host, ENT_COMPAT, 'UTF-8');
  172. if ($http)
  173. $host = (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').$host;
  174. return $host;
  175. }
  176. /**
  177. * getShopDomain returns domain name according to configuration and ignoring ssl
  178. *
  179. * @param boolean $http if true, return domain name with protocol
  180. * @param boolean $entities if true,
  181. * @return string domain
  182. */
  183. public static function getShopDomain($http = false, $entities = false)
  184. {
  185. if (!$domain = ShopUrl::getMainShopDomain())
  186. $domain = Tools::getHttpHost();
  187. if ($entities)
  188. $domain = htmlspecialchars($domain, ENT_COMPAT, 'UTF-8');
  189. if ($http)
  190. $domain = 'http://'.$domain;
  191. return $domain;
  192. }
  193. /**
  194. * getShopDomainSsl returns domain name according to configuration and depending on ssl activation
  195. *
  196. * @param boolean $http if true, return domain name with protocol
  197. * @param boolean $entities if true,
  198. * @return string domain
  199. */
  200. public static function getShopDomainSsl($http = false, $entities = false)
  201. {
  202. if (!$domain = ShopUrl::getMainShopDomainSSL())
  203. $domain = Tools::getHttpHost();
  204. if ($entities)
  205. $domain = htmlspecialchars($domain, ENT_COMPAT, 'UTF-8');
  206. if ($http)
  207. $domain = (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').$domain;
  208. return $domain;
  209. }
  210. /**
  211. * Get the server variable SERVER_NAME
  212. *
  213. * @return string server name
  214. */
  215. public static function getServerName()
  216. {
  217. if (isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && $_SERVER['HTTP_X_FORWARDED_SERVER'])
  218. return $_SERVER['HTTP_X_FORWARDED_SERVER'];
  219. return $_SERVER['SERVER_NAME'];
  220. }
  221. /**
  222. * Get the server variable REMOTE_ADDR, or the first ip of HTTP_X_FORWARDED_FOR (when using proxy)
  223. *
  224. * @return string $remote_addr ip of client
  225. */
  226. public static function getRemoteAddr()
  227. {
  228. // This condition is necessary when using CDN, don't remove it.
  229. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && (!isset($_SERVER['REMOTE_ADDR'])
  230. || preg_match('/^127\..*/i', trim($_SERVER['REMOTE_ADDR'])) || preg_match('/^172\.16.*/i', trim($_SERVER['REMOTE_ADDR']))
  231. || preg_match('/^192\.168\.*/i', trim($_SERVER['REMOTE_ADDR'])) || preg_match('/^10\..*/i', trim($_SERVER['REMOTE_ADDR']))))
  232. {
  233. if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ','))
  234. {
  235. $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  236. return $ips[0];
  237. }
  238. else
  239. return $_SERVER['HTTP_X_FORWARDED_FOR'];
  240. }
  241. return $_SERVER['REMOTE_ADDR'];
  242. }
  243. /**
  244. * Check if the current page use SSL connection on not
  245. *
  246. * @return bool uses SSL
  247. */
  248. public static function usingSecureMode()
  249. {
  250. if (isset($_SERVER['HTTPS']))
  251. return in_array(Tools::strtolower($_SERVER['HTTPS']), array(1, 'on'));
  252. // $_SERVER['SSL'] exists only in some specific configuration
  253. if (isset($_SERVER['SSL']))
  254. return in_array(Tools::strtolower($_SERVER['SSL']), array(1, 'on'));
  255. // $_SERVER['REDIRECT_HTTPS'] exists only in some specific configuration
  256. if (isset($_SERVER['REDIRECT_HTTPS']))
  257. return in_array(Tools::strtolower($_SERVER['REDIRECT_HTTPS']), array(1, 'on'));
  258. if (isset($_SERVER['HTTP_SSL']))
  259. return in_array(Tools::strtolower($_SERVER['HTTP_SSL']), array(1, 'on'));
  260. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']))
  261. return Tools::strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https';
  262. return false;
  263. }
  264. /**
  265. * Get the current url prefix protocol (https/http)
  266. *
  267. * @return string protocol
  268. */
  269. public static function getCurrentUrlProtocolPrefix()
  270. {
  271. if (Tools::usingSecureMode())
  272. return 'https://';
  273. else
  274. return 'http://';
  275. }
  276. /**
  277. * Secure an URL referrer
  278. *
  279. * @param string $referrer URL referrer
  280. * @return string secured referrer
  281. */
  282. public static function secureReferrer($referrer)
  283. {
  284. if (preg_match('/^http[s]?:\/\/'.Tools::getServerName().'(:'._PS_SSL_PORT_.')?\/.*$/Ui', $referrer))
  285. return $referrer;
  286. return __PS_BASE_URI__;
  287. }
  288. /**
  289. * Get a value from $_POST / $_GET
  290. * if unavailable, take a default value
  291. *
  292. * @param string $key Value key
  293. * @param mixed $default_value (optional)
  294. * @return mixed Value
  295. */
  296. public static function getValue($key, $default_value = false)
  297. {
  298. if (!isset($key) || empty($key) || !is_string($key))
  299. return false;
  300. $ret = (isset($_POST[$key]) ? $_POST[$key] : (isset($_GET[$key]) ? $_GET[$key] : $default_value));
  301. if (is_string($ret))
  302. return stripslashes(urldecode(preg_replace('/((\%5C0+)|(\%00+))/i', '', urlencode($ret))));
  303. return $ret;
  304. }
  305. public static function getIsset($key)
  306. {
  307. if (!isset($key) || empty($key) || !is_string($key))
  308. return false;
  309. return isset($_POST[$key]) ? true : (isset($_GET[$key]) ? true : false);
  310. }
  311. /**
  312. * Change language in cookie while clicking on a flag
  313. *
  314. * @return string iso code
  315. */
  316. public static function setCookieLanguage($cookie = null)
  317. {
  318. if (!$cookie)
  319. $cookie = Context::getContext()->cookie;
  320. /* If language does not exist or is disabled, erase it */
  321. if ($cookie->id_lang)
  322. {
  323. $lang = new Language((int)$cookie->id_lang);
  324. if (!Validate::isLoadedObject($lang) || !$lang->active || !$lang->isAssociatedToShop())
  325. $cookie->id_lang = null;
  326. }
  327. if (!Configuration::get('PS_DETECT_LANG'))
  328. unset($cookie->detect_language);
  329. /* Automatically detect language if not already defined, detect_language is set in Cookie::update */
  330. if (!Tools::getValue('isolang') && !Tools::getValue('id_lang') && (!$cookie->id_lang || isset($cookie->detect_language))
  331. && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
  332. {
  333. $array = explode(',', Tools::strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  334. $string = $array[0];
  335. if (Validate::isLanguageCode($string))
  336. {
  337. $lang = Language::getLanguageByIETFCode($string);
  338. if (Validate::isLoadedObject($lang) && $lang->active && $lang->isAssociatedToShop())
  339. {
  340. Context::getContext()->language = $lang;
  341. $cookie->id_lang = (int)$lang->id;
  342. }
  343. }
  344. }
  345. if (isset($cookie->detect_language))
  346. unset($cookie->detect_language);
  347. /* If language file not present, you must use default language file */
  348. if (!$cookie->id_lang || !Validate::isUnsignedId($cookie->id_lang))
  349. $cookie->id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
  350. $iso = Language::getIsoById((int)$cookie->id_lang);
  351. @include_once(_PS_THEME_DIR_.'lang/'.$iso.'.php');
  352. return $iso;
  353. }
  354. /**
  355. * Set cookie id_lang
  356. */
  357. public static function switchLanguage(Context $context = null)
  358. {
  359. if (!$context)
  360. $context = Context::getContext();
  361. // Install call the dispatcher and so the switchLanguage
  362. // Stop this method by checking the cookie
  363. if (!isset($context->cookie))
  364. return;
  365. if (($iso = Tools::getValue('isolang')) && Validate::isLanguageIsoCode($iso) && ($id_lang = (int)Language::getIdByIso($iso)))
  366. $_GET['id_lang'] = $id_lang;
  367. // update language only if new id is different from old id
  368. // or if default language changed
  369. $cookie_id_lang = $context->cookie->id_lang;
  370. $configuration_id_lang = Configuration::get('PS_LANG_DEFAULT');
  371. if ((($id_lang = (int)Tools::getValue('id_lang')) && Validate::isUnsignedId($id_lang) && $cookie_id_lang != (int)$id_lang)
  372. || (($id_lang == $configuration_id_lang) && Validate::isUnsignedId($id_lang) && $id_lang != $cookie_id_lang))
  373. {
  374. $context->cookie->id_lang = $id_lang;
  375. $language = new Language($id_lang);
  376. if (Validate::isLoadedObject($language) && $language->active)
  377. $context->language = $language;
  378. $params = $_GET;
  379. if (Configuration::get('PS_REWRITING_SETTINGS') || !Language::isMultiLanguageActivated())
  380. unset($params['id_lang']);
  381. }
  382. }
  383. public static function getCountry($address = null)
  384. {
  385. if ($id_country = Tools::getValue('id_country'));
  386. elseif (isset($address) && isset($address->id_country) && $address->id_country)
  387. $id_country = $address->id_country;
  388. elseif (Configuration::get('PS_DETECT_COUNTRY') && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
  389. {
  390. preg_match('#(?<=-)\w\w|\w\w(?!-)#', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $array);
  391. if (is_array($array) && isset($array[0]) && Validate::isLanguageIsoCode($array[0]))
  392. $id_country = Country::getByIso($array[0], true);
  393. }
  394. if (!isset($id_country) || !$id_country)
  395. $id_country = Configuration::get('PS_COUNTRY_DEFAULT');
  396. return (int)$id_country;
  397. }
  398. /**
  399. * Set cookie currency from POST or default currency
  400. *
  401. * @return Currency object
  402. */
  403. public static function setCurrency($cookie)
  404. {
  405. if (Tools::isSubmit('SubmitCurrency') && ($id_currency = Tools::getValue('id_currency')))
  406. {
  407. $currency = Currency::getCurrencyInstance((int)$id_currency);
  408. if (is_object($currency) && $currency->id && !$currency->deleted && $currency->isAssociatedToShop())
  409. $cookie->id_currency = (int)$currency->id;
  410. }
  411. $currency = null;
  412. if ((int)$cookie->id_currency)
  413. $currency = Currency::getCurrencyInstance((int)$cookie->id_currency);
  414. if (!Validate::isLoadedObject($currency) || (bool)$currency->deleted || !(bool)$currency->active)
  415. $currency = Currency::getCurrencyInstance(Configuration::get('PS_CURRENCY_DEFAULT'));
  416. $cookie->id_currency = (int)$currency->id;
  417. if ($currency->isAssociatedToShop())
  418. return $currency;
  419. else
  420. {
  421. // get currency from context
  422. $currency = Shop::getEntityIds('currency', Context::getContext()->shop->id, true, true);
  423. if (isset($currency[0]) && $currency[0]['id_currency'])
  424. {
  425. $cookie->id_currency = $currency[0]['id_currency'];
  426. return Currency::getCurrencyInstance((int)$cookie->id_currency);
  427. }
  428. }
  429. return $currency;
  430. }
  431. /**
  432. * Return price with currency sign for a given product
  433. *
  434. * @param float $price Product price
  435. * @param object|array $currency Current currency (object, id_currency, NULL => context currency)
  436. * @return string Price correctly formated (sign, decimal separator...)
  437. */
  438. public static function displayPrice($price, $currency = null, $no_utf8 = false, Context $context = null)
  439. {
  440. if (!is_numeric($price))
  441. return $price;
  442. if (!$context)
  443. $context = Context::getContext();
  444. if ($currency === null)
  445. $currency = $context->currency;
  446. // if you modified this function, don't forget to modify the Javascript function formatCurrency (in tools.js)
  447. elseif (is_int($currency))
  448. $currency = Currency::getCurrencyInstance((int)$currency);
  449. if (is_array($currency))
  450. {
  451. $c_char = $currency['sign'];
  452. $c_format = $currency['format'];
  453. $c_decimals = (int)$currency['decimals'] * _PS_PRICE_DISPLAY_PRECISION_;
  454. $c_blank = $currency['blank'];
  455. }
  456. elseif (is_object($currency))
  457. {
  458. $c_char = $currency->sign;
  459. $c_format = $currency->format;
  460. $c_decimals = (int)$currency->decimals * _PS_PRICE_DISPLAY_PRECISION_;
  461. $c_blank = $currency->blank;
  462. }
  463. else
  464. return false;
  465. $blank = ($c_blank ? ' ' : '');
  466. $ret = 0;
  467. if (($is_negative = ($price < 0)))
  468. $price *= -1;
  469. $price = Tools::ps_round($price, $c_decimals);
  470. /*
  471. * If the language is RTL and the selected currency format contains spaces as thousands separator
  472. * then the number will be printed in reverse since the space is interpreted as separating words.
  473. * To avoid this we replace the currency format containing a space with the one containing a comma (,) as thousand
  474. * separator when the language is RTL.
  475. *
  476. * TODO: This is not ideal, a currency format should probably be tied to a language, not to a currency.
  477. */
  478. if (($c_format == 2) && ($context->language->is_rtl == 1))
  479. $c_format = 4;
  480. switch ($c_format)
  481. {
  482. /* X 0,000.00 */
  483. case 1:
  484. $ret = $c_char.$blank.number_format($price, $c_decimals, '.', ',');
  485. break;
  486. /* 0 000,00 X*/
  487. case 2:
  488. $ret = number_format($price, $c_decimals, ',', ' ').$blank.$c_char;
  489. break;
  490. /* X 0.000,00 */
  491. case 3:
  492. $ret = $c_char.$blank.number_format($price, $c_decimals, ',', '.');
  493. break;
  494. /* 0,000.00 X */
  495. case 4:
  496. $ret = number_format($price, $c_decimals, '.', ',').$blank.$c_char;
  497. break;
  498. /* X 0'000.00 Added for the switzerland currency */
  499. case 5:
  500. $ret = $c_char.$blank.number_format($price, $c_decimals, '.', "'");
  501. break;
  502. }
  503. if ($is_negative)
  504. $ret = '-'.$ret;
  505. if ($no_utf8)
  506. return str_replace('€', chr(128), $ret);
  507. return $ret;
  508. }
  509. /* Just to fix a bug
  510. * Need real CLDR functions
  511. */
  512. public static function displayNumber($number, $currency)
  513. {
  514. if (is_array($currency))
  515. $format = $currency['format'];
  516. elseif (is_object($currency))
  517. $format = $currency->format;
  518. return number_format($number, 0, '.', in_array($format, array(1, 4)) ? ',': ' ');
  519. }
  520. public static function displayPriceSmarty($params, &$smarty)
  521. {
  522. if (array_key_exists('currency', $params))
  523. {
  524. $currency = Currency::getCurrencyInstance((int)$params['currency']);
  525. if (Validate::isLoadedObject($currency))
  526. return Tools::displayPrice($params['price'], $currency, false);
  527. }
  528. return Tools::displayPrice($params['price']);
  529. }
  530. /**
  531. * Return price converted
  532. *
  533. * @param float $price Product price
  534. * @param object|array $currency Current currency object
  535. * @param boolean $to_currency convert to currency or from currency to default currency
  536. * @param Context $context
  537. * @return float Price
  538. */
  539. public static function convertPrice($price, $currency = null, $to_currency = true, Context $context = null)
  540. {
  541. static $default_currency = null;
  542. if ($default_currency === null)
  543. $default_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
  544. if (!$context)
  545. $context = Context::getContext();
  546. if ($currency === null)
  547. $currency = $context->currency;
  548. elseif (is_numeric($currency))
  549. $currency = Currency::getCurrencyInstance($currency);
  550. $c_id = (is_array($currency) ? $currency['id_currency'] : $currency->id);
  551. $c_rate = (is_array($currency) ? $currency['conversion_rate'] : $currency->conversion_rate);
  552. if ($c_id != $default_currency)
  553. {
  554. if ($to_currency)
  555. $price *= $c_rate;
  556. else
  557. $price /= $c_rate;
  558. }
  559. return $price;
  560. }
  561. /**
  562. *
  563. * Convert amount from a currency to an other currency automatically
  564. * @param float $amount
  565. * @param Currency $currency_from if null we used the default currency
  566. * @param Currency $currency_to if null we used the default currency
  567. */
  568. public static function convertPriceFull($amount, Currency $currency_from = null, Currency $currency_to = null)
  569. {
  570. if ($currency_from === $currency_to)
  571. return $amount;
  572. if ($currency_from === null)
  573. $currency_from = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
  574. if ($currency_to === null)
  575. $currency_to = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
  576. if ($currency_from->id == Configuration::get('PS_CURRENCY_DEFAULT'))
  577. $amount *= $currency_to->conversion_rate;
  578. else
  579. {
  580. $conversion_rate = ($currency_from->conversion_rate == 0 ? 1 : $currency_from->conversion_rate);
  581. // Convert amount to default currency (using the old currency rate)
  582. $amount = $amount / $conversion_rate;
  583. // Convert to new currency
  584. $amount *= $currency_to->conversion_rate;
  585. }
  586. return Tools::ps_round($amount, _PS_PRICE_COMPUTE_PRECISION_);
  587. }
  588. /**
  589. * Display date regarding to language preferences
  590. *
  591. * @param array $params Date, format...
  592. * @param object $smarty Smarty object for language preferences
  593. * @return string Date
  594. */
  595. public static function dateFormat($params, &$smarty)
  596. {
  597. return Tools::displayDate($params['date'], null, (isset($params['full']) ? $params['full'] : false));
  598. }
  599. /**
  600. * Display date regarding to language preferences
  601. *
  602. * @param string $date Date to display format UNIX
  603. * @param integer $id_lang Language id DEPRECATED
  604. * @param boolean $full With time or not (optional)
  605. * @param string $separator DEPRECATED
  606. * @return string Date
  607. */
  608. public static function displayDate($date, $id_lang = null, $full = false, $separator = null)
  609. {
  610. if ($id_lang !== null)
  611. Tools::displayParameterAsDeprecated('id_lang');
  612. if ($separator !== null)
  613. Tools::displayParameterAsDeprecated('separator');
  614. if (!$date || !($time = strtotime($date)))
  615. return $date;
  616. if ($date == '0000-00-00 00:00:00' || $date == '0000-00-00')
  617. return '';
  618. if (!Validate::isDate($date) || !Validate::isBool($full))
  619. throw new PrestaShopException('Invalid date');
  620. $context = Context::getContext();
  621. $date_format = ($full ? $context->language->date_format_full : $context->language->date_format_lite);
  622. return date($date_format, $time);
  623. }
  624. /**
  625. * Sanitize a string
  626. *
  627. * @param string $string String to sanitize
  628. * @param boolean $full String contains HTML or not (optional)
  629. * @return string Sanitized string
  630. */
  631. public static function safeOutput($string, $html = false)
  632. {
  633. if (!$html)
  634. $string = strip_tags($string);
  635. return @Tools::htmlentitiesUTF8($string, ENT_QUOTES);
  636. }
  637. public static function htmlentitiesUTF8($string, $type = ENT_QUOTES)
  638. {
  639. if (is_array($string))
  640. return array_map(array('Tools', 'htmlentitiesUTF8'), $string);
  641. return htmlentities((string)$string, $type, 'utf-8');
  642. }
  643. public static function htmlentitiesDecodeUTF8($string)
  644. {
  645. if (is_array($string))
  646. {
  647. $string = array_map(array('Tools', 'htmlentitiesDecodeUTF8'), $string);
  648. return (string)array_shift($string);
  649. }
  650. return html_entity_decode((string)$string, ENT_QUOTES, 'utf-8');
  651. }
  652. public static function safePostVars()
  653. {
  654. if (!isset($_POST) || !is_array($_POST))
  655. $_POST = array();
  656. else
  657. $_POST = array_map(array('Tools', 'htmlentitiesUTF8'), $_POST);
  658. }
  659. /**
  660. * Delete directory and subdirectories
  661. *
  662. * @param string $dirname Directory name
  663. */
  664. public static function deleteDirectory($dirname, $delete_self = true)
  665. {
  666. $dirname = rtrim($dirname, '/').'/';
  667. if (file_exists($dirname))
  668. if ($files = scandir($dirname))
  669. {
  670. foreach ($files as $file)
  671. if ($file != '.' && $file != '..' && $file != '.svn')
  672. {
  673. if (is_dir($dirname.$file))
  674. Tools::deleteDirectory($dirname.$file, true);
  675. elseif (file_exists($dirname.$file))
  676. {
  677. @chmod($dirname.$file, 0777); // NT ?
  678. unlink($dirname.$file);
  679. }
  680. }
  681. if ($delete_self && file_exists($dirname))
  682. if (!rmdir($dirname))
  683. {
  684. @chmod($dirname, 0777); // NT ?
  685. return false;
  686. }
  687. return true;
  688. }
  689. return false;
  690. }
  691. /**
  692. * Delete file
  693. *
  694. * @param string File path
  695. * @param array Excluded files
  696. */
  697. public static function deleteFile($file, $exclude_files = array())
  698. {
  699. if (isset($exclude_files) && !is_array($exclude_files))
  700. $exclude_files = array($exclude_files);
  701. if (file_exists($file) && is_file($file) && array_search(basename($file), $exclude_files) === FALSE)
  702. {
  703. @chmod($dirname.$file, 0777); // NT ?
  704. unlink($file);
  705. }
  706. }
  707. /**
  708. * Clear XML cache folder
  709. */
  710. public static function clearXMLCache()
  711. {
  712. $themes = array();
  713. foreach (Theme::getThemes() as $theme)
  714. $themes[] = $theme->directory;
  715. foreach (scandir(_PS_ROOT_DIR_.'/config/xml') as $file)
  716. {
  717. $path_info = pathinfo($file, PATHINFO_EXTENSION);
  718. if (($path_info == 'xml') && ($file != 'default.xml') && !in_array(basename($file, '.'.$path_info), $themes))
  719. self::deleteFile(_PS_ROOT_DIR_.'/config/xml/'.$file);
  720. }
  721. }
  722. /**
  723. * Display an error according to an error code
  724. *
  725. * @param string $string Error message
  726. * @param boolean $htmlentities By default at true for parsing error message with htmlentities
  727. */
  728. public static function displayError($string = 'Fatal error', $htmlentities = true, Context $context = null)
  729. {
  730. global $_ERRORS;
  731. if (is_null($context))
  732. $context = Context::getContext();
  733. @include_once(_PS_TRANSLATIONS_DIR_.$context->language->iso_code.'/errors.php');
  734. if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ && $string == 'Fatal error')
  735. return ('<pre>'.print_r(debug_backtrace(), true).'</pre>');
  736. if (!is_array($_ERRORS))
  737. return $htmlentities ? Tools::htmlentitiesUTF8($string) : $string;
  738. $key = md5(str_replace('\'', '\\\'', $string));
  739. $str = (isset($_ERRORS) && is_array($_ERRORS) && array_key_exists($key, $_ERRORS)) ? $_ERRORS[$key] : $string;
  740. return $htmlentities ? Tools::htmlentitiesUTF8(stripslashes($str)) : $str;
  741. }
  742. /**
  743. * Display an error with detailed object
  744. *
  745. * @param mixed $object
  746. * @param boolean $kill
  747. * @return $object if $kill = false;
  748. */
  749. public static function dieObject($object, $kill = true)
  750. {
  751. echo '<xmp style="text-align: left;">';
  752. print_r($object);
  753. echo '</xmp><br />';
  754. if ($kill)
  755. die('END');
  756. return $object;
  757. }
  758. /**
  759. * Display a var dump in firebug console
  760. *
  761. * @param object $object Object to display
  762. */
  763. public static function fd($object, $type = 'log')
  764. {
  765. $types = array('log', 'debug', 'info', 'warn', 'error', 'assert');
  766. if (!in_array($type, $types))
  767. $type = 'log';
  768. echo '
  769. <script type="text/javascript">
  770. console.'.$type.'('.Tools::jsonEncode($object).');
  771. </script>
  772. ';
  773. }
  774. /**
  775. * ALIAS OF dieObject() - Display an error with detailed object
  776. *
  777. * @param object $object Object to display
  778. */
  779. public static function d($object, $kill = true)
  780. {
  781. return (Tools::dieObject($object, $kill));
  782. }
  783. public static function debug_backtrace($start = 0, $limit = null)
  784. {
  785. $backtrace = debug_backtrace();
  786. array_shift($backtrace);
  787. for ($i = 0; $i < $start; ++$i)
  788. array_shift($backtrace);
  789. echo '
  790. <div style="margin:10px;padding:10px;border:1px solid #666666">
  791. <ul>';
  792. $i = 0;
  793. foreach ($backtrace as $id => $trace)
  794. {
  795. if ((int)$limit && (++$i > $limit ))
  796. break;
  797. $relative_file = (isset($trace['file'])) ? 'in /'.ltrim(str_replace(array(_PS_ROOT_DIR_, '\\'), array('', '/'), $trace['file']), '/') : '';
  798. $current_line = (isset($trace['line'])) ? ':'.$trace['line'] : '';
  799. echo '<li>
  800. <b>'.((isset($trace['class'])) ? $trace['class'] : '').((isset($trace['type'])) ? $trace['type'] : '').$trace['function'].'</b>
  801. '.$relative_file.$current_line.'
  802. </li>';
  803. }
  804. echo '</ul>
  805. </div>';
  806. }
  807. /**
  808. * ALIAS OF dieObject() - Display an error with detailed object but don't stop the execution
  809. *
  810. * @param object $object Object to display
  811. */
  812. public static function p($object)
  813. {
  814. return (Tools::dieObject($object, false));
  815. }
  816. /**
  817. * Check if submit has been posted
  818. *
  819. * @param string $submit submit name
  820. */
  821. public static function isSubmit($submit)
  822. {
  823. return (
  824. isset($_POST[$submit]) || isset($_POST[$submit.'_x']) || isset($_POST[$submit.'_y'])
  825. || isset($_GET[$submit]) || isset($_GET[$submit.'_x']) || isset($_GET[$submit.'_y'])
  826. );
  827. }
  828. /**
  829. * @deprecated 1.5.0
  830. */
  831. public static function getMetaTags($id_lang, $page_name, $title = '')
  832. {
  833. Tools::displayAsDeprecated();
  834. return Meta::getMetaTags($id_lang, $page_name, $title);
  835. }
  836. /**
  837. * @deprecated 1.5.0
  838. */
  839. public static function getHomeMetaTags($id_lang, $page_name)
  840. {
  841. Tools::displayAsDeprecated();
  842. return Meta::getHomeMetas($id_lang, $page_name);
  843. }
  844. /**
  845. * @deprecated 1.5.0
  846. */
  847. public static function completeMetaTags($meta_tags, $default_value, Context $context = null)
  848. {
  849. Tools::displayAsDeprecated();
  850. return Meta::completeMetaTags($meta_tags, $default_value, $context);
  851. }
  852. /**
  853. * Encrypt password
  854. *
  855. * @param string $passwd String to encrypt
  856. */
  857. public static function encrypt($passwd)
  858. {
  859. return md5(_COOKIE_KEY_.$passwd);
  860. }
  861. /**
  862. * Encrypt data string
  863. *
  864. * @param string $data String to encrypt
  865. */
  866. public static function encryptIV($data)
  867. {
  868. return md5(_COOKIE_IV_.$data);
  869. }
  870. /**
  871. * Get token to prevent CSRF
  872. *
  873. * @param string $token token to encrypt
  874. */
  875. public static function getToken($page = true, Context $context = null)
  876. {
  877. if (!$context)
  878. $context = Context::getContext();
  879. if ($page === true)
  880. return (Tools::encrypt($context->customer->id.$context->customer->passwd.$_SERVER['SCRIPT_NAME']));
  881. else
  882. return (Tools::encrypt($context->customer->id.$context->customer->passwd.$page));
  883. }
  884. /**
  885. * Tokenize a string
  886. *
  887. * @param string $string string to encript
  888. */
  889. public static function getAdminToken($string)
  890. {
  891. return !empty($string) ? Tools::encrypt($string) : false;
  892. }
  893. public static function getAdminTokenLite($tab, Context $context = null)
  894. {
  895. if (!$context)
  896. $context = Context::getContext();
  897. return Tools::getAdminToken($tab.(int)Tab::getIdFromClassName($tab).(int)$context->employee->id);
  898. }
  899. public static function getAdminTokenLiteSmarty($params, &$smarty)
  900. {
  901. $context = Context::getContext();
  902. return Tools::getAdminToken($params['tab'].(int)Tab::getIdFromClassName($params['tab']).(int)$context->employee->id);
  903. }
  904. /**
  905. * Get a valid URL to use from BackOffice
  906. *
  907. * @param string $url An URL to use in BackOffice
  908. * @param boolean $entites Set to true to use htmlentities function on URL param
  909. */
  910. public static function getAdminUrl($url = null, $entities = false)
  911. {
  912. $link = Tools::getHttpHost(true).__PS_BASE_URI__;
  913. if (isset($url))
  914. $link .= ($entities ? Tools::htmlentitiesUTF8($url) : $url);
  915. return $link;
  916. }
  917. /**
  918. * Get a valid image URL to use from BackOffice
  919. *
  920. * @param string $image Image name
  921. * @param boolean $entites Set to true to use htmlentities function on image param
  922. */
  923. public static function getAdminImageUrl($image = null, $entities = false)
  924. {
  925. return Tools::getAdminUrl(basename(_PS_IMG_DIR_).'/'.$image, $entities);
  926. }
  927. /**
  928. * Get the user's journey
  929. *
  930. * @param integer $id_category Category ID
  931. * @param string $path Path end
  932. * @param boolean $linkOntheLastItem Put or not a link on the current category
  933. * @param string [optionnal] $categoryType defined what type of categories is used (products or cms)
  934. */
  935. public static function getPath($id_category, $path = '', $link_on_the_item = false, $category_type = 'products', Context $context = null)
  936. {
  937. if (!$context)
  938. $context = Context::getContext();
  939. $id_category = (int)$id_category;
  940. if ($id_category == 1)
  941. return '<span class="navigation_end">'.$path.'</span>';
  942. $pipe = Configuration::get('PS_NAVIGATION_PIPE');
  943. if (empty($pipe))
  944. $pipe = '>';
  945. $full_path = '';
  946. if ($category_type === 'products')
  947. {
  948. $interval = Category::getInterval($id_category);
  949. $id_root_category = $context->shop->getCategory();
  950. $interval_root = Category::getInterval($id_root_category);
  951. if ($interval)
  952. {
  953. $sql = 'SELECT c.id_category, cl.name, cl.link_rewrite
  954. FROM '._DB_PREFIX_.'category c
  955. LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = c.id_category'.Shop::addSqlRestrictionOnLang('cl').')
  956. '.Shop::addSqlAssociation('category', 'c').'
  957. WHERE c.nleft <= '.$interval['nleft'].'
  958. AND c.nright >= '.$interval['nright'].'
  959. AND c.nleft >= '.$interval_root['nleft'].'
  960. AND c.nright <= '.$interval_root['nright'].'
  961. AND cl.id_lang = '.(int)$context->language->id.'
  962. AND c.active = 1
  963. AND c.level_depth > '.(int)$interval_root['level_depth'].'
  964. ORDER BY c.level_depth ASC';
  965. $categories = Db::getInstance()->executeS($sql);
  966. $n = 1;
  967. $n_categories = count($categories);
  968. foreach ($categories as $category)
  969. {
  970. $full_path .=
  971. (($n < $n_categories || $link_on_the_item) ? '<a href="'.Tools::safeOutput($context->link->getCategoryLink((int)$category['id_category'], $category['link_rewrite'])).'" title="'.htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8').'" data-gg="">' : '').
  972. htmlentities($category['name'], ENT_NOQUOTES, 'UTF-8').
  973. (($n < $n_categories || $link_on_the_item) ? '</a>' : '').
  974. (($n++ != $n_categories || !empty($path)) ? '<span class="navigation-pipe">'.$pipe.'</span>' : '');
  975. }
  976. return $full_path.$path;
  977. }
  978. }
  979. elseif ($category_type === 'CMS')
  980. {
  981. $category = new CMSCategory($id_category, $context->language->id);
  982. if (!Validate::isLoadedObject($category))
  983. die(Tools::displayError());
  984. $category_link = $context->link->getCMSCategoryLink($category);
  985. if ($path != $category->name)
  986. $full_path .= '<a href="'.Tools::safeOutput($category_link).'" data-gg="">'.htmlentities($category->name, ENT_NOQUOTES, 'UTF-8').'</a><span class="navigation-pipe">'.$pipe.'</span>'.$path;
  987. else
  988. $full_path = ($link_on_the_item ? '<a href="'.Tools::safeOutput($category_link).'" data-gg="">' : '').htmlentities($path, ENT_NOQUOTES, 'UTF-8').($link_on_the_item ? '</a>' : '');
  989. return Tools::getPath($category->id_parent, $full_path, $link_on_the_item, $category_type);
  990. }
  991. }
  992. /**
  993. * @param string [optionnal] $type_cat defined what type of categories is used (products or cms)
  994. */
  995. public static function getFullPath($id_category, $end, $type_cat = 'products', Context $context = null)
  996. {
  997. if (!$context)
  998. $context = Context::getContext();
  999. $id_category = (int)$id_category;
  1000. $pipe = (Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>');
  1001. $default_category = 1;
  1002. if ($type_cat === 'products')
  1003. {
  1004. $default_category = $context->shop->getCategory();
  1005. $category = new Category($id_category, $context->language->id);
  1006. }
  1007. elseif ($type_cat === 'CMS')
  1008. $category = new CMSCategory($id_category, $context->language->id);
  1009. if (!Validate::isLoadedObject($category))
  1010. $id_category = $default_category;
  1011. if ($id_category == $default_category)
  1012. return htmlentities($end, ENT_NOQUOTES, 'UTF-8');
  1013. return Tools::getPath($id_category, $category->name, true, $type_cat).'<span class="navigation-pipe">'.$pipe.'</span> <span class="navigation_product">'.htmlentities($end, ENT_NOQUOTES, 'UTF-8').'</span>';
  1014. }
  1015. /**
  1016. * Return the friendly url from the provided string
  1017. *
  1018. * @param string $str
  1019. * @param bool $utf8_decode (deprecated)
  1020. * @return string
  1021. */
  1022. public static function link_rewrite($str, $utf8_decode = null)
  1023. {
  1024. if ($utf8_decode !== null)
  1025. Tools::displayParameterAsDeprecated('utf8_decode');
  1026. return Tools::str2url($str);
  1027. }
  1028. /**
  1029. * Return a friendly url made from the provided string
  1030. * If the mbstring library is available, the output is the same as the js function of the same name
  1031. *
  1032. * @param string $str
  1033. * @return string
  1034. */
  1035. public static function str2url($str)
  1036. {
  1037. static $allow_accented_chars = null;
  1038. if ($allow_accented_chars === null)
  1039. $allow_accented_chars = Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL');
  1040. if (!is_string($str))
  1041. return false;
  1042. $str = trim($str);
  1043. if (function_exists('mb_strtolower'))
  1044. $str = mb_strtolower($str, 'utf-8');
  1045. if (!$allow_accented_chars)
  1046. $str = Tools::replaceAccentedChars($str);
  1047. // Remove all non-whitelist chars.
  1048. if ($allow_accented_chars)
  1049. $str = preg_replace('/[^a-zA-Z0-9\s\'\:\/\[\]\-\pL]/u', '', $str);
  1050. else
  1051. $str = preg_replace('/[^a-zA-Z0-9\s\'\:\/\[\]\-]/','', $str);
  1052. $str = preg_replace('/[\s\'\:\/\[\]\-]+/', ' ', $str);
  1053. $str = str_replace(array(' ', '/'), '-', $str);
  1054. // If it was not possible to lowercase the string with mb_strtolower, we do it after the transformations.
  1055. // This way we lose fewer special chars.
  1056. if (!function_exists('mb_strtolower'))
  1057. $str = Tools::strtolower($str);
  1058. return $str;
  1059. }
  1060. /**
  1061. * Replace all accented chars by their equivalent non accented chars.
  1062. *
  1063. * @param string $str
  1064. * @return string
  1065. */
  1066. public static function replaceAccentedChars($str)
  1067. {
  1068. /* One source among others:
  1069. http://www.tachyonsoft.com/uc0000.htm
  1070. http://www.tachyonsoft.com/uc0001.htm
  1071. http://www.tachyonsoft.com/uc0004.htm
  1072. */
  1073. $patterns = array(
  1074. /* Lowercase */
  1075. /* a */ '/[\x{00E0}\x{00E1}\x{00E2}\x{00E3}\x{00E4}\x{00E5}\x{0101}\x{0103}\x{0105}\x{0430}\x{00C0}-\x{00C3}\x{1EA0}-\x{1EB7}]/u',
  1076. /* b */ '/[\x{0431}]/u',
  1077. /* c */ '/[\x{00E7}\x{0107}\x{0109}\x{010D}\x{0446}]/u',
  1078. /* d */ '/[\x{010F}\x{0111}\x{0434}\x{0110}]/u',
  1079. /* e */ '/[\x{00E8}\x{00E9}\x{00EA}\x{00EB}\x{0113}\x{0115}\x{0117}\x{0119}\x{011B}\x{0435}\x{044D}\x{00C8}-\x{00CA}\x{1EB8}-\x{1EC7}]/u',
  1080. /* f */ '/[\x{0444}]/u',
  1081. /* g */ '/[\x{011F}\x{0121}\x{0123}\x{0433}\x{0491}]/u',
  1082. /* h */ '/[\x{0125}\x{0127}]/u',
  1083. /* i */ '/[\x{00EC}\x{00ED}\x{00EE}\x{00EF}\x{0129}\x{012B}\x{012D}\x{012F}\x{0131}\x{0438}\x{0456}\x{00CC}\x{00CD}\x{1EC8}-\x{1ECB}\x{0128}]/u',
  1084. /* j */ '/[\x{0135}\x{0439}]/u',
  1085. /* k */ '/[\x{0137}\x{0138}\x{043A}]/u',
  1086. /* l */ '/[\x{013A}\x{013C}\x{013E}\x{0140}\x{0142}\x{043B}]/u',
  1087. /* m */ '/[\x{043C}]/u',
  1088. /* n */ '/[\x{00F1}\x{0144}\x{0146}\x{0148}\x{0149}\x{014B}\x{043D}]/u',
  1089. /* o */ '/[\x{00F2}\x{00F3}\x{00F4}\x{00F5}\x{00F6}\x{00F8}\x{014D}\x{014F}\x{0151}\x{043E}\x{00D2}-\x{00D5}\x{01A0}\x{01A1}\x{1ECC}-\x{1EE3}]/u',
  1090. /* p */ '/[\x{043F}]/u',
  1091. /* r */ '/[\x{0155}\x{0157}\x{0159}\x{0440}]/u',
  1092. /* s */ '/[\x{015B}\x{015D}\x{015F}\x{0161}\x{0441}]/u',
  1093. /* ss */ '/[\x{00DF}]/u',
  1094. /* t */ '/[\x{0163}\x{0165}\x{0167}\x{0442}]/u',
  1095. /* u */ '/[\x{00F9}\x{00FA}\x{00FB}\x{00FC}\x{0169}\x{016B}\x{016D}\x{016F}\x{0171}\x{0173}\x{0443}\x{00D9}-\x{00DA}\x{0168}\x{01AF}\x{01B0}\x{1EE4}-\x{1EF1}]/u',
  1096. /* v */ '/[\x{0432}]/u',
  1097. /* w */ '/[\x{0175}]/u',
  1098. /* y */ '/[\x{00FF}\x{0177}\x{00FD}\x{044B}\x{1EF2}-\x{1EF9}\x{00DD}]/u',
  1099. /* z */ '/[\x{017A}\x{017C}\x{017E}\x{0437}]/u',
  1100. /* ae */ '/[\x{00E6}]/u',
  1101. /* ch */ '/[\x{0447}]/u',
  1102. /* kh */ '/[\x{0445}]/u',
  1103. /* oe */ '/[\x{0153}]/u',
  1104. /* sh */ '/[\x{0448}]/u',
  1105. /* shh*/ '/[\x{0449}]/u',
  1106. /* ya */ '/[\x{044F}]/u',
  1107. /* ye */ '/[\x{0454}]/u',
  1108. /* yi */ '/[\x{0457}]/u',
  1109. /* yo */ '/[\x{0451}]/u',
  1110. /* yu */ '/[\x{044E}]/u',
  1111. /* zh */ '/[\x{0436}]/u',
  1112. /* Uppercase */
  1113. /* A */ '/[\x{0100}\x{0102}\x{0104}\x{00C0}\x{00C1}\x{00C2}\x{00C3}\x{00C4}\x{00C5}\x{0410}]/u',
  1114. /* B */ '/[\x{0411}]]/u',
  1115. /* C */ '/[\x{00C7}\x{0106}\x{0108}\x{010A}\x{010C}\x{0426}]/u',
  1116. /* D */ '/[\x{010E}\x{0110}\x{0414}]/u',
  1117. /* E */ '/[\x{00C8}\x{00C9}\x{00CA}\x{00CB}\x{0112}\x{0114}\x{0116}\x{0118}\x{011A}\x{0415}\x{042D}]/u',
  1118. /* F */ '/[\x{0424}]/u',
  1119. /* G */ '/[\x{011C}\x{011E}\x{0120}\x{0122}\x{0413}\x{0490}]/u',
  1120. /* H */ '/[\x{0124}\x{0126}]/u',
  1121. /* I */ '/[\x{0128}\x{012A}\x{012C}\x{012E}\x{0130}\x{0418}\x{0406}]/u',
  1122. /* J */ '/[\x{0134}\x{0419}]/u',
  1123. /* K */ '/[\x{0136}\x{041A}]/u',
  1124. /* L */ '/[\x{0139}\x{013B}\x{013D}\x{0139}\x{0141}\x{041B}]/u',
  1125. /* M */ '/[\x{041C}]/u',
  1126. /* N */ '/[\x{00D1}\x{0143}\x{0145}\x{0147}\x{014A}\x{041D}]/u',
  1127. /* O */ '/[\x{00D3}\x{014C}\x{014E}\x{0150}\x{041E}]/u',
  1128. /* P */ '/[\x{041F}]/u',
  1129. /* R */ '/[\x{0154}\x{0156}\x{0158}\x{0420}]/u',
  1130. /* S */ '/[\x{015A}\x{015C}\x{015E}\x{0160}\x{0421}]/u',
  1131. /* T */ '/[\x{0162}\x{0164}\x{0166}\x{0422}]/u',
  1132. /* U */ '/[\x{00D9}\x{00DA}\x{00DB}\x{00DC}\x{0168}\x{016A}\x{016C}\x{016E}\x{0170}\x{0172}\x{0423}]/u',
  1133. /* V */ '/[\x{0412}]/u',
  1134. /* W */ '/[\x{0174}]/u',
  1135. /* Y */ '/[\x{0176}\x{042B}]/u',
  1136. /* Z */ '/[\x{0179}\x{017B}\x{017D}\x{0417}]/u',
  1137. /* AE */ '/[\x{00C6}]/u',
  1138. /* CH */ '/[\x{0427}]/u',
  1139. /* KH */ '/[\x{0425}]/u',
  1140. /* OE */ '/[\x{0152}]/u',
  1141. /* SH */ '/[\x{0428}]/u',
  1142. /* SHH*/ '/[\x{0429}]/u',
  1143. /* YA */ '/[\x{042F}]/u',
  1144. /* YE */ '/[\x{0404}]/u',
  1145. /* YI */ '/[\x{0407}]/u',
  1146. /* YO */ '/[\x{0401}]/u',
  1147. /* YU */ '/[\x{042E}]/u',
  1148. /* ZH */ '/[\x{0416}]/u');
  1149. // ö to oe
  1150. // å to aa
  1151. // ä to ae
  1152. $replacements = array(
  1153. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 'ss', 't', 'u', 'v', 'w', 'y', 'z', 'ae', 'ch', 'kh', 'oe', 'sh', 'shh', 'ya', 'ye', 'yi', 'yo', 'yu', 'zh',
  1154. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z', 'AE', 'CH', 'KH', 'OE', 'SH', 'SHH', 'YA', 'YE', 'YI', 'YO', 'YU', 'ZH'
  1155. );
  1156. return preg_replace($patterns, $replacements, $str);
  1157. }
  1158. /**
  1159. * Truncate strings
  1160. *
  1161. * @param string $str
  1162. * @param integer $max_length Max length
  1163. * @param string $suffix Suffix optional
  1164. * @return string $str truncated
  1165. */
  1166. /* CAUTION : Use it only on module hookEvents.
  1167. ** For other purposes use the smarty function instead */
  1168. public static function truncate($str, $max_length, $suffix = '...')
  1169. {
  1170. if (Tools::strlen($str) <= $max_length)
  1171. return $str;
  1172. $str = utf8_decode($str);
  1173. return (utf8_encode(substr($str, 0, $max_length - Tools::strlen($suffix)).$suffix));
  1174. }
  1175. /*Copied from CakePHP String utility file*/
  1176. public static function truncateString($text, $length = 120, $options = array())
  1177. {
  1178. $default = array(
  1179. 'ellipsis' => '...', 'exact' => true, 'html' => true
  1180. );
  1181. $options = array_merge($default, $options);
  1182. extract($options);
  1183. if ($html)
  1184. {
  1185. if (Tools::strlen(preg_replace('/<.*?>/', '', $text)) <= $length)
  1186. return $text;
  1187. $totalLength = Tools::strlen(strip_tags($ellipsis));
  1188. $openTags = array();
  1189. $truncate = '';
  1190. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  1191. foreach ($tags as $tag)
  1192. {
  1193. if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2]))
  1194. {
  1195. if (preg_match('/<[\w]+[^>]*>/s', $tag[0]))
  1196. array_unshift($openTags, $tag[2]);
  1197. elseif (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag))
  1198. {
  1199. $pos = array_search($closeTag[1], $openTags);
  1200. if ($pos !== false)
  1201. array_splice($openTags, $pos, 1);
  1202. }
  1203. }
  1204. $truncate .= $tag[1];
  1205. $contentLength = Tools::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  1206. if ($contentLength + $totalLength > $length)
  1207. {
  1208. $left = $length - $totalLength;
  1209. $entitiesLength = 0;
  1210. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE))
  1211. {
  1212. foreach ($entities[0] as $entity)
  1213. {
  1214. if ($entity[1] + 1 - $entitiesLength <= $left)
  1215. {
  1216. $left--;
  1217. $entitiesLength += Tools::strlen($entity[0]);
  1218. }
  1219. else
  1220. break;
  1221. }
  1222. }
  1223. $truncate .= Tools::substr($tag[3], 0, $left + $entitiesLength);
  1224. break;
  1225. }
  1226. else
  1227. {
  1228. $truncate .= $tag[3];
  1229. $totalLength += $contentLength;
  1230. }
  1231. if ($totalLength >= $length)
  1232. break;
  1233. }
  1234. }
  1235. else
  1236. {
  1237. if (Tools::strlen($text) <= $length)
  1238. return $text;
  1239. $truncate = Tools::substr($text, 0, $length - Tools::strlen($ellipsis));
  1240. }
  1241. if (!$exact)
  1242. {
  1243. $spacepos = Tools::strrpos($truncate, ' ');
  1244. if ($html)
  1245. {
  1246. $truncateCheck = Tools::substr($truncate, 0, $spacepos);
  1247. $lastOpenTag = Tools::strrpos($truncateCheck, '<');
  1248. $lastCloseTag = Tools::strrpos($truncateCheck, '>');
  1249. if ($lastOpenTag > $lastCloseTag)
  1250. {
  1251. preg_match_all('/<[\w]+[^>]*>/s', $truncate, $lastTagMatches);
  1252. $lastTag = array_pop($lastTagMatches[0]);
  1253. $spacepos = Tools::strrpos($truncate, $lastTag) + Tools::strlen($lastTag);
  1254. }
  1255. $bits = Tools::substr($truncate, $spacepos);
  1256. preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
  1257. if (!empty($droppedTags))
  1258. {
  1259. if (!empty($openTags))
  1260. {
  1261. foreach ($droppedTags as $closingTag)
  1262. if (!in_array($closingTag[1], $openTags))
  1263. array_unshift($openTags, $closingTag[1]);
  1264. }
  1265. else
  1266. {
  1267. foreach ($droppedTags as $closingTag)
  1268. $openTags[] = $closingTag[1];
  1269. }
  1270. }
  1271. }
  1272. $truncate = Tools::substr($truncate, 0, $spacepos);
  1273. }
  1274. $truncate .= $ellipsis;
  1275. if ($html)
  1276. foreach ($openTags as $tag)
  1277. $truncate .= '</' . $tag . '>';
  1278. return $truncate;
  1279. }
  1280. public static function normalizeDirectory($directory)
  1281. {
  1282. $last = $directory[strlen($directory) - 1];
  1283. if (in_array($last, array('/', '\\')))
  1284. {
  1285. $directory[strlen($directory) - 1] = DIRECTORY_SEPARATOR;
  1286. return $directory;
  1287. }
  1288. $directory .= DIRECTORY_SEPARATOR;
  1289. return $directory;
  1290. }
  1291. /**
  1292. * Generate date form
  1293. *
  1294. * @param integer $year Year to select
  1295. * @param integer $month Month to select
  1296. * @param integer $day Day to select
  1297. * @return array $tab html data with 3 cells :['days'], ['months'], ['years']
  1298. *
  1299. */
  1300. public static function dateYears()
  1301. {
  1302. $tab = array();
  1303. for ($i = date('Y'); $i >= 1900; $i--)
  1304. $tab[] = $i;
  1305. return $tab;
  1306. }
  1307. public static function dateDays()
  1308. {
  1309. $tab = array();
  1310. for ($i = 1; $i != 32; $i++)
  1311. $tab[] = $i;
  1312. return $tab;
  1313. }
  1314. public static function dateMonths()
  1315. {
  1316. $tab = array();
  1317. for ($i = 1; $i != 13; $i++)
  1318. $tab[$i] = date('F', mktime(0, 0, 0, $i, date('m'), date('Y')));
  1319. return $tab;
  1320. }
  1321. public static function hourGenerate($hours, $minutes, $seconds)
  1322. {
  1323. return implode(':', array($hours, $minutes, $seconds));
  1324. }
  1325. public static function dateFrom($date)
  1326. {
  1327. $tab = explode(' ', $date);
  1328. if (!isset($tab[1]))
  1329. $date .= ' '.Tools::hourGenerate(0, 0, 0);
  1330. return $date;
  1331. }
  1332. public static function dateTo($date)
  1333. {
  1334. $tab = explode(' ', $date);
  1335. if (!isset($tab[1]))
  1336. $date .= ' '.Tools::hourGenerate(23, 59, 59);
  1337. return $date;
  1338. }
  1339. public static function strtolower($str)
  1340. {
  1341. if (is_array($str))
  1342. return false;
  1343. if (function_exists('mb_strtolower'))
  1344. return mb_strtolower($str, 'utf-8');
  1345. return strtolower($str);
  1346. }
  1347. public static function strlen($str, $encoding = 'UTF-8')
  1348. {
  1349. if (is_array($str))
  1350. return false;
  1351. $str = html_entity_decode($str, ENT_COMPAT, 'UTF-8');
  1352. if (function_exists('mb_strlen'))
  1353. return mb_strlen($str, $encoding);
  1354. return strlen($str);
  1355. }
  1356. public static function stripslashes($string)
  1357. {
  1358. if (_PS_MAGIC_QUOTES_GPC_)
  1359. $string = stripslashes($string);
  1360. return $string;
  1361. }
  1362. public static function strtoupper($str)
  1363. {
  1364. if (is_array($str))
  1365. return false;
  1366. if (function_exists('mb_strtoupper'))
  1367. return mb_strtoupper($str, 'utf-8');
  1368. return strtoupper($str);
  1369. }
  1370. public static function substr($str, $start, $length = false, $encoding = 'utf-8')
  1371. {
  1372. if (is_array($str))
  1373. return false;
  1374. if (function_exists('mb_substr'))
  1375. return mb_substr($str, (int)$start, ($length === false ? Tools::strlen($str) : (int)$length), $encoding);
  1376. return substr($str, $start, ($length === false ? Tools::strlen($str) : (int)$length));
  1377. }
  1378. public static function strpos($str, $find, $offset = 0, $encoding = 'UTF-8')
  1379. {
  1380. if (function_exists('mb_strpos'))
  1381. return mb_strpos($str, $find, $offset, $encoding);
  1382. return strpos($str, $find, $offset);
  1383. }
  1384. public static function strrpos($str, $find, $offset = 0, $encoding = 'utf-8')
  1385. {
  1386. if (function_exists('mb_strrpos'))
  1387. return mb_strrpos($str, $find, $offset, $encoding);
  1388. return strrpos($str, $find, $offset);
  1389. }
  1390. public static function ucfirst($str)
  1391. {
  1392. return Tools::strtoupper(Tools::substr($str, 0, 1)).Tools::substr($str, 1);
  1393. }
  1394. public static function ucwords($str)
  1395. {
  1396. if (function_exists('mb_convert_case'))
  1397. return mb_convert_case($str, MB_CASE_TITLE);
  1398. return ucwords(Tools::strtolower($str));
  1399. }
  1400. public static function orderbyPrice(&$array, $order_way)
  1401. {
  1402. foreach ($array as &$row)
  1403. $row['price_tmp'] = Product::getPriceStatic($row['id_product'], true, ((isset($row['id_product_attribute']) && !empty($row['id_product_attribute'])) ? (int)$row['id_product_attribute'] : null), 2);
  1404. unset($row);
  1405. if (Tools::strtolower($order_way) == 'desc')
  1406. uasort($array, 'cmpPriceDesc');
  1407. else
  1408. uasort($array, 'cmpPriceAsc');
  1409. foreach ($array as &$row)
  1410. unset($row['price_tmp']);
  1411. }
  1412. public static function iconv($from, $to, $string)
  1413. {
  1414. if (function_exists('iconv'))
  1415. return iconv($from, $to.'//TRANSLIT', str_replace('¥', '&yen;', str_replace('£', '&pound;', str_replace('€', '&euro;', $string))));
  1416. return html_entity_decode(htmlentities($string, ENT_NOQUOTES, $from), ENT_NOQUOTES, $to);
  1417. }
  1418. public static function isEmpty($field)
  1419. {
  1420. return ($field === '' || $field === null);
  1421. }
  1422. /**
  1423. * returns the rounded value of $value to specified precision, according to your configuration;
  1424. *
  1425. * @note : PHP 5.3.0 introduce a 3rd parameter mode in round function
  1426. *
  1427. * @param float $value
  1428. * @param int $precision
  1429. * @return float
  1430. */
  1431. public static function ps_round($value, $precision = 0)
  1432. {
  1433. if (Tools::$round_mode == null)
  1434. Tools::$round_mode = (int)Configuration::get('PS_PRICE_ROUND_MODE');
  1435. switch (Tools::$round_mode)
  1436. {
  1437. case PS_ROUND_UP:
  1438. return Tools::ceilf($value, $precision);
  1439. case PS_ROUND_DOWN:
  1440. return Tools::floorf($value, $precision);
  1441. case PS_ROUND_HALF_DOWN:
  1442. case PS_ROUND_HALF_EVEN:
  1443. case PS_ROUND_HALF_ODD:
  1444. return Tools::math_round($value, $precision, Tools::$round_mode);
  1445. case PS_ROUND_HALF_UP:
  1446. default:
  1447. return Tools::math_round($value, $precision, PS_ROUND_HALF_UP);
  1448. }
  1449. }
  1450. public static function math_round($value, $places, $mode = PS_ROUND_HALF_UP)
  1451. {
  1452. //If PHP_ROUND_HALF_UP exist (PHP 5.3) use it and pass correct mode value (PrestaShop define - 1)
  1453. if (defined('PHP_ROUND_HALF_UP'))
  1454. return round($value, $places, $mode-1);
  1455. $precision_places = 14 - floor(log10(abs($value)));
  1456. $f1 = pow(10.0, (double)abs($places));
  1457. /* If the decimal precision guaranteed by FP arithmetic is higher than
  1458. * the requested places BUT is small enough to make sure a non-zero value
  1459. * is returned, pre-round the result to the precision */
  1460. if ($precision_places > $places && $precision_places - $places < 15)
  1461. {
  1462. $f2 = pow(10.0, (double)abs($precision_places));
  1463. if ($precision_places >= 0)
  1464. $tmp_value = $value * $f2;
  1465. else
  1466. $tmp_value = $value / $f2;
  1467. /* preround the result (tmp_value will always be something * 1e14,
  1468. * thus never larger than 1e15 here) */
  1469. $tmp_value = Tools::round_helper($tmp_value, $mode);
  1470. /* now correctly move the decimal point */
  1471. $f2 = pow(10.0, (double)abs($places - $precision_places));
  1472. /* because places < precision_places */
  1473. $tmp_value = $tmp_value / $f2;
  1474. }
  1475. else
  1476. {
  1477. /* adjust the value */
  1478. if ($places >= 0)
  1479. $tmp_value = $value * $f1;
  1480. else
  1481. $tmp_value = $value / $f1;
  1482. /* This value is beyond our precision, so rounding it is pointless */
  1483. if (abs($tmp_value) >= 1e15)
  1484. return $value;
  1485. }
  1486. /* round the temp value */
  1487. $tmp_value = Tools::round_helper($tmp_value, $mode);
  1488. /* see if it makes sense to use simple division to round the value */
  1489. if (abs($places) < 23)
  1490. {
  1491. if ($places > 0)
  1492. $tmp_value /= $f1;
  1493. else
  1494. $tmp_value *= $f1;
  1495. }
  1496. return $tmp_value;
  1497. }
  1498. public static function round_helper($value, $mode)
  1499. {
  1500. if ($value >= 0.0)
  1501. {
  1502. $tmp_value = floor($value + 0.5);
  1503. if (($mode == PS_ROUND_HALF_DOWN && $value == (-0.5 + $tmp_value )) ||
  1504. ($mode == PS_ROUND_HALF_EVEN && $value == (0.5 + 2 * floor($tmp_value /2.0))) ||
  1505. ($mode == PS_ROUND_HALF_ODD && $value == (0.5 + 2 * floor($tmp_value /2.0) - 1.0)))
  1506. $tmp_value = $tmp_value - 1.0;
  1507. }
  1508. else
  1509. {
  1510. $tmp_value = ceil($value - 0.5);
  1511. if (($mode == PS_ROUND_HALF_DOWN && $value == (0.5 + $tmp_value )) ||
  1512. ($mode == PS_ROUND_HALF_EVEN && $value == (-0.5 + 2 * ceil($tmp_value /2.0))) ||
  1513. ($mode == PS_ROUND_HALF_ODD && $value == (-0.5 + 2 * ceil($tmp_value /2.0) + 1.0)))
  1514. $tmp_value = $tmp_value + 1.0;
  1515. }
  1516. return $tmp_value;
  1517. }
  1518. /**
  1519. * returns the rounded value down of $value to specified precision
  1520. *
  1521. * @param float $value
  1522. * @param int $precision
  1523. * @return float
  1524. */
  1525. public static function ceilf($value, $precision = 0)
  1526. {
  1527. $precision_factor = $precision == 0 ? 1 : pow(10, $precision);
  1528. $tmp = $value * $precision_factor;
  1529. $tmp2 = (string)$tmp;
  1530. // If the current value has already the desired precision
  1531. if (strpos($tmp2, '.') === false)
  1532. return ($value);
  1533. if ($tmp2[strlen($tmp2) - 1] == 0)
  1534. return $value;
  1535. return ceil($tmp) / $precision_factor;
  1536. }
  1537. /**
  1538. * returns the rounded value up of $value to specified precision
  1539. *
  1540. * @param float $value
  1541. * @param int $precision
  1542. * @return float
  1543. */
  1544. public static function floorf($value, $precision = 0)
  1545. {
  1546. $precision_factor = $precision == 0 ? 1 : pow(10, $precision);
  1547. $tmp = $value * $precision_factor;
  1548. $tmp2 = (string)$tmp;
  1549. // If the current value has already the desired precision
  1550. if (strpos($tmp2, '.') === false)
  1551. return ($value);
  1552. if ($tmp2[strlen($tmp2) - 1] == 0)
  1553. return $value;
  1554. return floor($tmp) / $precision_factor;
  1555. }
  1556. /**
  1557. * file_exists() wrapper with cache to speedup performance
  1558. *
  1559. * @param string $filename File name
  1560. * @return boolean Cached result of file_exists($filename)
  1561. */
  1562. public static function file_exists_cache($filename)
  1563. {
  1564. if (!isset(self::$file_exists_cache[$filename]))
  1565. self::$file_exists_cache[$filename] = file_exists($filename);
  1566. return self::$file_exists_cache[$filename];
  1567. }
  1568. /**
  1569. * file_exists() wrapper with a call to clearstatcache prior
  1570. *
  1571. * @param string $filename File name
  1572. * @return boolean Cached result of file_exists($filename)
  1573. */
  1574. public static function file_exists_no_cache($filename)
  1575. {
  1576. clearstatcache();
  1577. return file_exists($filename);
  1578. }
  1579. public static function file_get_contents($url, $use_include_path = false, $stream_context = null, $curl_timeout = 5)
  1580. {
  1581. if ($stream_context == null && preg_match('/^https?:\/\//', $url))
  1582. $stream_context = @stream_context_create(array('http' => array('timeout' => $curl_timeout)));
  1583. if (in_array(ini_get('allow_url_fopen'), array('On', 'on', '1')) || !preg_match('/^https?:\/\//', $url))
  1584. return @file_get_contents($url, $use_include_path, $stream_context);
  1585. elseif (function_exists('curl_init'))
  1586. {
  1587. $curl = curl_init();
  1588. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1589. curl_setopt($curl, CURLOPT_URL, $url);
  1590. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
  1591. curl_setopt($curl, CURLOPT_TIMEOUT, $curl_timeout);
  1592. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  1593. if ($stream_context != null) {
  1594. $opts = stream_context_get_options($stream_context);
  1595. if (isset($opts['http']['method']) && Tools::strtolower($opts['http']['method']) == 'post')
  1596. {
  1597. curl_setopt($curl, CURLOPT_POST, true);
  1598. if (isset($opts['http']['content']))
  1599. {
  1600. parse_str($opts['http']['content'], $datas);
  1601. curl_setopt($curl, CURLOPT_POSTFIELDS, $datas);
  1602. }
  1603. }
  1604. }
  1605. $content = curl_exec($curl);
  1606. curl_close($curl);
  1607. return $content;
  1608. }
  1609. else
  1610. return false;
  1611. }
  1612. public static function simplexml_load_file($url, $class_name = null)
  1613. {
  1614. return @simplexml_load_string(Tools::file_get_contents($url), $class_name);
  1615. }
  1616. public static function copy($source, $destination, $stream_context = null)
  1617. {
  1618. if (is_null($stream_context) && !preg_match('/^https?:\/\//', $source))
  1619. return @copy($source, $destination);
  1620. return @file_put_contents($destination, Tools::file_get_contents($source, false, $stream_context));
  1621. }
  1622. /**
  1623. * @deprecated as of 1.5 use Media::minifyHTML()
  1624. */
  1625. public static function minifyHTML($html_content)
  1626. {
  1627. Tools::displayAsDeprecated();
  1628. return Media::minifyHTML($html_content);
  1629. }
  1630. /**
  1631. * Translates a string with underscores into camel case (e.g. first_name -> firstName)
  1632. * @prototype string public static function toCamelCase(string $str[, bool $capitalise_first_char = false])
  1633. */
  1634. public static function toCamelCase($str, $catapitalise_first_char = false)
  1635. {
  1636. $str = Tools::strtolower($str);
  1637. if ($catapitalise_first_char)
  1638. $str = Tools::ucfirst($str);
  1639. return preg_replace_callback('/_+([a-z])/', create_function('$c', 'return strtoupper($c[1]);'), $str);
  1640. }
  1641. /**
  1642. * Transform a CamelCase string to underscore_case string
  1643. *
  1644. * @param string $string
  1645. * @return string
  1646. */
  1647. public static function toUnderscoreCase($string)
  1648. {
  1649. // 'CMSCategories' => 'cms_categories'
  1650. // 'RangePrice' => 'range_price'
  1651. return Tools::strtolower(trim(preg_replace('/([A-Z][a-z])/', '_$1', $string), '_'));
  1652. }
  1653. public static function getBrightness($hex)
  1654. {
  1655. $hex = str_replace('#', '', $hex);
  1656. $r = hexdec(substr($hex, 0, 2));
  1657. $g = hexdec(substr($hex, 2, 2));
  1658. $b = hexdec(substr($hex, 4, 2));
  1659. return (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
  1660. }
  1661. /**
  1662. * @deprecated as of 1.5 use Media::minifyHTMLpregCallback()
  1663. */
  1664. public static function minifyHTMLpregCallback($preg_matches)
  1665. {
  1666. Tools::displayAsDeprecated();
  1667. return Media::minifyHTMLpregCallback($preg_matches);
  1668. }
  1669. /**
  1670. * @deprecated as of 1.5 use Media::packJSinHTML()
  1671. */
  1672. public static function packJSinHTML($html_content)
  1673. {
  1674. Tools::displayAsDeprecated();
  1675. return Media::packJSinHTML($html_content);
  1676. }
  1677. /**
  1678. * @deprecated as of 1.5 use Media::packJSinHTMLpregCallback()
  1679. */
  1680. public static function packJSinHTMLpregCallback($preg_matches)
  1681. {
  1682. Tools::displayAsDeprecated();
  1683. return Media::packJSinHTMLpregCallback($preg_matches);
  1684. }
  1685. /**
  1686. * @deprecated as of 1.5 use Media::packJS()
  1687. */
  1688. public static function packJS($js_content)
  1689. {
  1690. Tools::displayAsDeprecated();
  1691. return Media::packJS($js_content);
  1692. }
  1693. public static function parserSQL($sql)
  1694. {
  1695. if (strlen($sql) > 0)
  1696. {
  1697. require_once(_PS_TOOL_DIR_.'parser_sql/PHPSQLParser.php');
  1698. $parser = new PHPSQLParser($sql);
  1699. return $parser->parsed;
  1700. }
  1701. return false;
  1702. }
  1703. /**
  1704. * @deprecated as of 1.5 use Media::minifyCSS()
  1705. */
  1706. public static function minifyCSS($css_content, $fileuri = false)
  1707. {
  1708. Tools::displayAsDeprecated();
  1709. return Media::minifyCSS($css_content, $fileuri);
  1710. }
  1711. public static function replaceByAbsoluteURL($matches)
  1712. {
  1713. global $current_css_file;
  1714. $protocol_link = Tools::getCurrentUrlProtocolPrefix();
  1715. if (array_key_exists(1, $matches) && array_key_exists(2, $matches))
  1716. {
  1717. if (!preg_match('/^(?:https?:)?\/\//iUs', $matches[2]))
  1718. {
  1719. $tmp = dirname($current_css_file).'/'.$matches[2];
  1720. return $matches[1].$protocol_link.Tools::getMediaServer($tmp).$tmp;
  1721. }
  1722. else
  1723. return $matches[0];
  1724. }
  1725. return false;
  1726. }
  1727. /**
  1728. * addJS load a javascript file in the header
  1729. *
  1730. * @deprecated as of 1.5 use FrontController->addJS()
  1731. * @param mixed $js_uri
  1732. * @return void
  1733. */
  1734. public static function addJS($js_uri)
  1735. {
  1736. Tools::displayAsDeprecated();
  1737. $context = Context::getContext();
  1738. $context->controller->addJs($js_uri);
  1739. }
  1740. /**
  1741. * @deprecated as of 1.5 use FrontController->addCSS()
  1742. */
  1743. public static function addCSS($css_uri, $css_media_type = 'all')
  1744. {
  1745. Tools::displayAsDeprecated();
  1746. $context = Context::getContext();
  1747. $context->controller->addCSS($css_uri, $css_media_type);
  1748. }
  1749. /**
  1750. * @deprecated as of 1.5 use Media::cccCss()
  1751. */
  1752. public static function cccCss($css_files)
  1753. {
  1754. Tools::displayAsDeprecated();
  1755. return Media::cccCss($css_files);
  1756. }
  1757. /**
  1758. * @deprecated as of 1.5 use Media::cccJS()
  1759. */
  1760. public static function cccJS($js_files)
  1761. {
  1762. Tools::displayAsDeprecated();
  1763. return Media::cccJS($js_files);
  1764. }
  1765. protected static $_cache_nb_media_servers = null;
  1766. public static function getMediaServer($filename)
  1767. {
  1768. if (self::$_cache_nb_media_servers === null && defined('_MEDIA_SERVER_1_') && defined('_MEDIA_SERVER_2_') && defined('_MEDIA_SERVER_3_'))
  1769. {
  1770. if (_MEDIA_SERVER_1_ == '')
  1771. self::$_cache_nb_media_servers = 0;
  1772. elseif (_MEDIA_SERVER_2_ == '')
  1773. self::$_cache_nb_media_servers = 1;
  1774. elseif (_MEDIA_SERVER_3_ == '')
  1775. self::$_cache_nb_media_servers = 2;
  1776. else
  1777. self::$_cache_nb_media_servers = 3;
  1778. }
  1779. if (self::$_cache_nb_media_servers && ($id_media_server = (abs(crc32($filename)) % self::$_cache_nb_media_servers + 1)))
  1780. return constant('_MEDIA_SERVER_'.$id_media_server.'_');
  1781. return Tools::usingSecureMode() ? Tools::getShopDomainSSL() : Tools::getShopDomain();
  1782. }
  1783. public static function generateHtaccess($path = null, $rewrite_settings = null, $cache_control = null, $specific = '', $disable_multiviews = null, $medias = false, $disable_modsec = null)
  1784. {
  1785. if (defined('PS_INSTALLATION_IN_PROGRESS') && $rewrite_settings === null)
  1786. return true;
  1787. // Default values for parameters
  1788. if (is_null($path))
  1789. $path = _PS_ROOT_DIR_.'/.htaccess';
  1790. if (is_null($cache_control))
  1791. $cache_control = (int)Configuration::get('PS_HTACCESS_CACHE_CONTROL');
  1792. if (is_null($disable_multiviews))
  1793. $disable_multiviews = (int)Configuration::get('PS_HTACCESS_DISABLE_MULTIVIEWS');
  1794. if ($disable_modsec === null)
  1795. $disable_modsec = (int)Configuration::get('PS_HTACCESS_DISABLE_MODSEC');
  1796. // Check current content of .htaccess and save all code outside of prestashop comments
  1797. $specific_before = $specific_after = '';
  1798. if (file_exists($path))
  1799. {
  1800. $content = file_get_contents($path);
  1801. if (preg_match('#^(.*)\# ~~start~~.*\# ~~end~~[^\n]*(.*)$#s', $content, $m))
  1802. {
  1803. $specific_before = $m[1];
  1804. $specific_after = $m[2];
  1805. }
  1806. else
  1807. {
  1808. // For retrocompatibility
  1809. if (preg_match('#\# http://www\.prestashop\.com - http://www\.prestashop\.com/forums\s*(.*)<IfModule mod_rewrite\.c>#si', $content, $m))
  1810. $specific_before = $m[1];
  1811. else
  1812. $specific_before = $content;
  1813. }
  1814. }
  1815. // Write .htaccess data
  1816. if (!$write_fd = @fopen($path, 'w'))
  1817. return false;
  1818. if ($specific_before)
  1819. fwrite($write_fd, trim($specific_before)."\n\n");
  1820. $domains = array();
  1821. foreach (ShopUrl::getShopUrls() as $shop_url)
  1822. {
  1823. if (!isset($domains[$shop_url->domain]))
  1824. $domains[$shop_url->domain] = array();
  1825. $domains[$shop_url->domain][] = array(
  1826. 'physical' => $shop_url->physical_uri,
  1827. 'virtual' => $shop_url->virtual_uri,
  1828. 'id_shop' => $shop_url->id_shop
  1829. );
  1830. if ($shop_url->domain == $shop_url->domain_ssl)
  1831. continue;
  1832. if (!isset($domains[$shop_url->domain_ssl]))
  1833. $domains[$shop_url->domain_ssl] = array();
  1834. $domains[$shop_url->domain_ssl][] = array(
  1835. 'physical' => $shop_url->physical_uri,
  1836. 'virtual' => $shop_url->virtual_uri,
  1837. 'id_shop' => $shop_url->id_shop
  1838. );
  1839. }
  1840. // Write data in .htaccess file
  1841. fwrite($write_fd, "# ~~start~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again\n");
  1842. fwrite($write_fd, "# .htaccess automaticaly generated by PrestaShop e-commerce open-source solution\n");
  1843. fwrite($write_fd, "# http://www.prestashop.com - http://www.prestashop.com/forums\n\n");
  1844. if ($disable_modsec)
  1845. fwrite($write_fd, "<IfModule mod_security.c>\nSecFilterEngine Off\nSecFilterScanPOST Off\n</IfModule>\n\n");
  1846. // RewriteEngine
  1847. fwrite($write_fd, "<IfModule mod_rewrite.c>\n");
  1848. // Ensure HTTP_MOD_REWRITE variable is set in environment
  1849. fwrite($write_fd, "<IfModule mod_env.c>\n");
  1850. fwrite($write_fd, "SetEnv HTTP_MOD_REWRITE On\n");
  1851. fwrite($write_fd, "</IfModule>\n\n");
  1852. // Disable multiviews ?
  1853. if ($disable_multiviews)
  1854. fwrite($write_fd, "\n# Disable Multiviews\nOptions -Multiviews\n\n");
  1855. fwrite($write_fd, "RewriteEngine on\n");
  1856. if (!$medias && defined('_MEDIA_SERVER_1_') && defined('_MEDIA_SERVER_2_') && defined('_MEDIA_SERVER_3_'))
  1857. $medias = array(_MEDIA_SERVER_1_, _MEDIA_SERVER_2_, _MEDIA_SERVER_3_);
  1858. $media_domains = '';
  1859. if ($medias[0] != '')
  1860. $media_domains = 'RewriteCond %{HTTP_HOST} ^'.$medias[0].'$ [OR]'."\n";
  1861. if ($medias[1] != '')
  1862. $media_domains .= 'RewriteCond %{HTTP_HOST} ^'.$medias[1].'$ [OR]'."\n";
  1863. if ($medias[2] != '')
  1864. $media_domains .= 'RewriteCond %{HTTP_HOST} ^'.$medias[2].'$ [OR]'."\n";
  1865. if (Configuration::get('PS_WEBSERVICE_CGI_HOST'))
  1866. fwrite($write_fd, "RewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule . - [E=HTTP_AUTHORIZATION:%1]\n\n");
  1867. foreach ($domains as $domain => $list_uri)
  1868. {
  1869. $physicals = array();
  1870. foreach ($list_uri as $uri)
  1871. {
  1872. fwrite($write_fd, PHP_EOL.PHP_EOL.'#Domain: '.$domain.PHP_EOL);
  1873. if (Shop::isFeatureActive())
  1874. fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^'.$domain.'$'."\n");
  1875. fwrite($write_fd, 'RewriteRule . - [E=REWRITEBASE:'.$uri['physical'].']'."\n");
  1876. // Webservice
  1877. fwrite($write_fd, 'RewriteRule ^api$ api/ [L]'."\n\n");
  1878. fwrite($write_fd, 'RewriteRule ^api/(.*)$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]'."\n\n");
  1879. if (!$rewrite_settings)
  1880. $rewrite_settings = (int)Configuration::get('PS_REWRITING_SETTINGS', null, null, (int)$uri['id_shop']);
  1881. $domain_rewrite_cond = 'RewriteCond %{HTTP_HOST} ^'.$domain.'$'."\n";
  1882. // Rewrite virtual multishop uri
  1883. if ($uri['virtual'])
  1884. {
  1885. if (!$rewrite_settings)
  1886. {
  1887. fwrite($write_fd, $media_domains);
  1888. if (Shop::isFeatureActive())
  1889. fwrite($write_fd, $domain_rewrite_cond);
  1890. fwrite($write_fd, 'RewriteRule ^'.trim($uri['virtual'], '/').'/?$ '.$uri['physical'].$uri['virtual']."index.php [L,R]\n");
  1891. }
  1892. else
  1893. {
  1894. fwrite($write_fd, $media_domains);
  1895. if (Shop::isFeatureActive())
  1896. fwrite($write_fd, $domain_rewrite_cond);
  1897. fwrite($write_fd, 'RewriteRule ^'.trim($uri['virtual'], '/').'$ '.$uri['physical'].$uri['virtual']." [L,R]\n");
  1898. }
  1899. fwrite($write_fd, $media_domains);
  1900. if (Shop::isFeatureActive())
  1901. fwrite($write_fd, $domain_rewrite_cond);
  1902. fwrite($write_fd, 'RewriteRule ^'.ltrim($uri['virtual'], '/').'(.*) '.$uri['physical']."$1 [L]\n\n");
  1903. }
  1904. if ($rewrite_settings)
  1905. {
  1906. // Compatibility with the old image filesystem
  1907. fwrite($write_fd, "# Images\n");
  1908. if (Configuration::get('PS_LEGACY_IMAGES'))
  1909. {
  1910. fwrite($write_fd, $media_domains);
  1911. if (Shop::isFeatureActive())
  1912. fwrite($write_fd, $domain_rewrite_cond);
  1913. fwrite($write_fd, 'RewriteRule ^([a-z0-9]+)\-([a-z0-9]+)(\-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1-$2$3$4.jpg [L]'."\n");
  1914. fwrite($write_fd, $media_domains);
  1915. if (Shop::isFeatureActive())
  1916. fwrite($write_fd, $domain_rewrite_cond);
  1917. fwrite($write_fd, 'RewriteRule ^([0-9]+)\-([0-9]+)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1-$2$3.jpg [L]'."\n");
  1918. }
  1919. // Rewrite product images < 100 millions
  1920. for ($i = 1; $i <= 8; $i++)
  1921. {
  1922. $img_path = $img_name = '';
  1923. for ($j = 1; $j <= $i; $j++)
  1924. {
  1925. $img_path .= '$'.$j.'/';
  1926. $img_name .= '$'.$j;
  1927. }
  1928. $img_name .= '$'.$j;
  1929. fwrite($write_fd, $media_domains);
  1930. if (Shop::isFeatureActive())
  1931. fwrite($write_fd, $domain_rewrite_cond);
  1932. fwrite($write_fd, 'RewriteRule ^'.str_repeat('([0-9])', $i).'(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/'.$img_path.$img_name.'$'.($j + 1).".jpg [L]\n");
  1933. }
  1934. fwrite($write_fd, $media_domains);
  1935. if (Shop::isFeatureActive())
  1936. fwrite($write_fd, $domain_rewrite_cond);
  1937. fwrite($write_fd, 'RewriteRule ^c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2$3.jpg [L]'."\n");
  1938. fwrite($write_fd, $media_domains);
  1939. if (Shop::isFeatureActive())
  1940. fwrite($write_fd, $domain_rewrite_cond);
  1941. fwrite($write_fd, 'RewriteRule ^c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2.jpg [L]'."\n");
  1942. }
  1943. fwrite($write_fd, "# AlphaImageLoader for IE and fancybox\n");
  1944. if (Shop::isFeatureActive())
  1945. fwrite($write_fd, $domain_rewrite_cond);
  1946. fwrite($write_fd, 'RewriteRule ^images_ie/?([^/]+)\.(jpe?g|png|gif)$ js/jquery/plugins/fancybox/images/$1.$2 [L]'."\n");
  1947. }
  1948. // Redirections to dispatcher
  1949. if ($rewrite_settings)
  1950. {
  1951. fwrite($write_fd, "\n# Dispatcher\n");
  1952. fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -s [OR]\n");
  1953. fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -l [OR]\n");
  1954. fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -d\n");
  1955. if (Shop::isFeatureActive())
  1956. fwrite($write_fd, $domain_rewrite_cond);
  1957. fwrite($write_fd, "RewriteRule ^.*$ - [NC,L]\n");
  1958. if (Shop::isFeatureActive())
  1959. fwrite($write_fd, $domain_rewrite_cond);
  1960. fwrite($write_fd, "RewriteRule ^.*\$ %{ENV:REWRITEBASE}index.php [NC,L]\n");
  1961. }
  1962. }
  1963. fwrite($write_fd, "</IfModule>\n\n");
  1964. fwrite($write_fd, "AddType application/vnd.ms-fontobject .eot\n");
  1965. fwrite($write_fd, "AddType font/ttf .ttf\n");
  1966. fwrite($write_fd, "AddType font/otf .otf\n");
  1967. fwrite($write_fd, "AddType application/x-font-woff .woff\n\n");
  1968. // Cache control
  1969. if ($cache_control)
  1970. {
  1971. $cache_control = "<IfModule mod_expires.c>
  1972. ExpiresActive On
  1973. ExpiresByType image/gif \"access plus 1 month\"
  1974. ExpiresByType image/jpeg \"access plus 1 month\"
  1975. ExpiresByType image/png \"access plus 1 month\"
  1976. ExpiresByType text/css \"access plus 1 week\"
  1977. ExpiresByType text/javascript \"access plus 1 week\"
  1978. ExpiresByType application/javascript \"access plus 1 week\"
  1979. ExpiresByType application/x-javascript \"access plus 1 week\"
  1980. ExpiresByType image/x-icon \"access plus 1 year\"
  1981. ExpiresByType image/svg+xml \"access plus 1 year\"
  1982. ExpiresByType image/vnd.microsoft.icon \"access plus 1 year\"
  1983. ExpiresByType application/font-woff \"access plus 1 year\"
  1984. ExpiresByType application/x-font-woff \"access plus 1 year\"
  1985. ExpiresByType application/vnd.ms-fontobject \"access plus 1 year\"
  1986. ExpiresByType font/opentype \"access plus 1 year\"
  1987. ExpiresByType font/ttf \"access plus 1 year\"
  1988. ExpiresByType font/otf \"access plus 1 year\"
  1989. ExpiresByType application/x-font-ttf \"access plus 1 year\"
  1990. ExpiresByType application/x-font-otf \"access plus 1 year\"
  1991. </IfModule>
  1992. <IfModule mod_headers.c>
  1993. Header unset Etag
  1994. </IfModule>
  1995. FileETag none
  1996. <IfModule mod_deflate.c>
  1997. <IfModule mod_filter.c>
  1998. AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/x-javascript font/ttf application/x-font-ttf font/otf application/x-font-otf font/opentype
  1999. </IfModule>
  2000. </IfModule>\n\n";
  2001. fwrite($write_fd, $cache_control);
  2002. }
  2003. // In case the user hasn't rewrite mod enabled
  2004. fwrite($write_fd, "#If rewrite mod isn't enabled\n");
  2005. // Do not remove ($domains is already iterated upper)
  2006. reset($domains);
  2007. $domain = current($domains);
  2008. fwrite($write_fd, 'ErrorDocument 404 '.$domain[0]['physical']."index.php?controller=404\n\n");
  2009. fwrite($write_fd, "# ~~end~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again");
  2010. if ($specific_after)
  2011. fwrite($write_fd, "\n\n".trim($specific_after));
  2012. fclose($write_fd);
  2013. if (!defined('PS_INSTALLATION_IN_PROGRESS'))
  2014. Hook::exec('actionHtaccessCreate');
  2015. return true;
  2016. }
  2017. public static function generateIndex()
  2018. {
  2019. if (defined('_DB_PREFIX_') && Configuration::get('PS_DISABLE_OVERRIDES'))
  2020. PrestaShopAutoload::getInstance()->_include_override_path = false;
  2021. PrestaShopAutoload::getInstance()->generateIndex();
  2022. }
  2023. public static function getDefaultIndexContent()
  2024. {
  2025. return '<?php
  2026. /**
  2027. * 2007-'.date('Y').' PrestaShop
  2028. *
  2029. * NOTICE OF LICENSE
  2030. *
  2031. * This source file is subject to the Open Software License (OSL 3.0)
  2032. * that is bundled with this package in the file LICENSE.txt.
  2033. * It is also available through the world-wide-web at this URL:
  2034. * http://opensource.org/licenses/osl-3.0.php
  2035. * If you did not receive a copy of the license and are unable to
  2036. * obtain it through the world-wide-web, please send an email
  2037. * to license@prestashop.com so we can send you a copy immediately.
  2038. *
  2039. * DISCLAIMER
  2040. *
  2041. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  2042. * versions in the future. If you wish to customize PrestaShop for your
  2043. * needs please refer to http://www.prestashop.com for more information.
  2044. *
  2045. * @author PrestaShop SA <contact@prestashop.com>
  2046. * @copyright 2007-'.date('Y').' PrestaShop SA
  2047. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  2048. * International Registered Trademark & Property of PrestaShop SA
  2049. */
  2050. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  2051. header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  2052. header("Cache-Control: no-store, no-cache, must-revalidate");
  2053. header("Cache-Control: post-check=0, pre-check=0", false);
  2054. header("Pragma: no-cache");
  2055. header("Location: ../");
  2056. exit;
  2057. ';
  2058. }
  2059. /**
  2060. * jsonDecode convert json string to php array / object
  2061. *
  2062. * @param string $json
  2063. * @param boolean $assoc (since 1.4.2.4) if true, convert to associativ array
  2064. * @return array
  2065. */
  2066. public static function jsonDecode($json, $assoc = false)
  2067. {
  2068. if (function_exists('json_decode'))
  2069. return json_decode($json, $assoc);
  2070. else
  2071. {
  2072. include_once(_PS_TOOL_DIR_.'json/json.php');
  2073. $pear_json = new Services_JSON(($assoc) ? SERVICES_JSON_LOOSE_TYPE : 0);
  2074. return $pear_json->decode($json);
  2075. }
  2076. }
  2077. /**
  2078. * Convert an array to json string
  2079. *
  2080. * @param array $data
  2081. * @return string json
  2082. */
  2083. public static function jsonEncode($data)
  2084. {
  2085. if (function_exists('json_encode'))
  2086. return json_encode($data);
  2087. else
  2088. {
  2089. include_once(_PS_TOOL_DIR_.'json/json.php');
  2090. $pear_json = new Services_JSON();
  2091. return $pear_json->encode($data);
  2092. }
  2093. }
  2094. /**
  2095. * Display a warning message indicating that the method is deprecated
  2096. */
  2097. public static function displayAsDeprecated($message = null)
  2098. {
  2099. $backtrace = debug_backtrace();
  2100. $callee = next($backtrace);
  2101. $class = isset($callee['class']) ? $callee['class'] : null;
  2102. if ($message === null)
  2103. $message = 'The function '.$callee['function'].' (Line '.$callee['line'].') is deprecated and will be removed in the next major version.';
  2104. $error = 'Function <b>'.$callee['function'].'()</b> is deprecated in <b>'.$callee['file'].'</b> on line <b>'.$callee['line'].'</b><br />';
  2105. Tools::throwDeprecated($error, $message, $class);
  2106. }
  2107. /**
  2108. * Display a warning message indicating that the parameter is deprecated
  2109. */
  2110. public static function displayParameterAsDeprecated($parameter)
  2111. {
  2112. $backtrace = debug_backtrace();
  2113. $callee = next($backtrace);
  2114. $error = 'Parameter <b>'.$parameter.'</b> in function <b>'.(isset($callee['function']) ? $callee['function'] : '').'()</b> is deprecated in <b>'.$callee['file'].'</b> on line <b>'.(isset($callee['line']) ? $callee['line'] : '(undefined)').'</b><br />';
  2115. $message = 'The parameter '.$parameter.' in function '.$callee['function'].' (Line '.(isset($callee['line']) ? $callee['line'] : 'undefined').') is deprecated and will be removed in the next major version.';
  2116. $class = isset($callee['class']) ? $callee['class'] : null;
  2117. Tools::throwDeprecated($error, $message, $class);
  2118. }
  2119. public static function displayFileAsDeprecated()
  2120. {
  2121. $backtrace = debug_backtrace();
  2122. $callee = current($backtrace);
  2123. $error = 'File <b>'.$callee['file'].'</b> is deprecated<br />';
  2124. $message = 'The file '.$callee['file'].' is deprecated and will be removed in the next major version.';
  2125. $class = isset($callee['class']) ? $callee['class'] : null;
  2126. Tools::throwDeprecated($error, $message, $class);
  2127. }
  2128. protected static function throwDeprecated($error, $message, $class)
  2129. {
  2130. if (_PS_DISPLAY_COMPATIBILITY_WARNING_)
  2131. {
  2132. trigger_error($error, E_USER_WARNING);
  2133. PrestaShopLogger::addLog($message, 3, $class);
  2134. }
  2135. }
  2136. public static function enableCache($level = 1, Context $context = null)
  2137. {
  2138. if (!$context)
  2139. $context = Context::getContext();
  2140. $smarty = $context->smarty;
  2141. if (!Configuration::get('PS_SMARTY_CACHE'))
  2142. return;
  2143. if ($smarty->force_compile == 0 && $smarty->caching == $level)
  2144. return;
  2145. self::$_forceCompile = (int)$smarty->force_compile;
  2146. self::$_caching = (int)$smarty->caching;
  2147. $smarty->force_compile = 0;
  2148. $smarty->caching = (int)$level;
  2149. $smarty->cache_lifetime = 31536000; // 1 Year
  2150. }
  2151. public static function restoreCacheSettings(Context $context = null)
  2152. {
  2153. if (!$context)
  2154. $context = Context::getContext();
  2155. if (isset(self::$_forceCompile))
  2156. $context->smarty->force_compile = (int)self::$_forceCompile;
  2157. if (isset(self::$_caching))
  2158. $context->smarty->caching = (int)self::$_caching;
  2159. }
  2160. public static function isCallable($function)
  2161. {
  2162. $disabled = explode(',', ini_get('disable_functions'));
  2163. return (!in_array($function, $disabled) && is_callable($function));
  2164. }
  2165. public static function pRegexp($s, $delim)
  2166. {
  2167. $s = str_replace($delim, '\\'.$delim, $s);
  2168. foreach (array('?', '[', ']', '(', ')', '{', '}', '-', '.', '+', '*', '^', '$', '`', '"', '%') as $char)
  2169. $s = str_replace($char, '\\'.$char, $s);
  2170. return $s;
  2171. }
  2172. public static function str_replace_once($needle, $replace, $haystack)
  2173. {
  2174. $pos = false;
  2175. if ($needle)
  2176. $pos = strpos($haystack, $needle);
  2177. if ($pos === false)
  2178. return $haystack;
  2179. return substr_replace($haystack, $replace, $pos, strlen($needle));
  2180. }
  2181. /**
  2182. * Function property_exists does not exist in PHP < 5.1
  2183. *
  2184. * @deprecated since 1.5.0 (PHP 5.1 required, so property_exists() is now natively supported)
  2185. * @param object or class $class
  2186. * @param string $property
  2187. * @return boolean
  2188. */
  2189. public static function property_exists($class, $property)
  2190. {
  2191. Tools::displayAsDeprecated();
  2192. if (function_exists('property_exists'))
  2193. return property_exists($class, $property);
  2194. if (is_object($class))
  2195. $vars = get_object_vars($class);
  2196. else
  2197. $vars = get_class_vars($class);
  2198. return array_key_exists($property, $vars);
  2199. }
  2200. /**
  2201. * @desc identify the version of php
  2202. * @return string
  2203. */
  2204. public static function checkPhpVersion()
  2205. {
  2206. $version = null;
  2207. if (defined('PHP_VERSION'))
  2208. $version = PHP_VERSION;
  2209. else
  2210. $version = phpversion('');
  2211. //Case management system of ubuntu, php version return 5.2.4-2ubuntu5.2
  2212. if (strpos($version, '-') !== false)
  2213. $version = substr($version, 0, strpos($version, '-'));
  2214. return $version;
  2215. }
  2216. /**
  2217. * @desc try to open a zip file in order to check if it's valid
  2218. * @return bool success
  2219. */
  2220. public static function ZipTest($from_file)
  2221. {
  2222. if (class_exists('ZipArchive', false))
  2223. {
  2224. $zip = new ZipArchive();
  2225. return ($zip->open($from_file, ZIPARCHIVE::CHECKCONS) === true);
  2226. }
  2227. else
  2228. {
  2229. require_once(_PS_ROOT_DIR_.'/tools/pclzip/pclzip.lib.php');
  2230. $zip = new PclZip($from_file);
  2231. return ($zip->privCheckFormat() === true);
  2232. }
  2233. }
  2234. public static function getSafeModeStatus()
  2235. {
  2236. if (!$safe_mode = @ini_get('safe_mode'))
  2237. $safe_mode = '';
  2238. return in_array(Tools::strtolower($safe_mode), array(1, 'on'));
  2239. }
  2240. /**
  2241. * @desc extract a zip file to the given directory
  2242. * @return bool success
  2243. */
  2244. public static function ZipExtract($from_file, $to_dir)
  2245. {
  2246. if (!file_exists($to_dir))
  2247. mkdir($to_dir, 0777);
  2248. if (class_exists('ZipArchive', false))
  2249. {
  2250. $zip = new ZipArchive();
  2251. if ($zip->open($from_file) === true && $zip->extractTo($to_dir) && $zip->close())
  2252. return true;
  2253. return false;
  2254. }
  2255. else
  2256. {
  2257. require_once(_PS_ROOT_DIR_.'/tools/pclzip/pclzip.lib.php');
  2258. $zip = new PclZip($from_file);
  2259. $list = $zip->extract(PCLZIP_OPT_PATH, $to_dir, PCLZIP_OPT_REPLACE_NEWER);
  2260. foreach ($list as $file)
  2261. if ($file['status'] != 'ok' && $file['status'] != 'already_a_directory')
  2262. return false;
  2263. return true;
  2264. }
  2265. }
  2266. public static function chmodr($path, $filemode)
  2267. {
  2268. if (!is_dir($path))
  2269. return @chmod($path, $filemode);
  2270. $dh = opendir($path);
  2271. while (($file = readdir($dh)) !== false)
  2272. {
  2273. if ($file != '.' && $file != '..')
  2274. {
  2275. $fullpath = $path.'/'.$file;
  2276. if (is_link($fullpath))
  2277. return false;
  2278. elseif (!is_dir($fullpath) && !@chmod($fullpath, $filemode))
  2279. return false;
  2280. elseif (!Tools::chmodr($fullpath, $filemode))
  2281. return false;
  2282. }
  2283. }
  2284. closedir($dh);
  2285. if (@chmod($path, $filemode))
  2286. return true;
  2287. else
  2288. return false;
  2289. }
  2290. /**
  2291. * Get products order field name for queries.
  2292. *
  2293. * @param string $type by|way
  2294. * @param string $value If no index given, use default order from admin -> pref -> products
  2295. * @param bool|\bool(false)|string $prefix
  2296. *
  2297. * @return string Order by sql clause
  2298. */
  2299. public static function getProductsOrder($type, $value = null, $prefix = false)
  2300. {
  2301. switch ($type)
  2302. {
  2303. case 'by' :
  2304. $list = array(0 => 'name', 1 => 'price', 2 => 'date_add', 3 => 'date_upd', 4 => 'position', 5 => 'manufacturer_name', 6 => 'quantity');
  2305. $value = (is_null($value) || $value === false || $value === '') ? (int)Configuration::get('PS_PRODUCTS_ORDER_BY') : $value;
  2306. $value = (isset($list[$value])) ? $list[$value] : ((in_array($value, $list)) ? $value : 'position');
  2307. $order_by_prefix = '';
  2308. if ($prefix)
  2309. {
  2310. if ($value == 'id_product' || $value == 'date_add' || $value == 'date_upd' || $value == 'price')
  2311. $order_by_prefix = 'p.';
  2312. elseif ($value == 'name')
  2313. $order_by_prefix = 'pl.';
  2314. elseif ($value == 'manufacturer_name' && $prefix)
  2315. {
  2316. $order_by_prefix = 'm.';
  2317. $value = 'name';
  2318. }
  2319. elseif ($value == 'position' || empty($value))
  2320. $order_by_prefix = 'cp.';
  2321. }
  2322. return $order_by_prefix.$value;
  2323. break;
  2324. case 'way' :
  2325. $value = (is_null($value) || $value === false || $value === '') ? (int)Configuration::get('PS_PRODUCTS_ORDER_WAY') : $value;
  2326. $list = array(0 => 'asc', 1 => 'desc');
  2327. return ((isset($list[$value])) ? $list[$value] : ((in_array($value, $list)) ? $value : 'asc'));
  2328. break;
  2329. }
  2330. }
  2331. /**
  2332. * Convert a shorthand byte value from a PHP configuration directive to an integer value
  2333. * @param string $value value to convert
  2334. * @return int
  2335. */
  2336. public static function convertBytes($value)
  2337. {
  2338. if (is_numeric($value))
  2339. return $value;
  2340. else
  2341. {
  2342. $value_length = strlen($value);
  2343. $qty = (int)substr($value, 0, $value_length - 1 );
  2344. $unit = Tools::strtolower(substr($value, $value_length - 1));
  2345. switch ($unit)
  2346. {
  2347. case 'k':
  2348. $qty *= 1024;
  2349. break;
  2350. case 'm':
  2351. $qty *= 1048576;
  2352. break;
  2353. case 'g':
  2354. $qty *= 1073741824;
  2355. break;
  2356. }
  2357. return $qty;
  2358. }
  2359. }
  2360. /**
  2361. * @deprecated as of 1.5 use Controller::getController('PageNotFoundController')->run();
  2362. */
  2363. public static function display404Error()
  2364. {
  2365. header('HTTP/1.1 404 Not Found');
  2366. header('Status: 404 Not Found');
  2367. include(dirname(__FILE__).'/../404.php');
  2368. die;
  2369. }
  2370. /**
  2371. * Concat $begin and $end, add ? or & between strings
  2372. *
  2373. * @since 1.5.0
  2374. * @param string $begin
  2375. * @param string $end
  2376. * @return string
  2377. */
  2378. public static function url($begin, $end)
  2379. {
  2380. return $begin.((strpos($begin, '?') !== false) ? '&' : '?').$end;
  2381. }
  2382. /**
  2383. * Display error and dies or silently log the error.
  2384. *
  2385. * @param string $msg
  2386. * @param bool $die
  2387. * @return bool success of logging
  2388. */
  2389. public static function dieOrLog($msg, $die = true)
  2390. {
  2391. if ($die || (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_))
  2392. die($msg);
  2393. return PrestaShopLogger::addLog($msg);
  2394. }
  2395. /**
  2396. * Convert \n and \r\n and \r to <br />
  2397. *
  2398. * @param string $string String to transform
  2399. * @return string New string
  2400. */
  2401. public static function nl2br($str)
  2402. {
  2403. return str_replace(array("\r\n", "\r", "\n"), '<br />', $str);
  2404. }
  2405. /**
  2406. * Clear cache for Smarty
  2407. *
  2408. * @param Smarty $smarty
  2409. */
  2410. public static function clearCache($smarty = null, $tpl = false, $cache_id = null, $compile_id = null)
  2411. {
  2412. if ($smarty === null)
  2413. $smarty = Context::getContext()->smarty;
  2414. if ($smarty === null)
  2415. return;
  2416. if (!$tpl && $cache_id === null && $compile_id === null)
  2417. return $smarty->clearAllCache();
  2418. return $smarty->clearCache($tpl, $cache_id, $compile_id);
  2419. }
  2420. /**
  2421. * Clear compile for Smarty
  2422. */
  2423. public static function clearCompile($smarty = null)
  2424. {
  2425. if ($smarty === null)
  2426. $smarty = Context::getContext()->smarty;
  2427. if ($smarty === null)
  2428. return;
  2429. return $smarty->clearCompiledTemplate();
  2430. }
  2431. /**
  2432. * Clear Smarty cache and compile folders
  2433. */
  2434. public static function clearSmartyCache()
  2435. {
  2436. $smarty = Context::getContext()->smarty;
  2437. Tools::clearCache($smarty);
  2438. Tools::clearCompile($smarty);
  2439. }
  2440. public static function clearColorListCache($id_product = false)
  2441. {
  2442. // Change template dir if called from the BackOffice
  2443. $current_template_dir = Context::getContext()->smarty->getTemplateDir();
  2444. Context::getContext()->smarty->setTemplateDir(_PS_THEME_DIR_);
  2445. Tools::clearCache(null, 'product-list-colors.tpl',
  2446. ($id_product ? 'productlist_colors|'.(int)$id_product.'|'.(int)Context::getContext()->shop->id : 'productlist_colors'));
  2447. Context::getContext()->smarty->setTemplateDir($current_template_dir);
  2448. }
  2449. /**
  2450. * getMemoryLimit allow to get the memory limit in octet
  2451. *
  2452. * @since 1.4.5.0
  2453. * @return int the memory limit value in octet
  2454. */
  2455. public static function getMemoryLimit()
  2456. {
  2457. $memory_limit = @ini_get('memory_limit');
  2458. return Tools::getOctets($memory_limit);
  2459. }
  2460. /**
  2461. * getOctet allow to gets the value of a configuration option in octet
  2462. *
  2463. * @since 1.5.0
  2464. * @return int the value of a configuration option in octet
  2465. */
  2466. public static function getOctets($option)
  2467. {
  2468. if (preg_match('/[0-9]+k/i', $option))
  2469. return 1024 * (int)$option;
  2470. if (preg_match('/[0-9]+m/i', $option))
  2471. return 1024 * 1024 * (int)$option;
  2472. if (preg_match('/[0-9]+g/i', $option))
  2473. return 1024 * 1024 * 1024 * (int)$option;
  2474. return $option;
  2475. }
  2476. /**
  2477. *
  2478. * @return bool true if the server use 64bit arch
  2479. */
  2480. public static function isX86_64arch()
  2481. {
  2482. return (PHP_INT_MAX == '9223372036854775807');
  2483. }
  2484. /**
  2485. *
  2486. * @return bool true if php-cli is used
  2487. */
  2488. public static function isPHPCLI()
  2489. {
  2490. return (defined('STDIN') || (Tools::strtolower(php_sapi_name()) == 'cli' && (!isset($_SERVER['REMOTE_ADDR']) || empty($_SERVER['REMOTE_ADDR']))));
  2491. }
  2492. public static function argvToGET($argc, $argv)
  2493. {
  2494. if ($argc <= 1)
  2495. return;
  2496. // get the first argument and parse it like a query string
  2497. parse_str($argv[1], $args);
  2498. if (!is_array($args) || !count($args))
  2499. return;
  2500. $_GET = array_merge($args, $_GET);
  2501. $_SERVER['QUERY_STRING'] = $argv[1];
  2502. }
  2503. /**
  2504. * Get max file upload size considering server settings and optional max value
  2505. *
  2506. * @param int $max_size optional max file size
  2507. * @return int max file size in bytes
  2508. */
  2509. public static function getMaxUploadSize($max_size = 0)
  2510. {
  2511. $post_max_size = Tools::convertBytes(ini_get('post_max_size'));
  2512. $upload_max_filesize = Tools::convertBytes(ini_get('upload_max_filesize'));
  2513. if ($max_size > 0)
  2514. $result = min($post_max_size, $upload_max_filesize, $max_size);
  2515. else
  2516. $result = min($post_max_size, $upload_max_filesize);
  2517. return $result;
  2518. }
  2519. /**
  2520. * apacheModExists return true if the apache module $name is loaded
  2521. * @TODO move this method in class Information (when it will exist)
  2522. *
  2523. * Notes: This method requires either apache_get_modules or phpinfo()
  2524. * to be available. With CGI mod, we cannot get php modules
  2525. *
  2526. * @param string $name module name
  2527. * @return boolean true if exists
  2528. * @since 1.4.5.0
  2529. */
  2530. public static function apacheModExists($name)
  2531. {
  2532. if (function_exists('apache_get_modules'))
  2533. {
  2534. static $apache_module_list = null;
  2535. if (!is_array($apache_module_list))
  2536. $apache_module_list = apache_get_modules();
  2537. // we need strpos (example, evasive can be evasive20)
  2538. foreach ($apache_module_list as $module)
  2539. {
  2540. if (strpos($module, $name) !== false)
  2541. return true;
  2542. }
  2543. }
  2544. return false;
  2545. }
  2546. /**
  2547. * Copy the folder $src into $dst, $dst is created if it do not exist
  2548. * @param $src
  2549. * @param $dst
  2550. * @param bool $del if true, delete the file after copy
  2551. */
  2552. public static function recurseCopy($src, $dst, $del = false)
  2553. {
  2554. if (!Tools::file_exists_cache($src))
  2555. return false;
  2556. $dir = opendir($src);
  2557. if (!Tools::file_exists_cache($dst))
  2558. mkdir($dst);
  2559. while (false !== ($file = readdir($dir)))
  2560. {
  2561. if (($file != '.') && ($file != '..'))
  2562. {
  2563. if (is_dir($src.DIRECTORY_SEPARATOR.$file))
  2564. self::recurseCopy($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file, $del);
  2565. else
  2566. {
  2567. copy($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file);
  2568. if ($del && is_writable($src.DIRECTORY_SEPARATOR.$file))
  2569. unlink($src.DIRECTORY_SEPARATOR.$file);
  2570. }
  2571. }
  2572. }
  2573. closedir($dir);
  2574. if ($del && is_writable($src))
  2575. rmdir($src);
  2576. }
  2577. /**
  2578. * @params string $path Path to scan
  2579. * @params string $ext Extention to filter files
  2580. * @params string $dir Add this to prefix output for example /path/dir/*
  2581. *
  2582. * @return array List of file found
  2583. * @since 1.5.0
  2584. */
  2585. public static function scandir($path, $ext = 'php', $dir = '', $recursive = false)
  2586. {
  2587. $path = rtrim(rtrim($path, '\\'), '/').'/';
  2588. $real_path = rtrim(rtrim($path.$dir, '\\'), '/').'/';
  2589. $files = scandir($real_path);
  2590. if (!$files)
  2591. return array();
  2592. $filtered_files = array();
  2593. $real_ext = false;
  2594. if (!empty($ext))
  2595. $real_ext = '.'.$ext;
  2596. $real_ext_length = strlen($real_ext);
  2597. $subdir = ($dir) ? $dir.'/' : '';
  2598. foreach ($files as $file)
  2599. {
  2600. if (!$real_ext || (strpos($file, $real_ext) && strpos($file, $real_ext) == (strlen($file) - $real_ext_length)))
  2601. $filtered_files[] = $subdir.$file;
  2602. if ($recursive && $file[0] != '.' && is_dir($real_path.$file))
  2603. foreach (Tools::scandir($path, $ext, $subdir.$file, $recursive) as $subfile)
  2604. $filtered_files[] = $subfile;
  2605. }
  2606. return $filtered_files;
  2607. }
  2608. /**
  2609. * Align version sent and use internal function
  2610. *
  2611. * @static
  2612. * @param $v1
  2613. * @param $v2
  2614. * @param string $operator
  2615. * @return mixed
  2616. */
  2617. public static function version_compare($v1, $v2, $operator = '<')
  2618. {
  2619. Tools::alignVersionNumber($v1, $v2);
  2620. return version_compare($v1, $v2, $operator);
  2621. }
  2622. /**
  2623. * Align 2 version with the same number of sub version
  2624. * version_compare will work better for its comparison :)
  2625. * (Means: '1.8' to '1.9.3' will change '1.8' to '1.8.0')
  2626. * @static
  2627. * @param $v1
  2628. * @param $v2
  2629. */
  2630. public static function alignVersionNumber(&$v1, &$v2)
  2631. {
  2632. $len1 = count(explode('.', trim($v1, '.')));
  2633. $len2 = count(explode('.', trim($v2, '.')));
  2634. $len = 0;
  2635. $str = '';
  2636. if ($len1 > $len2)
  2637. {
  2638. $len = $len1 - $len2;
  2639. $str = &$v2;
  2640. }
  2641. elseif ($len2 > $len1)
  2642. {
  2643. $len = $len2 - $len1;
  2644. $str = &$v1;
  2645. }
  2646. for ($len; $len > 0; $len--)
  2647. $str .= '.0';
  2648. }
  2649. public static function modRewriteActive()
  2650. {
  2651. if (Tools::apacheModExists('mod_rewrite'))
  2652. return true;
  2653. if ((isset($_SERVER['HTTP_MOD_REWRITE']) && Tools::strtolower($_SERVER['HTTP_MOD_REWRITE']) == 'on') || Tools::strtolower(getenv('HTTP_MOD_REWRITE')) == 'on')
  2654. return true;
  2655. return false;
  2656. }
  2657. public static function unSerialize($serialized, $object = false)
  2658. {
  2659. if (is_string($serialized) && (strpos($serialized, 'O:') === false || !preg_match('/(^|;|{|})O:[0-9]+:"/', $serialized)) && !$object || $object)
  2660. return @unserialize($serialized);
  2661. return false;
  2662. }
  2663. /**
  2664. * Reproduce array_unique working before php version 5.2.9
  2665. * @param array $array
  2666. * @return array
  2667. */
  2668. public static function arrayUnique($array)
  2669. {
  2670. if (version_compare(phpversion(), '5.2.9', '<'))
  2671. return array_unique($array);
  2672. else
  2673. return array_unique($array, SORT_REGULAR);
  2674. }
  2675. /**
  2676. * Delete unicode class from regular expression patterns
  2677. * @param string $pattern
  2678. * @return pattern
  2679. */
  2680. public static function cleanNonUnicodeSupport($pattern)
  2681. {
  2682. if (!defined('PREG_BAD_UTF8_OFFSET'))
  2683. return $pattern;
  2684. return preg_replace('/\\\[px]\{[a-z]{1,2}\}|(\/[a-z]*)u([a-z]*)$/i', "$1$2", $pattern);
  2685. }
  2686. protected static $is_addons_up = true;
  2687. public static function addonsRequest($request, $params = array())
  2688. {
  2689. if (!self::$is_addons_up)
  2690. return false;
  2691. $post_data = http_build_query(array(
  2692. 'version' => isset($params['version']) ? $params['version'] : _PS_VERSION_,
  2693. 'iso_lang' => Tools::strtolower(isset($params['iso_lang']) ? $params['iso_lang'] : Context::getContext()->language->iso_code),
  2694. 'iso_code' => Tools::strtolower(isset($params['iso_country']) ? $params['iso_country'] : Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'))),
  2695. 'shop_url' => isset($params['shop_url']) ? $params['shop_url'] : Tools::getShopDomain(),
  2696. 'mail' => isset($params['email']) ? $params['email'] : Configuration::get('PS_SHOP_EMAIL')
  2697. ));
  2698. $protocols = array('https');
  2699. $end_point = 'api.addons.prestashop.com';
  2700. switch ($request)
  2701. {
  2702. case 'native':
  2703. $protocols[] = 'http';
  2704. $post_data .= '&method=listing&action=native';
  2705. break;
  2706. case 'native_all':
  2707. $protocols[] = 'http';
  2708. $post_data .= '&method=listing&action=native&iso_code=all';
  2709. break;
  2710. case 'must-have':
  2711. $protocols[] = 'http';
  2712. $post_data .= '&method=listing&action=must-have';
  2713. break;
  2714. case 'must-have-themes':
  2715. $protocols[] = 'http';
  2716. $post_data .= '&method=listing&action=must-have-themes';
  2717. break;
  2718. case 'customer':
  2719. $post_data .= '&method=listing&action=customer&username='.urlencode(trim(Context::getContext()->cookie->username_addons))
  2720. .'&password='.urlencode(trim(Context::getContext()->cookie->password_addons));
  2721. break;
  2722. case 'customer_themes':
  2723. $post_data .= '&method=listing&action=customer-themes&username='.urlencode(trim(Context::getContext()->cookie->username_addons))
  2724. .'&password='.urlencode(trim(Context::getContext()->cookie->password_addons));
  2725. break;
  2726. case 'check_customer':
  2727. $post_data .= '&method=check_customer&username='.urlencode($params['username_addons']).'&password='.urlencode($params['password_addons']);
  2728. break;
  2729. case 'check_module':
  2730. $post_data .= '&method=check&module_name='.urlencode($params['module_name']).'&module_key='.urlencode($params['module_key']);
  2731. break;
  2732. case 'module':
  2733. $post_data .= '&method=module&id_module='.urlencode($params['id_module']);
  2734. if (isset($params['username_addons']) && isset($params['password_addons']))
  2735. $post_data .= '&username='.urlencode($params['username_addons']).'&password='.urlencode($params['password_addons']);
  2736. else
  2737. $protocols[] = 'http';
  2738. break;
  2739. case 'hosted_module':
  2740. $post_data .= '&method=module&id_module='.urlencode((int)$params['id_module']).'&username='.urlencode($params['hosted_email'])
  2741. .'&password='.urlencode($params['password_addons'])
  2742. .'&shop_url='.urlencode(isset($params['shop_url']) ? $params['shop_url'] : Tools::getShopDomain())
  2743. .'&mail='.urlencode(isset($params['email']) ? $params['email'] : Configuration::get('PS_SHOP_EMAIL'));
  2744. $protocols[] = 'https';
  2745. break;
  2746. case 'install-modules':
  2747. $protocols[] = 'http';
  2748. $post_data .= '&method=listing&action=install-modules';
  2749. break;
  2750. default:
  2751. return false;
  2752. }
  2753. $context = stream_context_create(array(
  2754. 'http' => array(
  2755. 'method' => 'POST',
  2756. 'content' => $post_data,
  2757. 'header' => 'Content-type: application/x-www-form-urlencoded',
  2758. 'timeout' => 5,
  2759. )
  2760. ));
  2761. foreach ($protocols as $protocol)
  2762. if ($content = Tools::file_get_contents($protocol.'://'.$end_point, false, $context))
  2763. return $content;
  2764. self::$is_addons_up = false;
  2765. return false;
  2766. }
  2767. public static function fileAttachment($input = 'fileUpload')
  2768. {
  2769. $file_attachment = null;
  2770. if (isset($_FILES[$input]['name']) && !empty($_FILES[$input]['name']) && !empty($_FILES[$input]['tmp_name']))
  2771. {
  2772. $file_attachment['rename'] = uniqid().Tools::strtolower(substr($_FILES[$input]['name'], -5));
  2773. $file_attachment['content'] = file_get_contents($_FILES[$input]['tmp_name']);
  2774. $file_attachment['tmp_name'] = $_FILES[$input]['tmp_name'];
  2775. $file_attachment['name'] = $_FILES[$input]['name'];
  2776. $file_attachment['mime'] = $_FILES[$input]['type'];
  2777. $file_attachment['error'] = $_FILES[$input]['error'];
  2778. $file_attachment['size'] = $_FILES[$input]['size'];
  2779. }
  2780. return $file_attachment;
  2781. }
  2782. public static function changeFileMTime($file_name)
  2783. {
  2784. touch($file_name);
  2785. }
  2786. public static function waitUntilFileIsModified($file_name, $timeout = 180)
  2787. {
  2788. @ini_set('max_execution_time', $timeout);
  2789. if (($time_limit = ini_get('max_execution_time')) === null)
  2790. $time_limit = 30;
  2791. $time_limit -= 5;
  2792. $start_time = microtime(true);
  2793. $last_modified = @filemtime($file_name);
  2794. while (true)
  2795. {
  2796. if (((microtime(true) - $start_time) > $time_limit) || @filemtime($file_name) > $last_modified)
  2797. break;
  2798. clearstatcache();
  2799. usleep(300);
  2800. }
  2801. }
  2802. /**
  2803. * Delete a substring from another one starting from the right
  2804. * @param string $str
  2805. * @param string $str_search
  2806. * @return string
  2807. */
  2808. public static function rtrimString($str, $str_search)
  2809. {
  2810. $length_str = strlen($str_search);
  2811. if (strlen($str) >= $length_str && substr($str, -$length_str) == $str_search)
  2812. $str = substr($str, 0, -$length_str);
  2813. return $str;
  2814. }
  2815. /**
  2816. * Format a number into a human readable format
  2817. * e.g. 24962496 => 23.81M
  2818. * @param $size
  2819. * @param int $precision
  2820. *
  2821. * @return string
  2822. */
  2823. public static function formatBytes($size, $precision = 2)
  2824. {
  2825. if (!$size)
  2826. return '0';
  2827. $base = log($size) / log(1024);
  2828. $suffixes = array('', 'k', 'M', 'G', 'T');
  2829. return round(pow(1024, $base - floor($base)), $precision).$suffixes[floor($base)];
  2830. }
  2831. public static function boolVal($value)
  2832. {
  2833. if (empty($value))
  2834. $value = false;
  2835. return (bool)$value;
  2836. }
  2837. public static function getUserPlatform()
  2838. {
  2839. if (isset(self::$_user_plateform))
  2840. return self::$_user_plateform;
  2841. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  2842. self::$_user_plateform = 'unknown';
  2843. if (preg_match('/linux/i', $user_agent))
  2844. self::$_user_plateform = 'Linux';
  2845. elseif (preg_match('/macintosh|mac os x/i', $user_agent))
  2846. self::$_user_plateform = 'Mac';
  2847. elseif (preg_match('/windows|win32/i', $user_agent))
  2848. self::$_user_plateform = 'Windows';
  2849. return self::$_user_plateform;
  2850. }
  2851. public static function getUserBrowser()
  2852. {
  2853. if (isset(self::$_user_browser))
  2854. return self::$_user_browser;
  2855. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  2856. self::$_user_browser = 'unknown';
  2857. if (preg_match('/MSIE/i',$user_agent) && !preg_match('/Opera/i',$user_agent))
  2858. self::$_user_browser = 'Internet Explorer';
  2859. elseif (preg_match('/Firefox/i',$user_agent))
  2860. self::$_user_browser = 'Mozilla Firefox';
  2861. elseif (preg_match('/Chrome/i',$user_agent))
  2862. self::$_user_browser = 'Google Chrome';
  2863. elseif (preg_match('/Safari/i',$user_agent))
  2864. self::$_user_browser = 'Apple Safari';
  2865. elseif (preg_match('/Opera/i',$user_agent))
  2866. self::$_user_browser = 'Opera';
  2867. elseif (preg_match('/Netscape/i',$user_agent))
  2868. self::$_user_browser = 'Netscape';
  2869. return self::$_user_browser;
  2870. }
  2871. /**
  2872. * Allows to display the category description without HTML tags and slashes
  2873. *
  2874. * @return string
  2875. */
  2876. public static function getDescriptionClean($description)
  2877. {
  2878. return strip_tags(stripslashes($description));
  2879. }
  2880. public static function purifyHTML($html)
  2881. {
  2882. static $use_html_purifier = null;
  2883. static $purifier = null;
  2884. if (defined('PS_INSTALLATION_IN_PROGRESS') || !Configuration::configurationIsLoaded())
  2885. return $html;
  2886. if ($use_html_purifier === null)
  2887. $use_html_purifier = (bool)Configuration::get('PS_USE_HTMLPURIFIER');
  2888. if ($use_html_purifier)
  2889. {
  2890. if ($purifier === null)
  2891. {
  2892. $config = HTMLPurifier_Config::createDefault();
  2893. // Set some HTML5 properties
  2894. $config->set('HTML.DefinitionID', 'html5-definitions'); // unqiue id
  2895. $config->set('HTML.DefinitionRev', 1);
  2896. $config->set('Attr.EnableID', true);
  2897. $config->set('HTML.Trusted', true);
  2898. $config->set('Cache.SerializerPath', _PS_CACHE_DIR_.'purifier');
  2899. $config->set('Attr.AllowedFrameTargets', array('_blank', '_self', '_parent', '_top'));
  2900. if (Configuration::get('PS_ALLOW_HTML_IFRAME'))
  2901. {
  2902. $config->set('HTML.SafeIframe', true);
  2903. $config->set('HTML.SafeObject', true);
  2904. $config->set('URI.SafeIframeRegexp','/.*/');
  2905. }
  2906. // http://developers.whatwg.org/the-video-element.html#the-video-element
  2907. if ($def = $config->maybeGetRawHTMLDefinition())
  2908. {
  2909. $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array(
  2910. 'src' => 'URI',
  2911. 'type' => 'Text',
  2912. 'width' => 'Length',
  2913. 'height' => 'Length',
  2914. 'poster' => 'URI',
  2915. 'preload' => 'Enum#auto,metadata,none',
  2916. 'controls' => 'Bool',
  2917. ));
  2918. $def->addElement('source', 'Block', 'Flow', 'Common', array(
  2919. 'src' => 'URI',
  2920. 'type' => 'Text',
  2921. ));
  2922. }
  2923. $purifier = new HTMLPurifier($config);
  2924. }
  2925. if (_PS_MAGIC_QUOTES_GPC_)
  2926. $html = stripslashes($html);
  2927. $html = $purifier->purify($html);
  2928. if (_PS_MAGIC_QUOTES_GPC_)
  2929. $html = addslashes($html);
  2930. }
  2931. return $html;
  2932. }
  2933. }
  2934. /**
  2935. * Compare 2 prices to sort products
  2936. *
  2937. * @param float $a
  2938. * @param float $b
  2939. * @return integer
  2940. */
  2941. /* Externalized because of a bug in PHP 5.1.6 when inside an object */
  2942. function cmpPriceAsc($a, $b)
  2943. {
  2944. if ((float)$a['price_tmp'] < (float)$b['price_tmp'])
  2945. return (-1);
  2946. elseif ((float)$a['price_tmp'] > (float)$b['price_tmp'])
  2947. return (1);
  2948. return 0;
  2949. }
  2950. function cmpPriceDesc($a, $b)
  2951. {
  2952. if ((float)$a['price_tmp'] < (float)$b['price_tmp'])
  2953. return 1;
  2954. elseif ((float)$a['price_tmp'] > (float)$b['price_tmp'])
  2955. return -1;
  2956. return 0;
  2957. }