Passed
Push — master ( 548996...0a3947 )
by
unknown
14:39
created

GeneralUtility   F

Complexity

Total Complexity 650

Size/Duplication

Total Lines 3514
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 650
eloc 1421
c 0
b 0
f 0
dl 0
loc 3514
rs 0.8

109 Methods

Rating   Name   Duplication   Size   Complexity  
A validEmail() 0 17 5
A _POST() 0 8 6
B get_tag_attributes() 0 27 7
A inList() 0 3 1
A validIP() 0 3 1
A split_fileref() 0 23 4
B intExplode() 0 21 9
A camelCaseToLowerCaseUnderscored() 0 4 1
A _GET() 0 10 5
A __construct() 0 2 1
A _GP() 0 17 6
A isFirstPartOfStr() 0 5 4
A explodeUrl2Array() 0 11 3
B isValidUrl() 0 26 8
A cmpIP() 0 13 5
B cmpIPv4() 0 39 9
A hmac() 0 25 6
A rmFromList() 0 9 3
A validIPv4() 0 3 1
A underscoredToUpperCamelCase() 0 3 1
B formatSize() 0 31 9
A isOnCurrentHost() 0 3 1
A uniqueList() 0 13 3
A _GPmerged() 0 7 5
C cmpFQDN() 0 59 15
A md5int() 0 3 1
A shortMD5() 0 3 1
A compileSelectedGetVarsFromArray() 0 12 4
B normalizeIPv6() 0 54 10
A fixed_lgd_cs() 0 11 4
A splitCalc() 0 13 2
A removeDotsFromTS() 0 12 3
A wrapJS() 0 17 3
B cmpIPv6() 0 47 11
A underscoredToLowerCamelCase() 0 3 1
A expandList() 0 20 5
A revExplode() 0 16 5
A dirname() 0 4 2
B implodeArrayForUrl() 0 13 7
B trimExplode() 0 20 8
A split_tag_attributes() 0 26 5
A validIPv6() 0 3 1
B implodeAttributes() 0 18 7
C makeInstance() 0 48 15
A hostHeaderValueMatchesTrustedHostsPattern() 0 19 6
F xml2tree() 0 66 16
A resolveBackPath() 0 22 5
A hideIfDefaultLanguage() 0 4 1
F array2xml() 0 104 32
F getIndpEnv() 0 286 72
B copyDirectory() 0 21 7
A mkdir_deep() 0 11 5
A minifyJavaScript() 0 18 3
A stdAuthCode() 0 19 4
A makeInstanceForDi() 0 10 2
A makeInstanceService() 0 30 5
A setIndpEnv() 0 3 1
A fixWindowsFilePath() 0 3 1
A linkThisScript() 0 13 4
A setContainer() 0 3 1
A xml2array() 0 11 4
A addInstance() 0 10 3
D rmdir() 0 47 18
A mkdir() 0 7 2
A upload_copy_move() 0 23 4
A getInstances() 0 3 1
A removeSingletonInstance() 0 10 3
A quoteJSvalue() 0 17 1
A jsonEncodeForHtmlAttribute() 0 4 2
A getUrl() 0 15 3
A writeFile() 0 18 5
A hideIfNotTranslated() 0 4 1
B callUserFunction() 0 33 8
A validPathStr() 0 4 3
A isAllowedHostHeaderValue() 0 22 5
C xmlRecompileFromStructValArray() 0 36 12
C writeFileToTypo3tempDir() 0 69 15
A removePrefixPathFromList() 0 11 3
A flushInternalRuntimeCaches() 0 3 1
A writeJavaScriptContentToTemporaryFile() 0 7 2
A checkInstanceClassName() 0 7 3
B unlink_tempfile() 0 19 7
A upload_to_tempfile() 0 17 5
A isInternalRequestType() 0 6 4
A isAbsPath() 0 6 6
A getLogger() 0 3 1
A getContainer() 0 6 2
A resetSingletonInstances() 0 5 2
A getSingletonInstances() 0 3 1
A writeStyleSheetContentToTemporaryFile() 0 7 2
B createVersionNumberedFilename() 0 47 10
A purgeInstances() 0 5 1
A getImplementationForClass() 0 3 1
B get_dirs() 0 17 7
A tempnam() 0 17 4
F xml2arrayProcess() 0 105 21
A createDirectoryPath() 0 18 6
C getFilesInDir() 0 52 14
A locationHeaderUrl() 0 18 4
B isAllowedAbsPath() 0 11 7
A getClassName() 0 8 3
B getAllFilesAndFoldersInPath() 0 15 8
A getMaxUploadFileSize() 0 12 3
A getBytesFromSizeMeasurement() 0 11 4
A classHasImplementation() 0 3 1
D fixPermissions() 0 55 20
C sanitizeLocalUrl() 0 27 16
A setSingletonInstance() 0 6 1
B getFileAbsFileName() 0 27 11

How to fix   Complexity   

Complex Class

Complex classes like GeneralUtility often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GeneralUtility, and based on these observations, apply Extract Interface, too.

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
        if (isset($_POST[$var])) {
122
            $value = $_POST[$var];
123
        } elseif (isset($_GET[$var])) {
124
            $value = $_GET[$var];
125
        } else {
126
            $value = null;
127
        }
128
        // This is there for backwards-compatibility, in order to avoid NULL
129
        if (isset($value) && !is_array($value)) {
130
            $value = (string)$value;
131
        }
132
        return $value;
133
    }
134
135
    /**
136
     * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
137
     *
138
     * @param string $parameter Key (variable name) from GET or POST vars
139
     * @return array Returns the GET vars merged recursively onto the POST vars.
140
     */
141
    public static function _GPmerged($parameter)
142
    {
143
        $postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : [];
144
        $getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : [];
145
        $mergedParameters = $getParameter;
146
        ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter);
147
        return $mergedParameters;
148
    }
149
150
    /**
151
     * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
152
     * This function was previously used to normalize between magic quotes logic, which was removed from PHP 5.5
153
     *
154
     * @param string $var Optional pointer to value in GET array (basically name of GET var)
155
     * @return mixed If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself.
156
     * @see _POST()
157
     * @see _GP()
158
     */
159
    public static function _GET($var = null)
160
    {
161
        $value = $var === null
162
            ? $_GET
163
            : (empty($var) ? null : ($_GET[$var] ?? null));
164
        // This is there for backwards-compatibility, in order to avoid NULL
165
        if (isset($value) && !is_array($value)) {
166
            $value = (string)$value;
167
        }
168
        return $value;
169
    }
170
171
    /**
172
     * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
173
     *
174
     * @param string $var Optional pointer to value in POST array (basically name of POST var)
175
     * @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself.
176
     * @see _GET()
177
     * @see _GP()
178
     */
179
    public static function _POST($var = null)
180
    {
181
        $value = $var === null ? $_POST : (empty($var) || !isset($_POST[$var]) ? null : $_POST[$var]);
182
        // This is there for backwards-compatibility, in order to avoid NULL
183
        if (isset($value) && !is_array($value)) {
184
            $value = (string)$value;
185
        }
186
        return $value;
187
    }
188
189
    /*************************
190
     *
191
     * STRING FUNCTIONS
192
     *
193
     *************************/
194
    /**
195
     * Truncates a string with appended/prepended "..." and takes current character set into consideration.
196
     *
197
     * @param string $string String to truncate
198
     * @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.
199
     * @param string $appendString Appendix to the truncated string
200
     * @return string Cropped string
201
     */
202
    public static function fixed_lgd_cs($string, $chars, $appendString = '...')
203
    {
204
        if ((int)$chars === 0 || mb_strlen($string, 'utf-8') <= abs($chars)) {
205
            return $string;
206
        }
207
        if ($chars > 0) {
208
            $string = mb_substr($string, 0, $chars, 'utf-8') . $appendString;
209
        } else {
210
            $string = $appendString . mb_substr($string, $chars, mb_strlen($string, 'utf-8'), 'utf-8');
211
        }
212
        return $string;
213
    }
214
215
    /**
216
     * Match IP number with list of numbers with wildcard
217
     * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
218
     *
219
     * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
220
     * @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.
221
     * @return bool TRUE if an IP-mask from $list matches $baseIP
222
     */
223
    public static function cmpIP($baseIP, $list)
