Passed
Push — master ( 72e0fa...2cc09d )
by
unknown
14:25
created

GeneralUtility::validIPv4()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Core\Utility;
17
18
use Egulias\EmailValidator\EmailValidator;
19
use Egulias\EmailValidator\Validation\EmailValidation;
20
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
21
use Egulias\EmailValidator\Validation\RFCValidation;
22
use GuzzleHttp\Exception\RequestException;
23
use Psr\Container\ContainerInterface;
24
use Psr\Http\Message\ServerRequestInterface;
25
use Psr\Log\LoggerAwareInterface;
26
use Psr\Log\LoggerInterface;
27
use TYPO3\CMS\Core\Cache\CacheManager;
28
use TYPO3\CMS\Core\Core\ClassLoadingInformation;
29
use TYPO3\CMS\Core\Core\Environment;
30
use TYPO3\CMS\Core\Http\ApplicationType;
31
use TYPO3\CMS\Core\Http\RequestFactory;
32
use TYPO3\CMS\Core\Log\LogManager;
33
use TYPO3\CMS\Core\SingletonInterface;
34
35
/**
36
 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
37
 * Most of the functions do not relate specifically to TYPO3
38
 * However a section of functions requires certain TYPO3 features available
39
 * See comments in the source.
40
 * You are encouraged to use this library in your own scripts!
41
 *
42
 * USE:
43
 * All methods in this class are meant to be called statically.
44
 * So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'
45
 */
46
class GeneralUtility
47
{
48
    const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*';
49
    const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME';
50
51
    /**
52
     * State of host header value security check
53
     * in order to avoid unnecessary multiple checks during one request
54
     *
55
     * @var bool
56
     */
57
    protected static $allowHostHeaderValue = false;
58
59
    /**
60
     * @var ContainerInterface|null
61
     */
62
    protected static $container;
63
64
    /**
65
     * Singleton instances returned by makeInstance, using the class names as
66
     * array keys
67
     *
68
     * @var array<string, SingletonInterface>
69
     */
70
    protected static $singletonInstances = [];
71
72
    /**
73
     * Instances returned by makeInstance, using the class names as array keys
74
     *
75
     * @var array<string, array<object>>
76
     */
77
    protected static $nonSingletonInstances = [];
78
79
    /**
80
     * Cache for makeInstance with given class name and final class names to reduce number of self::getClassName() calls
81
     *
82
     * @var array<string, class-string> Given class name => final class name
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string, class-string> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<string, class-string>.
Loading history...
83
     */
84
    protected static $finalClassNameCache = [];
85
86
    /**
87
     * @var array<string, mixed>
88
     */
89
    protected static $indpEnvCache = [];
90
91
    final private function __construct()
92
    {
93
    }
94
95
    /*************************
96
     *
97
     * GET/POST Variables
98
     *
99
     * Background:
100
     * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
101
     * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
102
     * But the clean solution is that quotes are never escaped and that is what the functions below offers.
103
     * Eventually TYPO3 should provide this in the global space as well.
104
     * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
105
     * This functionality was previously needed to normalize between magic quotes logic, which was removed from PHP 5.4,
106
     * so these methods are still in use, but not tackle the slash problem anymore.
107
     *
108
     *************************/
109
    /**
110
     * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST, which is equivalent to 'GP' order
111
     * In case you already know by which method your data is arriving consider using GeneralUtility::_GET or GeneralUtility::_POST.
112
     *
113
     * @param string $var GET/POST var to return
114
     * @return mixed POST var named $var, if not set, the GET var of the same name and if also not set, NULL.
115
     */
116
    public static function _GP($var)
117
    {
118
        if (empty($var)) {
119
            return;
120
        }
121
122
        $value = $_POST[$var] ?? $_GET[$var] ?? null;
123
124
        // This is there for backwards-compatibility, in order to avoid NULL
125
        if (isset($value) && !is_array($value)) {
126
            $value = (string)$value;
127
        }
128
        return $value;
129
    }
130
131
    /**
132
     * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
133
     *
134
     * @param string $parameter Key (variable name) from GET or POST vars
135
     * @return array Returns the GET vars merged recursively onto the POST vars.
136
     */
137
    public static function _GPmerged($parameter)
138
    {
139
        $postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : [];
140
        $getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : [];
141
        $mergedParameters = $getParameter;
142
        ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter);
143
        return $mergedParameters;
144
    }
145
146
    /**
147
     * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
148
     * This function was previously used to normalize between magic quotes logic, which was removed from PHP 5.5
149
     *
150
     * @param string $var Optional pointer to value in GET array (basically name of GET var)
151
     * @return mixed If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself.
152
     * @see _POST()
153
     * @see _GP()
154
     */
155
    public static function _GET($var = null)
156
    {
157
        $value = $var === null
158
            ? $_GET
159
            : (empty($var) ? null : ($_GET[$var] ?? null));
160
        // This is there for backwards-compatibility, in order to avoid NULL
161
        if (isset($value) && !is_array($value)) {
162
            $value = (string)$value;
163
        }
164
        return $value;
165
    }
166
167
    /**
168
     * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
169
     *
170
     * @param string $var Optional pointer to value in POST array (basically name of POST var)
171
     * @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself.
172
     * @see _GET()
173
     * @see _GP()
174
     */
175
    public static function _POST($var = null)
176
    {
177
        $value = $var === null ? $_POST : (empty($var) || !isset($_POST[$var]) ? null : $_POST[$var]);
178
        // This is there for backwards-compatibility, in order to avoid NULL
179
        if (isset($value) && !is_array($value)) {
180
            $value = (string)$value;
181
        }
182
        return $value;
183
    }
184
185
    /*************************
186
     *
187
     * STRING FUNCTIONS
188
     *
189
     *************************/
190
    /**
191
     * Truncates a string with appended/prepended "..." and takes current character set into consideration.
192
     *
193
     * @param string $string String to truncate
194
     * @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.
195
     * @param string $appendString Appendix to the truncated string
196
     * @return string Cropped string
197
     */
198
    public static function fixed_lgd_cs($string, $chars, $appendString = '...')
199
    {
200
        if ((int)$chars === 0 || mb_strlen($string, 'utf-8') <= abs($chars)) {
201
            return $string;
202
        }
203
        if ($chars > 0) {
204
            $string = mb_substr($string, 0, $chars, 'utf-8') . $appendString;
205
        } else {
206
            $string = $appendString . mb_substr($string, $chars, mb_strlen($string, 'utf-8'), 'utf-8');
207
        }
208
        return $string;
209
    }
210
211
    /**
212
     * Match IP number with list of numbers with wildcard
213
     * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
214
     *
215
     * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
216
     * @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.
217
     * @return bool TRUE if an IP-mask from $list matches $baseIP
218
     */
219
    public static function cmpIP($baseIP, $list)
220
    {
221
        $list = trim($list);
222
        if ($list === '') {
223
            return false;
224
        }
225
        if ($list === '*') {
226
            return true;
227
        }
228
        if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
229
            return self::cmpIPv6($baseIP, $list);
230
        }
231
        return self::cmpIPv4($baseIP, $list);
232
    }
233
234
    /**
235
     * Match IPv4 number with list of numbers with wildcard
236
     *
237
     * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
238
     * @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
239
     * @return bool TRUE if an IP-mask from $list matches $baseIP
240
     */
241
    public static function cmpIPv4($baseIP, $list)
242
    {
243
        $IPpartsReq = explode('.', $baseIP);
244
        if (count($IPpartsReq) === 4) {
245
            $values = self::trimExplode(',', $list, true);
246
            foreach ($values as $test) {
247
                $testList = explode('/', $test);
248
                if (count($testList) === 2) {
249
                    [$test, $mask] = $testList;
250
                } else {
251
                    $mask = false;
252
                }
253
                if ((int)$mask) {
254
                    $mask = (int)$mask;
255
                    // "192.168.3.0/24"
256
                    $lnet = (int)ip2long($test);
257
                    $lip = (int)ip2long($baseIP);
258
                    $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
259
                    $firstpart = substr($binnet, 0, $mask);
260
                    $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
261
                    $firstip = substr($binip, 0, $mask);
262
                    $yes = $firstpart === $firstip;
263
                } else {
264
                    // "192.168.*.*"
265
                    $IPparts = explode('.', $test);
266
                    $yes = 1;
267
                    foreach ($IPparts as $index => $val) {
268
                        $val = trim($val);
269
                        if ($val !== '*' && $IPpartsReq[$index] !== $val) {
270
                            $yes = 0;
271
                        }
272
                    }
273
                }
274
                if ($yes) {
275
                    return true;
276
                }
277
            }
278
        }
279
        return false;
280
    }
281
282
    /**
283
     * Match IPv6 address with a list of IPv6 prefixes
284
     *
285
     * @param string $baseIP Is the current remote IP address for instance
286
     * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
287
     * @return bool TRUE If a baseIP matches any prefix
288
     */
289
    public static function cmpIPv6($baseIP, $list)
290
    {
291
        // Policy default: Deny connection
292
        $success = false;
293
        $baseIP = self::normalizeIPv6($baseIP);
294
        $values = self::trimExplode(',', $list, true);
295
        foreach ($values as $test) {
296
            $testList = explode('/', $test);
297
            if (count($testList) === 2) {
298
                [$test, $mask] = $testList;
299
            } else {
300
                $mask = false;
301
            }
302
            if (self::validIPv6($test)) {
303
                $test = self::normalizeIPv6($test);
304
                $maskInt = (int)$mask ?: 128;
305
                // Special case; /0 is an allowed mask - equals a wildcard
306
                if ($mask === '0') {
307
                    $success = true;
308
                } elseif ($maskInt == 128) {
309
                    $success = $test === $baseIP;
310
                } else {
311
                    $testBin = (string)inet_pton($test);
312
                    $baseIPBin = (string)inet_pton($baseIP);
313
314
                    $success = true;
315
                    // Modulo is 0 if this is a 8-bit-boundary
316
                    $maskIntModulo = $maskInt % 8;
317
                    $numFullCharactersUntilBoundary = (int)($maskInt / 8);
318
                    $substring = (string)substr($baseIPBin, 0, $numFullCharactersUntilBoundary);
319
                    if (strpos($testBin, $substring) !== 0) {
320
                        $success = false;
321
                    } elseif ($maskIntModulo > 0) {
322
                        // If not an 8-bit-boundary, check bits of last character
323
                        $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
324
                        $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
325
                        if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
326
                            $success = false;
327
                        }
328
                    }
329
                }
330
            }
331
            if ($success) {
332
                return true;
333
            }
334
        }
335
        return false;
336
    }
337
338
    /**
339
     * Normalize an IPv6 address to full length
340
     *
341
     * @param string $address Given IPv6 address
342
     * @return string Normalized address
343
     */
344
    public static function normalizeIPv6($address)
345
    {
346
        $normalizedAddress = '';
347
        // According to RFC lowercase-representation is recommended
348
        $address = strtolower($address);
349
        // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
350
        if (strlen($address) === 39) {
351
            // Already in full expanded form
352
            return $address;
353
        }
354
        // Count 2 if if address has hidden zero blocks
355
        $chunks = explode('::', $address);
356
        if (count($chunks) === 2) {
357
            $chunksLeft = explode(':', $chunks[0]);
358
            $chunksRight = explode(':', $chunks[1]);
359
            $left = count($chunksLeft);
360
            $right = count($chunksRight);
361
            // Special case: leading zero-only blocks count to 1, should be 0
362
            if ($left === 1 && strlen($chunksLeft[0]) === 0) {
363
                $left = 0;
364
            }
365
            $hiddenBlocks = 8 - ($left + $right);
366
            $hiddenPart = '';
367
            $h = 0;
368
            while ($h < $hiddenBlocks) {
369
                $hiddenPart .= '0000:';
370
                $h++;
371
            }
372
            if ($left === 0) {
373
                $stageOneAddress = $hiddenPart . $chunks[1];
374
            } else {
375
                $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
376
            }
377
        } else {
378
            $stageOneAddress = $address;
379
        }
380
        // Normalize the blocks:
381
        $blocks = explode(':', $stageOneAddress);
382
        $divCounter = 0;
383
        foreach ($blocks as $block) {
384
            $tmpBlock = '';
385
            $i = 0;
386
            $hiddenZeros = 4 - strlen($block);
387
            while ($i < $hiddenZeros) {
388
                $tmpBlock .= '0';
389
                $i++;
390
            }
391
            $normalizedAddress .= $tmpBlock . $block;
392
            if ($divCounter < 7) {
393
                $normalizedAddress .= ':';
394
                $divCounter++;
395
            }
396
        }
397
        return $normalizedAddress;
398
    }
399
400
    /**
401
     * Validate a given IP address.
402
     *
403
     * Possible format are IPv4 and IPv6.
404
     *
405
     * @param string $ip IP address to be tested
406
     * @return bool TRUE if $ip is either of IPv4 or IPv6 format.
407
     */
408
    public static function validIP($ip)
409
    {
410
        return filter_var($ip, FILTER_VALIDATE_IP) !== false;
411
    }
412
413
    /**
414
     * Validate a given IP address to the IPv4 address format.
415
     *
416
     * Example for possible format: 10.0.45.99
417
     *
418
     * @param string $ip IP address to be tested
419
     * @return bool TRUE if $ip is of IPv4 format.
420
     */
421
    public static function validIPv4($ip)
422
    {
423
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
424
    }
425
426
    /**
427
     * Validate a given IP address to the IPv6 address format.
428
     *
429
     * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
430
     *
431
     * @param string $ip IP address to be tested
432
     * @return bool TRUE if $ip is of IPv6 format.
433
     */
434
    public static function validIPv6($ip)
435
    {
436
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
437
    }
438
439
    /**
440
     * Match fully qualified domain name with list of strings with wildcard
441
     *
442
     * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
443
     * @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)
444
     * @return bool TRUE if a domain name mask from $list matches $baseIP
445
     */
446
    public static function cmpFQDN($baseHost, $list)
447
    {
448
        $baseHost = trim($baseHost);
449
        if (empty($baseHost)) {
450
            return false;
451
        }
452
        if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
453
            // Resolve hostname
454
            // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
455
            // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
456
            $baseHostName = (string)gethostbyaddr($baseHost);
457
            if ($baseHostName === $baseHost) {
458
                // Unable to resolve hostname
459
                return false;
460
            }
461
        } else {
462
            $baseHostName = $baseHost;
463
        }
464
        $baseHostNameParts = explode('.', $baseHostName);
465
        $values = self::trimExplode(',', $list, true);
466
        foreach ($values as $test) {
467
            $hostNameParts = explode('.', $test);
468
            // To match hostNameParts can only be shorter (in case of wildcards) or equal
469
            $hostNamePartsCount = count($hostNameParts);
470
            $baseHostNamePartsCount = count($baseHostNameParts);
471
            if ($hostNamePartsCount > $baseHostNamePartsCount) {
472
                continue;
473
            }
474
            $yes = true;
475
            foreach ($hostNameParts as $index => $val) {
476
                $val = trim($val);
477
                if ($val === '*') {
478
                    // Wildcard valid for one or more hostname-parts
479
                    $wildcardStart = $index + 1;
480
                    // Wildcard as last/only part always matches, otherwise perform recursive checks
481
                    if ($wildcardStart < $hostNamePartsCount) {
482
                        $wildcardMatched = false;
483
                        $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
484
                        while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) {
485
                            $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
486
                            $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
487
                            $wildcardStart++;
488
                        }
489
                        if ($wildcardMatched) {
490
                            // Match found by recursive compare
491
                            return true;
492
                        }
493
                        $yes = false;
494
                    }
495
                } elseif ($baseHostNameParts[$index] !== $val) {
496
                    // In case of no match
497
                    $yes = false;
498
                }
499
            }
500
            if ($yes) {
501
                return true;
502
            }
503
        }
504
        return false;
505
    }
506
507
    /**
508
     * Checks if a given URL matches the host that currently handles this HTTP request.
509
     * Scheme, hostname and (optional) port of the given URL are compared.
510
     *
511
     * @param string $url URL to compare with the TYPO3 request host
512
     * @return bool Whether the URL matches the TYPO3 request host
513
     */
514
    public static function isOnCurrentHost($url)
515
    {
516
        return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
517
    }
518
519
    /**
520
     * Check for item in list
521
     * Check if an item exists in a comma-separated list of items.
522
     *
523
     * @param string $list Comma-separated list of items (string)
524
     * @param string $item Item to check for
525
     * @return bool TRUE if $item is in $list
526
     */
527
    public static function inList($list, $item)
528
    {
529
        return strpos(',' . $list . ',', ',' . $item . ',') !== false;
530
    }
531
532
    /**
533
     * Removes an item from a comma-separated list of items.
534
     *
535
     * If $element contains a comma, the behaviour of this method is undefined.
536
     * Empty elements in the list are preserved.
537
     *
538
     * @param string $element Element to remove
539
     * @param string $list Comma-separated list of items (string)
540
     * @return string New comma-separated list of items
541
     */
542
    public static function rmFromList($element, $list)
543
    {
544
        $items = explode(',', $list);
545
        foreach ($items as $k => $v) {
546
            if ($v == $element) {
547
                unset($items[$k]);
548
            }
549
        }
550
        return implode(',', $items);
551
    }
