-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelpers.php
More file actions
1301 lines (1132 loc) · 42.6 KB
/
Helpers.php
File metadata and controls
1301 lines (1132 loc) · 42.6 KB
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
/**
* This file is part of Blitz PHP framework.
*
* (c) 2022 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace BlitzPHP\Utilities;
use BackedEnum;
use BlitzPHP\Traits\Mixins\HigherOrderTapProxy;
use BlitzPHP\Utilities\Invade\Invader;
use BlitzPHP\Utilities\Invade\StaticInvader;
use BlitzPHP\Utilities\Iterable\Arr;
use BlitzPHP\Utilities\Iterable\Collection;
use Closure;
use DomainException;
use Exception;
use HTMLPurifier;
use HTMLPurifier_Config;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
use UnitEnum;
/**
* Classe utilitaire fournissant des fonctions d'aide courantes
*
* Cette classe contient une variété de méthodes statiques pour manipuler des données,
* gérer les environnements, effectuer des validations et d'autres opérations courantes.
*/
class Helpers
{
/**
* Configurations prédéfinies pour HTMLPurifier
*
* @var array<string, array>
*/
private static array $purifierConfigs = [
'comment' => [
'HTML.Allowed' => 'p,a[href|title],abbr[title],acronym[title],b,strong,blockquote[cite],code,em,i,strike',
'AutoFormat.AutoParagraph' => true,
'AutoFormat.Linkify' => true,
'AutoFormat.RemoveEmpty' => true,
],
'default' => [
// Configuration par défaut vide
],
];
/**
* Cache des versions PHP vérifiées
*
* @var array<string, bool>
*/
private static array $phpVersionCache = [];
/**
* Instance du escaper Laminas pour éviter les instanciations multiples
*
* @var \Laminas\Escaper\Escaper|null
*/
private static $escaper;
/**
* Récupère la classe "basename" de l'objet/classe donné.
*
* @param object|string $class L'objet ou le nom de classe
*
* @return string Le nom court de la classe (sans le namespace)
*
* @see https://github.com/laravel/framework/blob/8.x/src/Illuminate/Support/helpers.php
*/
public static function classBasename(object|string $class): string
{
$class = is_object($class) ? get_class($class) : $class;
return basename(str_replace('\\', '/', $class));
}
/**
* Renvoie tous les traits utilisés par une classe, ses classes parentes et le trait de leurs traits.
*
* @param object|string $class L'objet ou le nom de classe
*
* @return array Liste de tous les traits utilisés récursivement
*/
public static function classUsesRecursive(object|string $class): array
{
if (is_object($class)) {
$class = get_class($class);
}
$results = [];
foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) {
$results += self::traitUsesRecursive($class);
}
return array_unique($results);
}
/**
* Nettoie une URL en supprimant les références aux répertoires parents et en normalisant le format
*
* @param string $url L'URL à nettoyer
*
* @return string L'URL nettoyée
*/
public static function cleanUrl(string $url): string
{
$urlParts = parse_url($url);
if ($urlParts === false) {
return $url;
}
$result = '';
if (! empty($urlParts['scheme'])) {
$result .= $urlParts['scheme'] . '://';
}
if (! empty($urlParts['user'])) {
$result .= $urlParts['user'];
if (! empty($urlParts['pass'])) {
$result .= ':' . $urlParts['pass'];
}
$result .= '@';
}
if (! empty($urlParts['host'])) {
$result .= $urlParts['host'];
}
if (! empty($urlParts['port'])) {
$result .= ':' . $urlParts['port'];
}
if (! empty($urlParts['path'])) {
$path = $urlParts['path'];
$path = str_replace('/./', '/', $path);
while (substr_count($path, '../')) {
$path = preg_replace('!/([\\w\\d]+/\\.\\.)!', '', $path);
}
$result .= $path;
}
if (! empty($urlParts['query'])) {
$result .= '?' . $urlParts['query'];
}
if (! empty($urlParts['fragment'])) {
$result .= '#' . $urlParts['fragment'];
}
return $result;
}
/**
* Créez une collection à partir de la valeur donnée.
*
* @param mixed $value La valeur à transformer en collection
*
* @return Collection Une nouvelle instance de Collection
*/
public static function collect(mixed $value = null): Collection
{
return new Collection($value);
}
/**
* Remplit les données manquantes dans un tableau ou un objet en utilisant la notation "point".
*
* @param mixed &$target La cible à remplir (par référence)
* @param array|string $key La clé sous forme de tableau ou de chaîne avec notation point
* @param mixed $value La valeur à définir
*
* @return mixed La cible modifiée
*/
public static function dataFill(mixed &$target, array|string $key, mixed $value): mixed
{
return static::dataSet($target, $key, $value, false);
}
/**
* Supprime un élément d'un tableau ou d'un objet en utilisant la notation "point".
*
* @param mixed &$target La cible à modifier (par référence)
* @param array|int|string|null $key La clé à supprimer
*
* @return mixed La cible modifiée
*/
public static function dataForget(mixed &$target, array|int|string|null $key): mixed
{
$segments = is_array($key) ? $key : explode('.', $key);
if (($segment = array_shift($segments)) === '*' && Arr::accessible($target)) {
if ($segments) {
foreach ($target as &$inner) {
static::dataForget($inner, $segments);
}
}
} elseif (Arr::accessible($target)) {
if ($segments && Arr::exists($target, $segment)) {
static::dataForget($target[$segment], $segments);
} else {
Arr::forget($target, $segment);
}
} elseif (is_object($target)) {
if ($segments && isset($target->{$segment})) {
static::dataForget($target->{$segment}, $segments);
} elseif (isset($target->{$segment})) {
unset($target->{$segment});
}
}
return $target;
}
/**
* Détermine si une clé/propriété existe sur un tableau ou un objet en utilisant la notation "point".
*
* @param mixed $target La cible à vérifier
* @param array|int|string|null $key La clé à vérifier
*
* @return bool True si la clé existe, false sinon
*/
public static function dataHas(mixed $target, $key): bool
{
if (null === $key || $key === []) {
return false;
}
$key = is_array($key) ? $key : explode('.', $key);
foreach ($key as $segment) {
if (Arr::accessible($target) && Arr::exists($target, $segment)) {
$target = $target[$segment];
} elseif (is_object($target) && property_exists($target, $segment)) {
$target = $target->{$segment};
} else {
return false;
}
}
return true;
}
/**
* Récupère un élément d'un tableau ou d'un objet en utilisant la notation "point".
*
* @param mixed $target La cible à partir de laquelle récupérer
* @param array|int|string|null $key La clé à récupérer
* @param mixed $default La valeur par défaut si la clé n'existe pas
*
* @return mixed La valeur récupérée
*/
public static function dataGet(mixed $target, array|int|string|null $key, mixed $default = null): mixed
{
if (null === $key) {
return $target;
}
$key = is_array($key) ? $key : explode('.', $key);
foreach ($key as $i => $segment) {
unset($key[$i]);
if (null === $segment) {
return $target;
}
if ($segment === '*') {
if ($target instanceof Collection) {
$target = $target->all();
} elseif (! is_iterable($target)) {
return static::value($default);
}
$result = [];
foreach ($target as $item) {
$result[] = static::dataGet($item, $key);
}
return in_array('*', $key, true) ? Arr::collapse($result) : $result;
}
$segment = match ($segment) {
'\*' => '*',
'\{first}' => '{first}',
'{first}' => array_key_first(is_array($target) ? $target : static::collect($target)->all()),
'\{last}' => '{last}',
'{last}' => array_key_last(is_array($target) ? $target : static::collect($target)->all()),
default => $segment,
};
if (Arr::accessible($target) && Arr::exists($target, $segment)) {
$target = $target[$segment];
} elseif (is_object($target) && isset($target->{$segment})) {
$target = $target->{$segment};
} else {
return static::value($default);
}
}
return $target;
}
/**
* Définit un élément sur un tableau ou un objet en utilisant la notation point.
*
* @param mixed &$target La cible à modifier (par référence)
* @param array|string $key La clé sous forme de tableau ou de chaîne avec notation point
* @param mixed $value La valeur à définir
* @param bool $overwrite Si true, écrase les valeurs existantes
*
* @return mixed La cible modifiée
*/
public static function dataSet(mixed &$target, array|string $key, mixed $value, bool $overwrite = true): mixed
{
$segments = is_array($key) ? $key : explode('.', $key);
if (($segment = array_shift($segments)) === '*') {
if (! Arr::accessible($target)) {
$target = [];
}
if ($segments) {
foreach ($target as &$inner) {
static::dataSet($inner, $segments, $value, $overwrite);
}
} elseif ($overwrite) {
foreach ($target as &$inner) {
$inner = $value;
}
}
} elseif (Arr::accessible($target)) {
if ($segments) {
if (! Arr::exists($target, $segment)) {
$target[$segment] = [];
}
static::dataSet($target[$segment], $segments, $value, $overwrite);
} elseif ($overwrite || ! Arr::exists($target, $segment)) {
$target[$segment] = $value;
}
} elseif (is_object($target)) {
if ($segments) {
if (! isset($target->{$segment})) {
$target->{$segment} = [];
}
static::dataSet($target->{$segment}, $segments, $value, $overwrite);
} elseif ($overwrite || ! isset($target->{$segment})) {
$target->{$segment} = $value;
}
} else {
$target = [];
if ($segments) {
static::dataSet($target[$segment], $segments, $value, $overwrite);
} elseif ($overwrite) {
$target[$segment] = $value;
}
}
return $target;
}
/**
* Méthode d'assistance pour générer des avertissements d'obsolescence
*
* @param string $message Le message à afficher comme avertissement d'obsolescence.
* @param int $stackFrame Le cadre de pile à inclure dans l'erreur. Par défaut à 1
* car cela devrait pointer vers le code de l'application/du plugin.
*
* @return void
*/
public static function deprecationWarning(string $message, int $stackFrame = 1)
{
if (! (error_reporting() & E_USER_DEPRECATED)) {
return;
}
$trace = debug_backtrace();
if (isset($trace[$stackFrame])) {
$frame = $trace[$stackFrame];
$frame += ['file' => '[internal]', 'line' => '??'];
$message = sprintf(
"%s - %s, line: %s\n" .
' You can disable deprecation warnings by setting `Error.errorLevel` to' .
' `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.',
$message,
$frame['file'],
$frame['line']
);
}
@trigger_error($message, E_USER_DEPRECATED);
}
/**
* Garantit qu'une extension se trouve à la fin d'un nom de fichier
*
* @param string $path Le chemin du fichier
* @param string $ext L'extension à garantir
*
* @return string Le chemin avec l'extension garantie
*/
public static function ensureExt(string $path, string $ext = 'php'): string
{
if ($ext) {
$ext = '.' . preg_replace('#^\.#', '', $ext);
if (substr($path, -strlen($ext)) !== $ext) {
$path .= $ext;
}
}
return trim($path);
}
/**
* Renvoie une valeur scalaire pour la valeur donnée qui pourrait être une énumération.
*
* @template TValue
* @template TDefault
*
* @param TValue $value La valeur à convertir
* @param callable(TValue): TDefault|TDefault $default Valeur par défaut ou callback
*
* @return ($value is empty ? TDefault : mixed) La valeur scalaire ou la valeur par défaut
*/
public static function enumValue($value, $default = null)
{
return match (true) {
$value instanceof BackedEnum => $value->value,
$value instanceof UnitEnum => $value->name,
default => $value ?? static::value($default),
};
}
/**
* Obtient une variable d'environnement à partir des sources disponibles et fournit une émulation
* pour les variables d'environnement non prises en charge ou incohérentes (c'est-à-dire DOCUMENT_ROOT sur
* IIS, ou SCRIPT_NAME en mode CGI). Expose également quelques coutumes supplémentaires
* informations sur l'environnement.
*
* @param string $key Nom de la variable d'environnement
* @param mixed|null $default Spécifiez une valeur par défaut au cas où la variable d'environnement n'est pas définie.
*
* @return string Paramétrage des variables d'environnement.
*
* @credit CakePHP - http://book.cakephp.org/4.0/en/core-libraries/global-constants-and-functions.html#env
*/
public static function env(string $key, $default = null)
{
if ($key === 'HTTPS') {
if (isset($_SERVER['HTTPS'])) {
return ! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
}
return str_starts_with((string) self::env('SCRIPT_URI'), 'https://');
}
if ($key === 'SCRIPT_NAME' && self::env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) {
$key = 'SCRIPT_URL';
}
$val = $_SERVER[$key] ?? $_ENV[$key] ?? null;
if ($val === null && getenv($key) !== false) {
$val = getenv($key);
}
if ($key === 'REMOTE_ADDR' && $val === self::env('SERVER_ADDR')) {
$addr = self::env('HTTP_PC_REMOTE_ADDR');
if ($addr !== null) {
$val = $addr;
}
}
if ($val !== null) {
return $val;
}
switch ($key) {
case 'DOCUMENT_ROOT':
$name = (string) self::env('SCRIPT_NAME');
$filename = (string) self::env('SCRIPT_FILENAME');
$offset = 0;
if (! strpos($name, '.php')) {
$offset = 4;
}
return substr($filename, 0, -(strlen($name) + $offset));
case 'PHP_SELF':
return str_replace((string) self::env('DOCUMENT_ROOT'), '', (string) self::env('SCRIPT_FILENAME'));
case 'CGI_MODE':
return PHP_SAPI === 'cgi';
}
return $default;
}
/**
* Effectue un simple échappement automatique des données pour des raisons de sécurité.
* Pourrait envisager de rendre cela plus complexe à une date ultérieure.
*
* Si $data est une chaîne, il suffit alors de l'échapper et de la renvoyer.
* Si $data est un tableau, alors il boucle dessus, s'échappant de chaque
* 'valeur' des paires clé/valeur.
*
* Valeurs de contexte valides : html, js, css, url, attr, raw, null
*
* @param array|string $data Les données à échapper
* @param string|null $context Le contexte d'échappement
* @param string|null $encoding L'encodage à utiliser
*
* @return array|string Les données échappées
*
* @throws InvalidArgumentException Si le contexte n'est pas valide
*/
public static function esc($data, ?string $context = 'html', ?string $encoding = null)
{
if (is_array($data)) {
foreach ($data as $key => &$value) {
$value = self::esc($value, $context);
}
}
if (is_string($data)) {
$context = strtolower($context);
// Fournit un moyen de NE PAS échapper aux données depuis
// cela pourrait être appelé automatiquement par la bibliothèque View.
if (empty($context) || $context === 'raw') {
return $data;
}
if (! in_array($context, ['html', 'js', 'css', 'url', 'attr'], true)) {
throw new InvalidArgumentException("Contexte d'échappement invalide fourni.");
}
if ($context === 'attr') {
$method = 'escapeHtmlAttr';
} else {
$method = 'escape' . ucfirst($context);
}
if (self::$escaper === null) {
self::$escaper = new \Laminas\Escaper\Escaper($encoding);
} elseif ($encoding && self::$escaper->getEncoding() !== $encoding) {
self::$escaper = new \Laminas\Escaper\Escaper($encoding);
}
$data = self::$escaper->{$method}($data);
}
return $data;
}
/**
* Recherche l'URL de base de l'application indépendamment de la configuration de l'utilisateur
*
* @return string L'URL de base de l'application
*/
public static function findBaseUrl(): string
{
if (! isset($_SERVER['SERVER_ADDR'])) {
return 'http://localhost:' . ($_SERVER['SERVER_PORT'] ?? '80');
}
$server_addr = $_SERVER['HTTP_HOST'] ?? ((str_contains($_SERVER['SERVER_ADDR'], ':')) ? '[' . $_SERVER['SERVER_ADDR'] . ']' : $_SERVER['SERVER_ADDR']);
$scheme = 'http';
if (
(! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
|| (! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
) {
$scheme = 'https';
}
return trim($scheme . '://' . $server_addr . dirname(substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'], basename($_SERVER['SCRIPT_FILENAME'])))), '/\\') ?: '/';
}
/**
* Méthode pratique pour htmlspecialchars.
*
* @param mixed $text Texte à envelopper dans htmlspecialchars. Fonctionne également avec des tableaux et des objets.
* Les tableaux seront mappés et tous leurs éléments seront échappés. Les objets seront transtypés s'ils
* implémenter une méthode `__toString`. Sinon, le nom de la classe sera utilisé.
* Les autres types de scalaires seront renvoyés tels quels.
* @param bool $double Encodez les entités html existantes.
* @param string|null $charset Jeu de caractères à utiliser lors de l'échappement. La valeur par défaut est la valeur de configuration dans `mb_internal_encoding()` ou 'UTF-8'.
*
* @return mixed Texte enveloppé.
*
* @credit CackePHP (https://cakephp.org)
*/
public static function h($text, bool $double = true, ?string $charset = null): mixed
{
if (is_string($text)) {
// optimize for strings
} elseif (is_array($text)) {
$texts = [];
foreach ($text as $k => $t) {
$texts[$k] = static::h($t, $double, $charset);
}
return $texts;
} elseif (is_object($text)) {
if (method_exists($text, '__toString')) {
$text = (string) $text;
} else {
$text = '(object)' . get_class($text);
}
} elseif ($text === null || is_scalar($text)) {
return $text;
}
static $defaultCharset = false;
if ($defaultCharset === false) {
$defaultCharset = mb_internal_encoding();
if ($defaultCharset === null) {
$defaultCharset = 'UTF-8';
}
}
if (is_string($double)) {
self::deprecationWarning(
'Passing charset string for 2nd argument is deprecated. ' .
'Use the 3rd argument instead.'
);
$charset = $double;
$double = true;
}
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, $charset ?: $defaultCharset, $double);
}
/**
* Récupère le premier élément d'un tableau. Utile pour l'enchaînement de méthodes.
*
* @param array $array Le tableau à traiter
*
* @return mixed Le premier élément du tableau
*/
public static function head(array $array): mixed
{
return reset($array);
}
/**
* Crée un envahisseur pour accéder aux propriétés et méthodes privées
*
* @template T of object
*
* @param class-string|T $object L'objet ou le nom de classe à envahir
*
* @return Invader<T>|StaticInvader L'instance d'envahisseur
*/
public static function invade(object|string $object): Invader|StaticInvader
{
if (is_object($object)) {
return new Invader($object);
}
return new StaticInvader($object);
}
/**
* Obtenez l'adresse IP que le client utilise ou dit qu'il utilise.
*
* @return string L'adresse IP du client
*/
public static function ipAddress(): string
{
// Obtenez une véritable IP de visiteur derrière le réseau CloudFlare
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
$_SERVER['HTTP_CLIENT_IP'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
$client = $_SERVER['HTTP_CLIENT_IP'] ?? '';
$forward = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
$remote = $_SERVER['REMOTE_ADDR'] ?? '';
if (filter_var($client, FILTER_VALIDATE_IP)) {
$ip = $client;
} elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
$ip = $forward;
} elseif (filter_var($remote, FILTER_VALIDATE_IP)) {
$ip = $remote;
} else {
$ip = $_SERVER['SERVER_ADDR'] ?? '';
if (empty($ip) || $ip === '::1') {
$ip = gethostname();
if ($ip) {
$ip = gethostbyname($ip);
} else {
$ip = $_SESSION['HTTP_HOST'] ?? '127.0.0.1';
}
}
}
return $ip;
}
/**
* Vérifie si un chemin donné est un chemin absolu ou relatif
*
* @param string $path Le chemin à vérifier
* @param bool $verbose Si true, lance une exception en cas d'erreur
*
* @return bool True si le chemin est absolu, false sinon
*
* @throws DomainException Si le chemin contient des caractères non imprimables ou n'est pas valide
*/
public static function isAbsolutePath(string $path, bool $verbose = false): bool
{
if (! ctype_print($path)) {
if ($verbose) {
throw new DomainException('Le chemin ne peut PAS contenir de caractères non imprimables ou être vide');
}
return false;
}
// Emballage(s) facultatif(s).
$regExp = '%^(?<wrappers>(?:[[:print:]]{2,}://)*)';
// Préfixe racine facultatif.
$regExp .= '(?<root>(?:[[:alpha:]]:/|/)?)';
// Chemin réel.
$regExp .= '(?<path>(?:[[:print:]]*))$%';
$parts = [];
if (! preg_match($regExp, $path, $parts)) {
if ($verbose) {
throw new DomainException(sprintf('Le chemin n\'est PAS valide, a été donné %s', $path));
}
return false;
}
return '' !== $parts['root'];
}
/**
* Vérifie si un chemin donné est une URL absolue ou relative
*
* @param string $path Le chemin à vérifier
*
* @return bool True si le chemin est une URL absolue, false sinon
*/
public static function isAbsoluteUrl(string $path): bool
{
return preg_match('#^(?:[a-z+]+:)?//#i', $path) !== false;
}
/**
* Vérifie si la requête est exécutée en AJAX
*
* @return bool True si la requête est AJAX, false sinon
*/
public static function isAjaxRequest(): bool
{
return ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
/**
* Vérifiez si une chaîne est encodée en Base64.
*
* @param string $input La chaîne à vérifier
*
* @return bool True si la chaîne est encodée en Base64, false sinon
*/
public static function isBase64Encoded(string $input): bool
{
if (! preg_match('/^[a-zA-Z0-9\/+]*={0,2}$/', $input)) {
return false;
}
$decoded = base64_decode($input, true);
return $decoded !== false && base64_encode($decoded) === $input;
}
/**
* Testez pour voir si une demande a été faite à partir de la ligne de commande.
*
* @return bool True si l'exécution est en CLI, false sinon
*/
public static function isCli(): bool
{
return PHP_SAPI === 'cli' || defined('STDIN');
}
/**
* Vérifie si l'utilisateur a une connexion internet active.
*
* @param array $endpoints Liste des endpoints à vérifier (host:port)
* @param int $timeout Timeout en secondes pour chaque connexion
*
* @return bool True si connecté à Internet, false sinon
*/
public static function isConnected(array $endpoints = ['www.google.com:80', '8.8.8.8:53', '1.1.1.1:53'], int $timeout = 2): bool
{
foreach ($endpoints as $endpoint) {
[$host, $port] = explode(':', $endpoint . ':80'); // Port par défaut 80
$connected = @fsockopen($host, (int) $port, $errno, $errstr, $timeout);
if ($connected) {
fclose($connected);
return true;
}
}
return false;
}
/**
* Tester si une application s'exécute en local ou en ligne
*
* @return bool True si en ligne, false si en local
*/
public static function isOnline(): bool
{
$host = explode(':', $_SERVER['HTTP_HOST'] ?? '')[0];
if (empty($host)) {
return false;
}
$localPatterns = [
'/\.dev$/i',
'/\.test$/i',
'/\.lab$/i',
'/\.loc(al)?$/i',
'/\.localhost$/i',
];
foreach ($localPatterns as $pattern) {
if (preg_match($pattern, $host)) {
return false;
}
}
return ! in_array($host, ['localhost', '127.0.0.1'], true)
&& ! preg_match('/^192\.168/', $host);
}
/**
* Détermine si la version actuelle de PHP est égale ou supérieure à la valeur fournie
*
* @param string $version La version PHP à vérifier
*
* @return bool True si la version PHP est suffisante, false sinon
*/
public static function isPhp(string $version): bool
{
if (! isset(self::$phpVersionCache[$version])) {
self::$phpVersionCache[$version] = version_compare(PHP_VERSION, $version, '>=');
}
return self::$phpVersionCache[$version];
}
/**
* Tests d'inscriptibilité des fichiers
*
* is_writable() renvoie TRUE sur les serveurs Windows lorsque vous ne pouvez vraiment pas écrire
* le fichier, basé sur l'attribut en lecture seule. is_writable() n'est pas non plus fiable
* sur les serveurs Unix si safe_mode est activé.
*
* @param string $file Le chemin du fichier à vérifier
*
* @return bool True si le fichier est réellement accessible en écriture, false sinon
*
* @throws Exception
*
* @see https://bugs.php.net/bug.php?id=54709
*/
public static function isReallyWritable(string $file): bool
{
// Si nous sommes sur un serveur Unix avec safe_mode désactivé, nous appelons is_writable
if (DIRECTORY_SEPARATOR === '/' || ! ini_get('safe_mode')) {
return is_writable($file);
}
/* Pour les serveurs Windows et les installations safe_mode "on", nous allons en fait
* écrire un fichier puis le lire. Bah...
*/
if (is_dir($file)) {
$file = rtrim($file, '/') . '/' . bin2hex(random_bytes(16));
if (($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
@chmod($file, 0o777);
@unlink($file);
return true;
}
if (! is_file($file) || ($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
return true;
}
/**
* Récupère le dernier élément d'un tableau.
*
* @param array $array Le tableau à traiter
*
* @return mixed Le dernier élément du tableau
*/
public static function last(array $array): mixed
{
return end($array);
}
/**
* Séparez l'espace de noms du nom de classe.
*
* Couramment utilisé comme `list($namespace, $className) = Helpers::namespaceSplit($class);`.
*
* @param string $class Le nom complet de la classe, ie `BlitzPHP\Core\App`.
*
* @return list<string> Tableau avec 2 index. 0 => namespace, 1 => nom de la classe.
*/
public static function namespaceSplit(string $class): array
{
$pos = strrpos($class, '\\');
if ($pos === false) {
return ['', $class];
}
return [substr($class, 0, $pos), substr($class, $pos + 1)];
}
/**
* Jolie fonction de commodité d'impression JSON.
*
* Dans les terminaux, cela agira de la même manière que json_encode() avec JSON_PRETTY_PRINT directement, lorsqu'il n'est pas exécuté sur cli
* enveloppera également les balises <pre> autour de la sortie de la variable donnée. Similaire à pr().
*
* Cette fonction renvoie la même variable qui a été transmise.
*
* @param mixed $var Variable à imprimer.
*
* @return mixed le même $var qui a été passé à cette fonction
*
* @see pr()
*/
public static function pj($var)
{
$template = (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') ? '<pre class="pj">%s</pre>' : "\n%s\n\n";
printf($template, trim(json_encode($var, JSON_PRETTY_PRINT)));
return $var;
}
/**
* Enregistre une nouvelle configuration pour HTMLPurifier
*
* @param string $name Le nom de la configuration
* @param array $config La configuration
*/
public static function registerPurifierConfig(string $name, array $config): void
{
self::$purifierConfigs[$name] = $config;
}
/**
* Purifiez l'entrée à l'aide de la classe autonome HTMLPurifier.
* Utilisez facilement plusieurs configurations de purificateur.
*
* @param list<string>|string $dirty_html Le HTML à purifier
* @param false|string $config La configuration à utiliser
* @param string $charset Le charset à utiliser
*
* @return list<string>|string Le HTML purifié
*
* @throws InvalidArgumentException Si la configuration n'est pas trouvée