224
    {
225
        $list = trim($list);
226
        if ($list === '') {
227
            return false;
228
        }
229
        if ($list === '*') {
230
            return true;
231
        }
232
        if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
233
            return self::cmpIPv6($baseIP, $list);
234
        }
235
        return self::cmpIPv4($baseIP, $list);
236
    }
237
238
    /**
239
     * Match IPv4 number with list of numbers with wildcard
240
     *
241
     * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
242
     * @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
243
     * @return bool TRUE if an IP-mask from $list matches $baseIP
244
     */
245
    public static function cmpIPv4($baseIP, $list)
246
    {
247
        $IPpartsReq = explode('.', $baseIP);
248
        if (count($IPpartsReq) === 4) {
249
            $values = self::trimExplode(',', $list, true);
250
            foreach ($values as $test) {
251
                $testList = explode('/', $test);
252
                if (count($testList) === 2) {
253
                    [$test, $mask] = $testList;
254
                } else {
255
                    $mask = false;
256
                }
257
                if ((int)$mask) {
258
                    $mask = (int)$mask;
259
                    // "192.168.3.0/24"
260
                    $lnet = (int)ip2long($test);
261
                    $lip = (int)ip2long($baseIP);
262
                    $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
263
                    $firstpart = substr($binnet, 0, $mask);
264
                    $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
265
                    $firstip = substr($binip, 0, $mask);
266
                    $yes = $firstpart === $firstip;
267
                } else {
268
                    // "192.168.*.*"
269
                    $IPparts = explode('.', $test);
270
                    $yes = 1;
271
                    foreach ($IPparts as $index => $val) {
272
                        $val = trim($val);
273
                        if ($val !== '*' && $IPpartsReq[$index] !== $val) {
274
                            $yes = 0;
275
                        }
276
                    }
277
                }
278
                if ($yes) {
279
                    return true;
280
                }
281
            }
282
        }
283
        return false;
284
    }
285
286
    /**
287
     * Match IPv6 address with a list of IPv6 prefixes
288
     *
289
     * @param string $baseIP Is the current remote IP address for instance
290
     * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
291
     * @return bool TRUE If a baseIP matches any prefix
292
     */
293
    public static function cmpIPv6($baseIP, $list)
294
    {
295
        // Policy default: Deny connection
296
        $success = false;
297
        $baseIP = self::normalizeIPv6($baseIP);
298
        $values = self::trimExplode(',', $list, true);
299
        foreach ($values as $test) {
300
            $testList = explode('/', $test);
301
            if (count($testList) === 2) {
302
                [$test, $mask] = $testList;
303
            } else {
304
                $mask = false;
305
            }
306
            if (self::validIPv6($test)) {
307
                $test = self::normalizeIPv6($test);
308
                $maskInt = (int)$mask ?: 128;
309
                // Special case; /0 is an allowed mask - equals a wildcard
310
                if ($mask === '0') {
311
                    $success = true;
312
                } elseif ($maskInt == 128) {
313
                    $success = $test === $baseIP;
314
                } else {
315
                    $testBin = (string)inet_pton($test);
316
                    $baseIPBin = (string)inet_pton($baseIP);
317
318
                    $success = true;
319
                    // Modulo is 0 if this is a 8-bit-boundary
320
                    $maskIntModulo = $maskInt % 8;
321
                    $numFullCharactersUntilBoundary = (int)($maskInt / 8);
322
                    $substring = (string)substr($baseIPBin, 0, $numFullCharactersUntilBoundary);
323
                    if (strpos($testBin, $substring) !== 0) {
324
                        $success = false;
325
                    } elseif ($maskIntModulo > 0) {
326
                        // If not an 8-bit-boundary, check bits of last character
327
                        $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
328
                        $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
329
                        if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
330
                            $success = false;
331
                        }
332
                    }
333
                }
334
            }
335
            if ($success) {
336
                return true;
337
            }
338
        }
339
        return false;
340
    }
341
342
    /**
343
     * Normalize an IPv6 address to full length
344
     *
345
     * @param string $address Given IPv6 address
346
     * @return string Normalized address
347
     */
348
    public static function normalizeIPv6($address)
349
    {
350
        $normalizedAddress = '';
351
        // According to RFC lowercase-representation is recommended
352
        $address = strtolower($address);
353
        // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
354
        if (strlen($address) === 39) {
355
            // Already in full expanded form
356
            return $address;
357
        }
358
        // Count 2 if if address has hidden zero blocks
359
        $chunks = explode('::', $address);
360
        if (count($chunks) === 2) {
361
            $chunksLeft = explode(':', $chunks[0]);
362
            $chunksRight = explode(':', $chunks[1]);
363
            $left = count($chunksLeft);
364
            $right = count($chunksRight);
365
            // Special case: leading zero-only blocks count to 1, should be 0
366
            if ($left === 1 && strlen($chunksLeft[0]) === 0) {
367
                $left = 0;
368
            }
369
            $hiddenBlocks = 8 - ($left + $right);
370
            $hiddenPart = '';
371
            $h = 0;
372
            while ($h < $hiddenBlocks) {
373
                $hiddenPart .= '0000:';
374
                $h++;
375
            }
376
            if ($left === 0) {
377
                $stageOneAddress = $hiddenPart . $chunks[1];
378
            } else {
379
                $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
380
            }
381
        } else {
382
            $stageOneAddress = $address;
383
        }
384
        // Normalize the blocks:
385
        $blocks = explode(':', $stageOneAddress);
386
        $divCounter = 0;
387
        foreach ($blocks as $block) {
388
            $tmpBlock = '';
389
            $i = 0;
390
            $hiddenZeros = 4 - strlen($block);
391
            while ($i < $hiddenZeros) {
392
                $tmpBlock .= '0';
393
                $i++;
394
            }
395
            $normalizedAddress .= $tmpBlock . $block;
396
            if ($divCounter < 7) {
397
                $normalizedAddress .= ':';
398
                $divCounter++;
399
            }
400
        }
401
        return $normalizedAddress;
402
    }
403
404
    /**
405
     * Validate a given IP address.
406
     *
407
     * Possible format are IPv4 and IPv6.
408
     *
409
     * @param string $ip IP address to be tested
410
     * @return bool TRUE if $ip is either of IPv4 or IPv6 format.
411
     */
412
    public static function validIP($ip)
413
    {
414
        return filter_var($ip, FILTER_VALIDATE_IP) !== false;
415
    }
416
417
    /**
418
     * Validate a given IP address to the IPv4 address format.
419
     *
420
     * Example for possible format: 10.0.45.99
421
     *
422
     * @param string $ip IP address to be tested
423
     * @return bool TRUE if $ip is of IPv4 format.
424
     */
425
    public static function validIPv4($ip)
426
    {
427
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
428
    }
429
430
    /**
431
     * Validate a given IP address to the IPv6 address format.
432
     *
433
     * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
434
     *
435
     * @param string $ip IP address to be tested
436
     * @return bool TRUE if $ip is of IPv6 format.
437
     */
438
    public static function validIPv6($ip)
439
    {
440
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
441
    }
442
443
    /**
444
     * Match fully qualified domain name with list of strings with wildcard
445
     *
446
     * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
447
     * @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)
448
     * @return bool TRUE if a domain name mask from $list matches $baseIP
449
     */
450
    public static function cmpFQDN($baseHost, $list)
451
    {
452
        $baseHost = trim($baseHost);
453
        if (empty($baseHost)) {
454
            return false;
455
        }
456
        if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
457
            // Resolve hostname
458
            // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
459
            // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
460
            $baseHostName = (string)gethostbyaddr($baseHost);
461
            if ($baseHostName === $baseHost) {
462
                // Unable to resolve hostname
463
                return false;
464
            }
465
        } else {
466
            $baseHostName = $baseHost;
467
        }
468
        $baseHostNameParts = explode('.', $baseHostName);
469
        $values = self::trimExplode(',', $list, true);