552
553
    /**
554
     * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
555
     * Ranges are limited to 1000 values per range.
556
     *
557
     * @param string $list Comma-separated list of integers with ranges (string)
558
     * @return string New comma-separated list of items
559
     */
560
    public static function expandList($list)
561
    {
562
        $items = explode(',', $list);
563
        $list = [];
564
        foreach ($items as $item) {
565
            $range = explode('-', $item);
566
            if (isset($range[1])) {
567
                $runAwayBrake = 1000;
568
                for ($n = $range[0]; $n <= $range[1]; $n++) {
569
                    $list[] = $n;
570
                    $runAwayBrake--;
571
                    if ($runAwayBrake <= 0) {
572
                        break;
573
                    }
574
                }
575
            } else {
576
                $list[] = $item;
577
            }
578
        }
579
        return implode(',', $list);
580
    }
581
582
    /**
583
     * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
584
     *
585
     * @param string $str String to md5-hash
586
     * @return int Returns 28bit integer-hash
587
     */
588
    public static function md5int($str)
589
    {
590
        return hexdec(substr(md5($str), 0, 7));
591
    }
592
593
    /**
594
     * Returns the first 10 positions of the MD5-hash		(changed from 6 to 10 recently)
595
     *
596
     * @param string $input Input string to be md5-hashed
597
     * @param int $len The string-length of the output
598
     * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
599
     */
600
    public static function shortMD5($input, $len = 10)
601
    {
602
        return substr(md5($input), 0, $len);
603
    }
604
605
    /**
606
     * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
607
     *
608
     * @param string $input Input string to create HMAC from
609
     * @param string $additionalSecret additionalSecret to prevent hmac being used in a different context
610
     * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
611
     */
612
    public static function hmac($input, $additionalSecret = '')
613
    {
614
        $hashAlgorithm = 'sha1';
615
        $hashBlocksize = 64;
616
        $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
617
        if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
618
            $hmac = hash_hmac($hashAlgorithm, $input, $secret);
619
        } else {
620
            // Outer padding
621
            $opad = str_repeat(chr(92), $hashBlocksize);
622
            // Inner padding
623
            $ipad = str_repeat(chr(54), $hashBlocksize);
624
            if (strlen($secret) > $hashBlocksize) {
625
                // Keys longer than block size are shorten
626
                $key = str_pad(pack('H*', $hashAlgorithm($secret)), $hashBlocksize, "\0");
627
            } else {
628
                // Keys shorter than block size are zero-padded
629
                $key = str_pad($secret, $hashBlocksize, "\0");
630
            }
631
            $hmac = $hashAlgorithm(($key ^ $opad) . pack('H*', $hashAlgorithm(($key ^ $ipad) . $input)));
632
        }
633
        return $hmac;
634
    }
635
636
    /**
637
     * Takes comma-separated lists and arrays and removes all duplicates
638
     * If a value in the list is trim(empty), the value is ignored.
639
     *
640
     * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
641
     * @param mixed $secondParameter Dummy field, which if set will show a warning!
642
     * @return string Returns the list without any duplicates of values, space around values are trimmed
643
     * @deprecated since TYPO3 v11, will be removed in TYPO3 v12. Use StringUtility::uniqueList() instead.
644
     */
645
    public static function uniqueList($in_list, $secondParameter = null)
646
    {
647
        trigger_error(
648
            'GeneralUtility::uniqueList() is deprecated and will be removed in v12. Use StringUtility::uniqueList() instead.',
649
            E_USER_DEPRECATED
650
        );
651
        if (is_array($in_list)) {
0 ignored issues
show
introduced by
The condition is_array($in_list) is always false.
Loading history...
652
            throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
653
        }
654
        if (isset($secondParameter)) {
655
            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);
656
        }
657
        return implode(',', array_unique(self::trimExplode(',', $in_list, true)));
658
    }
659
660
    /**
661
     * Splits a reference to a file in 5 parts
662
     *
663
     * @param string $fileNameWithPath File name with path to be analyzed (must exist if open_basedir is set)
664
     * @return array<string, string> Contains keys [path], [file], [filebody], [fileext], [realFileext]
665
     */
666
    public static function split_fileref($fileNameWithPath)
667
    {
668
        $info = [];
669
        $reg = [];
670
        if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) {
671
            $info['path'] = $reg[1];
672
            $info['file'] = $reg[2];
673
        } else {
674
            $info['path'] = '';
675
            $info['file'] = $fileNameWithPath;
676
        }
677
        $reg = '';
678
        // If open_basedir is set and the fileName was supplied without a path the is_dir check fails
679
        if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) {
0 ignored issues
show
Bug introduced by
$reg of type string is incompatible with the type string[] expected by parameter $matches of preg_match(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

679
        if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], /** @scrutinizer ignore-type */ $reg)) {
Loading history...
680
            $info['filebody'] = $reg[1];
681
            $info['fileext'] = strtolower($reg[2]);
682
            $info['realFileext'] = $reg[2];
683
        } else {
684
            $info['filebody'] = $info['file'];
685
            $info['fileext'] = '';
686
        }
687
        reset($info);
688
        return $info;
689
    }
690
691
    /**
692
     * Returns the directory part of a path without trailing slash
693
     * If there is no dir-part, then an empty string is returned.
694
     * Behaviour:
695
     *
696
     * '/dir1/dir2/script.php' => '/dir1/dir2'
697
     * '/dir1/' => '/dir1'
698
     * 'dir1/script.php' => 'dir1'
699
     * 'd/script.php' => 'd'
700
     * '/script.php' => ''
701
     * '' => ''
702
     *
703
     * @param string $path Directory name / path
704
     * @return string Processed input value. See function description.
705
     */
706
    public static function dirname($path)
707
    {
708
        $p = self::revExplode('/', $path, 2);
709
        return count($p) === 2 ? $p[0] : '';
710
    }
711
712
    /**
713
     * Returns TRUE if the first part of $str matches the string $partStr
714
     *
715
     * @param string $str Full string to check
716
     * @param string $partStr Reference string which must be found as the "first part" of the full string
717
     * @return bool TRUE if $partStr was found to be equal to the first part of $str
718
     */
719
    public static function isFirstPartOfStr($str, $partStr)
720
    {
721
        $str = is_array($str) ? '' : (string)$str;
0 ignored issues
show
introduced by
The condition is_array($str) is always false.
Loading history...
722
        $partStr = is_array($partStr) ? '' : (string)$partStr;
0 ignored issues
show
introduced by
The condition is_array($partStr) is always false.
Loading history...
723
        return $partStr !== '' && strpos($str, $partStr, 0) === 0;
724
    }
725
726
    /**
727
     * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
728
     *
729
     * @param int $sizeInBytes Number of bytes to format.
730
     * @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".
731
     * @param int $base The unit base if not using a unit name. Defaults to 1024.
732
     * @return string Formatted representation of the byte number, for output.
733
     */
734
    public static function formatSize($sizeInBytes, $labels = '', $base = 0)
735
    {
736
        $defaultFormats = [
737
            'iec' => ['base' => 1024, 'labels' => [' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi']],
738
            'si' => ['base' => 1000, 'labels' => [' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']],
739
        ];
740
        // Set labels and base:
741
        if (empty($labels)) {
742
            $labels = 'iec';
743
        }
744
        if (isset($defaultFormats[$labels])) {
745
            $base = $defaultFormats[$labels]['base'];
746
            $labelArr = $defaultFormats[$labels]['labels'];
747
        } else {
748
            $base = (int)$base;
749
            if ($base !== 1000 && $base !== 1024) {
750
                $base = 1024;
751
            }
752
            $labelArr = explode('|', str_replace('"', '', $labels));
753
        }
754
        // This is set via Site Handling and in the Locales class via setlocale()
755
        $localeInfo = localeconv();
756
        $sizeInBytes = max($sizeInBytes, 0);
757
        $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base));
758
        $sizeInUnits = $sizeInBytes / $base ** $multiplier;
759
        if ($sizeInUnits > ($base * .9)) {
760
            $multiplier++;
761
        }
762
        $multiplier = min($multiplier, count($labelArr) - 1);
763
        $sizeInUnits = $sizeInBytes / $base ** $multiplier;
764
        return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier];
765
    }
766
767
    /**
768
     * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
769
     *
770
     * @param string $string Input string, eg "123 + 456 / 789 - 4
771
     * @param string $operators Operators to split by, typically "/+-*
772
     * @return array<int, array<int, string>> Array with operators and operands separated.
773
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc()
774
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
775
     */
776
    public static function splitCalc($string, $operators)
777
    {
778
        $res = [];
779
        $sign = '+';
780
        while ($string) {
781
            $valueLen = strcspn($string, $operators);
782
            $value = substr($string, 0, $valueLen);
783
            $res[] = [$sign, trim($value)];
784
            $sign = substr($string, $valueLen, 1);
785
            $string = substr($string, $valueLen + 1);
786
        }
787
        reset($res);
788
        return $res;
789
    }
790
791
    /**
792
     * Checking syntax of input email address
793
     *
794
     * @param string $email Input string to evaluate
795
     * @return bool Returns TRUE if the $email address (input string) is valid
796
     */
797
    public static function validEmail($email)
798
    {
799
        // Early return in case input is not a string
800
        if (!is_string($email)) {
0 ignored issues
show
introduced by
The condition is_string($email) is always true.
Loading history...
801
            return false;
802
        }
803
        if (trim($email) !== $email) {
804
            return false;
805
        }
806
        $validators = [];
807
        foreach ($GLOBALS['TYPO3_CONF_VARS']['MAIL']['validators'] ?? [RFCValidation::class] as $className) {
808
            $validator = new $className();
809
            if ($validator instanceof EmailValidation) {
810
                $validators[] = $validator;
811
            }
812
        }
813
        return (new EmailValidator())->isValid($email, new MultipleValidationWithAnd($validators, MultipleValidationWithAnd::STOP_ON_ERROR));
814
    }
815
816
    /**
817
     * Returns a given string with underscores as UpperCamelCase.
818
     * Example: Converts blog_example to BlogExample
819
     *
820
     * @param string $string String to be converted to camel case
821
     * @return string UpperCamelCasedWord
822
     */
823
    public static function underscoredToUpperCamelCase($string)
824
    {
825
        return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string))));
826
    }
827
828
    /**
829
     * Returns a given string with underscores as lowerCamelCase.
830
     * Example: Converts minimal_value to minimalValue
831
     *
832
     * @param string $string String to be converted to camel case
833
     * @return string lowerCamelCasedWord
834
     */
835
    public static function underscoredToLowerCamelCase($string)
836
    {
837
        return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string)))));
838
    }
839
840
    /**
841
     * Returns a given CamelCasedString as a lowercase string with underscores.
842
     * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
843
     *
844
     * @param string $string String to be converted to lowercase underscore
845
     * @return string lowercase_and_underscored_string
846
     */
847
    public static function camelCaseToLowerCaseUnderscored($string)
848
    {
849
        $value = preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string) ?? '';
850
        return mb_strtolower($value, 'utf-8');
851
    }
852
853
    /**
854
     * Checks if a given string is a Uniform Resource Locator (URL).
855
     *
856
     * On seriously malformed URLs, parse_url may return FALSE and emit an
857
     * E_WARNING.
858
     *
859
     * filter_var() requires a scheme to be present.
860
     *
861
     * http://www.faqs.org/rfcs/rfc2396.html
862
     * Scheme names consist of a sequence of characters beginning with a
863
     * lower case letter and followed by any combination of lower case letters,
864
     * digits, plus ("+"), period ("."), or hyphen ("-").  For resiliency,
865
     * programs interpreting URI should treat upper case letters as equivalent to
866
     * lower case in scheme names (e.g., allow "HTTP" as well as "http").
867
     * scheme = alpha *( alpha | digit | "+" | "-" | "." )
868
     *
869
     * Convert the domain part to punicode if it does not look like a regular
870
     * domain name. Only the domain part because RFC3986 specifies the the rest of
871
     * the url may not contain special characters:
872
     * https://tools.ietf.org/html/rfc3986#appendix-A
873
     *
874
     * @param string $url The URL to be validated
875
     * @return bool Whether the given URL is valid
876
     */
877
    public static function isValidUrl($url)
878
    {
879
        $parsedUrl = parse_url($url);
880
        if (!$parsedUrl || !isset($parsedUrl['scheme'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsedUrl of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
881
            return false;
882
        }
883
        // HttpUtility::buildUrl() will always build urls with <scheme>://
884
        // our original $url might only contain <scheme>: (e.g. mail:)
885
        // so we convert that to the double-slashed version to ensure
886
        // our check against the $recomposedUrl is proper
887
        if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
888
            $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
889
        }
890
        $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
891
        if ($recomposedUrl !== $url) {
892
            // The parse_url() had to modify characters, so the URL is invalid
893
            return false;
894
        }
895
        if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
896
            $host = (string)idn_to_ascii($parsedUrl['host']);
897
            if ($host === false) {
0 ignored issues
show
introduced by
The condition $host === false is always false.
Loading history...
898
                return false;
899
            }
900
            $parsedUrl['host'] = $host;
901
        }
902
        return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false;
903
    }
904
905
    /*************************
906
     *
907
     * ARRAY FUNCTIONS
908
     *
909
     *************************/
910
911
    /**
912
     * Explodes a $string delimited by $delimiter and casts each item in the array to (int).
913
     * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
914
     *
915
     * @param string $delimiter Delimiter string to explode with
916
     * @param string $string The string to explode
917
     * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
918
     * @param int $limit If positive, the result will contain a maximum of limit elements,
919
     * @return int[] Exploded values, all converted to integers
920
     */
921
    public static function intExplode($delimiter, $string, $removeEmptyValues = false, $limit = 0)
922
    {
923
        $result = explode($delimiter, $string) ?: [];
924
        foreach ($result as $key => &$value) {
925
            if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
926
                unset($result[$key]);
927
            } else {
928
                $value = (int)$value;
929
            }
930
        }
931
        unset($value);
932
        if ($limit !== 0) {
933
            if ($limit < 0) {
934
                $result = array_slice($result, 0, $limit);
935
            } elseif (count($result) > $limit) {
936
                $lastElements = array_slice($result, $limit - 1);
937
                $result = array_slice($result, 0, $limit - 1);
938
                $result[] = implode($delimiter, $lastElements);
939
            }
940
        }
941
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result returns an array which contains values of type string which are incompatible with the documented value type integer.
Loading history...
942
    }
943
944
    /**
945
     * Reverse explode which explodes the string counting from behind.
946
     *
947
     * Note: The delimiter has to given in the reverse order as
948
     *       it is occurring within the string.
949
     *
950
     * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
951
     *   ==> array('[my][words', 'here]')
952
     *
953
     * @param string $delimiter Delimiter string to explode with
954
     * @param string $string The string to explode
955
     * @param int $count Number of array entries
956
     * @return string[] Exploded values
957
     */
958
    public static function revExplode($delimiter, $string, $count = 0)
959
    {
960
        // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
961
        if ($count === 2) {
962
            $position = strrpos($string, strrev($delimiter));
963
            if ($position !== false) {
964
                return [substr($string, 0, $position), substr($string, $position + strlen($delimiter))];
965
            }
966
            return [$string];
967
        }
968
        if ($count <= 1) {
969
            return [$string];
970
        }
971
        $explodedValues = explode($delimiter, strrev($string), $count) ?: [];
972
        $explodedValues = array_map('strrev', $explodedValues);
973
        return array_reverse($explodedValues);
974
    }
975
976
    /**
977
     * Explodes a string and removes whitespace-only values.
978
     *
979
     * If $onlyNonEmptyValues is set, then all values that contain only whitespace are removed.
980
     *
981
     * Each item will have leading and trailing whitespace removed. However, if the tail items are
982
     * returned as a single array item, their internal whitespace will not be modified.
983
     *
984
     * @param string $delim Delimiter string to explode with
985
     * @param string $string The string to explode
986
     * @param bool $removeEmptyValues If set, all empty values will be removed in output
987
     * @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with
988
     *                   the last element containing the rest of string. If the limit parameter is negative, all components
989
     *                   except the last -limit are returned.
990
     * @return string[] Exploded values
991
     */
992
    public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0): array
993
    {
994
        $result = explode($delim, $string) ?: [];
995
        if ($removeEmptyValues) {
996
            // Remove items that are just whitespace, but leave whitespace intact for the rest.
997
            $result = array_values(array_filter($result, fn ($item) => trim($item) !== ''));
998
        }
999
1000
        if ($limit === 0) {
1001
            // Return everything.
1002
            return array_map('trim', $result);
1003
        }
1004
1005
        if ($limit < 0) {
1006
            // Trim and return just the first $limit elements and ignore the rest.
1007
            return array_map('trim', array_slice($result, 0, $limit));
1008
        }
1009
1010
        // Fold the last length - $limit elements into a single trailing item, then trim and return the result.
1011
        $tail = array_slice($result, $limit - 1);
1012
        $result = array_slice($result, 0, $limit - 1);
1013
        if ($tail) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tail of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1014
            $result[] = implode($delim, $tail);
1015
        }
1016
        return array_map('trim', $result);
1017
    }
1018
1019
    /**
1020
     * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1021
     *
1022
     * @param string $name Name prefix for entries. Set to blank if you wish none.
1023
     * @param array $theArray The (multidimensional) array to implode
1024
     * @param string $str (keep blank)
1025
     * @param bool $skipBlank If set, parameters which were blank strings would be removed.
1026
     * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1027
     * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1028
     * @see explodeUrl2Array()
1029
     */
