/
Tools.php
4454 lines (3883 loc) · 145 KB
/
Tools.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* 2007-2020 PrestaShop SA and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
use Composer\CaBundle\CaBundle;
use PHPSQLParser\PHPSQLParser;
use PrestaShop\PrestaShop\Adapter\ContainerFinder;
use PrestaShop\PrestaShop\Core\Exception\ContainerNotFoundException;
use PrestaShop\PrestaShop\Core\Foundation\Filesystem\FileSystem as PsFileSystem;
use PrestaShop\PrestaShop\Core\Localization\Exception\LocalizationException;
use PrestaShop\PrestaShop\Core\Localization\Locale;
use PrestaShop\PrestaShop\Core\Localization\Locale\Repository as LocaleRepository;
use PrestaShop\PrestaShop\Core\String\CharacterCleaner;
use PrestaShop\PrestaShop\Core\Util\ColorBrightnessCalculator;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
class ToolsCore
{
const CACERT_LOCATION = 'https://curl.haxx.se/ca/cacert.pem';
const SERVICE_LOCALE_REPOSITORY = 'prestashop.core.localization.locale.repository';
protected static $file_exists_cache = [];
protected static $_forceCompile;
protected static $_caching;
protected static $_user_plateform;
protected static $_user_browser;
protected static $request;
protected static $cldr_cache = [];
protected static $colorBrightnessCalculator;
public static $round_mode = null;
/**
* @param Request $request
*/
public function __construct(Request $request = null)
{
if ($request) {
self::$request = $request;
}
}
/**
* Properly clean static cache
*/
public static function resetStaticCache()
{
static::$cldr_cache = [];
}
/**
* Reset the request set during the first new Tools($request) call.
*/
public static function resetRequest()
{
self::$request = null;
}
/**
* Random password generator.
*
* @param int $length Desired length (optional)
* @param string $flag Output type (NUMERIC, ALPHANUMERIC, NO_NUMERIC, RANDOM)
*
* @return bool|string Password
*/
public static function passwdGen($length = 8, $flag = 'ALPHANUMERIC')
{
$length = (int) $length;
if ($length <= 0) {
return false;
}
switch ($flag) {
case 'NUMERIC':
$str = '0123456789';
break;
case 'NO_NUMERIC':
$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'RANDOM':
$num_bytes = ceil($length * 0.75);
$bytes = self::getBytes($num_bytes);
return substr(rtrim(base64_encode($bytes), '='), 0, $length);
case 'ALPHANUMERIC':
default:
$str = 'abcdefghijkmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
}
$bytes = Tools::getBytes($length);
$position = 0;
$result = '';
for ($i = 0; $i < $length; ++$i) {
$position = ($position + ord($bytes[$i])) % strlen($str);
$result .= $str[$position];
}
return $result;
}
/**
* Random bytes generator.
*
* Limited to OpenSSL since 1.7.0.0
*
* @param int $length Desired length of random bytes
*
* @return bool|string Random bytes
*/
public static function getBytes($length)
{
$length = (int) $length;
if ($length <= 0) {
return false;
}
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
if ($cryptoStrong === true) {
return $bytes;
}
return false;
}
/**
* Replace text within a portion of a string.
*
* Replaces a string matching a search, (optionally) string from a certain position
*
* @param string $search The string to search in the input string
* @param string $replace The replacement string
* @param string $subject The input string
* @param int $cur Starting position cursor for the search
*
* @return string the result string is returned
*/
public static function strReplaceFirst($search, $replace, $subject, $cur = 0)
{
$strPos = strpos($subject, $search, $cur);
return $strPos !== false ? substr_replace($subject, $replace, (int) $strPos, strlen($search)) : $subject;
}
/**
* Redirect user to another page.
*
* Warning: uses exit
*
* @param string $url Desired URL
* @param string $base_uri Base URI (optional)
* @param Link $link
* @param string|array $headers A list of headers to send before redirection
*/
public static function redirect($url, $base_uri = __PS_BASE_URI__, Link $link = null, $headers = null)
{
if (!$link) {
$link = Context::getContext()->link;
}
if (strpos($url, 'http://') === false && strpos($url, 'https://') === false && $link) {
if (strpos($url, $base_uri) === 0) {
$url = substr($url, strlen($base_uri));
}
if (strpos($url, 'index.php?controller=') !== false && strpos($url, 'index.php/') == 0) {
$url = substr($url, strlen('index.php?controller='));
if (Configuration::get('PS_REWRITING_SETTINGS')) {
$url = Tools::strReplaceFirst('&', '?', $url);
}
}
$explode = explode('?', $url);
// don't use ssl if url is home page
// used when logout for example
$use_ssl = !empty($url);
$url = $link->getPageLink($explode[0], $use_ssl);
if (isset($explode[1])) {
$url .= '?' . $explode[1];
}
}
// Send additional headers
if ($headers) {
if (!is_array($headers)) {
$headers = [$headers];
}
foreach ($headers as $header) {
header($header);
}
}
header('Location: ' . $url);
exit;
}
/**
* Redirect URLs already containing PS_BASE_URI.
*
* Warning: uses exit
*
* @param string $url Desired URL
*/
public static function redirectLink($url)
{
if (!preg_match('@^https?://@i', $url)) {
if (strpos($url, __PS_BASE_URI__) !== false && strpos($url, __PS_BASE_URI__) == 0) {
$url = substr($url, strlen(__PS_BASE_URI__));
}
if (strpos($url, 'index.php?controller=') !== false && strpos($url, 'index.php/') == 0) {
$url = substr($url, strlen('index.php?controller='));
}
$explode = explode('?', $url);
$url = Context::getContext()->link->getPageLink($explode[0]);
if (isset($explode[1])) {
$url .= '?' . $explode[1];
}
}
header('Location: ' . $url);
exit;
}
/**
* Redirect user to another page (using header Location)
*
* Warning: uses exit
*
* @param string $url Desired URL
*/
public static function redirectAdmin($url)
{
header('Location: ' . $url);
exit;
}
/**
* Returns the available protocol for the current shop in use
* SSL if Configuration is set on and available for the server.
*
* @return string
*/
public static function getShopProtocol()
{
$protocol = (Configuration::get('PS_SSL_ENABLED') || (!empty($_SERVER['HTTPS'])
&& Tools::strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
return $protocol;
}
/**
* Returns the set protocol according to configuration (http[s]).
*
* @param bool $use_ssl true if require ssl
*
* @return string (http|https)
*/
public static function getProtocol($use_ssl = null)
{
return null !== $use_ssl && $use_ssl ? 'https://' : 'http://';
}
/**
* Returns the <b>current</b> host used, with the protocol (http or https) if $http is true
* This function should not be used to choose http or https domain name.
* Use Tools::getShopDomain() or Tools::getShopDomainSsl instead.
*
* @param bool $http
* @param bool $entities
* @param bool $ignore_port
*
* @return string host
*/
public static function getHttpHost($http = false, $entities = false, $ignore_port = false)
{
$httpHost = '';
if (array_key_exists('HTTP_HOST', $_SERVER)) {
$httpHost = $_SERVER['HTTP_HOST'];
}
$host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $httpHost);
if ($ignore_port && $pos = strpos($host, ':')) {
$host = substr($host, 0, $pos);
}
if ($entities) {
$host = htmlspecialchars($host, ENT_COMPAT, 'UTF-8');
}
if ($http) {
$host = (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . $host;
}
return $host;
}
/**
* Returns domain name according to configuration and ignoring ssl.
*
* @param bool $http if true, return domain name with protocol
* @param bool $entities if true, convert special chars to HTML entities
*
* @return string domain
*/
public static function getShopDomain($http = false, $entities = false)
{
if (!$domain = ShopUrl::getMainShopDomain()) {
$domain = Tools::getHttpHost();
}
if ($entities) {
$domain = htmlspecialchars($domain, ENT_COMPAT, 'UTF-8');
}
if ($http) {
$domain = 'http://' . $domain;
}
return $domain;
}
/**
* Returns domain name according to configuration and depending on ssl activation.
*
* @param bool $http if true, return domain name with protocol
* @param bool $entities if true, convert special chars to HTML entities
*
* @return string domain
*/
public static function getShopDomainSsl($http = false, $entities = false)
{
if (!$domain = ShopUrl::getMainShopDomainSSL()) {
$domain = Tools::getHttpHost();
}
if ($entities) {
$domain = htmlspecialchars($domain, ENT_COMPAT, 'UTF-8');
}
if ($http) {
$domain = (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . $domain;
}
return $domain;
}
/**
* Get the server variable SERVER_NAME.
* Relies on $_SERVER
*
* @return string server name
*/
public static function getServerName()
{
if (isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && $_SERVER['HTTP_X_FORWARDED_SERVER']) {
return $_SERVER['HTTP_X_FORWARDED_SERVER'];
}
return $_SERVER['SERVER_NAME'];
}
/**
* Get the server variable REMOTE_ADDR, or the first ip of HTTP_X_FORWARDED_FOR (when using proxy).
*
* @return string $remote_addr ip of client
*/
public static function getRemoteAddr()
{
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
} else {
$headers = $_SERVER;
}
if (array_key_exists('X-Forwarded-For', $headers)) {
$_SERVER['HTTP_X_FORWARDED_FOR'] = $headers['X-Forwarded-For'];
}
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\.(1[6-9]|2\d|30|31)\..*/i', trim($_SERVER['REMOTE_ADDR']))
|| preg_match('/^192\.168\.*/i', trim($_SERVER['REMOTE_ADDR'])) || preg_match('/^10\..*/i', trim($_SERVER['REMOTE_ADDR'])))) {
if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')) {
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return $ips[0];
} else {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
/**
* Check if the current page use SSL connection on not.
* Relies on $_SERVER global being filled
*
* @return bool true if SSL is used
*/
public static function usingSecureMode()
{
if (isset($_SERVER['HTTPS'])) {
return in_array(Tools::strtolower($_SERVER['HTTPS']), [1, 'on']);
}
// $_SERVER['SSL'] exists only in some specific configuration
if (isset($_SERVER['SSL'])) {
return in_array(Tools::strtolower($_SERVER['SSL']), [1, 'on']);
}
// $_SERVER['REDIRECT_HTTPS'] exists only in some specific configuration
if (isset($_SERVER['REDIRECT_HTTPS'])) {
return in_array(Tools::strtolower($_SERVER['REDIRECT_HTTPS']), [1, 'on']);
}
if (isset($_SERVER['HTTP_SSL'])) {
return in_array(Tools::strtolower($_SERVER['HTTP_SSL']), [1, 'on']);
}
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
return Tools::strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https';
}
return false;
}
/**
* Get the current url prefix protocol (https/http).
*
* @return string protocol
*/
public static function getCurrentUrlProtocolPrefix()
{
if (Tools::usingSecureMode()) {
return 'https://';
} else {
return 'http://';
}
}
/**
* Returns a safe URL referrer.
*
* @param string $referrer URL referrer
*
* @return string secured referrer
*/
public static function secureReferrer($referrer)
{
if (static::urlBelongsToShop($referrer)) {
return $referrer;
}
return __PS_BASE_URI__;
}
/**
* Indicates if the provided URL belongs to this shop (relative urls count as belonging to the shop).
*
* @param string $url
*
* @return bool
*/
public static function urlBelongsToShop($url)
{
$urlHost = Tools::extractHost($url);
return empty($urlHost) || $urlHost === Tools::getServerName();
}
/**
* Safely extracts the host part from an URL.
*
* @param string $url
*
* @return string
*/
public static function extractHost($url)
{
$parsed = parse_url($url);
if (!is_array($parsed)) {
return $url;
}
if (empty($parsed['host']) || empty($parsed['scheme'])) {
return '';
}
return $parsed['host'];
}
/**
* Get a value from $_POST / $_GET
* if unavailable, take a default value.
*
* @param string $key Value key
* @param mixed $default_value (optional)
*
* @return mixed Value
*/
public static function getValue($key, $default_value = false)
{
if (empty($key) || !is_string($key)) {
return false;
}
if (getenv('kernel.environment') === 'test' && self::$request instanceof Request) {
$value = self::$request->request->get($key, self::$request->query->get($key, $default_value));
} else {
$value = (isset($_POST[$key]) ? $_POST[$key] : (isset($_GET[$key]) ? $_GET[$key] : $default_value));
}
if (is_string($value)) {
return urldecode(preg_replace('/((\%5C0+)|(\%00+))/i', '', urlencode($value)));
}
return $value;
}
/**
* Get all values from $_POST/$_GET.
*
* @return mixed
*/
public static function getAllValues()
{
return $_POST + $_GET;
}
/**
* Checks if a key exists either in $_POST or $_GET.
*
* @param string $key
*
* @return bool
*/
public static function getIsset($key)
{
if (!is_string($key)) {
return false;
}
return isset($_POST[$key]) || isset($_GET[$key]);
}
/**
* Change language in cookie while clicking on a flag.
*
* @return string iso code
*/
public static function setCookieLanguage($cookie = null)
{
if (!$cookie) {
$cookie = Context::getContext()->cookie;
}
/* If language does not exist or is disabled, erase it */
if ($cookie->id_lang) {
$lang = new Language((int) $cookie->id_lang);
if (!Validate::isLoadedObject($lang) || !$lang->active || !$lang->isAssociatedToShop()) {
$cookie->id_lang = null;
}
}
if (!Configuration::get('PS_DETECT_LANG')) {
unset($cookie->detect_language);
}
/* Automatically detect language if not already defined, detect_language is set in Cookie::update */
if (!Tools::getValue('isolang') && !Tools::getValue('id_lang') && (!$cookie->id_lang || isset($cookie->detect_language))
&& isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$array = explode(',', Tools::strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
$string = $array[0];
if (Validate::isLanguageCode($string)) {
$lang = Language::getLanguageByIETFCode($string);
if (Validate::isLoadedObject($lang) && $lang->active && $lang->isAssociatedToShop()) {
Context::getContext()->language = $lang;
$cookie->id_lang = (int) $lang->id;
}
}
}
if (isset($cookie->detect_language)) {
unset($cookie->detect_language);
}
/* If language file not present, you must use default language file */
if (!$cookie->id_lang || !Validate::isUnsignedId($cookie->id_lang)) {
$cookie->id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
}
$iso = Language::getIsoById((int) $cookie->id_lang);
@include_once _PS_THEME_DIR_ . 'lang/' . $iso . '.php';
return $iso;
}
/**
* If necessary change cookie language ID and context language.
*
* @param Context|null $context
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public static function switchLanguage(Context $context = null)
{
if (null === $context) {
$context = Context::getContext();
}
// On PrestaShop installations Dispatcher::__construct() gets called (and so Tools::switchLanguage())
// Stop in this case by checking the cookie
if (!isset($context->cookie)) {
return;
}
if (
($iso = Tools::getValue('isolang')) &&
Validate::isLanguageIsoCode($iso) &&
($id_lang = (int) Language::getIdByIso($iso))
) {
$_GET['id_lang'] = $id_lang;
}
// Only switch if new ID is different from old ID
$newLanguageId = (int) Tools::getValue('id_lang');
if (
Validate::isUnsignedId($newLanguageId) &&
$newLanguageId !== 0 &&
$context->cookie->id_lang !== $newLanguageId
) {
$context->cookie->id_lang = $newLanguageId;
$language = new Language($newLanguageId);
if (Validate::isLoadedObject($language) && $language->active && $language->isAssociatedToShop()) {
$context->language = $language;
}
}
Tools::setCookieLanguage($context->cookie);
}
public static function getCountry($address = null)
{
$id_country = (int) Tools::getValue('id_country');
if (!$id_country && isset($address, $address->id_country) && $address->id_country) {
$id_country = (int) $address->id_country;
} elseif (Configuration::get('PS_DETECT_COUNTRY') && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
preg_match('#(?<=-)\w\w|\w\w(?!-)#', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $array);
if (is_array($array) && isset($array[0]) && Validate::isLanguageIsoCode($array[0])) {
$id_country = (int) Country::getByIso($array[0], true);
}
}
if (!isset($id_country) || !$id_country) {
$id_country = (int) Configuration::get('PS_COUNTRY_DEFAULT');
}
return (int) $id_country;
}
/**
* Set cookie currency from POST or default currency.
*
* @return Currency object
*/
public static function setCurrency($cookie)
{
if (Tools::isSubmit('SubmitCurrency') && ($id_currency = Tools::getValue('id_currency'))) {
/** @var Currency $currency */
$currency = Currency::getCurrencyInstance((int) $id_currency);
if (is_object($currency) && $currency->id && !$currency->deleted && $currency->isAssociatedToShop()) {
$cookie->id_currency = (int) $currency->id;
}
}
$currency = null;
if ((int) $cookie->id_currency) {
$currency = Currency::getCurrencyInstance((int) $cookie->id_currency);
}
if (!Validate::isLoadedObject($currency) || (bool) $currency->deleted || !(bool) $currency->active) {
$currency = Currency::getCurrencyInstance(Configuration::get('PS_CURRENCY_DEFAULT'));
}
$cookie->id_currency = (int) $currency->id;
if ($currency->isAssociatedToShop()) {
return $currency;
} else {
// get currency from context
$currency = Shop::getEntityIds('currency', Context::getContext()->shop->id, true, true);
if (isset($currency[0]) && $currency[0]['id_currency']) {
$cookie->id_currency = $currency[0]['id_currency'];
return Currency::getCurrencyInstance((int) $cookie->id_currency);
}
}
return $currency;
}
/**
* Return the CLDR associated with the context or given language_code.
*
* @see Tools::getContextLocale
* @deprecated since PrestaShop 1.7.6.0
*
* @param Context|null $context
* @param null $language_code
*
* @throws PrestaShopException
*/
public static function getCldr(Context $context = null, $language_code = null)
{
throw new PrestaShopException('This CLDR library has been removed. See Tools::getContextLocale instead.');
}
/**
* Return price with currency sign for a given product.
*
* @deprecated Since 1.7.6.0. Please use Locale::formatPrice() instead
* @see PrestaShop\PrestaShop\Core\Localization\Locale
*
* @param float $price Product price
* @param object|array $currency Current currency (object, id_currency, NULL => context currency)
* @param bool $no_utf8 Not used anymore
* @param Context|null $context
*
* @return string Price correctly formatted (sign, decimal separator...)
* if you modify this function, don't forget to modify the Javascript function formatCurrency (in tools.js)
*
* @throws LocalizationException
*/
public static function displayPrice($price, $currency = null, $no_utf8 = false, Context $context = null)
{
@trigger_error(
'Tools::displayPrice() is deprecated since version 1.7.6.0. '
. 'Use ' . Locale::class . '::formatPrice() instead.',
E_USER_DEPRECATED
);
if (!is_numeric($price)) {
return $price;
}
$context = $context ?: Context::getContext();
$currency = $currency ?: $context->currency;
if (is_int($currency)) {
$currency = Currency::getCurrencyInstance($currency);
}
$locale = static::getContextLocale($context);
$currencyCode = is_array($currency) ? $currency['iso_code'] : $currency->iso_code;
return $locale->formatPrice($price, $currencyCode);
}
/**
* Return current locale
*
* @param Context $context
*
* @return Locale
*
* @throws Exception
*/
public static function getContextLocale(Context $context)
{
$locale = $context->getCurrentLocale();
if (null !== $locale) {
return $locale;
}
$containerFinder = new ContainerFinder($context);
$container = $containerFinder->getContainer();
if (null === $context->container) {
$context->container = $container;
}
/** @var LocaleRepository $localeRepository */
$localeRepository = $container->get(self::SERVICE_LOCALE_REPOSITORY);
$locale = $localeRepository->getLocale(
$context->language->getLocale()
);
return $locale;
}
/**
* Returns a well formatted number.
*
* @deprecated Since 1.7.6.0. Please use Locale::formatNumber() instead
* @see Locale
*
* @param float $number The number to format
* @param null $currency not used anymore
*
* @return string The formatted number
*
* @throws Exception
* @throws LocalizationException
*/
public static function displayNumber($number, $currency = null)
{
@trigger_error(
'Tools::displayNumber() is deprecated since version 1.7.5.0. '
. 'Use ' . Locale::class . ' instead.',
E_USER_DEPRECATED
);
$context = Context::getContext();
$locale = static::getContextLocale($context);
return $locale->formatNumber($number);
}
public static function displayPriceSmarty($params, &$smarty)
{
$context = Context::getContext();
$locale = static::getContextLocale($context);
if (array_key_exists('currency', $params)) {
$currency = Currency::getCurrencyInstance((int) $params['currency']);
if (Validate::isLoadedObject($currency)) {
return $locale->formatPrice($params['price'], $currency->iso_code);
}
}
return $locale->formatPrice($params['price'], $context->currency->iso_code);
}
/**
* Return price converted.
*
* @deprecated since 1.7.4 use convertPriceToCurrency()
*
* @param float $price Product price
* @param object|array $currency Current currency object
* @param bool $to_currency convert to currency or from currency to default currency
* @param Context $context
*
* @return float Price
*/
public static function convertPrice($price, $currency = null, $to_currency = true, Context $context = null)
{
$default_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT');
if (!$context) {
$context = Context::getContext();
}
if ($currency === null) {
$currency = $context->currency;
} elseif (is_numeric($currency)) {
$currency = Currency::getCurrencyInstance($currency);
}
$c_id = (is_array($currency) ? $currency['id_currency'] : $currency->id);
$c_rate = (is_array($currency) ? $currency['conversion_rate'] : $currency->conversion_rate);
if ($c_id != $default_currency) {
if ($to_currency) {
$price *= $c_rate;
} else {
$price /= $c_rate;
}
}
return $price;
}
/**
* Implement array_replace for PHP <= 5.2.
*
* @return array|mixed|null
*
* @deprecated since version 1.7.4.0, to be removed.
*/
public static function array_replace()
{
Tools::displayAsDeprecated('Use PHP\'s array_replace() instead');
if (!function_exists('array_replace')) {
$args = func_get_args();
$num_args = func_num_args();
$res = [];
for ($i = 0; $i < $num_args; ++$i) {
if (is_array($args[$i])) {
foreach ($args[$i] as $key => $val) {
$res[$key] = $val;
}
} else {
trigger_error(__FUNCTION__ . '(): Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
return null;
}
}
return $res;
} else {
return call_user_func_array('array_replace', func_get_args());
}
}
/**
* Convert amount from a currency to an other currency automatically.
*
* @param float $amount
* @param Currency $currency_from if null we used the default currency
* @param Currency $currency_to if null we used the default currency
*/
public static function convertPriceFull($amount, Currency $currency_from = null, Currency $currency_to = null)
{
if ($currency_from == $currency_to) {
return $amount;
}
if ($currency_from === null) {
$currency_from = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
}
if ($currency_to === null) {
$currency_to = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
}
if ($currency_from->id == Configuration::get('PS_CURRENCY_DEFAULT')) {
$amount *= $currency_to->conversion_rate;
} else {
$conversion_rate = ($currency_from->conversion_rate == 0 ? 1 : $currency_from->conversion_rate);
// Convert amount to default currency (using the old currency rate)
$amount = $amount / $conversion_rate;
// Convert to new currency
$amount *= $currency_to->conversion_rate;
}
return Tools::ps_round($amount, Context::getContext()->getComputingPrecision());
}
/**
* Display date regarding to language preferences.
*
* @param array $params Date, format...
* @param object $smarty Smarty object for language preferences
*
* @return string Date
*/
public static function dateFormat($params, &$smarty)
{
return Tools::displayDate($params['date'], null, (isset($params['full']) ? $params['full'] : false));
}
/**
* Display date regarding to language preferences.
*
* @param string $date Date to display format UNIX
* @param int $id_lang Language id DEPRECATED
* @param bool $full With time or not (optional)
* @param string $separator DEPRECATED
*
* @return string Date
*/
public static function displayDate($date, $id_lang = null, $full = false, $separator = null)
{
if ($id_lang !== null) {
Tools::displayParameterAsDeprecated('id_lang');
}
if ($separator !== null) {
Tools::displayParameterAsDeprecated('separator');
}
if (!$date || !($time = strtotime($date))) {
return $date;
}
if ($date == '0000-00-00 00:00:00' || $date == '0000-00-00') {
return '';
}
if (!Validate::isDate($date) || !Validate::isBool($full)) {
throw new PrestaShopException('Invalid date');
}
$context = Context::getContext();
$date_format = ($full ? $context->language->date_format_full : $context->language->date_format_lite);