470
        foreach ($values as $test) {
471
            $hostNameParts = explode('.', $test);
472
            // To match hostNameParts can only be shorter (in case of wildcards) or equal
473
            $hostNamePartsCount = count($hostNameParts);
474
            $baseHostNamePartsCount = count($baseHostNameParts);
475
            if ($hostNamePartsCount > $baseHostNamePartsCount) {
476
                continue;
477
            }
478
            $yes = true;
479
            foreach ($hostNameParts as $index => $val) {
480
                $val = trim($val);
481
                if ($val === '*') {
482
                    // Wildcard valid for one or more hostname-parts
483
                    $wildcardStart = $index + 1;
484
                    // Wildcard as last/only part always matches, otherwise perform recursive checks
485
                    if ($wildcardStart < $hostNamePartsCount) {
486
                        $wildcardMatched = false;
487
                        $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
488
                        while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) {
489
                            $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
490
                            $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
491
                            $wildcardStart++;
492
                        }
493
                        if ($wildcardMatched) {
494
                            // Match found by recursive compare
495
                            return true;
496
                        }
497
                        $yes = false;
498
                    }
499
                } elseif ($baseHostNameParts[$index] !== $val) {
500
                    // In case of no match
501
                    $yes = false;
502
                }
503
            }
504
            if ($yes) {
505
                return true;
506
            }
507
        }
508
        return false;
509
    }
510
511
    /**
512
     * Checks if a given URL matches the host that currently handles this HTTP request.
513
     * Scheme, hostname and (optional) port of the given URL are compared.
514
     *
515
     * @param string $url URL to compare with the TYPO3 request host
516
     * @return bool Whether the URL matches the TYPO3 request host
517
     */
518
    public static function isOnCurrentHost($url)
519
    {
520
        return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
521
    }
522
523
    /**
524
     * Check for item in list
525
     * Check if an item exists in a comma-separated list of items.
526
     *
527
     * @param string $list Comma-separated list of items (string)
528
     * @param string $item Item to check for
529
     * @return bool TRUE if $item is in $list
530
     */
531
    public static function inList($list, $item)
532
    {
533
        return strpos(',' . $list . ',', ',' . $item . ',') !== false;
534
    }
535
536
    /**
537
     * Removes an item from a comma-separated list of items.
538
     *
539
     * If $element contains a comma, the behaviour of this method is undefined.
540
     * Empty elements in the list are preserved.
541
     *
542
     * @param string $element Element to remove
543
     * @param string $list Comma-separated list of items (string)
544
     * @return string New comma-separated list of items
545
     */
546
    public static function rmFromList($element, $list)
547
    {
548
        $items = explode(',', $list);
549
        foreach ($items as $k => $v) {
550
            if ($v == $element) {
551
                unset($items[$k]);
552
            }
553
        }
554
        return implode(',', $items);
555
    }
556
557
    /**
558
     * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
559
     * Ranges are limited to 1000 values per range.
560
     *
561
     * @param string $list Comma-separated list of integers with ranges (string)
562
     * @return string New comma-separated list of items
563
     */
564
    public static function expandList($list)
565
    {
566
        $items = explode(',', $list);
567
        $list = [];
568
        foreach ($items as $item) {
569
            $range = explode('-', $item);
570
            if (isset($range[1])) {
571
                $runAwayBrake = 1000;
572
                for ($n = $range[0]; $n <= $range[1]; $n++) {
573
                    $list[] = $n;
574
                    $runAwayBrake--;
575
                    if ($runAwayBrake <= 0) {
576
                        break;
577
                    }
578
                }
579
            } else {
580
                $list[] = $item;
581
            }
582
        }
583
        return implode(',', $list);
584
    }
585
586
    /**
587
     * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
588
     *
589
     * @param string $str String to md5-hash
590
     * @return int Returns 28bit integer-hash
591
     */
592
    public static function md5int($str)
593
    {
594
        return hexdec(substr(md5($str), 0, 7));
595
    }
596
597
    /**
598
     * Returns the first 10 positions of the MD5-hash		(changed from 6 to 10 recently)
599
     *
600
     * @param string $input Input string to be md5-hashed
601
     * @param int $len The string-length of the output
602
     * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
603
     */
604
    public static function shortMD5($input, $len = 10)
605
    {
606
        return substr(md5($input), 0, $len);
607
    }
608
609
    /**
610
     * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
611
     *
612
     * @param string $input Input string to create HMAC from
613
     * @param string $additionalSecret additionalSecret to prevent hmac being used in a different context
614
     * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
615
     */
616
    public static function hmac($input, $additionalSecret = '')
617
    {
618
        $hashAlgorithm = 'sha1';
619
        $hashBlocksize = 64;
620
        $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
621
        if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
622
            $hmac = hash_hmac($hashAlgorithm, $input, $secret);
623
        } else {
624
            // Outer padding
625
            $opad = str_repeat(chr(92), $hashBlocksize);
626
            // Inner padding
627
            $ipad = str_repeat(chr(54), $hashBlocksize);
628
            if (strlen($secret) > $hashBlocksize) {
629
                // Keys longer than block size are shorten
630
                $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, "\0");
631
            } else {
632
                // Keys shorter than block size are zero-padded
633
                $key = str_pad($secret, $hashBlocksize, "\0");
634
            }
635
            $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func(
636
                $hashAlgorithm,
637
                ($key ^ $ipad) . $input
638
            )));
639
        }
640
        return $hmac;
641
    }
642
643
    /**
644
     * Takes comma-separated lists and arrays and removes all duplicates
645
     * If a value in the list is trim(empty), the value is ignored.
646
     *
647
     * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
648
     * @param mixed $secondParameter Dummy field, which if set will show a warning!
649
     * @return string Returns the list without any duplicates of values, space around values are trimmed
650
     * @deprecated since TYPO3 v11, will be removed in TYPO3 v12. Use StringUtility::uniqueList() instead.
651
     */
652
    public static function uniqueList($in_list, $secondParameter = null)
653
    {
654
        trigger_error(
655
            'GeneralUtility::uniqueList() is deprecated and will be removed in v12. Use StringUtility::uniqueList() instead.',
656
            E_USER_DEPRECATED
657
        );
658
        if (is_array($in_list)) {
0 ignored issues
show
introduced by
The condition is_array($in_list) is always false.
Loading history...
659
            throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
660
        }
661
        if (isset($secondParameter)) {
662
            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);
663
        }
664
        return implode(',', array_unique(self::trimExplode(',', $in_list, true)));
665
    }
666
667
    /**
668
     * Splits a reference to a file in 5 parts
669
     *
670
     * @param string $fileNameWithPath File name with path to be analyzed (must exist if open_basedir is set)
671
     * @return array<string, string> Contains keys [path], [file], [filebody], [fileext], [realFileext]
672
     */
673
    public static function split_fileref($fileNameWithPath)
674
    {
675
        $info = [];
676
        $reg = [];
677
        if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) {
678
            $info['path'] = $reg[1];
679
            $info['file'] = $reg[2];
680
        } else {
681
            $info['path'] = '';
682
            $info['file'] = $fileNameWithPath;
683
        }
684
        $reg = '';
685
        // If open_basedir is set and the fileName was supplied without a path the is_dir check fails
686
        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 array|null 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

686
        if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], /** @scrutinizer ignore-type */ $reg)) {
Loading history...
687
            $info['filebody'] = $reg[1];
688
            $info['fileext'] = strtolower($reg[2]);
689
            $info['realFileext'] = $reg[2];
690
        } else {
691
            $info['filebody'] = $info['file'];
692
            $info['fileext'] = '';
693
        }
694
        reset($info);
695
        return $info;
696
    }
697
698
    /**
699
     * Returns the directory part of a path without trailing slash
700
     * If there is no dir-part, then an empty string is returned.
701
     * Behaviour:
702
     *
703
     * '/dir1/dir2/script.php' => '/dir1/dir2'
704
     * '/dir1/' => '/dir1'
705
     * 'dir1/script.php' => 'dir1'
706
     * 'd/script.php' => 'd'
707
     * '/script.php' => ''
708
     * '' => ''
709
     *
710
     * @param string $path Directory name / path
711
     * @return string Processed input value. See function description.
712
     */
713
    public static function dirname($path)
714
    {
715
        $p = self::revExplode('/', $path, 2);
716
        return count($p) === 2 ? $p[0] : '';
717
    }
718
719
    /**
720
     * Returns TRUE if the first part of $str matches the string $partStr
721
     *
722
     * @param string $str Full string to check
723
     * @param string $partStr Reference string which must be found as the "first part" of the full string
724
     * @return bool TRUE if $partStr was found to be equal to the first part of $str
725
     */
726
    public static function isFirstPartOfStr($str, $partStr)
727
    {
728
        $str = is_array($str) ? '' : (string)$str;
0 ignored issues
show
introduced by
The condition is_array($str) is always false.
Loading history...
729
        $partStr = is_array($partStr) ? '' : (string)$partStr;
0 ignored issues
show
introduced by
The condition is_array($partStr) is always false.
Loading history...
730
        return $partStr !== '' && strpos($str, $partStr, 0) === 0;
731
    }