1030
    public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false)
1031
    {
1032
        foreach ($theArray as $Akey => $AVal) {
1033
            $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1034
            if (is_array($AVal)) {
1035
                $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1036
            } else {
1037
                if (!$skipBlank || (string)$AVal !== '') {
1038
                    $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1039
                }
1040
            }
1041
        }
1042
        return $str;
1043
    }
1044
1045
    /**
1046
     * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array.
1047
     *
1048
     * Note! If you want to use a multi-dimensional string, consider this plain simple PHP code instead:
1049
     *
1050
     * $result = [];
1051
     * parse_str($queryParametersAsString, $result);
1052
     *
1053
     * However, if you do magic with a flat structure (e.g. keeping "ext[mykey]" as flat key in a one-dimensional array)
1054
     * then this method is for you.
1055
     *
1056
     * @param string $string GETvars string
1057
     * @return array<string, string> Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it!
1058
     * @see implodeArrayForUrl()
1059
     */
1060
    public static function explodeUrl2Array($string)
1061
    {
1062
        $output = [];
1063
        $p = explode('&', $string);
1064
        foreach ($p as $v) {
1065
            if ($v !== '') {
1066
                [$pK, $pV] = explode('=', $v, 2);
1067
                $output[rawurldecode($pK)] = rawurldecode($pV);
1068
            }
1069
        }
1070
        return $output;
1071
    }
1072
1073
    /**
1074
     * Returns an array with selected keys from incoming data.
1075
     * (Better read source code if you want to find out...)
1076
     *
1077
     * @param string $varList List of variable/key names
1078
     * @param array $getArray Array from where to get values based on the keys in $varList
1079
     * @param bool $GPvarAlt If set, then \TYPO3\CMS\Core\Utility\GeneralUtility::_GP() is used to fetch the value if not found (isset) in the $getArray
1080
     * @return array Output array with selected variables.
1081
     */
1082
    public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = true)
1083
    {
1084
        $keys = self::trimExplode(',', $varList, true);
1085
        $outArr = [];
1086
        foreach ($keys as $v) {
1087
            if (isset($getArray[$v])) {
1088
                $outArr[$v] = $getArray[$v];
1089
            } elseif ($GPvarAlt) {
1090
                $outArr[$v] = self::_GP($v);
1091
            }
1092
        }
1093
        return $outArr;
1094
    }
1095
1096
    /**
1097
     * Removes dots "." from end of a key identifier of TypoScript styled array.
1098
     * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1099
     *
1100
     * @param array $ts TypoScript configuration array
1101
     * @return array TypoScript configuration array without dots at the end of all keys
1102
     */
1103
    public static function removeDotsFromTS(array $ts)
1104
    {
1105
        $out = [];
1106
        foreach ($ts as $key => $value) {
1107
            if (is_array($value)) {
1108
                $key = rtrim($key, '.');
1109
                $out[$key] = self::removeDotsFromTS($value);
1110
            } else {
1111
                $out[$key] = $value;
1112
            }
1113
        }
1114
        return $out;
1115
    }
1116
1117
    /*************************
1118
     *
1119
     * HTML/XML PROCESSING
1120
     *
1121
     *************************/
1122
    /**
1123
     * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1124
     * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1125
     * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1126
     *
1127
     * @param string $tag HTML-tag string (or attributes only)
1128
     * @param bool $decodeEntities Whether to decode HTML entities
1129
     * @return array<string, string> Array with the attribute values.
1130
     */
1131
    public static function get_tag_attributes($tag, bool $decodeEntities = false)
1132
    {
1133
        $components = self::split_tag_attributes($tag);
1134
        // Attribute name is stored here
1135
        $name = '';
1136
        $valuemode = false;
1137
        $attributes = [];
1138
        foreach ($components as $key => $val) {
1139
            // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
1140
            if ($val !== '=') {
1141
                if ($valuemode) {
1142
                    if ($name) {
1143
                        $attributes[$name] = $decodeEntities ? htmlspecialchars_decode($val) : $val;
1144
                        $name = '';
1145
                    }
1146
                } else {
1147
                    if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val) ?? '')) {
1148
                        $attributes[$key] = '';
1149
                        $name = $key;
1150
                    }
1151
                }
1152
                $valuemode = false;
1153
            } else {
1154
                $valuemode = true;
1155
            }
1156
        }
1157
        return $attributes;
1158
    }
1159
1160
    /**
1161
     * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1162
     * Removes tag-name if found
1163
     *
1164
     * @param string $tag HTML-tag string (or attributes only)
1165
     * @return string[] Array with the attribute values.
1166
     */
1167
    public static function split_tag_attributes($tag)
1168
    {
1169
        $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)) ?? '');
1170
        // Removes any > in the end of the string
1171
        $tag_tmp = trim(rtrim($tag_tmp, '>'));
1172
        $value = [];
1173
        // Compared with empty string instead , 030102
1174
        while ($tag_tmp !== '') {
1175
            $firstChar = $tag_tmp[0];
1176
            if ($firstChar === '"' || $firstChar === '\'') {
1177
                $reg = explode($firstChar, $tag_tmp, 3);
1178
                $value[] = $reg[1];
1179
                $tag_tmp = trim($reg[2]);
1180
            } elseif ($firstChar === '=') {
1181
                $value[] = '=';
1182
                // Removes = chars.
1183
                $tag_tmp = trim(substr($tag_tmp, 1));
1184
            } else {
1185
                // There are '' around the value. We look for the next ' ' or '>'
1186
                $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1187
                $value[] = trim($reg[0]);
1188
                $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . ($reg[1] ?? ''));
1189
            }
1190
        }
1191
        reset($value);
1192
        return $value;
1193
    }
1194
1195
    /**
1196
     * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1197
     *
1198
     * @param array<string, string> $arr Array with attribute key/value pairs, eg. "bgcolor" => "red", "border" => "0"
1199
     * @param bool $xhtmlSafe If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch!
1200
     * @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1201
     * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1202
     */
1203
    public static function implodeAttributes(array $arr, $xhtmlSafe = false, $dontOmitBlankAttribs = false)
1204
    {
1205
        if ($xhtmlSafe) {
1206
            $newArr = [];
1207
            foreach ($arr as $p => $v) {
1208
                if (!isset($newArr[strtolower($p)])) {
1209
                    $newArr[strtolower($p)] = htmlspecialchars($v);
1210
                }
1211
            }
1212
            $arr = $newArr;
1213
        }
1214
        $list = [];
1215
        foreach ($arr as $p => $v) {
1216
            if ((string)$v !== '' || $dontOmitBlankAttribs) {
1217
                $list[] = $p . '="' . $v . '"';
1218
            }
1219
        }
1220
        return implode(' ', $list);
1221
    }
1222
1223
    /**
1224
     * Wraps JavaScript code XHTML ready with <script>-tags
1225
     * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1226
     * This is nice for indenting JS code with PHP code on the same level.
1227
     *
1228
     * @param string $string JavaScript code
1229
     * @return string The wrapped JS code, ready to put into a XHTML page
1230
     */
1231
    public static function wrapJS($string)
1232
    {
1233
        if (trim($string)) {
1234
            // remove nl from the beginning
1235
            $string = ltrim($string, LF);
1236
            // re-ident to one tab using the first line as reference
1237
            $match = [];
1238
            if (preg_match('/^(\\t+)/', $string, $match)) {
1239
                $string = str_replace($match[1], "\t", $string);
1240
            }
1241
            return '<script>
1242
/*<![CDATA[*/
1243
' . $string . '
1244
/*]]>*/
1245
</script>';
1246
        }
1247
        return '';
1248
    }
1249
1250
    /**
1251
     * Parses XML input into a PHP array with associative keys
1252
     *
1253
     * @param string $string XML data input
1254
     * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1255
     * @param array $parserOptions Options that will be passed to PHP's xml_parser_set_option()
1256
     * @return mixed The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned.
1257
     */
1258
    public static function xml2tree($string, $depth = 999, $parserOptions = [])
1259
    {
1260
        // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1261
        $previousValueOfEntityLoader = null;
1262
        if (PHP_MAJOR_VERSION < 8) {
1263
            $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1264
        }
1265
        $parser = xml_parser_create();
1266
        $vals = [];
1267
        $index = [];
1268
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1269
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1270
        foreach ($parserOptions as $option => $value) {
1271
            xml_parser_set_option($parser, $option, $value);
1272
        }
1273
        xml_parse_into_struct($parser, $string, $vals, $index);
1274
        if (PHP_MAJOR_VERSION < 8) {
1275
            libxml_disable_entity_loader($previousValueOfEntityLoader);
0 ignored issues
show
Bug introduced by
It seems like $previousValueOfEntityLoader can also be of type null; however, parameter $disable of libxml_disable_entity_loader() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1275
            libxml_disable_entity_loader(/** @scrutinizer ignore-type */ $previousValueOfEntityLoader);
Loading history...
1276
        }
1277
        if (xml_get_error_code($parser)) {
1278
            return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1279
        }
1280
        xml_parser_free($parser);
1281
        $stack = [[]];
1282
        $stacktop = 0;
1283
        $startPoint = 0;
1284
        $tagi = [];
1285
        foreach ($vals as $key => $val) {
1286
            $type = $val['type'];
1287
            // open tag:
1288
            if ($type === 'open' || $type === 'complete') {
1289
                $stack[$stacktop++] = $tagi;
1290
                if ($depth == $stacktop) {
1291
                    $startPoint = $key;
1292
                }
1293
                $tagi = ['tag' => $val['tag']];
1294
                if (isset($val['attributes'])) {
1295
                    $tagi['attrs'] = $val['attributes'];
1296
                }
1297
                if (isset($val['value'])) {
1298
                    $tagi['values'][] = $val['value'];
1299
                }
1300
            }
1301
            // finish tag:
1302
            if ($type === 'complete' || $type === 'close') {
1303
                $oldtagi = $tagi;
1304
                $tagi = $stack[--$stacktop];
1305
                $oldtag = $oldtagi['tag'];
1306
                unset($oldtagi['tag']);
1307
                if ($depth == $stacktop + 1) {
1308
                    if ($key - $startPoint > 0) {
1309
                        $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
1310
                        $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
1311
                    } else {
1312
                        $oldtagi['XMLvalue'] = $oldtagi['values'][0];
1313
                    }
1314
                }
1315
                $tagi['ch'][$oldtag][] = $oldtagi;
1316
                unset($oldtagi);
1317
            }
1318
            // cdata
1319
            if ($type === 'cdata') {
1320
                $tagi['values'][] = $val['value'];
1321
            }
1322
        }
1323
        return $tagi['ch'];
1324
    }
1325
1326
    /**
1327
     * Converts a PHP array into an XML string.
1328
     * The XML output is optimized for readability since associative keys are used as tag names.
1329
     * This also means that only alphanumeric characters are allowed in the tag names AND only keys NOT starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem.
1330
     * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
1331
     * The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string
1332
     * The PHP variable type of the data IS preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set.
1333
     * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances with 4.x versions. However, with PHP5 there seems to be the need to add an XML prologue a la <?xml version="1.0" encoding="[charset]" standalone="yes" ?> - otherwise UTF-8 is assumed! Unfortunately, many times the output from this function is used without adding that prologue meaning that non-ASCII characters will break the parsing!! This sucks of course! Effectively it means that the prologue should always be prepended setting the right characterset, alternatively the system should always run as utf-8!
1334
     * However using MSIE to read the XML output didn't always go well: One reason could be that the character encoding is not observed in the PHP data. The other reason may be if the tag-names are invalid in the eyes of MSIE. Also using the namespace feature will make MSIE break parsing. There might be more reasons...
1335
     *
1336
     * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1337
     * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
1338
     * @param int $level Current recursion level. Don't change, stay at zero!
1339
     * @param string $docTag Alternative document tag. Default is "phparray".
1340
     * @param int $spaceInd If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single TAB is used
1341
     * @param array $options Options for the compilation. Key "useNindex" => 0/1 (boolean: whether to use "n0, n1, n2" for num. indexes); Key "useIndexTagForNum" => "[tag for numerical indexes]"; Key "useIndexTagForAssoc" => "[tag for associative indexes"; Key "parentTagMap" => array('parentTag' => 'thisLevelTag')
1342
     * @param array $stackData Stack data. Don't touch.
1343
     * @return string An XML string made from the input content in the array.
1344
     * @see xml2array()
1345
     */
1346
    public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = [], array $stackData = [])
1347
    {
1348
        // The list of byte values which will trigger binary-safe storage. If any value has one of these char values in it, it will be encoded in base64
1349
        $binaryChars = "\0" . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) . chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) . chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) . chr(30) . chr(31);
1350
        // Set indenting mode:
1351
        $indentChar = $spaceInd ? ' ' : "\t";
1352
        $indentN = $spaceInd > 0 ? $spaceInd : 1;
1353
        $nl = $spaceInd >= 0 ? LF : '';
1354
        // Init output variable:
1355
        $output = '';
1356
        // Traverse the input array
1357
        foreach ($array as $k => $v) {
1358
            $attr = '';
1359
            $tagName = $k;
1360
            // Construct the tag name.
1361
            // Use tag based on grand-parent + parent tag name
1362
            if (isset($stackData['grandParentTagName'], $stackData['parentTagName'], $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
1363
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1364
                $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
1365
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) {
1366
                // Use tag based on parent tag name + if current tag is numeric
1367
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1368
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
1369
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
1370
                // Use tag based on parent tag name + current tag
1371
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1372
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
1373
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName']])) {
1374
                // Use tag based on parent tag name:
1375
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1376
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
1377
            } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) {
1378
                // If integer...;
1379
                if ($options['useNindex']) {
1380
                    // If numeric key, prefix "n"
1381
                    $tagName = 'n' . $tagName;
1382
                } else {
1383
                    // Use special tag for num. keys:
1384
                    $attr .= ' index="' . $tagName . '"';
1385
                    $tagName = $options['useIndexTagForNum'] ?: 'numIndex';
1386
                }
1387
            } elseif (!empty($options['useIndexTagForAssoc'])) {
1388
                // Use tag for all associative keys:
1389
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1390
                $tagName = $options['useIndexTagForAssoc'];
1391
            }
1392
            // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
1393
            $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
1394
            // If the value is an array then we will call this function recursively:
1395
            if (is_array($v)) {
1396
                // Sub elements:
1397
                if (isset($options['alt_options']) && $options['alt_options'][($stackData['path'] ?? '') . '/' . $tagName]) {
1398
                    $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
1399
                    $clearStackPath = $subOptions['clearStackPath'];
1400
                } else {
1401
                    $subOptions = $options;
1402
                    $clearStackPath = false;
1403
                }
1404
                if (empty($v)) {
1405
                    $content = '';
1406
                } else {
1407
                    $content = $nl . self::array2xml($v, $NSprefix, $level + 1, '', $spaceInd, $subOptions, [
1408
                            'parentTagName' => $tagName,
1409
                            'grandParentTagName' => $stackData['parentTagName'] ?? '',
1410
                            'path' => $clearStackPath ? '' : ($stackData['path'] ?? '') . '/' . $tagName
1411
                        ]) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
1412
                }
1413
                // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
1414
                if (!isset($options['disableTypeAttrib']) || (int)$options['disableTypeAttrib'] != 2) {
1415
                    $attr .= ' type="array"';
1416
                }
1417
            } else {
1418
                // Just a value:
1419
                // Look for binary chars:
1420
                $vLen = strlen($v);
1421
                // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
1422
                if ($vLen && strcspn($v, $binaryChars) != $vLen) {
1423
                    // If the value contained binary chars then we base64-encode it and set an attribute to notify this situation:
1424
                    $content = $nl . chunk_split(base64_encode($v));
1425
                    $attr .= ' base64="1"';
1426
                } else {
1427
                    // Otherwise, just htmlspecialchar the stuff:
1428
                    $content = htmlspecialchars($v);
1429
                    $dType = gettype($v);
1430
                    if ($dType === 'string') {
1431
                        if (isset($options['useCDATA']) && $options['useCDATA'] && $content != $v) {
1432
                            $content = '<![CDATA[' . $v . ']]>';
1433
                        }
1434
                    } elseif (!$options['disableTypeAttrib']) {
1435
                        $attr .= ' type="' . $dType . '"';
1436
                    }
1437
                }
1438
            }
1439
            if ((string)$tagName !== '') {
1440
                // Add the element to the output string:
1441
                $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
1442
                    . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
1443
            }
1444
        }
1445
        // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
1446
        if (!$level) {
1447
            $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
1448
        }
1449
        return $output;
1450
    }
1451
1452
    /**
1453
     * Converts an XML string to a PHP array.
1454
     * This is the reverse function of array2xml()
1455
     * This is a wrapper for xml2arrayProcess that adds a two-level cache
1456
     *
1457
     * @param string $string XML content to convert into an array
1458
     * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1459
     * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1460
     * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1461
     * @see array2xml()
1462
     * @see xml2arrayProcess()
1463
     */
1464
    public static function xml2array($string, $NSprefix = '', $reportDocTag = false)
