PageRenderTime 36ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/classes/Tools.php

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