732
733
    /**
734
     * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
735
     *
736
     * @param int $sizeInBytes Number of bytes to format.
737
     * @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".
738
     * @param int $base The unit base if not using a unit name. Defaults to 1024.
739
     * @return string Formatted representation of the byte number, for output.
740
     */
741
    public static function formatSize($sizeInBytes, $labels = '', $base = 0)
742
    {
743
        $defaultFormats = [
744
            'iec' => ['base' => 1024, 'labels' => [' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi']],
745
            'si' => ['base' => 1000, 'labels' => [' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']],
746
        ];
747
        // Set labels and base:
748
        if (empty($labels)) {
749
            $labels = 'iec';
750
        }
751
        if (isset($defaultFormats[$labels])) {
752
            $base = $defaultFormats[$labels]['base'];
753
            $labelArr = $defaultFormats[$labels]['labels'];
754
        } else {
755
            $base = (int)$base;
756
            if ($base !== 1000 && $base !== 1024) {
757
                $base = 1024;
758
            }
759
            $labelArr = explode('|', str_replace('"', '', $labels));
760
        }
761
        // This is set via Site Handling and in the Locales class via setlocale()
762
        $localeInfo = localeconv();
763
        $sizeInBytes = max($sizeInBytes, 0);
764
        $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base));
765
        $sizeInUnits = $sizeInBytes / $base ** $multiplier;
766
        if ($sizeInUnits > ($base * .9)) {
767
            $multiplier++;
768
        }
769
        $multiplier = min($multiplier, count($labelArr) - 1);
770
        $sizeInUnits = $sizeInBytes / $base ** $multiplier;
771
        return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier];
772
    }
773
774
    /**
775
     * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
776
     *
777
     * @param string $string Input string, eg "123 + 456 / 789 - 4
778
     * @param string $operators Operators to split by, typically "/+-*
779
     * @return array<int, array<int, string>> Array with operators and operands separated.
780
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc()
781
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
782
     */
783
    public static function splitCalc($string, $operators)
784
    {
785
        $res = [];
786
        $sign = '+';
787
        while ($string) {
788
            $valueLen = strcspn($string, $operators);
789
            $value = substr($string, 0, $valueLen);
790
            $res[] = [$sign, trim($value)];
791
            $sign = substr($string, $valueLen, 1);
792
            $string = substr($string, $valueLen + 1);
793
        }
794
        reset($res);
795
        return $res;
796
    }
797
798
    /**
799
     * Checking syntax of input email address
800
     *
801
     * @param string $email Input string to evaluate
802
     * @return bool Returns TRUE if the $email address (input string) is valid
803
     */
804
    public static function validEmail($email)
805
    {
806
        // Early return in case input is not a string
807
        if (!is_string($email)) {
0 ignored issues
show
introduced by
The condition is_string($email) is always true.
Loading history...
808
            return false;
809
        }
810
        if (trim($email) !== $email) {
811
            return false;
812
        }
813
        $validators = [];
814
        foreach ($GLOBALS['TYPO3_CONF_VARS']['MAIL']['validators'] ?? [RFCValidation::class] as $className) {
815
            $validator = new $className();
816
            if ($validator instanceof EmailValidation) {
817
                $validators[] = $validator;
818
            }
819
        }
820
        return (new EmailValidator())->isValid($email, new MultipleValidationWithAnd($validators));
821
    }
822
823
    /**
824
     * Returns a given string with underscores as UpperCamelCase.
825
     * Example: Converts blog_example to BlogExample
826
     *
827
     * @param string $string String to be converted to camel case
828
     * @return string UpperCamelCasedWord
829
     */
830
    public static function underscoredToUpperCamelCase($string)
831
    {
832
        return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string))));
833
    }
834
835
    /**
836
     * Returns a given string with underscores as lowerCamelCase.
837
     * Example: Converts minimal_value to minimalValue
838
     *
839
     * @param string $string String to be converted to camel case
840
     * @return string lowerCamelCasedWord
841
     */
842
    public static function underscoredToLowerCamelCase($string)
843
    {
844
        return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string)))));
845
    }
846
847
    /**
848
     * Returns a given CamelCasedString as a lowercase string with underscores.
849
     * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
850
     *
851
     * @param string $string String to be converted to lowercase underscore
852
     * @return string lowercase_and_underscored_string
853
     */
854
    public static function camelCaseToLowerCaseUnderscored($string)
855
    {
856
        $value = preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string) ?? '';
857
        return mb_strtolower($value, 'utf-8');
858
    }
859
860
    /**
861
     * Checks if a given string is a Uniform Resource Locator (URL).
862
     *
863
     * On seriously malformed URLs, parse_url may return FALSE and emit an
864
     * E_WARNING.
865
     *
866
     * filter_var() requires a scheme to be present.
867
     *
868
     * http://www.faqs.org/rfcs/rfc2396.html
869
     * Scheme names consist of a sequence of characters beginning with a
870
     * lower case letter and followed by any combination of lower case letters,
871
     * digits, plus ("+"), period ("."), or hyphen ("-").  For resiliency,
872
     * programs interpreting URI should treat upper case letters as equivalent to
873
     * lower case in scheme names (e.g., allow "HTTP" as well as "http").
874
     * scheme = alpha *( alpha | digit | "+" | "-" | "." )
875
     *
876
     * Convert the domain part to punicode if it does not look like a regular
877
     * domain name. Only the domain part because RFC3986 specifies the the rest of
878
     * the url may not contain special characters:
879
     * https://tools.ietf.org/html/rfc3986#appendix-A
880
     *
881
     * @param string $url The URL to be validated
882
     * @return bool Whether the given URL is valid
883
     */
884
    public static function isValidUrl($url)
885
    {
886
        $parsedUrl = parse_url($url);
887
        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...
888
            return false;
889
        }
890
        // HttpUtility::buildUrl() will always build urls with <scheme>://
891
        // our original $url might only contain <scheme>: (e.g. mail:)
892
        // so we convert that to the double-slashed version to ensure
893
        // our check against the $recomposedUrl is proper
894
        if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
895
            $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
896
        }
897
        $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
898
        if ($recomposedUrl !== $url) {
899
            // The parse_url() had to modify characters, so the URL is invalid
900
            return false;
901
        }
902
        if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
903
            $host = HttpUtility::idn_to_ascii($parsedUrl['host']);
904
            if ($host === false) {
905
                return false;
906
            }
907
            $parsedUrl['host'] = $host;
908
        }
909
        return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false;
910
    }
911
912
    /*************************
913
     *
914
     * ARRAY FUNCTIONS
915
     *
916
     *************************/
917
918
    /**
919
     * Explodes a $string delimited by $delimiter and casts each item in the array to (int).
920
     * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
921
     *
922
     * @param string $delimiter Delimiter string to explode with
923
     * @param string $string The string to explode
924
     * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
925
     * @param int $limit If positive, the result will contain a maximum of limit elements,
926
     * @return int[] Exploded values, all converted to integers
927
     */
928
    public static function intExplode($delimiter, $string, $removeEmptyValues = false, $limit = 0)
929
    {
930
        $result = explode($delimiter, $string) ?: [];
931
        foreach ($result as $key => &$value) {
932
            if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
933
                unset($result[$key]);
934
            } else {
935
                $value = (int)$value;
936
            }
937
        }
938
        unset($value);
939
        if ($limit !== 0) {
940
            if ($limit < 0) {
941
                $result = array_slice($result, 0, $limit);
942
            } elseif (count($result) > $limit) {
943
                $lastElements = array_slice($result, $limit - 1);
944
                $result = array_slice($result, 0, $limit - 1);
945
                $result[] = implode($delimiter, $lastElements);
946
            }
947
        }
948
        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...
949
    }
950
951
    /**
952
     * Reverse explode which explodes the string counting from behind.
953
     *
954
     * Note: The delimiter has to given in the reverse order as
955
     *       it is occurring within the string.
956
     *
957
     * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
958
     *   ==> array('[my][words', 'here]')
959
     *
960
     * @param string $delimiter Delimiter string to explode with
961
     * @param string $string The string to explode
962
     * @param int $count Number of array entries
963
     * @return string[] Exploded values
964
     */
