GeneralUtility.php 166 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Core\Utility;

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
Wouter Wolters's avatar
Wouter Wolters committed
16

17
use GuzzleHttp\Exception\RequestException;
18
use Psr\Container\ContainerInterface;
19
use Psr\Log\LoggerAwareInterface;
20
use Psr\Log\LoggerInterface;
21
use TYPO3\CMS\Core\Cache\CacheManager;
22
use TYPO3\CMS\Core\Core\ApplicationContext;
23
use TYPO3\CMS\Core\Core\ClassLoadingInformation;
24
use TYPO3\CMS\Core\Core\Environment;
25
use TYPO3\CMS\Core\Http\RequestFactory;
26
use TYPO3\CMS\Core\Log\LogManager;
27
use TYPO3\CMS\Core\Service\OpcodeCacheService;
28
use TYPO3\CMS\Core\SingletonInterface;
29

30
31
32
33
34
35
36
37
38
/**
 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
 * Most of the functions do not relate specifically to TYPO3
 * However a section of functions requires certain TYPO3 features available
 * See comments in the source.
 * You are encouraged to use this library in your own scripts!
 *
 * USE:
 * The class is intended to be used without creating an instance of it.
39
 * So: Don't instantiate - call functions with "\TYPO3\CMS\Core\Utility\GeneralUtility::" prefixed the function name.
40
 * So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'
41
 */
42
43
44
45
46
47
48
49
50
51
52
53
54
class GeneralUtility
{
    const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*';
    const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME';

    /**
     * State of host header value security check
     * in order to avoid unnecessary multiple checks during one request
     *
     * @var bool
     */
    protected static $allowHostHeaderValue = false;

55
56
57
58
59
    /**
     * @var ContainerInterface|null
     */
    protected static $container;

60
61
62
63
64
65
    /**
     * Singleton instances returned by makeInstance, using the class names as
     * array keys
     *
     * @var array<\TYPO3\CMS\Core\SingletonInterface>
     */
66
    protected static $singletonInstances = [];
67
68
69
70
71
72

    /**
     * Instances returned by makeInstance, using the class names as array keys
     *
     * @var array<array><object>
     */
73
    protected static $nonSingletonInstances = [];
74
75
76
77
78
79

    /**
     * Cache for makeInstance with given class name and final class names to reduce number of self::getClassName() calls
     *
     * @var array Given class name => final class name
     */
80
    protected static $finalClassNameCache = [];
81
82
83
84
85

    /**
     * The application context
     *
     * @var \TYPO3\CMS\Core\Core\ApplicationContext
86
     * @deprecated will be removed in TYPO3 v11.
87
     */
88
    protected static $applicationContext;
89
90
91
92
93
94

    /**
     * A list of supported CGI server APIs
     * NOTICE: This is a duplicate of the SAME array in SystemEnvironmentBuilder
     * @var array
     */
95
    protected static $supportedCgiServerApis = [
96
97
98
99
100
        'fpm-fcgi',
        'cgi',
        'isapi',
        'cgi-fcgi',
        'srv', // HHVM with fastcgi
101
    ];
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    /**
     * @var array
     */
    protected static $indpEnvCache = [];

    /*************************
     *
     * GET/POST Variables
     *
     * Background:
     * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
     * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
     * But the clean solution is that quotes are never escaped and that is what the functions below offers.
     * Eventually TYPO3 should provide this in the global space as well.
     * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
     * This functionality was previously needed to normalize between magic quotes logic, which was removed from PHP 5.4,
     * so these methods are still in use, but not tackle the slash problem anymore.
     *
     *************************/
    /**
123
     * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST, which is equivalent to 'GP' order
124
     * In case you already know by which method your data is arriving consider using GeneralUtility::_GET or GeneralUtility::_POST.
125
126
     *
     * @param string $var GET/POST var to return
127
     * @return mixed POST var named $var, if not set, the GET var of the same name and if also not set, NULL.
128
129
130
131
132
133
     */
    public static function _GP($var)
    {
        if (empty($var)) {
            return;
        }
134
135
136
137
138
139
140
        if (isset($_POST[$var])) {
            $value = $_POST[$var];
        } elseif (isset($_GET[$var])) {
            $value = $_GET[$var];
        } else {
            $value = null;
        }
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        // This is there for backwards-compatibility, in order to avoid NULL
        if (isset($value) && !is_array($value)) {
            $value = (string)$value;
        }
        return $value;
    }