1465
    {
1466
        $runtimeCache = static::makeInstance(CacheManager::class)->getCache('runtime');
1467
        $firstLevelCache = $runtimeCache->get('generalUtilityXml2Array') ?: [];
1468
        $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
1469
        // Look up in first level cache
1470
        if (empty($firstLevelCache[$identifier])) {
1471
            $firstLevelCache[$identifier] = self::xml2arrayProcess(trim($string), $NSprefix, $reportDocTag);
1472
            $runtimeCache->set('generalUtilityXml2Array', $firstLevelCache);
1473
        }
1474
        return $firstLevelCache[$identifier];
1475
    }
1476
1477
    /**
1478
     * Converts an XML string to a PHP array.
1479
     * This is the reverse function of array2xml()
1480
     *
1481
     * @param string $string XML content to convert into an array
1482
     * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1483
     * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1484
     * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1485
     * @see array2xml()
1486
     */
1487
    protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = false)
1488
    {
1489
        // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1490
        $previousValueOfEntityLoader = null;
1491
        if (PHP_MAJOR_VERSION < 8) {
1492
            $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1493
        }
1494
        // Create parser:
1495
        $parser = xml_parser_create();
1496
        $vals = [];
1497
        $index = [];
1498
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1499
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1500
        // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
1501
        $match = [];
1502
        preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
1503
        $theCharset = $match[1] ?? 'utf-8';
1504
        // us-ascii / utf-8 / iso-8859-1
1505
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
1506
        // Parse content:
1507
        xml_parse_into_struct($parser, $string, $vals, $index);
1508
        if (PHP_MAJOR_VERSION < 8) {
1509
            libxml_disable_entity_loader($previousValueOfEntityLoader);
0 ignored issues
show
Bug introduced by
It seems like $previousValueOfEntityLoader can also be of type null; however, parameter $disable of libxml_disable_entity_loader() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1509
            libxml_disable_entity_loader(/** @scrutinizer ignore-type */ $previousValueOfEntityLoader);
Loading history...
1510
        }
1511
        // If error, return error message:
1512
        if (xml_get_error_code($parser)) {
1513
            return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1514
        }
1515
        xml_parser_free($parser);
1516
        // Init vars:
1517
        $stack = [[]];
1518
        $stacktop = 0;
1519
        $current = [];
1520
        $tagName = '';
1521
        $documentTag = '';
1522
        // Traverse the parsed XML structure:
1523
        foreach ($vals as $key => $val) {
1524
            // First, process the tag-name (which is used in both cases, whether "complete" or "close")
1525
            $tagName = $val['tag'];
1526
            if (!$documentTag) {
1527
                $documentTag = $tagName;
1528
            }
1529
            // Test for name space:
1530
            $tagName = $NSprefix && strpos($tagName, $NSprefix) === 0 ? substr($tagName, strlen($NSprefix)) : $tagName;
1531
            // Test for numeric tag, encoded on the form "nXXX":
1532
            $testNtag = substr($tagName, 1);
1533
            // Closing tag.
1534
            $tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName;
1535
            // Test for alternative index value:
1536
            if ((string)($val['attributes']['index'] ?? '') !== '') {
1537
                $tagName = $val['attributes']['index'];
1538
            }
1539
            // Setting tag-values, manage stack:
1540
            switch ($val['type']) {
1541
                case 'open':
1542
                    // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
1543
                    // Setting blank place holder
1544
                    $current[$tagName] = [];
1545
                    $stack[$stacktop++] = $current;
1546
                    $current = [];
1547
                    break;
1548
                case 'close':
1549
                    // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
1550
                    $oldCurrent = $current;
1551
                    $current = $stack[--$stacktop];
1552
                    // Going to the end of array to get placeholder key, key($current), and fill in array next:
1553
                    end($current);
1554
                    $current[key($current)] = $oldCurrent;
1555
                    unset($oldCurrent);
1556
                    break;
1557
                case 'complete':
1558
                    // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
1559
                    if (!empty($val['attributes']['base64'])) {
1560
                        $current[$tagName] = base64_decode($val['value']);
1561
                    } else {
1562
                        // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
1563
                        $current[$tagName] = (string)($val['value'] ?? '');
1564
                        // Cast type:
1565
                        switch ((string)($val['attributes']['type'] ?? '')) {
1566
                            case 'integer':
1567
                                $current[$tagName] = (int)$current[$tagName];
1568
                                break;
1569
                            case 'double':
1570
                                $current[$tagName] = (double)$current[$tagName];
1571
                                break;
1572
                            case 'boolean':
1573
                                $current[$tagName] = (bool)$current[$tagName];
1574
                                break;
1575
                            case 'NULL':
1576
                                $current[$tagName] = null;
1577
                                break;
1578
                            case 'array':
1579
                                // MUST be an empty array since it is processed as a value; Empty arrays would end up here because they would have no tags inside...
1580
                                $current[$tagName] = [];
1581
                                break;
1582
                        }
1583
                    }
1584
                    break;
1585
            }
1586
        }
1587
        if ($reportDocTag) {
1588
            $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
1589
        }
1590
        // Finally return the content of the document tag.
1591
        return $current[$tagName];
1592
    }
1593
1594
    /**
1595
     * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
1596
     *
1597
     * @param array<int, array<string, mixed>> $vals An array of XML parts, see xml2tree
1598
     * @return string Re-compiled XML data.
1599
     */
1600
    public static function xmlRecompileFromStructValArray(array $vals)
1601
    {
1602
        $XMLcontent = '';
1603
        foreach ($vals as $val) {
1604
            $type = $val['type'];
1605
            // Open tag:
1606
            if ($type === 'open' || $type === 'complete') {
1607
                $XMLcontent .= '<' . $val['tag'];
1608
                if (isset($val['attributes'])) {
1609
                    foreach ($val['attributes'] as $k => $v) {
1610
                        $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
1611
                    }
1612
                }
1613
                if ($type === 'complete') {
1614
                    if (isset($val['value'])) {
1615
                        $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
1616
                    } else {
1617
                        $XMLcontent .= '/>';
1618
                    }
1619
                } else {
1620
                    $XMLcontent .= '>';
1621
                }
1622
                if ($type === 'open' && isset($val['value'])) {
1623
                    $XMLcontent .= htmlspecialchars($val['value']);
1624
                }
1625
            }
1626
            // Finish tag:
1627
            if ($type === 'close') {
1628
                $XMLcontent .= '</' . $val['tag'] . '>';
1629
            }
1630
            // Cdata
1631
            if ($type === 'cdata') {
1632
                $XMLcontent .= htmlspecialchars($val['value']);
1633
            }
1634
        }
1635
        return $XMLcontent;
1636
    }
1637
1638
    /**
1639
     * Minifies JavaScript
1640
     *
1641
     * @param string $script Script to minify
1642
     * @param string $error Error message (if any)
1643
     * @return string Minified script or source string if error happened
1644
     */
1645
    public static function minifyJavaScript($script, &$error = '')
1646
    {
1647
        $fakeThis = null;
1648
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] ?? [] as $hookMethod) {
1649
            try {
1650
                $parameters = ['script' => $script];
1651
                $script = static::callUserFunction($hookMethod, $parameters, $fakeThis);
1652
            } catch (\Exception $e) {
1653
                $errorMessage = 'Error minifying java script: ' . $e->getMessage();
1654
                $error .= $errorMessage;
1655
                static::getLogger()->warning($errorMessage, [
1656
                    'JavaScript' => $script,
1657
                    'hook' => $hookMethod,
1658
                    'exception' => $e,
1659
                ]);
1660
            }
1661
        }
1662
        return $script;
1663
    }
1664
1665
    /*************************
1666
     *
1667
     * FILES FUNCTIONS
1668
     *
1669
     *************************/
1670
    /**
1671
     * Reads the file or url $url and returns the content
1672
     * If you are having trouble with proxies when reading URLs you can configure your way out of that with settings within $GLOBALS['TYPO3_CONF_VARS']['HTTP'].
1673
     *
1674
     * @param string $url File/URL to read
1675
     * @return mixed The content from the resource given as input. FALSE if an error has occurred.
1676
     */
1677
    public static function getUrl($url)
1678
    {
1679
        // Looks like it's an external file, use Guzzle by default
1680
        if (preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
1681
            $requestFactory = static::makeInstance(RequestFactory::class);
1682
            try {
1683
                $response = $requestFactory->request($url);
1684
            } catch (RequestException $exception) {
1685
                return false;
1686
            }
1687
            $content = $response->getBody()->getContents();
1688
        } else {
1689
            $content = @file_get_contents($url);
1690
        }
1691
        return $content;
1692
    }
1693
1694
    /**
1695
     * Writes $content to the file $file
1696
     *
1697
     * @param string $file Filepath to write to
1698
     * @param string $content Content to write
1699
     * @param bool $changePermissions If TRUE, permissions are forced to be set
1700
     * @return bool TRUE if the file was successfully opened and written to.
1701
     */
1702
    public static function writeFile($file, $content, $changePermissions = false)
1703
    {
1704
        if (!@is_file($file)) {
1705
            $changePermissions = true;
1706
        }
1707
        if ($fd = fopen($file, 'wb')) {
1708
            $res = fwrite($fd, $content);
1709
            fclose($fd);
1710
            if ($res === false) {
1711
                return false;
1712
            }
1713
            // Change the permissions only if the file has just been created
1714
            if ($changePermissions) {
1715
                static::fixPermissions($file);
1716
            }
1717
            return true;
1718
        }
1719
        return false;
1720
    }
1721
1722
    /**
1723
     * Sets the file system mode and group ownership of a file or a folder.
1724
     *
1725
     * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
1726
     * @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
1727
     * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
1728
     */
1729
    public static function fixPermissions($path, $recursive = false)
1730
    {
1731
        $targetPermissions = null;
1732
        if (Environment::isWindows()) {
1733
            return true;
1734
        }
1735
        $result = false;
1736
        // Make path absolute
1737
        if (!static::isAbsPath($path)) {
1738
            $path = static::getFileAbsFileName($path);
1739
        }
1740
        if (static::isAllowedAbsPath($path)) {
1741
            if (@is_file($path)) {
1742
                $targetPermissions = (string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] ?? '0644');
1743
            } elseif (@is_dir($path)) {
1744
                $targetPermissions = (string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] ?? '0755');
1745
            }
1746
            if (!empty($targetPermissions)) {
1747
                // make sure it's always 4 digits
1748
                $targetPermissions = str_pad($targetPermissions, 4, '0', STR_PAD_LEFT);
1749
                $targetPermissions = octdec($targetPermissions);
1750
                // "@" is there because file is not necessarily OWNED by the user
1751
                $result = @chmod($path, (int)$targetPermissions);
1752
            }
1753
            // Set createGroup if not empty
1754
            if (
1755
                isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'])
1756
                && $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] !== ''
1757
            ) {
1758
                // "@" is there because file is not necessarily OWNED by the user
1759
                $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']);
1760
                $result = $changeGroupResult ? $result : false;
1761
            }
1762
            // Call recursive if recursive flag if set and $path is directory
1763
            if ($recursive && @is_dir($path)) {
1764
                $handle = opendir($path);
1765
                if (is_resource($handle)) {
1766
                    while (($file = readdir($handle)) !== false) {
1767
                        $recursionResult = null;
1768
                        if ($file !== '.' && $file !== '..') {
1769
                            if (@is_file($path . '/' . $file)) {
1770
                                $recursionResult = static::fixPermissions($path . '/' . $file);
1771
                            } elseif (@is_dir($path . '/' . $file)) {
1772
                                $recursionResult = static::fixPermissions($path . '/' . $file, true);
1773
                            }
1774
                            if (isset($recursionResult) && !$recursionResult) {
1775
                                $result = false;
1776
                            }
1777
                        }
1778
                    }
1779
                    closedir($handle);
1780
                }
1781
            }
1782
        }
1783
        return $result;
1784
    }
1785
1786
    /**
1787
     * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
1788
     * Accepts an additional subdirectory in the file path!
1789
     *
1790
     * @param string $filepath Absolute file path to write within the typo3temp/ or Environment::getVarPath() folder - the file path must be prefixed with this path
1791
     * @param string $content Content string to write
1792
     * @return string Returns NULL on success, otherwise an error string telling about the problem.
1793
     */
1794
    public static function writeFileToTypo3tempDir($filepath, $content)
1795
    {
1796
        // Parse filepath into directory and basename:
1797
        $fI = pathinfo($filepath);
1798
        $fI['dirname'] .= '/';
1799
        // Check parts:
1800
        if (!static::validPathStr($filepath) || !$fI['basename'] || strlen($fI['basename']) >= 60) {
1801
            return 'Input filepath "' . $filepath . '" was generally invalid!';
1802
        }
1803
1804
        // Setting main temporary directory name (standard)
1805
        $allowedPathPrefixes = [
1806
            Environment::getPublicPath() . '/typo3temp' => 'Environment::getPublicPath() + "/typo3temp/"'
1807
        ];
1808
        // Also allow project-path + /var/
1809
        if (Environment::getVarPath() !== Environment::getPublicPath() . '/typo3temp/var') {
1810
            $relPath = substr(Environment::getVarPath(), strlen(Environment::getProjectPath()) + 1);
1811
            $allowedPathPrefixes[Environment::getVarPath()] = 'ProjectPath + ' . $relPath;
1812
        }
1813
1814
        $errorMessage = null;
1815
        foreach ($allowedPathPrefixes as $pathPrefix => $prefixLabel) {
1816
            $dirName = $pathPrefix . '/';
1817
            // Invalid file path, let's check for the other path, if it exists
1818
            if (!static::isFirstPartOfStr($fI['dirname'], $dirName)) {
1819
                if ($errorMessage === null) {
1820
                    $errorMessage = '"' . $fI['dirname'] . '" was not within directory ' . $prefixLabel;
1821
                }
1822
                continue;
1823
            }
1824
            // This resets previous error messages from the first path
1825
            $errorMessage = null;
1826
1827
            if (!@is_dir($dirName)) {
1828
                $errorMessage = $prefixLabel . ' was not a directory!';
1829
                // continue and see if the next iteration resets the errorMessage above
1830
                continue;
1831
            }
1832
            // Checking if the "subdir" is found
1833
            $subdir = substr($fI['dirname'], strlen($dirName));
1834
            if ($subdir) {
1835
                if (preg_match('#^(?:[[:alnum:]_]+/)+$#', $subdir)) {
1836
                    $dirName .= $subdir;
1837
                    if (!@is_dir($dirName)) {
1838
                        static::mkdir_deep($pathPrefix . '/' . $subdir);
1839
                    }
1840
                } else {
1841
                    $errorMessage = 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/+"';
1842
                    break;
1843
                }
1844
            }
1845
            // Checking dir-name again (sub-dir might have been created)
1846
            if (@is_dir($dirName)) {
1847
                if ($filepath === $dirName . $fI['basename']) {
1848
                    static::writeFile($filepath, $content);
1849
                    if (!@is_file($filepath)) {
1850
                        $errorMessage = 'The file was not written to the disk. Please, check that you have write permissions to the ' . $prefixLabel . ' directory.';
1851
                    }
1852
                    break;
1853
                }
1854
                $errorMessage = 'Calculated file location didn\'t match input "' . $filepath . '".';
1855
                break;
1856
            }
1857
            $errorMessage = '"' . $dirName . '" is not a directory!';
1858
            break;
1859
        }
1860
        return $errorMessage;
1861
    }
1862
1863
    /**
1864
     * Wrapper function for mkdir.
1865
     * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']
1866
     * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']
1867
     *
1868
     * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
1869
     * @return bool TRUE if operation was successful
1870
     */
1871
    public static function mkdir($newFolder)
1872
    {
1873
        $result = @mkdir($newFolder, (int)octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']));
1874
        if ($result) {
1875
            static::fixPermissions($newFolder);
1876
        }
1877
        return $result;
1878
    }
1879
1880
    /**
1881
     * Creates a directory - including parent directories if necessary and
1882
     * sets permissions on newly created directories.
1883
     *
1884
     * @param string $directory Target directory to create. Must a have trailing slash
1885
     * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
1886
     * @throws \RuntimeException If directory could not be created
1887
     */
1888
    public static function mkdir_deep($directory)
1889
    {
1890
        if (!is_string($directory)) {
0 ignored issues
show
introduced by
The condition is_string($directory) is always true.
Loading history...
1891
            throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955);
1892
        }
1893
        // Ensure there is only one slash
1894
        $fullPath = rtrim($directory, '/') . '/';
1895
        if ($fullPath !== '/' && !is_dir($fullPath)) {
1896
            $firstCreatedPath = static::createDirectoryPath($fullPath);
1897
            if ($firstCreatedPath !== '') {
1898
                static::fixPermissions($firstCreatedPath, true);
1899
            }
1900
        }
1901
    }
1902
1903
    /**
1904
     * Creates directories for the specified paths if they do not exist. This
1905
     * functions sets proper permission mask but does not set proper user and
1906
     * group.
1907
     *
1908
     * @static
1909
     * @param string $fullDirectoryPath
1910
     * @return string Path to the the first created directory in the hierarchy
1911
     * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep
1912
     * @throws \RuntimeException If directory could not be created
1913
     */
1914
    protected static function createDirectoryPath($fullDirectoryPath)