965
    public static function revExplode($delimiter, $string, $count = 0)
966
    {
967
        // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
968
        if ($count === 2) {
969
            $position = strrpos($string, strrev($delimiter));
970
            if ($position !== false) {
971
                return [substr($string, 0, $position), substr($string, $position + strlen($delimiter))];
972
            }
973
            return [$string];
974
        }
975
        if ($count <= 1) {
976
            return [$string];
977
        }
978
        $explodedValues = explode($delimiter, strrev($string), $count) ?: [];
979
        $explodedValues = array_map('strrev', $explodedValues);
980
        return array_reverse($explodedValues);
981
    }
982
983
    /**
984
     * Explodes a string and trims all values for whitespace in the end.
985
     * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
986
     *
987
     * @param string $delim Delimiter string to explode with
988
     * @param string $string The string to explode
989
     * @param bool $removeEmptyValues If set, all empty values will be removed in output
990
     * @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with
991
     *                   the last element containing the rest of string. If the limit parameter is negative, all components
992
     *                   except the last -limit are returned.
993
     * @return string[] Exploded values
994
     */
995
    public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0)
996
    {
997
        $result = explode($delim, $string) ?: [];
998
        if ($removeEmptyValues) {
999
            $temp = [];
1000
            foreach ($result as $value) {
1001
                if (trim($value) !== '') {
1002
                    $temp[] = $value;
1003
                }
1004
            }
1005
            $result = $temp;
1006
        }
1007
        if ($limit > 0 && count($result) > $limit) {
1008
            $lastElements = array_splice($result, $limit - 1);
1009
            $result[] = implode($delim, $lastElements);
1010
        } elseif ($limit < 0) {
1011
            $result = array_slice($result, 0, $limit);
1012
        }
1013
        $result = array_map('trim', $result);
1014
        return $result;
1015
    }
1016
1017
    /**
1018
     * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1019
     *
1020
     * @param string $name Name prefix for entries. Set to blank if you wish none.
1021
     * @param array $theArray The (multidimensional) array to implode
1022
     * @param string $str (keep blank)
1023
     * @param bool $skipBlank If set, parameters which were blank strings would be removed.
1024
     * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1025
     * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1026
     * @see explodeUrl2Array()
1027
     */
1028
    public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false)
1029
    {
1030
        foreach ($theArray as $Akey => $AVal) {
1031
            $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1032
            if (is_array($AVal)) {
1033
                $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1034
            } else {
1035
                if (!$skipBlank || (string)$AVal !== '') {
1036
                    $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1037
                }
1038
            }
1039
        }
1040
        return $str;
1041
    }
1042
1043
    /**
1044
     * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array.
1045
     *
1046
     * Note! If you want to use a multi-dimensional string, consider this plain simple PHP code instead:
1047
     *
1048
     * $result = [];
1049
     * parse_str($queryParametersAsString, $result);
1050
     *
1051
     * However, if you do magic with a flat structure (e.g. keeping "ext[mykey]" as flat key in a one-dimensional array)
1052
     * then this method is for you.
1053
     *
1054
     * @param string $string GETvars string
1055
     * @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!
1056
     * @see implodeArrayForUrl()
1057
     */
1058
    public static function explodeUrl2Array($string)
1059
    {
1060
        $output = [];
1061
        $p = explode('&', $string);
1062
        foreach ($p as $v) {
1063
            if ($v !== '') {
1064
                [$pK, $pV] = explode('=', $v, 2);
1065
                $output[rawurldecode($pK)] = rawurldecode($pV);
1066
            }
1067
        }
1068
        return $output;
1069
    }
1070
1071
    /**
1072
     * Returns an array with selected keys from incoming data.
1073
     * (Better read source code if you want to find out...)
1074
     *
1075
     * @param string $varList List of variable/key names
1076
     * @param array $getArray Array from where to get values based on the keys in $varList
1077
     * @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
1078
     * @return array Output array with selected variables.
1079
     */
1080
    public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = true)
1081
    {
1082
        $keys = self::trimExplode(',', $varList, true);
1083
        $outArr = [];
1084
        foreach ($keys as $v) {
1085
            if (isset($getArray[$v])) {
1086
                $outArr[$v] = $getArray[$v];
1087
            } elseif ($GPvarAlt) {
1088
                $outArr[$v] = self::_GP($v);
1089
            }
1090
        }
1091
        return $outArr;
1092
    }
1093
1094
    /**
1095
     * Removes dots "." from end of a key identifier of TypoScript styled array.
1096
     * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1097
     *
1098
     * @param array $ts TypoScript configuration array
1099
     * @return array TypoScript configuration array without dots at the end of all keys
1100
     */
1101
    public static function removeDotsFromTS(array $ts)
1102
    {
1103
        $out = [];
1104
        foreach ($ts as $key => $value) {
1105
            if (is_array($value)) {
1106
                $key = rtrim($key, '.');
1107
                $out[$key] = self::removeDotsFromTS($value);
1108
            } else {
1109
                $out[$key] = $value;
1110
            }
1111
        }
1112
        return $out;
1113
    }
1114
1115
    /*************************
1116
     *
1117
     * HTML/XML PROCESSING
1118
     *
1119
     *************************/
1120
    /**
1121
     * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1122
     * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1123
     * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1124
     *
1125
     * @param string $tag HTML-tag string (or attributes only)
1126
     * @param bool $decodeEntities Whether to decode HTML entities
1127
     * @return array<string, string> Array with the attribute values.
1128
     */
1129
    public static function get_tag_attributes($tag, bool $decodeEntities = false)
1130
    {
1131
        $components = self::split_tag_attributes($tag);
1132
        // Attribute name is stored here
1133
        $name = '';
1134
        $valuemode = false;
1135
        $attributes = [];
1136
        foreach ($components as $key => $val) {
1137
            // 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
1138
            if ($val !== '=') {
1139
                if ($valuemode) {
1140
                    if ($name) {
1141
                        $attributes[$name] = $decodeEntities ? htmlspecialchars_decode($val) : $val;
1142
                        $name = '';
1143
                    }
1144
                } else {
1145
                    if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val) ?? '')) {
1146
                        $attributes[$key] = '';
1147
                        $name = $key;
1148
                    }
1149
                }
1150
                $valuemode = false;
1151
            } else {
1152
                $valuemode = true;
1153
            }
1154
        }
1155
        return $attributes;
1156
    }
1157
1158
    /**
1159
     * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1160
     * Removes tag-name if found
1161
     *
1162
     * @param string $tag HTML-tag string (or attributes only)
1163
     * @return string[] Array with the attribute values.
1164
     */
1165
    public static function split_tag_attributes($tag)
1166
    {
1167
        $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)) ?? '');
1168
        // Removes any > in the end of the string
1169
        $tag_tmp = trim(rtrim($tag_tmp, '>'));
1170
        $value = [];
1171
        // Compared with empty string instead , 030102
1172
        while ($tag_tmp !== '') {
1173
            $firstChar = $tag_tmp[0];
1174
            if ($firstChar === '"' || $firstChar === '\'') {
1175
                $reg = explode($firstChar, $tag_tmp, 3);
1176
                $value[] = $reg[1];
1177
                $tag_tmp = trim($reg[2]);
1178
            } elseif ($firstChar === '=') {
1179
                $value[] = '=';
1180
                // Removes = chars.
1181
                $tag_tmp = trim(substr($tag_tmp, 1));
1182
            } else {
1183
                // There are '' around the value. We look for the next ' ' or '>'
1184
                $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1185
                $value[] = trim($reg[0]);
1186
                $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . ($reg[1] ?? ''));
1187
            }
1188
        }
1189
        reset($value);
1190
        return $value;
1191
    }
1192
1193
    /**
1194
     * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1195
     *
1196
     * @param array<string, string> $arr Array with attribute key/value pairs, eg. "bgcolor" => "red", "border" => "0"
1197
     * @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!
1198
     * @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1199
     * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1200
     */
1201
    public static function implodeAttributes(array $arr, $xhtmlSafe = false, $dontOmitBlankAttribs = false)
1202
    {
1203
        if ($xhtmlSafe) {
1204
            $newArr = [];
1205
            foreach ($arr as $p => $v) {
1206
                if (!isset($newArr[strtolower($p)])) {
1207
                    $newArr[strtolower($p)] = htmlspecialchars($v);
1208
                }
1209
            }
1210
            $arr = $newArr;
1211
        }
1212
        $list = [];
1213
        foreach ($arr as $p => $v) {
1214
            if ((string)$v !== '' || $dontOmitBlankAttribs) {
1215
                $list[] = $p . '="' . $v . '"';
1216
            }
1217
        }
1218
        return implode(' ', $list);
1219
    }