    /**
     * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
     *
     * @param string $parameter Key (variable name) from GET or POST vars
     * @return array Returns the GET vars merged recursively onto the POST vars.
     */
    public static function _GPmerged($parameter)
    {
156
157
        $postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : [];
        $getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : [];
158
159
160
161
162
163
164
165
166
167
        $mergedParameters = $getParameter;
        ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter);
        return $mergedParameters;
    }

    /**
     * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
     * This function was previously used to normalize between magic quotes logic, which was removed from PHP 5.5
     *
     * @param string $var Optional pointer to value in GET array (basically name of GET var)
168
     * @return mixed If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself.
169
170
     * @see _POST()
     * @see _GP()
171
172
173
     */
    public static function _GET($var = null)
    {
174
175
176
        $value = $var === null
            ? $_GET
            : (empty($var) ? null : ($_GET[$var] ?? null));
177
178
179
180
181
182
183
184
185
186
187
        // This is there for backwards-compatibility, in order to avoid NULL
        if (isset($value) && !is_array($value)) {
            $value = (string)$value;
        }
        return $value;
    }

    /**
     * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
     *
     * @param string $var Optional pointer to value in POST array (basically name of POST var)
188
     * @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself.
189
190
     * @see _GET()
     * @see _GP()
191
192
193
     */
    public static function _POST($var = null)
    {
194
        $value = $var === null ? $_POST : (empty($var) || !isset($_POST[$var]) ? null : $_POST[$var]);
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        // This is there for backwards-compatibility, in order to avoid NULL
        if (isset($value) && !is_array($value)) {
            $value = (string)$value;
        }
        return $value;
    }

    /*************************
     *
     * STRING FUNCTIONS
     *
     *************************/
    /**
     * Truncates a string with appended/prepended "..." and takes current character set into consideration.
     *
     * @param string $string String to truncate
     * @param int $chars Must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
     * @param string $appendString Appendix to the truncated string
     * @return string Cropped string
     */
    public static function fixed_lgd_cs($string, $chars, $appendString = '...')
    {
217
218
219
220
221
222
        if ((int)$chars === 0 || mb_strlen($string, 'utf-8') <= abs($chars)) {
            return $string;
        }
        if ($chars > 0) {
            $string = mb_substr($string, 0, $chars, 'utf-8') . $appendString;
        } else {
223
            $string = $appendString . mb_substr($string, $chars, mb_strlen($string, 'utf-8'), 'utf-8');
224
225
        }
        return $string;
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    }

    /**
     * Match IP number with list of numbers with wildcard
     * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
     *
     * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
     * @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE.
     * @return bool TRUE if an IP-mask from $list matches $baseIP
     */
    public static function cmpIP($baseIP, $list)
    {
        $list = trim($list);
        if ($list === '') {
            return false;
241
242
        }
        if ($list === '*') {
243
244
245
246
247
            return true;
        }
        if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
            return self::cmpIPv6($baseIP, $list);
        }