1915
    {
1916
        $currentPath = $fullDirectoryPath;
1917
        $firstCreatedPath = '';
1918
        $permissionMask = (int)octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']);
1919
        if (!@is_dir($currentPath)) {
1920
            do {
1921
                $firstCreatedPath = $currentPath;
1922
                $separatorPosition = (int)strrpos($currentPath, DIRECTORY_SEPARATOR);
1923
                $currentPath = substr($currentPath, 0, $separatorPosition);
1924
            } while (!is_dir($currentPath) && $separatorPosition > 0);
1925
            $result = @mkdir($fullDirectoryPath, $permissionMask, true);
1926
            // Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir()
1927
            if (!$result && !@is_dir($fullDirectoryPath)) {
1928
                throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401);
1929
            }
1930
        }
1931
        return $firstCreatedPath;
1932
    }
1933
1934
    /**
1935
     * Wrapper function for rmdir, allowing recursive deletion of folders and files
1936
     *
1937
     * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
1938
     * @param bool $removeNonEmpty Allow deletion of non-empty directories
1939
     * @return bool TRUE if operation was successful
1940
     */
1941
    public static function rmdir($path, $removeNonEmpty = false)
1942
    {
1943
        $OK = false;
1944
        // Remove trailing slash
1945
        $path = preg_replace('|/$|', '', $path) ?? '';
1946
        $isWindows = DIRECTORY_SEPARATOR === '\\';
1947
        if (file_exists($path)) {
1948
            $OK = true;
1949
            if (!is_link($path) && is_dir($path)) {
1950
                if ($removeNonEmpty === true && ($handle = @opendir($path))) {
1951
                    $entries = [];
1952
1953
                    while (false !== ($file = readdir($handle))) {
1954
                        if ($file === '.' || $file === '..') {
1955
                            continue;
1956
                        }
1957
1958
                        $entries[] = $path . '/' . $file;
1959
                    }
1960
1961
                    closedir($handle);
1962
1963
                    foreach ($entries as $entry) {
1964
                        if (!static::rmdir($entry, $removeNonEmpty)) {
1965
                            $OK = false;
1966
                        }
1967
                    }
1968
                }
1969
                if ($OK) {
1970
                    $OK = @rmdir($path);
1971
                }
1972
            } elseif (is_link($path) && is_dir($path) && $isWindows) {
1973
                $OK = @rmdir($path);
1974
            } else {
1975
                // If $path is a file, simply remove it
1976
                $OK = @unlink($path);
1977
            }
1978
            clearstatcache();
1979
        } elseif (is_link($path)) {
1980
            $OK = @unlink($path);
1981
            if (!$OK && $isWindows) {
1982
                // Try to delete dead folder links on Windows systems
1983
                $OK = @rmdir($path);
1984
            }
1985
            clearstatcache();
1986
        }
1987
        return $OK;
1988
    }
1989
1990
    /**
1991
     * Returns an array with the names of folders in a specific path
1992
     * Will return 'error' (string) if there were an error with reading directory content.
1993
     * Will return null if provided path is false.
1994
     *
1995
     * @param string $path Path to list directories from
1996
     * @return string[]|string|null Returns an array with the directory entries as values. If no path is provided, the return value will be null.
1997
     */
1998
    public static function get_dirs($path)
1999
    {
2000
        $dirs = null;
2001
        if ($path) {
2002
            if (is_dir($path)) {
2003
                $dir = scandir($path);
2004
                $dirs = [];
2005
                foreach ($dir as $entry) {
2006
                    if (is_dir($path . '/' . $entry) && $entry !== '..' && $entry !== '.') {
2007
                        $dirs[] = $entry;
2008
                    }
2009
                }
2010
            } else {
2011
                $dirs = 'error';
2012
            }
2013
        }
2014
        return $dirs;
2015
    }
2016
2017
    /**
2018
     * Finds all files in a given path and returns them as an array. Each
2019
     * array key is a md5 hash of the full path to the file. This is done because
2020
     * 'some' extensions like the import/export extension depend on this.
2021
     *
2022
     * @param string $path The path to retrieve the files from.
2023
     * @param string $extensionList A comma-separated list of file extensions. Only files of the specified types will be retrieved. When left blank, files of any type will be retrieved.
2024
     * @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned.
2025
     * @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time.
2026
     * @param string $excludePattern A regular expression pattern of file names to exclude. For example: 'clear.gif' or '(clear.gif|.htaccess)'. The pattern will be wrapped with: '/^' and '$/'.
2027
     * @return array<string, string>|string Array of the files found, or an error message in case the path could not be opened.
2028
     */
2029
    public static function getFilesInDir($path, $extensionList = '', $prependPath = false, $order = '', $excludePattern = '')
2030
    {
2031
        $excludePattern = (string)$excludePattern;
2032
        $path = rtrim($path, '/');
2033
        if (!@is_dir($path)) {
2034
            return [];
2035
        }
2036
2037
        $rawFileList = scandir($path);
2038
        if ($rawFileList === false) {
2039
            return 'error opening path: "' . $path . '"';
2040
        }
2041
2042
        $pathPrefix = $path . '/';
2043
        $allowedFileExtensionArray = self::trimExplode(',', $extensionList);
2044
        $extensionList = ',' . str_replace(' ', '', $extensionList) . ',';
2045
        $files = [];
2046
        foreach ($rawFileList as $entry) {
2047
            $completePathToEntry = $pathPrefix . $entry;
2048
            if (!@is_file($completePathToEntry)) {
2049
                continue;
2050
            }
2051
2052
            foreach ($allowedFileExtensionArray as $allowedFileExtension) {
2053
                if (
2054
                    ($extensionList === ',,' || stripos($extensionList, ',' . substr($entry, strlen($allowedFileExtension) * -1, strlen($allowedFileExtension)) . ',') !== false)
2055
                    && ($excludePattern === '' || !preg_match('/^' . $excludePattern . '$/', $entry))
2056
                ) {
2057
                    if ($order !== 'mtime') {
2058
                        $files[] = $entry;
2059
                    } else {
2060
                        // Store the value in the key so we can do a fast asort later.
2061
                        $files[$entry] = filemtime($completePathToEntry);
2062
                    }
2063
                }
2064
            }
2065
        }
2066
2067
        $valueName = 'value';
2068
        if ($order === 'mtime') {
2069
            asort($files);
2070
            $valueName = 'key';
2071
        }
2072
2073
        $valuePathPrefix = $prependPath ? $pathPrefix : '';
2074
        $foundFiles = [];
2075
        foreach ($files as $key => $value) {
2076
            // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
2077
            $foundFiles[md5($pathPrefix . ${$valueName})] = $valuePathPrefix . ${$valueName};
2078
        }
2079
2080
        return $foundFiles;
2081
    }
2082
2083
    /**
2084
     * Recursively gather all files and folders of a path.
2085
     *
2086
     * @param string[] $fileArr Empty input array (will have files added to it)
2087
     * @param string $path The path to read recursively from (absolute) (include trailing slash!)
2088
     * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2089
     * @param bool $regDirs If set, directories are also included in output.
2090
     * @param int $recursivityLevels The number of levels to dig down...
2091
     * @param string $excludePattern regex pattern of files/directories to exclude
2092
     * @return array<string, string> An array with the found files/directories.
2093
     */
2094
    public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = false, $recursivityLevels = 99, $excludePattern = '')
2095
    {
2096
        if ($regDirs) {
2097
            $fileArr[md5($path)] = $path;
2098
        }
2099
        $fileArr = array_merge($fileArr, (array)self::getFilesInDir($path, $extList, true, '', $excludePattern));
2100
        $dirs = self::get_dirs($path);
2101
        if ($recursivityLevels > 0 && is_array($dirs)) {
0 ignored issues
show
introduced by
The condition is_array($dirs) is always false.
Loading history...
2102
            foreach ($dirs as $subdirs) {
2103
                if ((string)$subdirs !== '' && ($excludePattern === '' || !preg_match('/^' . $excludePattern . '$/', $subdirs))) {
2104
                    $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
2105
                }
2106
            }
2107
        }
2108
        return $fileArr;
2109
    }
2110
2111
    /**
2112
     * Removes the absolute part of all files/folders in fileArr
2113
     *
2114
     * @param string[] $fileArr The file array to remove the prefix from
2115
     * @param string $prefixToRemove The prefix path to remove (if found as first part of string!)
2116
     * @return string[]|string The input $fileArr processed, or a string with an error message, when an error occurred.
2117
     */
2118
    public static function removePrefixPathFromList(array $fileArr, $prefixToRemove)
2119
    {
2120
        foreach ($fileArr as $k => &$absFileRef) {
2121
            if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
2122
                $absFileRef = substr($absFileRef, strlen($prefixToRemove));
2123
            } else {
2124
                return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2125
            }
2126
        }
2127
        unset($absFileRef);
2128
        return $fileArr;
2129
    }
2130
2131
    /**
2132
     * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2133
     *
2134
     * @param string $theFile File path to process
2135
     * @return string
2136
     */
2137
    public static function fixWindowsFilePath($theFile)
2138
    {
2139
        return str_replace(['\\', '//'], '/', $theFile);
2140
    }
2141
2142
    /**
2143
     * Resolves "../" sections in the input path string.
2144
     * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2145
     *
2146
     * @param string $pathStr File path in which "/../" is resolved
2147
     * @return string
2148
     */
2149
    public static function resolveBackPath($pathStr)
2150
    {
2151
        if (strpos($pathStr, '..') === false) {
2152
            return $pathStr;
2153
        }
2154
        $parts = explode('/', $pathStr);
2155
        $output = [];
2156
        $c = 0;
2157
        foreach ($parts as $part) {
2158
            if ($part === '..') {
2159
                if ($c) {
2160
                    array_pop($output);
2161
                    --$c;
2162
                } else {
2163
                    $output[] = $part;
2164
                }
2165
            } else {
2166
                ++$c;
2167
                $output[] = $part;
2168
            }
2169
        }
2170
        return implode('/', $output);
2171
    }
2172
2173
    /**
2174
     * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2175
     * - If already having a scheme, nothing is prepended
2176
     * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2177
     * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2178
     *
2179
     * @param string $path URL / path to prepend full URL addressing to.
2180
     * @return string
2181
     */
2182
    public static function locationHeaderUrl($path)
2183
    {
2184
        if (strpos($path, '//') === 0) {
2185
            return $path;
2186
        }
2187
2188
        // relative to HOST
2189
        if (strpos($path, '/') === 0) {
2190
            return self::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
2191
        }
2192
2193
        $urlComponents = parse_url($path);
2194
        if (!($urlComponents['scheme'] ?? false)) {
2195
            // No scheme either
2196
            return self::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
2197
        }
2198
2199
        return $path;
2200
    }
2201
2202
    /**
2203
     * Returns the maximum upload size for a file that is allowed. Measured in KB.
2204
     * This might be handy to find out the real upload limit that is possible for this
2205
     * TYPO3 installation.
2206
     *
2207
     * @return int The maximum size of uploads that are allowed (measured in kilobytes)
2208
     */
2209
    public static function getMaxUploadFileSize()
2210
    {
2211
        $uploadMaxFilesize = (string)ini_get('upload_max_filesize');
2212
        $postMaxSize = (string)ini_get('post_max_size');
2213
        // Check for PHP restrictions of the maximum size of one of the $_FILES
2214
        $phpUploadLimit = self::getBytesFromSizeMeasurement($uploadMaxFilesize);
2215
        // Check for PHP restrictions of the maximum $_POST size
2216
        $phpPostLimit = self::getBytesFromSizeMeasurement($postMaxSize);
2217
        // If the total amount of post data is smaller (!) than the upload_max_filesize directive,
2218
        // then this is the real limit in PHP
2219
        $phpUploadLimit = $phpPostLimit > 0 && $phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit;
2220
        return floor($phpUploadLimit) / 1024;
2221
    }
2222
2223
    /**
2224
     * Gets the bytes value from a measurement string like "100k".
2225
     *
2226
     * @param string $measurement The measurement (e.g. "100k")
2227
     * @return int The bytes value (e.g. 102400)
2228
     */
2229
    public static function getBytesFromSizeMeasurement($measurement)
2230
    {
2231
        $bytes = (float)$measurement;
2232
        if (stripos($measurement, 'G')) {
2233
            $bytes *= 1024 * 1024 * 1024;
2234
        } elseif (stripos($measurement, 'M')) {
2235
            $bytes *= 1024 * 1024;
2236
        } elseif (stripos($measurement, 'K')) {
2237
            $bytes *= 1024;
2238
        }
2239
        return (int)$bytes;
2240
    }
2241
2242
    /**
2243
     * Function for static version numbers on files, based on the filemtime
2244
     *
2245
     * This will make the filename automatically change when a file is
2246
     * changed, and by that re-cached by the browser. If the file does not
2247
     * exist physically the original file passed to the function is
2248
     * returned without the timestamp.
2249
     *
2250
     * Behaviour is influenced by the setting
2251
     * TYPO3_CONF_VARS['BE' and 'FE'][versionNumberInFilename]
2252
     * = TRUE (BE) / "embed" (FE) : modify filename
2253
     * = FALSE (BE) / "querystring" (FE) : add timestamp as parameter
2254
     *
2255
     * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
2256
     * @return string Relative path with version filename including the timestamp
2257
     */
2258
    public static function createVersionNumberedFilename($file)