1220
1221
    /**
1222
     * Wraps JavaScript code XHTML ready with <script>-tags
1223
     * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1224
     * This is nice for indenting JS code with PHP code on the same level.
1225
     *
1226
     * @param string $string JavaScript code
1227
     * @return string The wrapped JS code, ready to put into a XHTML page
1228
     */
1229
    public static function wrapJS($string)
1230
    {
1231
        if (trim($string)) {
1232
            // remove nl from the beginning
1233
            $string = ltrim($string, LF);
1234
            // re-ident to one tab using the first line as reference
1235
            $match = [];
1236
            if (preg_match('/^(\\t+)/', $string, $match)) {
1237
                $string = str_replace($match[1], "\t", $string);
1238
            }
1239
            return '<script>
1240
/*<![CDATA[*/
1241
' . $string . '
1242
/*]]>*/
1243
</script>';
1244
        }
1245
        return '';
1246
    }
1247
1248
    /**
1249
     * Parses XML input into a PHP array with associative keys
1250
     *
1251
     * @param string $string XML data input
1252
     * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1253
     * @param array $parserOptions Options that will be passed to PHP's xml_parser_set_option()
1254
     * @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.
1255
     */
1256
    public static function xml2tree($string, $depth = 999, $parserOptions = [])
1257
    {
1258
        // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1259
        $previousValueOfEntityLoader = null;
1260
        if (PHP_MAJOR_VERSION < 8) {
1261
            $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1262
        }
1263
        $parser = xml_parser_create();
1264
        $vals = [];
1265
        $index = [];
1266
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1267
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1268
        foreach ($parserOptions as $option => $value) {
1269
            xml_parser_set_option($parser, $option, $value);
1270
        }
1271
        xml_parse_into_struct($parser, $string, $vals, $index);
1272
        if (PHP_MAJOR_VERSION < 8) {
1273
            libxml_disable_entity_loader($previousValueOfEntityLoader);
1274
        }
1275
        if (xml_get_error_code($parser)) {
1276
            return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1277
        }
1278
        xml_parser_free($parser);
1279
        $stack = [[]];
1280
        $stacktop = 0;
1281
        $startPoint = 0;
1282
        $tagi = [];
1283
        foreach ($vals as $key => $val) {
1284
            $type = $val['type'];
1285
            // open tag:
1286
            if ($type === 'open' || $type === 'complete') {
1287
                $stack[$stacktop++] = $tagi;
1288
                if ($depth == $stacktop) {
1289
                    $startPoint = $key;
1290
                }
1291
                $tagi = ['tag' => $val['tag']];
1292
                if (isset($val['attributes'])) {
1293
                    $tagi['attrs'] = $val['attributes'];
1294
                }
1295
                if (isset($val['value'])) {
1296
                    $tagi['values'][] = $val['value'];
1297
                }
1298
            }
1299
            // finish tag:
1300
            if ($type === 'complete' || $type === 'close') {
1301
                $oldtagi = $tagi;
1302
                $tagi = $stack[--$stacktop];
1303
                $oldtag = $oldtagi['tag'];
1304
                unset($oldtagi['tag']);
1305
                if ($depth == $stacktop + 1) {
1306
                    if ($key - $startPoint > 0) {
1307
                        $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
1308
                        $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
1309
                    } else {
1310
                        $oldtagi['XMLvalue'] = $oldtagi['values'][0];
1311
                    }
1312
                }
1313
                $tagi['ch'][$oldtag][] = $oldtagi;
1314
                unset($oldtagi);
1315
            }
1316
            // cdata
1317
            if ($type === 'cdata') {
1318
                $tagi['values'][] = $val['value'];
1319
            }
1320
        }
1321
        return $tagi['ch'];
1322
    }
1323
1324
    /**
1325
     * Converts a PHP array into an XML string.
1326
     * The XML output is optimized for readability since associative keys are used as tag names.
1327
     * 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.
1328
     * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
1329
     * 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
1330
     * 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.
1331
     * 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!
1332
     * 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...
1333
     *
1334
     * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1335
     * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
1336
     * @param int $level Current recursion level. Don't change, stay at zero!
1337
     * @param string $docTag Alternative document tag. Default is "phparray".
1338
     * @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
1339
     * @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')
1340
     * @param array $stackData Stack data. Don't touch.
1341
     * @return string An XML string made from the input content in the array.
1342
     * @see xml2array()
1343
     */
1344
    public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = [], array $stackData = [])
1345
    {
1346
        // 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
1347
        $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);
1348
        // Set indenting mode:
1349
        $indentChar = $spaceInd ? ' ' : "\t";
1350
        $indentN = $spaceInd > 0 ? $spaceInd : 1;
1351
        $nl = $spaceInd >= 0 ? LF : '';
1352
        // Init output variable:
1353
        $output = '';
1354
        // Traverse the input array
1355
        foreach ($array as $k => $v) {
1356
            $attr = '';
1357
            $tagName = $k;
1358
            // Construct the tag name.
1359
            // Use tag based on grand-parent + parent tag name
1360
            if (isset($stackData['grandParentTagName'], $stackData['parentTagName'], $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
1361
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1362
                $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
1363
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) {
1364
                // Use tag based on parent tag name + if current tag is numeric
1365
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1366
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
1367
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
1368
                // Use tag based on parent tag name + current tag
1369
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1370
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
1371
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName']])) {
1372
                // Use tag based on parent tag name:
1373
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1374
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
1375
            } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) {
1376
                // If integer...;
1377
                if ($options['useNindex']) {
1378
                    // If numeric key, prefix "n"
1379
                    $tagName = 'n' . $tagName;
1380
                } else {
1381
                    // Use special tag for num. keys:
1382
                    $attr .= ' index="' . $tagName . '"';
1383
                    $tagName = $options['useIndexTagForNum'] ?: 'numIndex';
1384
                }
1385
            } elseif (!empty($options['useIndexTagForAssoc'])) {
1386
                // Use tag for all associative keys:
1387
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1388
                $tagName = $options['useIndexTagForAssoc'];
1389
            }
1390
            // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
1391
            $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
1392
            // If the value is an array then we will call this function recursively:
1393
            if (is_array($v)) {
1394
                // Sub elements:
1395
                if (isset($options['alt_options']) && $options['alt_options'][($stackData['path'] ?? '') . '/' . $tagName]) {
1396
                    $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
1397
                    $clearStackPath = $subOptions['clearStackPath'];
1398
                } else {
1399
                    $subOptions = $options;
1400
                    $clearStackPath = false;
1401
                }
1402
                if (empty($v)) {
1403
                    $content = '';
1404
                } else {
1405
                    $content = $nl . self::array2xml($v, $NSprefix, $level + 1, '', $spaceInd, $subOptions, [
1406
                            'parentTagName' => $tagName,
1407
                            'grandParentTagName' => $stackData['parentTagName'] ?? '',
1408
                            'path' => $clearStackPath ? '' : ($stackData['path'] ?? '') . '/' . $tagName
1409
                        ]) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
1410
                }
1411
                // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
1412
                if (!isset($options['disableTypeAttrib']) || (int)$options['disableTypeAttrib'] != 2) {
1413
                    $attr .= ' type="array"';
1414
                }
1415
            } else {
1416
                // Just a value:
1417
                // Look for binary chars:
1418
                $vLen = strlen($v);
1419
                // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
1420
                if ($vLen && strcspn($v, $binaryChars) != $vLen) {
1421
                    // If the value contained binary chars then we base64-encode it and set an attribute to notify this situation:
1422
                    $content = $nl . chunk_split(base64_encode($v));
1423
                    $attr .= ' base64="1"';
1424
                } else {
1425
                    // Otherwise, just htmlspecialchar the stuff:
1426
                    $content = htmlspecialchars($v);
1427
                    $dType = gettype($v);
1428
                    if ($dType === 'string') {
1429
                        if (isset($options['useCDATA']) && $options['useCDATA'] && $content != $v) {
1430
                            $content = '<![CDATA[' . $v . ']]>';
1431
                        }
1432
                    } elseif (!$options['disableTypeAttrib']) {
1433
                        $attr .= ' type="' . $dType . '"';
1434
                    }
1435
                }
1436
            }
1437
            if ((string)$tagName !== '') {
1438
                // Add the element to the output string:
1439
                $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
1440
                    . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
1441
            }
1442
        }