248
        return self::cmpIPv4($baseIP, $list);
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
    }

    /**
     * Match IPv4 number with list of numbers with wildcard
     *
     * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
     * @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168), could also contain IPv6 addresses
     * @return bool TRUE if an IP-mask from $list matches $baseIP
     */
    public static function cmpIPv4($baseIP, $list)
    {
        $IPpartsReq = explode('.', $baseIP);
        if (count($IPpartsReq) === 4) {
            $values = self::trimExplode(',', $list, true);
            foreach ($values as $test) {
                $testList = explode('/', $test);
                if (count($testList) === 2) {
                    list($test, $mask) = $testList;
                } else {
                    $mask = false;
                }
                if ((int)$mask) {
                    // "192.168.3.0/24"
                    $lnet = ip2long($test);
                    $lip = ip2long($baseIP);
                    $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
                    $firstpart = substr($binnet, 0, $mask);
                    $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
                    $firstip = substr($binip, 0, $mask);
                    $yes = $firstpart === $firstip;
                } else {
                    // "192.168.*.*"
                    $IPparts = explode('.', $test);
                    $yes = 1;
                    foreach ($IPparts as $index => $val) {
                        $val = trim($val);
                        if ($val !== '*' && $IPpartsReq[$index] !== $val) {
                            $yes = 0;
                        }
                    }
                }
                if ($yes) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Match IPv6 address with a list of IPv6 prefixes
     *
     * @param string $baseIP Is the current remote IP address for instance
     * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
303
     * @return bool TRUE If a baseIP matches any prefix
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
     */
    public static function cmpIPv6($baseIP, $list)
    {
        // Policy default: Deny connection
        $success = false;
        $baseIP = self::normalizeIPv6($baseIP);
        $values = self::trimExplode(',', $list, true);
        foreach ($values as $test) {
            $testList = explode('/', $test);
            if (count($testList) === 2) {
                list($test, $mask) = $testList;
            } else {
                $mask = false;
            }
            if (self::validIPv6($test)) {
                $test = self::normalizeIPv6($test);
                $maskInt = (int)$mask ?: 128;
                // Special case; /0 is an allowed mask - equals a wildcard
                if ($mask === '0') {
                    $success = true;
                } elseif ($maskInt == 128) {
                    $success = $test === $baseIP;
                } else {
                    $testBin = self::IPv6Hex2Bin($test);
                    $baseIPBin = self::IPv6Hex2Bin($baseIP);
                    $success = true;
                    // Modulo is 0 if this is a 8-bit-boundary
                    $maskIntModulo = $maskInt % 8;
                    $numFullCharactersUntilBoundary = (int)($maskInt / 8);
333
                    if (strpos($testBin, substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) !== 0) {
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
                        $success = false;
                    } elseif ($maskIntModulo > 0) {
                        // If not an 8-bit-boundary, check bits of last character
                        $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
                        $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
                        if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
                            $success = false;
                        }
                    }
                }
            }
            if ($success) {
                return true;
            }
        }
        return false;
    }

    /**
     * Transform a regular IPv6 address from hex-representation into binary
     *
     * @param string $hex IPv6 address in hex-presentation
     * @return string Binary representation (16 characters, 128 characters)
     * @see IPv6Bin2Hex()
     */
    public static function IPv6Hex2Bin($hex)
    {
        return inet_pton($hex);
    }

    /**
     * Transform an IPv6 address from binary to hex-representation
     *
     * @param string $bin IPv6 address in hex-presentation
     * @return string Binary representation (16 characters, 128 characters)
     * @see IPv6Hex2Bin()
     */
    public static function IPv6Bin2Hex($bin)
    {
        return inet_ntop($bin);
    }

    /**
     * Normalize an IPv6 address to full length
     *
     * @param string $address Given IPv6 address
     * @return string Normalized address
     * @see compressIPv6()
     */
    public static function normalizeIPv6($address)
    {
        $normalizedAddress = '';
        // According to RFC lowercase-representation is recommended
        $address = strtolower($address);
        // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
Benni Mack's avatar
Benni Mack committed
389
        if (strlen($address) === 39) {
390
391
392
393
394
395
396
397
398
399
400
            // Already in full expanded form
            return $address;
        }
        // Count 2 if if address has hidden zero blocks
        $chunks = explode('::', $address);
        if (count($chunks) === 2) {
            $chunksLeft = explode(':', $chunks[0]);
            $chunksRight = explode(':', $chunks[1]);
            $left = count($chunksLeft);
            $right = count($chunksRight);
            // Special case: leading zero-only blocks count to 1, should be 0
Benni Mack's avatar
Benni Mack committed
401
            if ($left === 1 && strlen($chunksLeft[0]) === 0) {
402
403
404
405
406
407
408
409
410
                $left = 0;
            }
            $hiddenBlocks = 8 - ($left + $right);
            $hiddenPart = '';
            $h = 0;
            while ($h < $hiddenBlocks) {
                $hiddenPart .= '0000:';
                $h++;
            }
Benni Mack's avatar
Benni Mack committed
411
            if ($left === 0) {
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
                $stageOneAddress = $hiddenPart . $chunks[1];
            } else {
                $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
            }
        } else {
            $stageOneAddress = $address;
        }
        // Normalize the blocks:
        $blocks = explode(':', $stageOneAddress);
        $divCounter = 0;
        foreach ($blocks as $block) {
            $tmpBlock = '';
            $i = 0;
            $hiddenZeros = 4 - strlen($block);
            while ($i < $hiddenZeros) {
                $tmpBlock .= '0';
                $i++;
            }
            $normalizedAddress .= $tmpBlock . $block;
            if ($divCounter < 7) {
                $normalizedAddress .= ':';
                $divCounter++;
            }
        }
        return $normalizedAddress;
    }

    /**
     * Compress an IPv6 address to the shortest notation
     *
     * @param string $address Given IPv6 address
     * @return string Compressed address
     * @see normalizeIPv6()
     */
    public static function compressIPv6($address)
    {
        return inet_ntop(inet_pton($address));
    }

    /**
     * Validate a given IP address.
     *
     * Possible format are IPv4 and IPv6.
     *
     * @param string $ip IP address to be tested
     * @return bool TRUE if $ip is either of IPv4 or IPv6 format.
     */
    public static function validIP($ip)
    {
        return filter_var($ip, FILTER_VALIDATE_IP) !== false;
    }

    /**
     * Validate a given IP address to the IPv4 address format.
     *
     * Example for possible format: 10.0.45.99
     *
     * @param string $ip IP address to be tested
     * @return bool TRUE if $ip is of IPv4 format.
     */
    public static function validIPv4($ip)
    {
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
    }

    /**
     * Validate a given IP address to the IPv6 address format.
     *
     * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
     *
     * @param string $ip IP address to be tested
     * @return bool TRUE if $ip is of IPv6 format.
     */
    public static function validIPv6($ip)
    {
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
    }

    /**
     * Match fully qualified domain name with list of strings with wildcard
     *
     * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
     * @param string $list A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
     * @return bool TRUE if a domain name mask from $list matches $baseIP
     */
    public static function cmpFQDN($baseHost, $list)
    {
        $baseHost = trim($baseHost);
        if (empty($baseHost)) {
            return false;
        }
        if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
            // Resolve hostname
            // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
            // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
            $baseHostName = gethostbyaddr($baseHost);
            if ($baseHostName === $baseHost) {
                // Unable to resolve hostname
                return false;
            }
        } else {
            $baseHostName = $baseHost;
        }
        $baseHostNameParts = explode('.', $baseHostName);
        $values = self::trimExplode(',', $list, true);
        foreach ($values as $test) {
            $hostNameParts = explode('.', $test);
            // To match hostNameParts can only be shorter (in case of wildcards) or equal
            $hostNamePartsCount = count($hostNameParts);
            $baseHostNamePartsCount = count($baseHostNameParts);
            if ($hostNamePartsCount > $baseHostNamePartsCount) {
                continue;
            }
            $yes = true;
            foreach ($hostNameParts as $index => $val) {
                $val = trim($val);
                if ($val === '*') {
                    // Wildcard valid for one or more hostname-parts
                    $wildcardStart = $index + 1;
                    // Wildcard as last/only part always matches, otherwise perform recursive checks
                    if ($wildcardStart < $hostNamePartsCount) {
                        $wildcardMatched = false;
                        $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
                        while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) {
                            $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
                            $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
                            $wildcardStart++;
                        }
                        if ($wildcardMatched) {
                            // Match found by recursive compare
                            return true;
                        }
544
                        $yes = false;
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
                    }
                } elseif ($baseHostNameParts[$index] !== $val) {
                    // In case of no match
                    $yes = false;
                }
            }
            if ($yes) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks if a given URL matches the host that currently handles this HTTP request.
     * Scheme, hostname and (optional) port of the given URL are compared.
     *
     * @param string $url URL to compare with the TYPO3 request host
     * @return bool Whether the URL matches the TYPO3 request host
     */
    public static function isOnCurrentHost($url)
    {
        return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
    }

    /**
     * Check for item in list
     * Check if an item exists in a comma-separated list of items.
     *
     * @param string $list Comma-separated list of items (string)
     * @param string $item Item to check for
     * @return bool TRUE if $item is in $list
     */
    public static function inList($list, $item)
    {
        return strpos(',' . $list . ',', ',' . $item . ',') !== false;
    }

    /**
     * Removes an item from a comma-separated list of items.
     *
     * If $element contains a comma, the behaviour of this method is undefined.
     * Empty elements in the list are preserved.
     *
     * @param string $element Element to remove
     * @param string $list Comma-separated list of items (string)
     * @return string New comma-separated list of items
     */
    public static function rmFromList($element, $list)
    {
        $items = explode(',', $list);
        foreach ($items as $k => $v) {
            if ($v == $element) {
                unset($items[$k]);
            }
        }
        return implode(',', $items);
    }

    /**
     * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
     * Ranges are limited to 1000 values per range.
     *
     * @param string $list Comma-separated list of integers with ranges (string)
     * @return string New comma-separated list of items
     */
    public static function expandList($list)
    {
        $items = explode(',', $list);
614
        $list = [];
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
        foreach ($items as $item) {
            $range = explode('-', $item);
            if (isset($range[1])) {
                $runAwayBrake = 1000;
                for ($n = $range[0]; $n <= $range[1]; $n++) {
                    $list[] = $n;
                    $runAwayBrake--;
                    if ($runAwayBrake <= 0) {
                        break;
                    }
                }
            } else {
                $list[] = $item;
            }
        }
        return implode(',', $list);
    }

    /**
     * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
     *
     * @param string $str String to md5-hash
     * @return int Returns 28bit integer-hash
     */
    public static function md5int($str)
    {
        return hexdec(substr(md5($str), 0, 7));
    }

    /**
     * Returns the first 10 positions of the MD5-hash		(changed from 6 to 10 recently)
     *
     * @param string $input Input string to be md5-hashed
     * @param int $len The string-length of the output
     * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
     */
    public static function shortMD5($input, $len = 10)
    {
        return substr(md5($input), 0, $len);
    }

    /**
     * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
     *
     * @param string $input Input string to create HMAC from
660
     * @param string $additionalSecret additionalSecret to prevent hmac being used in a different context
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
     * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
     */
    public static function hmac($input, $additionalSecret = '')
    {
        $hashAlgorithm = 'sha1';
        $hashBlocksize = 64;
        $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
        if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
            $hmac = hash_hmac($hashAlgorithm, $input, $secret);
        } else {
            // Outer padding
            $opad = str_repeat(chr(92), $hashBlocksize);
            // Inner padding
            $ipad = str_repeat(chr(54), $hashBlocksize);
            if (strlen($secret) > $hashBlocksize) {
                // Keys longer than block size are shorten
677
                $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, "\0");
678
679
            } else {
                // Keys shorter than block size are zero-padded
680
                $key = str_pad($secret, $hashBlocksize, "\0");
681
            }
682
683
            $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func(
                $hashAlgorithm,
Benni Mack's avatar
Benni Mack committed
684
                ($key ^ $ipad) . $input
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
        }
        return $hmac;
    }

    /**
     * Takes comma-separated lists and arrays and removes all duplicates
     * If a value in the list is trim(empty), the value is ignored.
     *
     * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
     * @param mixed $secondParameter Dummy field, which if set will show a warning!
     * @return string Returns the list without any duplicates of values, space around values are trimmed
     */
    public static function uniqueList($in_list, $secondParameter = null)
    {
        if (is_array($in_list)) {
            throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
        }
        if (isset($secondParameter)) {
            throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!', 1270853886);
        }
        return implode(',', array_unique(self::trimExplode(',', $in_list, true)));
    }

    /**
     * Splits a reference to a file in 5 parts
     *
712
     * @param string $fileNameWithPath File name with path to be analyzed (must exist if open_basedir is set)
713
714
715
716
     * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
     */
    public static function split_fileref($fileNameWithPath)
    {
717
        $reg = [];
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
        if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) {
            $info['path'] = $reg[1];
            $info['file'] = $reg[2];
        } else {
            $info['path'] = '';
            $info['file'] = $fileNameWithPath;
        }
        $reg = '';
        // If open_basedir is set and the fileName was supplied without a path the is_dir check fails
        if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) {
            $info['filebody'] = $reg[1];
            $info['fileext'] = strtolower($reg[2]);
            $info['realFileext'] = $reg[2];
        } else {
            $info['filebody'] = $info['file'];
            $info['fileext'] = '';
        }
        reset($info);
        return $info;
    }

    /**
     * Returns the directory part of a path without trailing slash
     * If there is no dir-part, then an empty string is returned.
     * Behaviour:
     *
     * '/dir1/dir2/script.php' => '/dir1/dir2'
     * '/dir1/' => '/dir1'
     * 'dir1/script.php' => 'dir1'
     * 'd/script.php' => 'd'
     * '/script.php' => ''
     * '' => ''
     *
     * @param string $path Directory name / path
     * @return string Processed input value. See function description.
     */
    public static function dirname($path)
    {
        $p = self::revExplode('/', $path, 2);
        return count($p) === 2 ? $p[0] : '';
    }

    /**
     * Returns TRUE if the first part of $str matches the string $partStr
     *
     * @param string $str Full string to check
     * @param string $partStr Reference string which must be found as the "first part" of the full string
     * @return bool TRUE if $partStr was found to be equal to the first part of $str
     */
    public static function isFirstPartOfStr($str, $partStr)
    {
769
770
771
        $str = is_array($str) ? '' : (string)$str;
        $partStr = is_array($partStr) ? '' : (string)$partStr;
        return $partStr !== '' && strpos($str, $partStr, 0) === 0;
772
773
774
775
776
777
778
779
780
781
782
783
    }

    /**
     * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
     *
     * @param int $sizeInBytes Number of bytes to format.
     * @param string $labels Binary unit name "iec", decimal unit name "si" or labels for bytes, kilo, mega, giga, and so on separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G". Defaults to "iec".
     * @param int $base The unit base if not using a unit name. Defaults to 1024.
     * @return string Formatted representation of the byte number, for output.
     */
    public static function formatSize($sizeInBytes, $labels = '', $base = 0)
    {
784
785
786
787
        $defaultFormats = [
            'iec' => ['base' => 1024, 'labels' => [' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi']],
            'si' => ['base' => 1000, 'labels' => [' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']],
        ];
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
        // Set labels and base:
        if (empty($labels)) {
            $labels = 'iec';
        }
        if (isset($defaultFormats[$labels])) {
            $base = $defaultFormats[$labels]['base'];
            $labelArr = $defaultFormats[$labels]['labels'];
        } else {
            $base = (int)$base;
            if ($base !== 1000 && $base !== 1024) {
                $base = 1024;
            }
            $labelArr = explode('|', str_replace('"', '', $labels));
        }
        // @todo find out which locale is used for current BE user to cover the BE case as well
        $oldLocale = setlocale(LC_NUMERIC, 0);
804
        $newLocale = $GLOBALS['TSFE']->config['config']['locale_all'] ?? '';
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
        if ($newLocale) {
            setlocale(LC_NUMERIC, $newLocale);
        }
        $localeInfo = localeconv();
        if ($newLocale) {
            setlocale(LC_NUMERIC, $oldLocale);
        }
        $sizeInBytes = max($sizeInBytes, 0);
        $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base));
        $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
        if ($sizeInUnits > ($base * .9)) {
            $multiplier++;
        }
        $multiplier = min($multiplier, count($labelArr) - 1);
        $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
        return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier];
    }

    /**
     * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
     *
     * @param string $string Input string, eg "123 + 456 / 789 - 4
     * @param string $operators Operators to split by, typically "/+-*
     * @return array Array with operators and operands separated.
829
830
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc()
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
831
832
833
     */
    public static function splitCalc($string, $operators)
    {
834
        $res = [];
835
836
837
838
        $sign = '+';
        while ($string) {
            $valueLen = strcspn($string, $operators);
            $value = substr($string, 0, $valueLen);
839
            $res[] = [$sign, trim($value)];
840
841
842
843
844
845
846
847
848
849
850
851
            $sign = substr($string, $valueLen, 1);
            $string = substr($string, $valueLen + 1);
        }
        reset($res);
        return $res;
    }

    /**
     * Checking syntax of input email address
     *
     * http://tools.ietf.org/html/rfc3696
     * International characters are allowed in email. So the whole address needs
852
     * to be converted to punicode before passing it to filter_var().
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
     *
     * Also the @ sign may appear multiple times in an address. If not used as
     * a boundary marker between the user- and domain part, it must be escaped
     * with a backslash: \@. This mean we can not just explode on the @ sign and
     * expect to get just two parts. So we pop off the domain and then glue the
     * rest together again.
     *
     * @param string $email Input string to evaluate
     * @return bool Returns TRUE if the $email address (input string) is valid
     */
    public static function validEmail($email)
    {
        // Early return in case input is not a string
        if (!is_string($email)) {
            return false;
        }
        $atPosition = strrpos($email, '@');
        if (!$atPosition || $atPosition + 1 === strlen($email)) {
            // Return if no @ found or it is placed at the very beginning or end of the email
            return false;
        }
        $domain = substr($email, $atPosition + 1);
        $user = substr($email, 0, $atPosition);
        if (!preg_match('/^[a-z0-9.\\-]*$/i', $domain)) {
877
            $domain = HttpUtility::idn_to_ascii($domain);
878
            if ($domain === false) {
879
880
                return false;
            }
881
882
883
884
885
886
887
888
889
        }
        return filter_var($user . '@' . $domain, FILTER_VALIDATE_EMAIL) !== false;
    }

    /**
     * Returns an ASCII string (punicode) representation of $value
     *
     * @param string $value
     * @return string An ASCII encoded (punicode) string
890
     * @deprecated since TYPO3 v10.0, will be removed in TYPO3 v11.0, use PHP's native idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) function directly.
891
892
893
     */
    public static function idnaEncode($value)
    {
894
        trigger_error(__METHOD__ . ' will be removed in TYPO3 v11.0. Use PHPs native "idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46)" function directly instead.', E_USER_DEPRECATED);
895
896
897
898
899
900
901
902
903
904
        // Early return in case input is not a string or empty
        if (!is_string($value) || empty($value)) {
            return (string)$value;
        }
        // Split on the last "@" since addresses like "foo@bar"@example.org are valid where the only focus
        // is an email address
        $atPosition = strrpos($value, '@');
        if ($atPosition !== false) {
            $domain = substr($value, $atPosition + 1);
            $local = substr($value, 0, $atPosition);
905
            $domain = (string)HttpUtility::idn_to_ascii($domain);
906
907
            // Return if no @ found or it is placed at the very beginning or end of the email
            return $local . '@' . $domain;
908
        }
909
        return (string)HttpUtility::idn_to_ascii($value);
910
911
912
913
914
915
916
917
918
919
920
    }

    /**
     * Returns a given string with underscores as UpperCamelCase.
     * Example: Converts blog_example to BlogExample
     *
     * @param string $string String to be converted to camel case
     * @return string UpperCamelCasedWord
     */
    public static function underscoredToUpperCamelCase($string)
    {
921
        return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string))));