2259
    {
2260
        $lookupFile = explode('?', $file);
2261
        $path = self::resolveBackPath(self::dirname(Environment::getCurrentScript()) . '/' . $lookupFile[0]);
2262
2263
        $doNothing = false;
2264
2265
        if (($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface
2266
            && ApplicationType::fromRequest($GLOBALS['TYPO3_REQUEST'])->isFrontend()
2267
        ) {
2268
            $mode = strtolower($GLOBALS['TYPO3_CONF_VARS']['FE']['versionNumberInFilename']);
2269
            if ($mode === 'embed') {
2270
                $mode = true;
2271
            } else {
2272
                if ($mode === 'querystring') {
2273
                    $mode = false;
2274
                } else {
2275
                    $doNothing = true;
2276
                }
2277
            }
2278
        } else {
2279
            $mode = $GLOBALS['TYPO3_CONF_VARS']['BE']['versionNumberInFilename'];
2280
        }
2281
        if ($doNothing || !file_exists($path)) {
2282
            // File not found, return filename unaltered
2283
            $fullName = $file;
2284
        } else {
2285
            if (!$mode) {
2286
                // If use of .htaccess rule is not configured,
2287
                // we use the default query-string method
2288
                if (!empty($lookupFile[1])) {
2289
                    $separator = '&';
2290
                } else {
2291
                    $separator = '?';
2292
                }
2293
                $fullName = $file . $separator . filemtime($path);
2294
            } else {
2295
                // Change the filename
2296
                $name = explode('.', $lookupFile[0]);
2297
                $extension = array_pop($name);
2298
                array_push($name, filemtime($path), $extension);
2299
                $fullName = implode('.', $name);
2300
                // Append potential query string
2301
                $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
2302
            }
2303
        }
2304
        return $fullName;
2305
    }
2306
2307
    /**
2308
     * Writes string to a temporary file named after the md5-hash of the string
2309
     * Quite useful for extensions adding their custom built JavaScript during runtime.
2310
     *
2311
     * @param string $content JavaScript to write to file.
2312
     * @return string filename to include in the <script> tag
2313
     */
2314
    public static function writeJavaScriptContentToTemporaryFile(string $content)
2315
    {
2316
        $script = 'typo3temp/assets/js/' . GeneralUtility::shortMD5($content) . '.js';
2317
        if (!@is_file(Environment::getPublicPath() . '/' . $script)) {
2318
            self::writeFileToTypo3tempDir(Environment::getPublicPath() . '/' . $script, $content);
2319
        }
2320
        return $script;
2321
    }
2322
2323
    /**
2324
     * Writes string to a temporary file named after the md5-hash of the string
2325
     * Quite useful for extensions adding their custom built StyleSheet during runtime.
2326
     *
2327
     * @param string $content CSS styles to write to file.
2328
     * @return string filename to include in the <link> tag
2329
     */
2330
    public static function writeStyleSheetContentToTemporaryFile(string $content)
2331
    {
2332
        $script = 'typo3temp/assets/css/' . self::shortMD5($content) . '.css';
2333
        if (!@is_file(Environment::getPublicPath() . '/' . $script)) {
2334
            self::writeFileToTypo3tempDir(Environment::getPublicPath() . '/' . $script, $content);
2335
        }
2336
        return $script;
2337
    }
2338
2339
    /*************************
2340
     *
2341
     * SYSTEM INFORMATION
2342
     *
2343
     *************************/
2344
2345
    /**
2346
     * Returns the link-url to the current script.
2347
     * In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.
2348
     * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
2349
     *
2350
     * @param array $getParams Array of GET parameters to include
2351
     * @return string
2352
     */
2353
    public static function linkThisScript(array $getParams = [])
2354
    {
2355
        $parts = self::getIndpEnv('SCRIPT_NAME');
2356
        $params = self::_GET();
2357
        foreach ($getParams as $key => $value) {
2358
            if ($value !== '') {
2359
                $params[$key] = $value;
2360
            } else {
2361
                unset($params[$key]);
2362
            }
2363
        }
2364
        $pString = self::implodeArrayForUrl('', $params);
2365
        return $pString ? $parts . '?' . ltrim($pString, '&') : $parts;
2366
    }
2367
2368
    /**
2369
     * This method is only for testing and should never be used outside tests-
2370
     *
2371
     * @param string $envName
2372
     * @param mixed $value
2373
     * @internal
2374
     */
2375
    public static function setIndpEnv($envName, $value)
2376
    {
2377
        self::$indpEnvCache[$envName] = $value;
2378
    }
2379
2380
    /**
2381
     * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2382
     * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2383
     *
2384
     * @param string $getEnvName Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
2385
     * @return string Value based on the input key, independent of server/os environment.
2386
     * @throws \UnexpectedValueException
2387
     */
2388
    public static function getIndpEnv($getEnvName)
2389
    {
2390
        if (array_key_exists($getEnvName, self::$indpEnvCache)) {
2391
            return self::$indpEnvCache[$getEnvName];
2392
        }
2393
2394
        /*
2395
        Conventions:
2396
        output from parse_url():
2397
        URL:	http://username:[email protected]:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
2398
        [scheme] => 'http'
2399
        [user] => 'username'
2400
        [pass] => 'password'
2401
        [host] => '192.168.1.4'
2402
        [port] => '8080'
2403
        [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2404
        [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2405
        [fragment] => 'link1'Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2406
        [path_dir] = '/typo3/32/temp/phpcheck/'
2407
        [path_info] = '/arg1/arg2/arg3/'
2408
        [path] = [path_script/path_dir][path_info]Keys supported:URI______:
2409
        REQUEST_URI		=	[path]?[query]		= /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2410
        HTTP_HOST		=	[host][:[port]]		= 192.168.1.4:8080
2411
        SCRIPT_NAME		=	[path_script]++		= /typo3/32/temp/phpcheck/index.php		// NOTICE THAT SCRIPT_NAME will return the php-script name ALSO. [path_script] may not do that (eg. '/somedir/' may result in SCRIPT_NAME '/somedir/index.php')!
2412
        PATH_INFO		=	[path_info]			= /arg1/arg2/arg3/
2413
        QUERY_STRING	=	[query]				= arg1,arg2,arg3&p1=parameter1&p2[key]=value
2414
        HTTP_REFERER	=	[scheme]://[host][:[port]][path]	= http://192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2415
        (Notice: NO username/password + NO fragment)CLIENT____:
2416
        REMOTE_ADDR		=	(client IP)
2417
        REMOTE_HOST		=	(client host)
2418
        HTTP_USER_AGENT	=	(client user agent)
2419
        HTTP_ACCEPT_LANGUAGE	= (client accept language)SERVER____:
2420
        SCRIPT_FILENAME	=	Absolute filename of script		(Differs between windows/unix). On windows 'C:\\some\\path\\' will be converted to 'C:/some/path/'Special extras:
2421
        TYPO3_HOST_ONLY =		[host] = 192.168.1.4
2422
        TYPO3_PORT =			[port] = 8080 (blank if 80, taken from host value)
2423
        TYPO3_REQUEST_HOST = 		[scheme]://[host][:[port]]
2424
        TYPO3_REQUEST_URL =		[scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
2425
        TYPO3_REQUEST_SCRIPT =  	[scheme]://[host][:[port]][path_script]
2426
        TYPO3_REQUEST_DIR =		[scheme]://[host][:[port]][path_dir]
2427
        TYPO3_SITE_URL = 		[scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2428
        TYPO3_SITE_PATH = 		[path_dir] of the TYPO3 website frontend
2429
        TYPO3_SITE_SCRIPT = 		[script / Speaking URL] of the TYPO3 website
2430
        TYPO3_DOCUMENT_ROOT =		Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2431
        TYPO3_SSL = 			Returns TRUE if this session uses SSL/TLS (https)
2432
        TYPO3_PROXY = 			Returns TRUE if this session runs over a well known proxyNotice: [fragment] is apparently NEVER available to the script!Testing suggestions:
2433
        - Output all the values.
2434
        - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
2435
        - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2436
         */
2437
        $retVal = '';
2438
        switch ((string)$getEnvName) {
2439
            case 'SCRIPT_NAME':
2440
                $retVal = Environment::isRunningOnCgiServer()
2441
                    && (($_SERVER['ORIG_PATH_INFO'] ?? false) ?: ($_SERVER['PATH_INFO'] ?? false))
2442
                        ? (($_SERVER['ORIG_PATH_INFO'] ?? '') ?: ($_SERVER['PATH_INFO'] ?? ''))
2443
                        : (($_SERVER['ORIG_SCRIPT_NAME'] ?? '') ?: ($_SERVER['SCRIPT_NAME'] ?? ''));
2444
                // Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
2445
                if (self::cmpIP($_SERVER['REMOTE_ADDR'] ?? '', $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'] ?? '')) {
2446
                    if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
2447
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
2448
                    } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
2449
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
2450
                    }
2451
                }
2452
                break;
2453
            case 'SCRIPT_FILENAME':
2454
                $retVal = Environment::getCurrentScript();
2455
                break;
2456
            case 'REQUEST_URI':
2457
                // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('REQUEST_URI'))
2458
                if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar'])) {
2459
                    // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
2460
                    [$v, $n] = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
2461
                    $retVal = $GLOBALS[$v][$n];
2462
                } elseif (empty($_SERVER['REQUEST_URI'])) {
2463
                    // This is for ISS/CGI which does not have the REQUEST_URI available.
2464
                    $retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '');
2465
                } else {
2466
                    $retVal = '/' . ltrim($_SERVER['REQUEST_URI'], '/');
2467
                }
2468
                // Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
2469
                if (isset($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])
2470
                    && self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])
2471
                ) {
2472
                    if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
2473
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
2474
                    } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
2475
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
2476
                    }
2477
                }
2478
                break;
2479
            case 'PATH_INFO':
2480
                // $_SERVER['PATH_INFO'] != $_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI)
2481
                // are seen to set PATH_INFO equal to script_name
2482
                // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2483
                // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers,
2484
                // then 'PHP_SAPI=='cgi'' might be a better check.
2485
                // Right now strcmp($_SERVER['PATH_INFO'], GeneralUtility::getIndpEnv('SCRIPT_NAME')) will always
2486
                // return FALSE for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO
2487
                // because of PHP_SAPI=='cgi' (see above)
2488
                if (!Environment::isRunningOnCgiServer()) {
2489
                    $retVal = $_SERVER['PATH_INFO'];
2490
                }
2491
                break;
2492
            case 'TYPO3_REV_PROXY':
2493
                $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
2494
                break;
2495
            case 'REMOTE_ADDR':
2496
                $retVal = $_SERVER['REMOTE_ADDR'] ?? null;
2497
                if (self::cmpIP($retVal, $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'] ?? '')) {
2498
                    $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
2499
                    // Choose which IP in list to use
2500
                    if (!empty($ip)) {
2501
                        switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
2502
                            case 'last':
2503
                                $ip = array_pop($ip);
2504
                                break;
2505
                            case 'first':
2506
                                $ip = array_shift($ip);
2507
                                break;
2508
                            case 'none':
2509
2510
                            default:
2511
                                $ip = '';
2512
                        }
2513
                    }
2514
                    if (self::validIP((string)$ip)) {
2515
                        $retVal = $ip;
2516
                    }
2517
                }
2518
                break;
2519
            case 'HTTP_HOST':
2520
                // if it is not set we're most likely on the cli
2521
                $retVal = $_SERVER['HTTP_HOST'] ?? null;
2522
                if (isset($_SERVER['REMOTE_ADDR']) && static::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
2523
                    $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
2524
                    // Choose which host in list to use
2525
                    if (!empty($host)) {
2526
                        switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
2527
                            case 'last':
2528
                                $host = array_pop($host);
2529
                                break;
2530
                            case 'first':
2531
                                $host = array_shift($host);
2532
                                break;
2533
                            case 'none':
2534
2535
                            default:
2536
                                $host = '';
2537
                        }
2538
                    }
2539
                    if ($host) {
2540
                        $retVal = $host;
2541
                    }
2542
                }
2543
                if (!static::isAllowedHostHeaderValue($retVal)) {
2544
                    throw new \UnexpectedValueException(
2545
                        'The current host header value does not match the configured trusted hosts pattern! Check the pattern defined in $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'trustedHostsPattern\'] and adapt it, if you want to allow the current host header \'' . $retVal . '\' for your installation.',
2546
                        1396795884
2547
                    );
2548
                }
2549
                break;
2550
            case 'HTTP_REFERER':
2551
2552
            case 'HTTP_USER_AGENT':
2553
2554
            case 'HTTP_ACCEPT_ENCODING':
2555
2556
            case 'HTTP_ACCEPT_LANGUAGE':
2557
2558
            case 'REMOTE_HOST':
2559
2560
            case 'QUERY_STRING':
2561
                $retVal = $_SERVER[$getEnvName] ?? '';
2562
                break;
2563
            case 'TYPO3_DOCUMENT_ROOT':
2564
                // Get the web root (it is not the root of the TYPO3 installation)
2565
                // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
2566
                // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
2567
                // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2568
                $SFN = self::getIndpEnv('SCRIPT_FILENAME');
2569
                $SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME')));
2570
                $SFN_A = explode('/', strrev($SFN));
2571
                $acc = [];
2572
                foreach ($SN_A as $kk => $vv) {
2573
                    if ((string)$SFN_A[$kk] === (string)$vv) {
2574
                        $acc[] = $vv;
2575
                    } else {
2576
                        break;
2577
                    }
2578
                }
2579
                $commonEnd = strrev(implode('/', $acc));
2580
                if ((string)$commonEnd !== '') {
2581
                    $retVal = substr($SFN, 0, -(strlen($commonEnd) + 1));
2582
                }
2583
                break;
2584
            case 'TYPO3_HOST_ONLY':
2585
                $httpHost = self::getIndpEnv('HTTP_HOST');
2586
                $httpHostBracketPosition = strpos($httpHost, ']');
2587
                $httpHostParts = explode(':', $httpHost);
2588
                $retVal = $httpHostBracketPosition !== false ? substr($httpHost, 0, $httpHostBracketPosition + 1) : array_shift($httpHostParts);
2589
                break;
2590
            case 'TYPO3_PORT':
2591
                $httpHost = self::getIndpEnv('HTTP_HOST');
2592
                $httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY');
2593
                $retVal = strlen($httpHost) > strlen($httpHostOnly) ? substr($httpHost, strlen($httpHostOnly) + 1) : '';
2594
                break;
2595
            case 'TYPO3_REQUEST_HOST':
2596
                $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') . self::getIndpEnv('HTTP_HOST');
2597
                break;
2598
            case 'TYPO3_REQUEST_URL':
2599
                $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI');
2600
                break;
2601
            case 'TYPO3_REQUEST_SCRIPT':
2602
                $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME');
2603
                break;
2604
            case 'TYPO3_REQUEST_DIR':
2605
                $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/';
2606
                break;
2607
            case 'TYPO3_SITE_URL':
2608
                if (Environment::getCurrentScript()) {
2609
                    $lPath = PathUtility::stripPathSitePrefix(PathUtility::dirnameDuringBootstrap(Environment::getCurrentScript())) . '/';
2610
                    $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
2611
                    $siteUrl = substr($url, 0, -strlen($lPath));
2612
                    if (substr($siteUrl, -1) !== '/') {
2613
                        $siteUrl .= '/';
2614
                    }
2615
                    $retVal = $siteUrl;
2616
                }
2617
                break;
2618
            case 'TYPO3_SITE_PATH':
2619
                $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
2620
                break;
2621
            case 'TYPO3_SITE_SCRIPT':
2622
                $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL')));
2623
                break;
2624
            case 'TYPO3_SSL':
2625
                $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL'] ?? null);
0 ignored issues
show
Bug introduced by
It seems like $GLOBALS['TYPO3_CONF_VAR...verseProxySSL'] ?? null can also be of type null; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2625
                $proxySSL = trim(/** @scrutinizer ignore-type */ $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL'] ?? null);
Loading history...
2626
                if ($proxySSL === '*') {
2627
                    $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
2628
                }
2629
                if (self::cmpIP($_SERVER['REMOTE_ADDR'] ?? '', $proxySSL)) {
2630
                    $retVal = true;
2631
                } else {
2632
                    $retVal = self::webserverUsesHttps();
2633
                }
2634
                break;
2635
            case '_ARRAY':
2636
                $out = [];
2637
                // Here, list ALL possible keys to this function for debug display.
2638
                $envTestVars = [
2639
                    'HTTP_HOST',
2640
                    'TYPO3_HOST_ONLY',
2641
                    'TYPO3_PORT',
2642
                    'PATH_INFO',
2643
                    'QUERY_STRING',
2644
                    'REQUEST_URI',
2645
                    'HTTP_REFERER',
2646
                    'TYPO3_REQUEST_HOST',
2647
                    'TYPO3_REQUEST_URL',
2648
                    'TYPO3_REQUEST_SCRIPT',
2649
                    'TYPO3_REQUEST_DIR',
2650
                    'TYPO3_SITE_URL',
2651
                    'TYPO3_SITE_SCRIPT',
2652
                    'TYPO3_SSL',
2653
                    'TYPO3_REV_PROXY',
2654
                    'SCRIPT_NAME',
2655
                    'TYPO3_DOCUMENT_ROOT',
2656
                    'SCRIPT_FILENAME',
2657
                    'REMOTE_ADDR',
2658
                    'REMOTE_HOST',
2659
                    'HTTP_USER_AGENT',
2660
                    'HTTP_ACCEPT_LANGUAGE'
2661
                ];
2662
                foreach ($envTestVars as $v) {
2663
                    $out[$v] = self::getIndpEnv($v);
2664
                }
2665
                reset($out);
2666
                $retVal = $out;
2667
                break;
2668
        }
2669
        self::$indpEnvCache[$getEnvName] = $retVal;
2670
        return $retVal;
2671
    }
2672
2673
    /**
2674
     * Checks if the provided host header value matches the trusted hosts pattern.
2675
     * If the pattern is not defined (which only can happen early in the bootstrap), deny any value.
2676
     * The result is saved, so the check needs to be executed only once.
2677
     *
2678
     * @param string $hostHeaderValue HTTP_HOST header value as sent during the request (may include port)
2679
     * @return bool
2680
     */
2681
    public static function isAllowedHostHeaderValue($hostHeaderValue)
2682
    {
2683
        if (static::$allowHostHeaderValue === true) {
2684
            return true;
2685
        }
2686
2687
        if (static::isInternalRequestType()) {
2688
            return static::$allowHostHeaderValue = true;
2689
        }
2690
2691
        // Deny the value if trusted host patterns is empty, which means we are early in the bootstrap
2692
        if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'])) {
2693
            return false;
2694
        }
2695
2696
        if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL) {
2697
            static::$allowHostHeaderValue = true;
2698
        } else {
2699
            static::$allowHostHeaderValue = static::hostHeaderValueMatchesTrustedHostsPattern($hostHeaderValue);
2700
        }
2701
2702
        return static::$allowHostHeaderValue;
2703
    }
2704
2705
    /**
2706
     * Checks if the provided host header value matches the trusted hosts pattern without any preprocessing.
2707
     *
2708
     * @param string $hostHeaderValue
2709
     * @return bool
2710
     * @internal
2711
     */
2712
    public static function hostHeaderValueMatchesTrustedHostsPattern($hostHeaderValue)
2713
    {
2714
        if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME) {
2715
            $host = strtolower($hostHeaderValue);
2716
            // Default port to be verified if HTTP_HOST does not contain explicit port information.
2717
            // Deriving from raw/local webserver HTTPS information (not taking possible proxy configurations into account)
2718
            // as we compare against the raw/local server information (SERVER_PORT).
2719
            $port = self::webserverUsesHttps() ? '443' : '80';
2720
2721
            $parsedHostValue = parse_url('http://' . $host);
2722
            if (isset($parsedHostValue['port'])) {
2723
                $host = $parsedHostValue['host'];
2724
                $port = (string)$parsedHostValue['port'];
2725
            }
2726
2727
            // Allow values that equal the server name
2728
            // Note that this is only secure if name base virtual host are configured correctly in the webserver
2729
            $hostMatch = $host === strtolower($_SERVER['SERVER_NAME']) && $port === $_SERVER['SERVER_PORT'];
2730
        } else {
2731
            // In case name based virtual hosts are not possible, we allow setting a trusted host pattern
2732
            // See https://typo3.org/teams/security/security-bulletins/typo3-core/typo3-core-sa-2014-001/ for further details
2733
            $hostMatch = (bool)preg_match('/^' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] . '$/i', $hostHeaderValue);
2734
        }
2735
2736
        return $hostMatch;
2737
    }
2738
2739
    /**
2740
     * Determine if the webserver uses HTTPS.
2741
     *
2742
     * HEADS UP: This does not check if the client performed a
2743
     * HTTPS request, as possible proxies are not taken into
2744
     * account. It provides raw information about the current
2745
     * webservers configuration only.
2746
     *
2747
     * @return bool
2748
     */
2749
    protected static function webserverUsesHttps()
2750
    {
2751
        if (!empty($_SERVER['SSL_SESSION_ID'])) {
2752
            return true;
2753
        }
2754
2755
        // https://secure.php.net/manual/en/reserved.variables.server.php
2756
        // "Set to a non-empty value if the script was queried through the HTTPS protocol."
2757
        return !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off';
2758
    }