1443
        // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
1444
        if (!$level) {
1445
            $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
1446
        }
1447
        return $output;
1448
    }
1449
1450
    /**
1451
     * Converts an XML string to a PHP array.
1452
     * This is the reverse function of array2xml()
1453
     * This is a wrapper for xml2arrayProcess that adds a two-level cache
1454
     *
1455
     * @param string $string XML content to convert into an array
1456
     * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1457
     * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1458
     * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1459
     * @see array2xml()
1460
     * @see xml2arrayProcess()
1461
     */
1462
    public static function xml2array($string, $NSprefix = '', $reportDocTag = false)
1463
    {
1464
        $runtimeCache = static::makeInstance(CacheManager::class)->getCache('runtime');
1465
        $firstLevelCache = $runtimeCache->get('generalUtilityXml2Array') ?: [];
1466
        $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
1467
        // Look up in first level cache
1468
        if (empty($firstLevelCache[$identifier])) {
1469
            $firstLevelCache[$identifier] = self::xml2arrayProcess(trim($string), $NSprefix, $reportDocTag);
1470
            $runtimeCache->set('generalUtilityXml2Array', $firstLevelCache);
1471
        }
1472
        return $firstLevelCache[$identifier];
1473
    }
1474
1475
    /**
1476
     * Converts an XML string to a PHP array.
1477
     * This is the reverse function of array2xml()
1478
     *
1479
     * @param string $string XML content to convert into an array
1480
     * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1481
     * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1482
     * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1483
     * @see array2xml()
1484
     */
1485
    protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = false)
1486
    {
1487
        // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1488
        $previousValueOfEntityLoader = null;
1489
        if (PHP_MAJOR_VERSION < 8) {
1490
            $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1491
        }
1492
        // Create parser:
1493
        $parser = xml_parser_create();
1494
        $vals = [];
1495
        $index = [];
1496
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1497
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1498
        // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
1499
        $match = [];
1500
        preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
1501
        $theCharset = $match[1] ?? 'utf-8';
1502
        // us-ascii / utf-8 / iso-8859-1
1503
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
1504
        // Parse content:
1505
        xml_parse_into_struct($parser, $string, $vals, $index);
1506
        if (PHP_MAJOR_VERSION < 8) {
1507
            libxml_disable_entity_loader($previousValueOfEntityLoader);
1508
        }
1509
        // If error, return error message:
1510
        if (xml_get_error_code($parser)) {
1511
            return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1512
        }
1513
        xml_parser_free($parser);
1514
        // Init vars:
1515
        $stack = [[]];
1516
        $stacktop = 0;
1517
        $current = [];
1518
        $tagName = '';
1519
        $documentTag = '';
1520
        // Traverse the parsed XML structure:
1521
        foreach ($vals as $key => $val) {
1522
            // First, process the tag-name (which is used in both cases, whether "complete" or "close")
1523
            $tagName = $val['tag'];
1524
            if (!$documentTag) {
1525
                $documentTag = $tagName;
1526
            }
1527
            // Test for name space:
1528
            $tagName = $NSprefix && strpos($tagName, $NSprefix) === 0 ? substr($tagName, strlen($NSprefix)) : $tagName;
1529
            // Test for numeric tag, encoded on the form "nXXX":
1530
            $testNtag = substr($tagName, 1);
1531
            // Closing tag.
1532
            $tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName;
1533
            // Test for alternative index value:
1534
            if ((string)($val['attributes']['index'] ?? '') !== '') {
1535
                $tagName = $val['attributes']['index'];
1536
            }
1537
            // Setting tag-values, manage stack:
1538
            switch ($val['type']) {
1539
                case 'open':
1540
                    // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
1541
                    // Setting blank place holder
1542
                    $current[$tagName] = [];
1543
                    $stack[$stacktop++] = $current;
1544
                    $current = [];
1545
                    break;
1546
                case 'close':
1547
                    // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
1548
                    $oldCurrent = $current;
1549
                    $current = $stack[--$stacktop];
1550
                    // Going to the end of array to get placeholder key, key($current), and fill in array next:
1551
                    end($current);
1552
                    $current[key($current)] = $oldCurrent;
1553
                    unset($oldCurrent);
1554
                    break;
1555
                case 'complete':
1556
                    // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
1557
                    if (!empty($val['attributes']['base64'])) {
1558
                        $current[$tagName] = base64_decode($val['value']);
1559
                    } else {
1560
                        // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
1561
                        $current[$tagName] = (string)($val['value'] ?? '');
1562
                        // Cast type:
1563
                        switch ((string)($val['attributes']['type'] ?? '')) {
1564
                            case 'integer':
1565
                                $current[$tagName] = (int)$current[$tagName];
1566
                                break;
1567
                            case 'double':
1568
                                $current[$tagName] = (double)$current[$tagName];
1569
                                break;
1570
                            case 'boolean':
1571
                                $current[$tagName] = (bool)$current[$tagName];
1572
                                break;
1573
                            case 'NULL':
1574
                                $current[$tagName] = null;
1575
                                break;
1576
                            case 'array':
1577
                                // 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...
1578
                                $current[$tagName] = [];
1579
                                break;
1580
                        }
1581
                    }
1582
                    break;
1583
            }
1584
        }
1585
        if ($reportDocTag) {
1586
            $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
1587
        }
1588
        // Finally return the content of the document tag.
1589
        return $current[$tagName];
1590
    }
1591
1592
    /**
1593
     * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
1594
     *
1595
     * @param array<int, array<string, mixed>> $vals An array of XML parts, see xml2tree
1596
     * @return string Re-compiled XML data.
1597
     */
1598
    public static function xmlRecompileFromStructValArray(array $vals)
1599
    {
1600
        $XMLcontent = '';
1601
        foreach ($vals as $val) {
1602
            $type = $val['type'];
1603
            // Open tag:
1604
            if ($type === 'open' || $type === 'complete') {
1605
                $XMLcontent .= '<' . $val['tag'];
1606
                if (isset($val['attributes'])) {
1607
                    foreach ($val['attributes'] as $k => $v) {
1608
                        $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
1609
                    }
1610
                }
1611
                if ($type === 'complete') {
1612
                    if (isset($val['value'])) {
1613
                        $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
1614
                    } else {
1615
                        $XMLcontent .= '/>';
1616
                    }
1617
                } else {
1618
                    $XMLcontent .= '>';
1619
                }
1620
                if ($type === 'open' && isset($val['value'])) {
1621
                    $XMLcontent .= htmlspecialchars($val['value']);
1622
                }
1623
            }
1624
            // Finish tag:
1625
            if ($type === 'close') {
1626
                $XMLcontent .= '</' . $val['tag'] . '>';
1627
            }
1628
            // Cdata
1629
            if ($type === 'cdata') {
1630
                $XMLcontent .= htmlspecialchars($val['value']);
1631
            }
1632
        }
1633
        return $XMLcontent;
1634
    }
1635
1636
    /**
1637
     * Minifies JavaScript
1638
     *
1639
     * @param string $script Script to minify
1640
     * @param string $error Error message (if any)
1641
     * @return string Minified script or source string if error happened
1642
     */
1643
    public static function minifyJavaScript($script, &$error = '')
1644
    {
1645
        $fakeThis = null;
1646
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] ?? [] as $hookMethod) {
1647
            try {
1648
                $parameters = ['script' => $script];
1649
                $script = static::callUserFunction($hookMethod, $parameters, $fakeThis);
1650
            } catch (\Exception $e) {
1651
                $errorMessage = 'Error minifying java script: ' . $e->getMessage();
1652
                $error .= $errorMessage;
1653
                static::getLogger()->warning($errorMessage, [
1654
                    'JavaScript' => $script,
1655
                    'hook' => $hookMethod,
1656
                    'exception' => $e,
1657
                ]);
1658
            }
1659
        }
1660
        return $script;
1661
    }
1662
1663
    /*************************
1664
     *
1665
     * FILES FUNCTIONS
1666
     *
1667
     *************************/
1668
    /**
1669
     * Reads the file or url $url and returns the content
1670
     * 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'].
1671
     *
1672
     * @param string $url File/URL to read
1673
     * @return mixed The content from the resource given as input. FALSE if an error has occurred.
1674
     */
