PageRenderTime 136ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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 …

Large files files are truncated, but you can click here to view the full file