2759
2760
    /**
2761
     * Allows internal requests to the install tool and from the command line.
2762
     * We accept this risk to have the install tool always available.
2763
     * Also CLI needs to be allowed as unfortunately AbstractUserAuthentication::getAuthInfoArray()
2764
     * accesses HTTP_HOST without reason on CLI
2765
     * Additionally, allows requests when no REQUESTTYPE is set, which can happen quite early in the
2766
     * Bootstrap. See Application.php in EXT:backend/Classes/Http/.
2767
     *
2768
     * @return bool
2769
     */
2770
    protected static function isInternalRequestType()
2771
    {
2772
        return Environment::isCli()
2773
            || !isset($GLOBALS['TYPO3_REQUEST'])
2774
            || !($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface)
2775
            || (bool)((int)($GLOBALS['TYPO3_REQUEST'])->getAttribute('applicationType') & TYPO3_REQUESTTYPE_INSTALL);
2776
    }
2777
2778
    /*************************
2779
     *
2780
     * TYPO3 SPECIFIC FUNCTIONS
2781
     *
2782
     *************************/
2783
    /**
2784
     * Returns the absolute filename of a relative reference, resolves the "EXT:" prefix
2785
     * (way of referring to files inside extensions) and checks that the file is inside
2786
     * the TYPO3's base folder and implies a check with
2787
     * \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr().
2788
     *
2789
     * @param string $filename The input filename/filepath to evaluate
2790
     * @return string Returns the absolute filename of $filename if valid, otherwise blank string.
2791
     */
2792
    public static function getFileAbsFileName($filename)
2793
    {
2794
        if ((string)$filename === '') {
2795
            return '';
2796
        }
2797
        // Extension
2798
        if (strpos($filename, 'EXT:') === 0) {
2799
            [$extKey, $local] = explode('/', substr($filename, 4), 2);
2800
            $filename = '';
2801
            if ((string)$extKey !== '' && ExtensionManagementUtility::isLoaded($extKey) && (string)$local !== '') {
2802
                $filename = ExtensionManagementUtility::extPath($extKey) . $local;
2803
            }
2804
        } elseif (!static::isAbsPath($filename)) {
2805
            // is relative. Prepended with the public web folder
2806
            $filename = Environment::getPublicPath() . '/' . $filename;
2807
        } elseif (!(
2808
            static::isFirstPartOfStr($filename, Environment::getProjectPath())
2809
                  || static::isFirstPartOfStr($filename, Environment::getPublicPath())
2810
        )) {
2811
            // absolute, but set to blank if not allowed
2812
            $filename = '';
2813
        }
2814
        if ((string)$filename !== '' && static::validPathStr($filename)) {
2815
            // checks backpath.
2816
            return $filename;
2817
        }
2818
        return '';
2819
    }
2820
2821
    /**
2822
     * Checks for malicious file paths.
2823
     *
2824
     * Returns TRUE if no '//', '..', '\' or control characters are found in the $theFile.
2825
     * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2826
     * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2827
     *
2828
     * @param string $theFile File path to evaluate
2829
     * @return bool TRUE, $theFile is allowed path string, FALSE otherwise
2830
     * @see https://php.net/manual/en/security.filesystem.nullbytes.php
2831
     */
2832
    public static function validPathStr($theFile)
2833
    {
2834
        return strpos($theFile, '//') === false && strpos($theFile, '\\') === false
2835
            && preg_match('#(?:^\\.\\.|/\\.\\./|[[:cntrl:]])#u', $theFile) === 0;
2836
    }
2837
2838
    /**
2839
     * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns TRUE if so.
2840
     *
2841
     * @param string $path File path to evaluate
2842
     * @return bool
2843
     */
2844
    public static function isAbsPath($path)
2845
    {
2846
        if (substr($path, 0, 6) === 'vfs://') {
2847
            return true;
2848
        }
2849
        return
2850
            (isset($path[0]) && $path[0] === '/')
2851
            || (Environment::isWindows() && (strpos($path, ':/') === 1))
2852
            || strpos($path, ':\\') === 1;
2853
    }
2854
2855
    /**
2856
     * Returns TRUE if the path is absolute, without backpath '..' and within TYPO3s project or public folder OR within the lockRootPath
2857
     *
2858
     * @param string $path File path to evaluate
2859
     * @return bool
2860
     */
2861
    public static function isAllowedAbsPath($path)
2862
    {
2863
        if (substr($path, 0, 6) === 'vfs://') {
2864
            return true;
2865
        }
2866
        $lockRootPath = $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] ?? '';
2867
        return static::isAbsPath($path) && static::validPathStr($path)
2868
            && (
2869
                static::isFirstPartOfStr($path, Environment::getProjectPath())
2870
                || static::isFirstPartOfStr($path, Environment::getPublicPath())
2871
                || ($lockRootPath && static::isFirstPartOfStr($path, $lockRootPath))
2872
            );
2873
    }
2874
2875
    /**
2876
     * Low level utility function to copy directories and content recursive
2877
     *
2878
     * @param string $source Path to source directory, relative to document root or absolute
2879
     * @param string $destination Path to destination directory, relative to document root or absolute
2880
     */
2881
    public static function copyDirectory($source, $destination)
2882
    {
2883
        if (strpos($source, Environment::getProjectPath() . '/') === false) {
2884
            $source = Environment::getPublicPath() . '/' . $source;
2885
        }
2886
        if (strpos($destination, Environment::getProjectPath() . '/') === false) {
2887
            $destination = Environment::getPublicPath() . '/' . $destination;
2888
        }
2889
        if (static::isAllowedAbsPath($source) && static::isAllowedAbsPath($destination)) {
2890
            static::mkdir_deep($destination);
2891
            $iterator = new \RecursiveIteratorIterator(
2892
                new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
2893
                \RecursiveIteratorIterator::SELF_FIRST
2894
            );
2895
            /** @var \SplFileInfo $item */
2896
            foreach ($iterator as $item) {
2897
                $target = $destination . '/' . static::fixWindowsFilePath($iterator->getSubPathName());
0 ignored issues
show
Bug introduced by
The method getSubPathName() does not exist on RecursiveIteratorIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2897
                $target = $destination . '/' . static::fixWindowsFilePath($iterator->/** @scrutinizer ignore-call */ getSubPathName());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2898
                if ($item->isDir()) {
2899
                    static::mkdir($target);
2900
                } else {
2901
                    static::upload_copy_move(static::fixWindowsFilePath($item->getPathname()), $target);
2902
                }
2903
            }
2904
        }
2905
    }
2906
2907
    /**
2908
     * Checks if a given string is a valid frame URL to be loaded in the
2909
     * backend.
2910
     *
2911
     * If the given url is empty or considered to be harmless, it is returned
2912
     * as is, else the event is logged and an empty string is returned.
2913
     *
2914
     * @param string $url potential URL to check
2915
     * @return string $url or empty string
2916
     */
2917
    public static function sanitizeLocalUrl($url = '')
2918
    {
2919
        $sanitizedUrl = '';
2920
        if (!empty($url)) {
2921
            $decodedUrl = rawurldecode($url);
2922
            $parsedUrl = parse_url($decodedUrl);
2923
            $testAbsoluteUrl = self::resolveBackPath($decodedUrl);
2924
            $testRelativeUrl = self::resolveBackPath(self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl);
2925
            // Pass if URL is on the current host:
2926
            if (self::isValidUrl($decodedUrl)) {
2927
                if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) {
2928
                    $sanitizedUrl = $url;
2929
                }
2930
            } elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) {
2931
                $sanitizedUrl = $url;
2932
            } elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && $decodedUrl[0] === '/' &&
2933
                substr($decodedUrl, 0, 2) !== '//'
2934
            ) {
2935
                $sanitizedUrl = $url;
2936
            } elseif (empty($parsedUrl['scheme']) && strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0
2937
                && $decodedUrl[0] !== '/' && strpbrk($decodedUrl, '*:|"<>') === false && strpos($decodedUrl, '\\\\') === false
2938
            ) {
2939
                $sanitizedUrl = $url;
2940
            }
2941
        }
2942
        if (!empty($url) && empty($sanitizedUrl)) {
2943
            static::getLogger()->notice('The URL "' . $url . '" is not considered to be local and was denied.');
2944
        }
2945
        return $sanitizedUrl;
2946
    }
2947
2948
    /**
2949
     * Moves $source file to $destination if uploaded, otherwise try to make a copy
2950
     *
2951
     * @param string $source Source file, absolute path
2952
     * @param string $destination Destination file, absolute path
2953
     * @return bool Returns TRUE if the file was moved.
2954
     * @see upload_to_tempfile()
2955
     */
2956
    public static function upload_copy_move($source, $destination)
2957
    {
2958
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] ?? null)) {
2959
            $params = ['source' => $source, 'destination' => $destination, 'method' => 'upload_copy_move'];
2960
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] as $hookMethod) {
2961
                $fakeThis = null;
2962
                self::callUserFunction($hookMethod, $params, $fakeThis);
2963
            }
2964
        }
2965
2966
        $result = false;
2967
        if (is_uploaded_file($source)) {
2968
            // Return the value of move_uploaded_file, and if FALSE the temporary $source is still
2969
            // around so the user can use unlink to delete it:
2970
            $result = move_uploaded_file($source, $destination);
2971
        } else {
2972
            @copy($source, $destination);
2973
        }
2974
        // Change the permissions of the file
2975
        self::fixPermissions($destination);
2976
        // If here the file is copied and the temporary $source is still around,
2977
        // so when returning FALSE the user can try unlink to delete the $source
2978
        return $result;
2979
    }
2980
2981
    /**
2982
     * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in Environment::getProjectPath() . "var/" from where TYPO3 can use it.
2983
     * Use this function to move uploaded files to where you can work on them.
2984
     * REMEMBER to use \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in the temporary folder!
2985
     *
2986
     * @param string $uploadedFileName The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
2987
     * @return string If a new file was successfully created, return its filename, otherwise blank string.
2988
     * @see unlink_tempfile()
2989
     * @see upload_copy_move()
2990
     */
2991
    public static function upload_to_tempfile($uploadedFileName)
2992
    {
2993
        if (is_uploaded_file($uploadedFileName)) {
2994
            $tempFile = self::tempnam('upload_temp_');
2995
            if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] ?? null)) {
2996
                $params = ['source' => $uploadedFileName, 'destination' => $tempFile, 'method' => 'upload_to_tempfile'];
2997
                foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] as $hookMethod) {
2998
                    $fakeThis = null;
2999
                    self::callUserFunction($hookMethod, $params, $fakeThis);
3000
                }
3001
            }
3002
3003
            move_uploaded_file($uploadedFileName, $tempFile);
3004
            return @is_file($tempFile) ? $tempFile : '';
3005
        }
3006
3007
        return '';
3008
    }
3009
3010
    /**
3011
     * Deletes (unlink) a temporary filename in the var/ or typo3temp folder given as input.
3012
     * The function will check that the file exists, is within TYPO3's var/ or typo3temp/ folder and does not contain back-spaces ("../") so it should be pretty safe.
3013
     * Use this after upload_to_tempfile() or tempnam() from this class!
3014
     *
3015
     * @param string $uploadedTempFileName absolute file path - must reside within var/ or typo3temp/ folder.
3016
     * @return bool|null Returns TRUE if the file was unlink()'ed
3017
     * @see upload_to_tempfile()
3018
     * @see tempnam()
3019
     */
3020
    public static function unlink_tempfile($uploadedTempFileName)
3021
    {
3022
        if ($uploadedTempFileName) {
3023
            $uploadedTempFileName = self::fixWindowsFilePath($uploadedTempFileName);
3024
            if (
3025
                self::validPathStr($uploadedTempFileName)
3026
                && (
3027
                    self::isFirstPartOfStr($uploadedTempFileName, Environment::getPublicPath() . '/typo3temp/')
3028
                    || self::isFirstPartOfStr($uploadedTempFileName, Environment::getVarPath() . '/')
3029
                )
3030
                && @is_file($uploadedTempFileName)
3031
            ) {
3032
                if (unlink($uploadedTempFileName)) {
3033
                    return true;
3034
                }
3035
            }
3036
        }
3037
3038
        return null;
3039
    }
3040
3041
    /**
3042
     * Create temporary filename (Create file with unique file name)
3043
     * This function should be used for getting temporary file names - will make your applications safe for open_basedir = on
3044
     * REMEMBER to delete the temporary files after use! This is done by \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile()
3045
     *
3046
     * @param string $filePrefix Prefix for temporary file
3047
     * @param string $fileSuffix Suffix for temporary file, for example a special file extension
3048
     * @return string result from PHP function tempnam() with the temp/var folder prefixed.
3049
     * @see unlink_tempfile()
3050
     * @see upload_to_tempfile()
3051
     */
3052
    public static function tempnam($filePrefix, $fileSuffix = '')
3053
    {
3054
        $temporaryPath = Environment::getVarPath() . '/transient/';
3055
        if (!is_dir($temporaryPath)) {
3056
            self::mkdir_deep($temporaryPath);
3057
        }
3058
        if ($fileSuffix === '') {
3059
            $path = (string)tempnam($temporaryPath, $filePrefix);
3060
            $tempFileName = $temporaryPath . PathUtility::basename($path);
3061
        } else {
3062
            do {
3063
                $tempFileName = $temporaryPath . $filePrefix . random_int(1, PHP_INT_MAX) . $fileSuffix;
3064
            } while (file_exists($tempFileName));
3065
            touch($tempFileName);
3066
            clearstatcache(false, $tempFileName);
3067
        }
3068
        return $tempFileName;
3069
    }
3070
3071
    /**
3072
     * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
3073
     *
3074
     * @param mixed $uid_or_record Uid (int) or record (array)
3075
     * @param string $fields List of fields from the record if that is given.
3076
     * @param int $codeLength Length of returned authentication code.
3077
     * @return string MD5 hash of 8 chars.
3078
     */
3079
    public static function stdAuthCode($uid_or_record, $fields = '', $codeLength = 8)
3080
    {
3081
        if (is_array($uid_or_record)) {
3082
            $recCopy_temp = [];
3083
            if ($fields) {
3084
                $fieldArr = self::trimExplode(',', $fields, true);
3085
                foreach ($fieldArr as $k => $v) {
3086
                    $recCopy_temp[$k] = $uid_or_record[$v];
3087
                }
3088
            } else {
3089
                $recCopy_temp = $uid_or_record;
3090
            }
3091
            $preKey = implode('|', $recCopy_temp);
3092
        } else {
3093
            $preKey = $uid_or_record;
3094
        }
3095
        $authCode = $preKey . '||' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
3096
        $authCode = substr(md5($authCode), 0, $codeLength);
3097
        return $authCode;
3098
    }
3099
3100
    /**
3101
     * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
3102
     *
3103
     * @param int $l18n_cfg_fieldValue Value from "l18n_cfg" field of a page record
3104
     * @return bool TRUE if the page should be hidden
3105
     * @deprecated since TYPO3 v11, will be removed in TYPO3 v12. Use PageTranslationVisibility BitSet instead.
3106
     */
3107
    public static function hideIfNotTranslated($l18n_cfg_fieldValue)
3108
    {
3109
        trigger_error('GeneralUtility::hideIfNotTranslated() will be removed in TYPO3 v12, use the PageTranslationVisibility BitSet API instead.', E_USER_DEPRECATED);
3110
        return $GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault'] xor ($l18n_cfg_fieldValue & 2);
3111
    }
3112
3113
    /**
3114
     * Returns true if the "l18n_cfg" field value is not set to hide
3115
     * pages in the default language
3116
     *
3117
     * @param int $localizationConfiguration
3118
     * @return bool
3119
     * @deprecated since TYPO3 v11, will be removed in TYPO3 v12. Use PageTranslationVisibility BitSet instead.
3120
     */
3121
    public static function hideIfDefaultLanguage($localizationConfiguration)
3122
    {
3123
        trigger_error('GeneralUtility::hideIfDefaultLanguage() will be removed in TYPO3 v12, use the PageTranslationVisibility BitSet API instead.', E_USER_DEPRECATED);
3124
        return (bool)($localizationConfiguration & 1);
3125
    }
3126
3127
    /**
3128
     * Calls a user-defined function/method in class
3129
     * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
3130
     *
3131
     * @param string $funcName Function/Method reference or Closure.
3132
     * @param mixed $params Parameters to be pass along (typically an array) (REFERENCE!)
3133
     * @param object|null $ref Reference to be passed along (typically "$this" - being a reference to the calling object)
3134
     * @return mixed Content from method/function call
3135
     * @throws \InvalidArgumentException
3136
     */
3137
    public static function callUserFunction($funcName, &$params, ?object $ref = null)