1675
    public static function getUrl($url)
1676
    {
1677
        // Looks like it's an external file, use Guzzle by default
1678
        if (preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
1679
            $requestFactory = static::makeInstance(RequestFactory::class);
1680
            try {
1681
                $response = $requestFactory->request($url);
1682
            } catch (RequestException $exception) {
1683
                return false;
1684
            }
1685
            $content = $response->getBody()->getContents();
1686
        } else {
1687
            $content = @file_get_contents($url);
1688
        }
1689
        return $content;
1690
    }
1691
1692
    /**
1693
     * Writes $content to the file $file
1694
     *
1695
     * @param string $file Filepath to write to
1696
     * @param string $content Content to write
1697
     * @param bool $changePermissions If TRUE, permissions are forced to be set
1698
     * @return bool TRUE if the file was successfully opened and written to.
1699
     */
1700
    public static function writeFile($file, $content, $changePermissions = false)
1701
    {
1702
        if (!@is_file($file)) {
1703
            $changePermissions = true;
1704
        }
1705
        if ($fd = fopen($file, 'wb')) {
1706
            $res = fwrite($fd, $content);
1707
            fclose($fd);
1708
            if ($res === false) {
1709
                return false;
1710
            }
1711
            // Change the permissions only if the file has just been created
1712
            if ($changePermissions) {
1713
                static::fixPermissions($file);
1714
            }
1715
            return true;
1716
        }
1717
        return false;
1718
    }
1719
1720
    /**
1721
     * Sets the file system mode and group ownership of a file or a folder.
1722
     *
1723
     * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
1724
     * @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
1725
     * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
1726
     */
1727
    public static function fixPermissions($path, $recursive = false)
1728
    {
1729
        $targetPermissions = null;
1730
        if (Environment::isWindows()) {
1731
            return true;
1732
        }
1733
        $result = false;
1734
        // Make path absolute
1735
        if (!static::isAbsPath($path)) {
1736
            $path = static::getFileAbsFileName($path);
1737
        }
1738
        if (static::isAllowedAbsPath($path)) {
1739
            if (@is_file($path)) {
1740
                $targetPermissions = (string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] ?? '0644');
1741
            } elseif (@is_dir($path)) {
1742
                $targetPermissions = (string)($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] ?? '0755');
1743
            }
1744
            if (!empty($targetPermissions)) {
1745
                // make sure it's always 4 digits
1746
                $targetPermissions = str_pad($targetPermissions, 4, '0', STR_PAD_LEFT);
1747
                $targetPermissions = octdec($targetPermissions);
1748
                // "@" is there because file is not necessarily OWNED by the user
1749
                $result = @chmod($path, $targetPermissions);
0 ignored issues
show
Bug introduced by
It seems like $targetPermissions can also be of type double; however, parameter $mode of chmod() does only seem to accept integer, 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

1749
                $result = @chmod($path, /** @scrutinizer ignore-type */ $targetPermissions);
Loading history...
1750
            }
1751
            // Set createGroup if not empty
1752
            if (
1753
                isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'])
1754
                && $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] !== ''
1755
            ) {
1756
                // "@" is there because file is not necessarily OWNED by the user
1757
                $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']);
1758
                $result = $changeGroupResult ? $result : false;
1759
            }
1760
            // Call recursive if recursive flag if set and $path is directory
1761
            if ($recursive && @is_dir($path)) {
1762
                $handle = opendir($path);
1763
                if (is_resource($handle)) {
1764
                    while (($file = readdir($handle)) !== false) {
1765
                        $recursionResult = null;
1766
                        if ($file !== '.' && $file !== '..') {
1767
                            if (@is_file($path . '/' . $file)) {
1768
                                $recursionResult = static::fixPermissions($path . '/' . $file);
1769
                            } elseif (@is_dir($path . '/' . $file)) {
1770
                                $recursionResult = static::fixPermissions($path . '/' . $file, true);
1771
                            }
1772
                            if (isset($recursionResult) && !$recursionResult) {
1773
                                $result = false;
1774
                            }
1775
                        }
1776
                    }
1777
                    closedir($handle);
1778
                }
1779
            }
1780
        }
1781
        return $result;
1782
    }
1783
1784
    /**
1785
     * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
1786
     * Accepts an additional subdirectory in the file path!
1787
     *
1788
     * @param string $filepath Absolute file path to write within the typo3temp/ or Environment::getVarPath() folder - the file path must be prefixed with this path
1789
     * @param string $content Content string to write
1790
     * @return string Returns NULL on success, otherwise an error string telling about the problem.
1791
     */
1792
    public static function writeFileToTypo3tempDir($filepath, $content)
1793
    {
1794
        // Parse filepath into directory and basename:
1795
        $fI = pathinfo($filepath);
1796
        $fI['dirname'] .= '/';
1797
        // Check parts:
1798
        if (!static::validPathStr($filepath) || !$fI['basename'] || strlen($fI['basename']) >= 60) {
1799
            return 'Input filepath "' . $filepath . '" was generally invalid!';
1800
        }
1801
1802
        // Setting main temporary directory name (standard)
1803
        $allowedPathPrefixes = [
1804
            Environment::getPublicPath() . '/typo3temp' => 'Environment::getPublicPath() + "/typo3temp/"'
1805
        ];
1806
        // Also allow project-path + /var/
1807
        if (Environment::getVarPath() !== Environment::getPublicPath() . '/typo3temp/var') {
1808
            $relPath = substr(Environment::getVarPath(), strlen(Environment::getProjectPath()) + 1);
1809
            $allowedPathPrefixes[Environment::getVarPath()] = 'ProjectPath + ' . $relPath;
1810
        }
1811
1812
        $errorMessage = null;
1813
        foreach ($allowedPathPrefixes as $pathPrefix => $prefixLabel) {
1814
            $dirName = $pathPrefix . '/';
1815
            // Invalid file path, let's check for the other path, if it exists
1816
            if (!static::isFirstPartOfStr($fI['dirname'], $dirName)) {
1817
                if ($errorMessage === null) {
1818
                    $errorMessage = '"' . $fI['dirname'] . '" was not within directory ' . $prefixLabel;
1819
                }
1820
                continue;
1821
            }
1822
            // This resets previous error messages from the first path
1823
            $errorMessage = null;
1824
1825
            if (!@is_dir($dirName)) {
1826
                $errorMessage = $prefixLabel . ' was not a directory!';
1827
                // continue and see if the next iteration resets the errorMessage above
1828
                continue;
1829
            }
1830
            // Checking if the "subdir" is found
1831
            $subdir = substr($fI['dirname'], strlen($dirName));
1832
            if ($subdir) {
1833
                if (preg_match('#^(?:[[:alnum:]_]+/)+$#', $subdir)) {
1834
                    $dirName .= $subdir;
1835
                    if (!@is_dir($dirName)) {
1836
                        static::mkdir_deep($pathPrefix . '/' . $subdir);
1837
                    }
1838
                } else {
1839
                    $errorMessage = 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/+"';
1840
                    break;
1841
                }
1842
            }
1843
            // Checking dir-name again (sub-dir might have been created)
1844
            if (@is_dir($dirName)) {
1845
                if ($filepath === $dirName . $fI['basename']) {
1846
                    static::writeFile($filepath, $content);
1847
                    if (!@is_file($filepath)) {
1848
                        $errorMessage = 'The file was not written to the disk. Please, check that you have write permissions to the ' . $prefixLabel . ' directory.';
1849
                        break;
1850
                    }
1851
                } else {
1852
                    $errorMessage = 'Calculated file location didn\'t match input "' . $filepath . '".';
1853
                    break;
1854
                }
1855
            } else {
1856
                $errorMessage = '"' . $dirName . '" is not a directory!';
1857
                break;
1858
            }
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, octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']));
0 ignored issues
show
Bug introduced by
It seems like octdec($GLOBALS['TYPO3_C...']['folderCreateMask']) can also be of type double; however, parameter $mode of mkdir() does only seem to accept integer, 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

1873
        $result = @mkdir($newFolder, /** @scrutinizer ignore-type */ octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']));
Loading history...
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 = 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);
0 ignored issues
show
Bug introduced by
It seems like $permissionMask can also be of type double; however, parameter $mode of mkdir() does only seem to accept integer, 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

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

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