922
923
924
925
926
927
928
929
930
931
932
    }

    /**
     * Returns a given string with underscores as lowerCamelCase.
     * Example: Converts minimal_value to minimalValue
     *
     * @param string $string String to be converted to camel case
     * @return string lowerCamelCasedWord
     */
    public static function underscoredToLowerCamelCase($string)
    {
933
        return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string)))));
934
935
936
    }

    /**
937
     * Returns a given CamelCasedString as a lowercase string with underscores.
938
939
940
941
942
943
944
     * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
     *
     * @param string $string String to be converted to lowercase underscore
     * @return string lowercase_and_underscored_string
     */
    public static function camelCaseToLowerCaseUnderscored($string)
    {
945
        $value = preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string);
946
        return mb_strtolower($value, 'utf-8');
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
    }

    /**
     * Checks if a given string is a Uniform Resource Locator (URL).
     *
     * On seriously malformed URLs, parse_url may return FALSE and emit an
     * E_WARNING.
     *
     * filter_var() requires a scheme to be present.
     *
     * http://www.faqs.org/rfcs/rfc2396.html
     * Scheme names consist of a sequence of characters beginning with a
     * lower case letter and followed by any combination of lower case letters,
     * digits, plus ("+"), period ("."), or hyphen ("-").  For resiliency,
     * programs interpreting URI should treat upper case letters as equivalent to
     * lower case in scheme names (e.g., allow "HTTP" as well as "http").
     * scheme = alpha *( alpha | digit | "+" | "-" | "." )
     *
     * Convert the domain part to punicode if it does not look like a regular
     * domain name. Only the domain part because RFC3986 specifies the the rest of
     * the url may not contain special characters:
     * http://tools.ietf.org/html/rfc3986#appendix-A
     *
     * @param string $url The URL to be validated
     * @return bool Whether the given URL is valid
     */
    public static function isValidUrl($url)
    {
        $parsedUrl = parse_url($url);
        if (!$parsedUrl || !isset($parsedUrl['scheme'])) {
            return false;
        }
        // HttpUtility::buildUrl() will always build urls with <scheme>://
        // our original $url might only contain <scheme>: (e.g. mail:)
        // so we convert that to the double-slashed version to ensure
        // our check against the $recomposedUrl is proper
        if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
            $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
        }
        $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
        if ($recomposedUrl !== $url) {
            // The parse_url() had to modify characters, so the URL is invalid
            return false;
        }
        if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
992
            $host = HttpUtility::idn_to_ascii($parsedUrl['host']);
993
            if ($host === false) {
994
995
                return false;
            }
996
            $parsedUrl['host'] = $host;
997
998
999
1000
        }
        return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false;
    }