3138
    {
3139
        // Check if we're using a closure and invoke it directly.
3140
        if (is_object($funcName) && is_a($funcName, \Closure::class)) {
0 ignored issues
show
introduced by
The condition is_object($funcName) is always false.
Loading history...
3141
            return call_user_func_array($funcName, [&$params, &$ref]);
3142
        }
3143
        $funcName = trim($funcName);
3144
        $parts = explode('->', $funcName);
3145
        // Call function or method
3146
        if (count($parts) === 2) {
3147
            // It's a class/method
3148
            // Check if class/method exists:
3149
            if (class_exists($parts[0])) {
3150
                // Create object
3151
                $classObj = self::makeInstance($parts[0]);
3152
                $methodName = (string)$parts[1];
3153
                $callable = [$classObj, $methodName];
3154
                if (is_callable($callable)) {
3155
                    // Call method:
3156
                    $content = call_user_func_array($callable, [&$params, &$ref]);
3157
                } else {
3158
                    throw new \InvalidArgumentException('No method name \'' . $parts[1] . '\' in class ' . $parts[0], 1294585865);
3159
                }
3160
            } else {
3161
                throw new \InvalidArgumentException('No class named ' . $parts[0], 1294585866);
3162
            }
3163
        } elseif (function_exists($funcName) && is_callable($funcName)) {
3164
            // It's a function
3165
            $content = call_user_func_array($funcName, [&$params, &$ref]);
3166
        } else {
3167
            throw new \InvalidArgumentException('No function named: ' . $funcName, 1294585867);
3168
        }
3169
        return $content;
3170
    }
3171
3172
    /**
3173
     * @param ContainerInterface $container
3174
     * @internal
3175
     */
3176
    public static function setContainer(ContainerInterface $container): void
3177
    {
3178
        self::$container = $container;
3179
    }
3180
3181
    /**
3182
     * @return ContainerInterface
3183
     * @internal
3184
     */
3185
    public static function getContainer(): ContainerInterface
3186
    {
3187
        if (self::$container === null) {
3188
            throw new \LogicException('PSR-11 Container is not available', 1549404144);
3189
        }
3190
        return self::$container;
3191
    }
3192
3193
    /**
3194
     * Creates an instance of a class taking into account the class-extensions
3195
     * API of TYPO3. USE THIS method instead of the PHP "new" keyword.
3196
     * Eg. "$obj = new myclass;" should be "$obj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance("myclass")" instead!
3197
     *
3198
     * You can also pass arguments for a constructor:
3199
     * \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\myClass::class, $arg1, $arg2, ..., $argN)
3200
     *
3201
     * You may want to use \TYPO3\CMS\Extbase\Object\ObjectManager::get() if you
3202
     * want TYPO3 to take care about injecting dependencies of the class to be
3203
     * created. Therefore create an instance of ObjectManager via
3204
     * GeneralUtility::makeInstance() first and call its get() method to get
3205
     * the instance of a specific class.
3206
     *
3207
     * @param string $className name of the class to instantiate, must not be empty and not start with a backslash
3208
     * @param array<int, mixed> $constructorArguments Arguments for the constructor
3209
     * @return object the created instance
3210
     * @throws \InvalidArgumentException if $className is empty or starts with a backslash
3211
     */
3212
    public static function makeInstance($className, ...$constructorArguments)
3213
    {
3214
        if (!is_string($className) || empty($className)) {
0 ignored issues
show
introduced by
The condition is_string($className) is always true.
Loading history...
3215
            throw new \InvalidArgumentException('$className must be a non empty string.', 1288965219);
3216
        }
3217
        // Never instantiate with a beginning backslash, otherwise things like singletons won't work.
3218
        if ($className[0] === '\\') {
3219
            throw new \InvalidArgumentException(
3220
                '$className "' . $className . '" must not start with a backslash.',
3221
                1420281366
3222
            );
3223
        }
3224
        if (isset(static::$finalClassNameCache[$className])) {
3225
            $finalClassName = static::$finalClassNameCache[$className];
3226
        } else {
3227
            $finalClassName = self::getClassName($className);
3228
            static::$finalClassNameCache[$className] = $finalClassName;
3229
        }
3230
        // Return singleton instance if it is already registered
3231
        if (isset(self::$singletonInstances[$finalClassName])) {
3232
            return self::$singletonInstances[$finalClassName];
3233
        }
3234
        // Return instance if it has been injected by addInstance()
3235
        if (
3236
            isset(self::$nonSingletonInstances[$finalClassName])
3237
            && !empty(self::$nonSingletonInstances[$finalClassName])
3238
        ) {
3239
            return array_shift(self::$nonSingletonInstances[$finalClassName]);
3240
        }
3241
3242
        // Read service and prototypes from the DI container, this is required to
3243
        // support classes that require dependency injection.
3244
        // We operate on the original class name on purpose, as class overrides
3245
        // are resolved inside the container
3246
        if (self::$container !== null && $constructorArguments === [] && self::$container->has($className)) {
3247
            return self::$container->get($className);
3248
        }
3249
3250
        // Create new instance and call constructor with parameters
3251
        $instance = new $finalClassName(...$constructorArguments);
3252
        // Register new singleton instance, but only if it is not a known PSR-11 container service
3253
        if ($instance instanceof SingletonInterface && !(self::$container !== null && self::$container->has($className))) {
3254
            self::$singletonInstances[$finalClassName] = $instance;
3255
        }
3256
        if ($instance instanceof LoggerAwareInterface) {
3257
            $instance->setLogger(static::makeInstance(LogManager::class)->getLogger($className));
3258
        }
3259
        return $instance;
3260
    }
3261
3262
    /**
3263
     * Creates a class taking implementation settings and class aliases into account.
3264
     *
3265
     * Intended to be used to create objects by the dependency injection
3266
     * container.
3267
     *
3268
     * @param string $className name of the class to instantiate
3269
     * @param array<int, mixed> $constructorArguments Arguments for the constructor
3270
     * @return object the created instance
3271
     * @internal
3272
     */
3273
    public static function makeInstanceForDi(string $className, ...$constructorArguments): object
3274
    {
3275
        $finalClassName = static::$finalClassNameCache[$className] ?? static::$finalClassNameCache[$className] = self::getClassName($className);
3276
3277
        // Return singleton instance if it is already registered (currently required for unit and functional tests)
3278
        if (isset(self::$singletonInstances[$finalClassName])) {
3279
            return self::$singletonInstances[$finalClassName];
3280
        }
3281
        // Create new instance and call constructor with parameters
3282
        return new $finalClassName(...$constructorArguments);
3283
    }
3284
3285
    /**
3286
     * Returns the class name for a new instance, taking into account
3287
     * registered implementations for this class
3288
     *
3289
     * @param string $className Base class name to evaluate
3290
     * @return class-string Final class name to instantiate with "new [classname]
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
3291
     */
3292
    protected static function getClassName($className)
3293
    {
3294
        if (class_exists($className)) {
3295
            while (static::classHasImplementation($className)) {
3296
                $className = static::getImplementationForClass($className);
3297
            }
3298
        }
3299
        return ClassLoadingInformation::getClassNameForAlias($className);
3300
    }
3301
3302
    /**
3303
     * Returns the configured implementation of the class
3304
     *
3305
     * @param string $className
3306
     * @return string
3307
     */
3308
    protected static function getImplementationForClass($className)
3309
    {
3310
        return $GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][$className]['className'];
3311
    }
3312
3313
    /**
3314
     * Checks if a class has a configured implementation
3315
     *
3316
     * @param string $className
3317
     * @return bool
3318
     */
3319
    protected static function classHasImplementation($className)
3320
    {
3321
        return !empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][$className]['className']);
3322
    }
3323
3324
    /**
3325
     * Sets the instance of a singleton class to be returned by makeInstance.
3326
     *
3327
     * If this function is called multiple times for the same $className,
3328
     * makeInstance will return the last set instance.
3329
     *
3330
     * Warning:
3331
     * This is NOT a public API method and must not be used in own extensions!
3332
     * This methods exists mostly for unit tests to inject a mock of a singleton class.
3333
     * If you use this, make sure to always combine this with getSingletonInstances()
3334
     * and resetSingletonInstances() in setUp() and tearDown() of the test class.
3335
     *
3336
     * @see makeInstance
3337
     * @param string $className
3338
     * @param \TYPO3\CMS\Core\SingletonInterface $instance
3339
     * @internal
3340
     */
3341
    public static function setSingletonInstance($className, SingletonInterface $instance)
3342
    {
3343
        self::checkInstanceClassName($className, $instance);
3344
        // Check for XCLASS registration (same is done in makeInstance() in order to store the singleton of the final class name)
3345
        $finalClassName = self::getClassName($className);
3346
        self::$singletonInstances[$finalClassName] = $instance;
3347
    }
3348
3349
    /**
3350
     * Removes the instance of a singleton class to be returned by makeInstance.
3351
     *
3352
     * Warning:
3353
     * This is NOT a public API method and must not be used in own extensions!
3354
     * This methods exists mostly for unit tests to inject a mock of a singleton class.
3355
     * If you use this, make sure to always combine this with getSingletonInstances()
3356
     * and resetSingletonInstances() in setUp() and tearDown() of the test class.
3357
     *
3358
     * @see makeInstance
3359
     * @throws \InvalidArgumentException
3360
     * @param string $className
3361
     * @param \TYPO3\CMS\Core\SingletonInterface $instance
3362
     * @internal
3363
     */
3364
    public static function removeSingletonInstance($className, SingletonInterface $instance)
3365
    {
3366
        self::checkInstanceClassName($className, $instance);
3367
        if (!isset(self::$singletonInstances[$className])) {
3368
            throw new \InvalidArgumentException('No Instance registered for ' . $className . '.', 1394099179);
3369
        }
3370
        if ($instance !== self::$singletonInstances[$className]) {
3371
            throw new \InvalidArgumentException('The instance you are trying to remove has not been registered before.', 1394099256);
3372
        }
3373
        unset(self::$singletonInstances[$className]);
3374
    }
3375
3376
    /**
3377
     * Set a group of singleton instances. Similar to setSingletonInstance(),
3378
     * but multiple instances can be set.
3379
     *
3380
     * Warning:
3381
     * This is NOT a public API method and must not be used in own extensions!
3382
     * This method is usually only used in tests to restore the list of singletons in
3383
     * tearDown(), that was backed up with getSingletonInstances() in setUp() and
3384
     * manipulated in tests with setSingletonInstance()
3385
     *
3386
     * @internal
3387
     * @param array<string, SingletonInterface> $newSingletonInstances
3388
     */
3389
    public static function resetSingletonInstances(array $newSingletonInstances)
3390
    {
3391
        static::$singletonInstances = [];
3392
        foreach ($newSingletonInstances as $className => $instance) {
3393
            static::setSingletonInstance($className, $instance);
3394
        }
3395
    }
3396
3397
    /**
3398
     * Get all currently registered singletons
3399
     *
3400
     * Warning:
3401
     * This is NOT a public API method and must not be used in own extensions!
3402
     * This method is usually only used in tests in setUp() to fetch the list of
3403
     * currently registered singletons, if this list is manipulated with
3404
     * setSingletonInstance() in tests.
3405
     *
3406
     * @internal
3407
     * @return array<string, SingletonInterface>
3408
     */
3409
    public static function getSingletonInstances()
3410
    {
3411
        return static::$singletonInstances;
3412
    }
3413
3414
    /**
3415
     * Get all currently registered non singleton instances
3416
     *
3417
     * Warning:
3418
     * This is NOT a public API method and must not be used in own extensions!
3419
     * This method is only used in UnitTestCase base test tearDown() to verify tests
3420
     * have no left over instances that were previously added using addInstance().
3421
     *
3422
     * @internal
3423
     * @return array<string, array<object>>
3424
     */
3425
    public static function getInstances()
3426
    {
3427
        return static::$nonSingletonInstances;
3428
    }
3429
3430
    /**
3431
     * Sets the instance of a non-singleton class to be returned by makeInstance.
3432
     *
3433
     * If this function is called multiple times for the same $className,
3434
     * makeInstance will return the instances in the order in which they have
3435
     * been added (FIFO).
3436
     *
3437
     * Warning: This is a helper method for unit tests. Do not call this directly in production code!
3438
     *
3439
     * @see makeInstance
3440
     * @throws \InvalidArgumentException if class extends \TYPO3\CMS\Core\SingletonInterface
3441
     * @param string $className
3442
     * @param object $instance
3443
     */
3444
    public static function addInstance($className, $instance)
3445
    {
3446
        self::checkInstanceClassName($className, $instance);
3447
        if ($instance instanceof SingletonInterface) {
3448
            throw new \InvalidArgumentException('$instance must not be an instance of TYPO3\\CMS\\Core\\SingletonInterface. For setting singletons, please use setSingletonInstance.', 1288969325);
3449
        }
3450
        if (!isset(self::$nonSingletonInstances[$className])) {
3451
            self::$nonSingletonInstances[$className] = [];
3452
        }
3453
        self::$nonSingletonInstances[$className][] = $instance;
3454
    }
3455
3456
    /**
3457
     * Checks that $className is non-empty and that $instance is an instance of
3458
     * $className.
3459
     *
3460
     * @throws \InvalidArgumentException if $className is empty or if $instance is no instance of $className
3461
     * @param string $className a class name
3462
     * @param object $instance an object
3463
     */
3464
    protected static function checkInstanceClassName($className, $instance)
3465
    {
3466
        if ($className === '') {
3467
            throw new \InvalidArgumentException('$className must not be empty.', 1288967479);
3468
        }
3469
        if (!$instance instanceof $className) {
3470
            throw new \InvalidArgumentException('$instance must be an instance of ' . $className . ', but actually is an instance of ' . get_class($instance) . '.', 1288967686);
3471
        }
3472
    }
3473
3474
    /**
3475
     * Purge all instances returned by makeInstance.
3476
     *
3477
     * This function is most useful when called from tearDown in a test case
3478
     * to drop any instances that have been created by the tests.
3479
     *
3480
     * Warning: This is a helper method for unit tests. Do not call this directly in production code!
3481
     *
3482
     * @see makeInstance
3483
     */
3484
    public static function purgeInstances()
3485
    {
3486
        self::$container = null;
3487
        self::$singletonInstances = [];
3488
        self::$nonSingletonInstances = [];
3489
    }
3490
3491
    /**
3492
     * Flush internal runtime caches
3493
     *
3494
     * Used in unit tests only.
3495
     *
3496
     * @internal
3497
     */
3498
    public static function flushInternalRuntimeCaches()
3499
    {
3500
        self::$indpEnvCache = [];
3501
    }
3502
3503
    /**
3504
     * Find the best service and check if it works.
3505
     * Returns object of the service class.
3506
     *
3507
     * @param string $serviceType Type of service (service key).
3508
     * @param string $serviceSubType Sub type like file extensions or similar. Defined by the service.
3509
     * @param array $excludeServiceKeys List of service keys which should be excluded in the search for a service
3510
     * @throws \RuntimeException
3511
     * @return object|string[] The service object or an array with error infos.
3512
     */
3513
    public static function makeInstanceService($serviceType, $serviceSubType = '', array $excludeServiceKeys = [])
3514
    {
3515
        $error = false;
3516
        $requestInfo = [
3517
            'requestedServiceType' => $serviceType,
3518
            'requestedServiceSubType' => $serviceSubType,
3519
            'requestedExcludeServiceKeys' => $excludeServiceKeys
3520
        ];
3521
        while ($info = ExtensionManagementUtility::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
3522
            // provide information about requested service to service object
3523
            $info = array_merge($info, $requestInfo);
3524
            $obj = self::makeInstance($info['className']);
3525
            if (is_object($obj)) {
3526
                if (!@is_callable([$obj, 'init'])) {
3527
                    self::getLogger()->error('Requested service ' . $info['className'] . ' has no init() method.', ['service' => $info]);
3528
                    throw new \RuntimeException('Broken service: ' . $info['className'], 1568119209);
3529
                }
3530
                $obj->info = $info;
3531
                // service available?
3532
                if ($obj->init()) {
3533
                    return $obj;
3534
                }
3535
                $error = $obj->getLastErrorArray();
3536
                unset($obj);
3537
            }
3538
3539
            // deactivate the service
3540
            ExtensionManagementUtility::deactivateService($info['serviceType'], $info['serviceKey']);
3541
        }
3542
        return $error;
3543
    }
3544
3545
    /**
3546
     * Quotes a string for usage as JS parameter.
3547
     *
3548
     * @param string $value the string to encode, may be empty
3549
     * @return string the encoded value already quoted (with single quotes),
3550
     */
3551
    public static function quoteJSvalue($value)
3552
    {
3553
        $json = (string)json_encode(
3554
            (string)$value,
3555
            JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG
3556
        );
3557
3558
        return strtr(
3559
            $json,
3560
            [
3561
                '"' => '\'',
3562
                '\\\\' => '\\u005C',
3563
                ' ' => '\\u0020',
3564
                '!' => '\\u0021',
3565
                '\\t' => '\\u0009',
3566
                '\\n' => '\\u000A',
3567
                '\\r' => '\\u000D'
3568
            ]
3569
        );
3570
    }
3571
3572
    /**
3573
     * @param mixed $value
3574
     * @param bool $useHtmlEntities
3575
     * @return string
3576
     */
3577
    public static function jsonEncodeForHtmlAttribute($value, bool $useHtmlEntities = true): string
3578
    {
3579
        $json = (string)json_encode($value, JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG);
3580
        return $useHtmlEntities ? htmlspecialchars($json) : $json;
3581
    }
3582
3583
    /**
3584
     * @return LoggerInterface
3585
     */
3586
    protected static function getLogger()
3587
    {
3588
        return static::makeInstance(LogManager::class)->getLogger(__CLASS__);
3589
    }
3590
}
3591