GeneralUtility   F
last analyzed

Complexity

Total Complexity 647

Size/Duplication

Total Lines 3557
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 647
eloc 1427
dl 0
loc 3557
rs 0.8
c 1
b 0
f 0

110 Methods

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

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

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

685
        if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], /** @scrutinizer ignore-type */ $reg)) {
Loading history...
686
            $info['filebody'] = $reg[1];
687
            $info['fileext'] = strtolower($reg[2]);
688
            $info['realFileext'] = $reg[2];
689
        } else {
690
            $info['filebody'] = $info['file'];
691
            $info['fileext'] = '';
692
        }
693
        reset($info);
694
        return $info;
695
    }
696
697
    /**
698
     * Returns the directory part of a path without trailing slash
699
     * If there is no dir-part, then an empty string is returned.
700
     * Behaviour:
701
     *
702
     * '/dir1/dir2/script.php' => '/dir1/dir2'
703
     * '/dir1/' => '/dir1'
704
     * 'dir1/script.php' => 'dir1'
705
     * 'd/script.php' => 'd'
706
     * '/script.php' => ''
707
     * '' => ''
708
     *
709
     * @param string $path Directory name / path
710
     * @return string Processed input value. See function description.
711
     */
712
    public static function dirname($path)
713
    {
714
        $p = self::revExplode('/', $path, 2);
715
        return count($p) === 2 ? $p[0] : '';
716
    }
717
718
    /**
719
     * Returns TRUE if the first part of $str matches the string $partStr
720
     *
721
     * @param string $str Full string to check
722
     * @param string $partStr Reference string which must be found as the "first part" of the full string
723
     * @return bool TRUE if $partStr was found to be equal to the first part of $str
724
     */
725
    public static function isFirstPartOfStr($str, $partStr)
726
    {
727
        $str = is_array($str) ? '' : (string)$str;
0 ignored issues
show
introduced by
The condition is_array($str) is always false.
Loading history...
728
        $partStr = is_array($partStr) ? '' : (string)$partStr;
0 ignored issues
show
introduced by
The condition is_array($partStr) is always false.
Loading history...
729
        return $partStr !== '' && strpos($str, $partStr, 0) === 0;
730
    }
731
732
    /**
733
     * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
734
     *
735
     * @param int $sizeInBytes Number of bytes to format.
736
     * @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".
737
     * @param int $base The unit base if not using a unit name. Defaults to 1024.
738
     * @return string Formatted representation of the byte number, for output.
739
     */
740
    public static function formatSize($sizeInBytes, $labels = '', $base = 0)
741
    {
742
        $defaultFormats = [
743
            'iec' => ['base' => 1024, 'labels' => [' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi']],
744
            'si' => ['base' => 1000, 'labels' => [' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']],
745
        ];
746
        // Set labels and base:
747
        if (empty($labels)) {
748
            $labels = 'iec';
749
        }
750
        if (isset($defaultFormats[$labels])) {
751
            $base = $defaultFormats[$labels]['base'];
752
            $labelArr = $defaultFormats[$labels]['labels'];
753
        } else {
754
            $base = (int)$base;
755
            if ($base !== 1000 && $base !== 1024) {
756
                $base = 1024;
757
            }
758
            $labelArr = explode('|', str_replace('"', '', $labels));
759
        }
760
        // This is set via Site Handling and in the Locales class via setlocale()
761
        $localeInfo = localeconv();
762
        $sizeInBytes = max($sizeInBytes, 0);
763
        $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base));
764
        $sizeInUnits = $sizeInBytes / $base ** $multiplier;
765
        if ($sizeInUnits > ($base * .9)) {
766
            $multiplier++;
767
        }
768
        $multiplier = min($multiplier, count($labelArr) - 1);
769
        $sizeInUnits = $sizeInBytes / $base ** $multiplier;
770
        return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier];
771
    }
772
773
    /**
774
     * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
775
     *
776
     * @param string $string Input string, eg "123 + 456 / 789 - 4
777
     * @param string $operators Operators to split by, typically "/+-*
778
     * @return array<int, array<int, string>> Array with operators and operands separated.
779
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc()
780
     * @see \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
781
     */
782
    public static function splitCalc($string, $operators)
783
    {
784
        $res = [];
785
        $sign = '+';
786
        while ($string) {
787
            $valueLen = strcspn($string, $operators);
788
            $value = substr($string, 0, $valueLen);
789
            $res[] = [$sign, trim($value)];
790
            $sign = substr($string, $valueLen, 1);
791
            $string = substr($string, $valueLen + 1);
792
        }
793
        reset($res);
794
        return $res;
795
    }
796
797
    /**
798
     * Checking syntax of input email address
799
     *
800
     * @param string $email Input string to evaluate
801
     * @return bool Returns TRUE if the $email address (input string) is valid
802
     */
803
    public static function validEmail($email)
804
    {
805
        // Early return in case input is not a string
806
        if (!is_string($email)) {
0 ignored issues
show
introduced by
The condition is_string($email) is always true.
Loading history...
807
            return false;
808
        }
809
        if (trim($email) !== $email) {
810
            return false;
811
        }
812
        $validators = [];
813
        foreach ($GLOBALS['TYPO3_CONF_VARS']['MAIL']['validators'] ?? [RFCValidation::class] as $className) {
814
            $validator = new $className();
815
            if ($validator instanceof EmailValidation) {
816
                $validators[] = $validator;
817
            }
818
        }
819
        return (new EmailValidator())->isValid($email, new MultipleValidationWithAnd($validators, MultipleValidationWithAnd::STOP_ON_ERROR));
820
    }
821
822
    /**
823
     * Returns a given string with underscores as UpperCamelCase.
824
     * Example: Converts blog_example to BlogExample
825
     *
826
     * @param string $string String to be converted to camel case
827
     * @return string UpperCamelCasedWord
828
     */
829
    public static function underscoredToUpperCamelCase($string)
830
    {
831
        return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string))));
832
    }
833
834
    /**
835
     * Returns a given string with underscores as lowerCamelCase.
836
     * Example: Converts minimal_value to minimalValue
837
     *
838
     * @param string $string String to be converted to camel case
839
     * @return string lowerCamelCasedWord
840
     */
841
    public static function underscoredToLowerCamelCase($string)
842
    {
843
        return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string)))));
844
    }
845
846
    /**
847
     * Returns a given CamelCasedString as a lowercase string with underscores.
848
     * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
849
     *
850
     * @param string $string String to be converted to lowercase underscore
851
     * @return string lowercase_and_underscored_string
852
     */
853
    public static function camelCaseToLowerCaseUnderscored($string)
854
    {
855
        $value = preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string) ?? '';
856
        return mb_strtolower($value, 'utf-8');
857
    }
858
859
    /**
860
     * Checks if a given string is a Uniform Resource Locator (URL).
861
     *
862
     * On seriously malformed URLs, parse_url may return FALSE and emit an
863
     * E_WARNING.
864
     *
865
     * filter_var() requires a scheme to be present.
866
     *
867
     * http://www.faqs.org/rfcs/rfc2396.html
868
     * Scheme names consist of a sequence of characters beginning with a
869
     * lower case letter and followed by any combination of lower case letters,
870
     * digits, plus ("+"), period ("."), or hyphen ("-").  For resiliency,
871
     * programs interpreting URI should treat upper case letters as equivalent to
872
     * lower case in scheme names (e.g., allow "HTTP" as well as "http").
873
     * scheme = alpha *( alpha | digit | "+" | "-" | "." )
874
     *
875
     * Convert the domain part to punicode if it does not look like a regular
876
     * domain name. Only the domain part because RFC3986 specifies the the rest of
877
     * the url may not contain special characters:
878
     * https://tools.ietf.org/html/rfc3986#appendix-A
879
     *
880
     * @param string $url The URL to be validated
881
     * @return bool Whether the given URL is valid
882
     */
883
    public static function isValidUrl($url)
884
    {
885
        $parsedUrl = parse_url($url);
886
        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...
887
            return false;
888
        }
889
        // HttpUtility::buildUrl() will always build urls with <scheme>://
890
        // our original $url might only contain <scheme>: (e.g. mail:)
891
        // so we convert that to the double-slashed version to ensure
892
        // our check against the $recomposedUrl is proper
893
        if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
894
            $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
895
        }
896
        $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
897
        if ($recomposedUrl !== $url) {
898
            // The parse_url() had to modify characters, so the URL is invalid
899
            return false;
900
        }
901
        if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
902
            $host = (string)idn_to_ascii($parsedUrl['host']);
903
            if ($host === false) {
0 ignored issues
show
introduced by
The condition $host === false is always false.
Loading history...
904
                return false;
905
            }
906
            $parsedUrl['host'] = $host;
907
        }
908
        return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false;
909
    }
910
911
    /*************************
912
     *
913
     * ARRAY FUNCTIONS
914
     *
915
     *************************/
916
917
    /**
918
     * Explodes a $string delimited by $delimiter and casts each item in the array to (int).
919
     * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
920
     *
921
     * @param string $delimiter Delimiter string to explode with
922
     * @param string $string The string to explode
923
     * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
924
     * @param int $limit If positive, the result will contain a maximum of limit elements,
925
     * @return int[] Exploded values, all converted to integers
926
     */
927
    public static function intExplode($delimiter, $string, $removeEmptyValues = false, $limit = 0)
928
    {
929
        $result = explode($delimiter, $string) ?: [];
930
        foreach ($result as $key => &$value) {
931
            if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
932
                unset($result[$key]);
933
            } else {
934
                $value = (int)$value;
935
            }
936
        }
937
        unset($value);
938
        if ($limit !== 0) {
939
            if ($limit < 0) {
940
                $result = array_slice($result, 0, $limit);
941
            } elseif (count($result) > $limit) {
942
                $lastElements = array_slice($result, $limit - 1);
943
                $result = array_slice($result, 0, $limit - 1);
944
                $result[] = implode($delimiter, $lastElements);
945
            }
946
        }
947
        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...
948
    }
949
950
    /**
951
     * Reverse explode which explodes the string counting from behind.
952
     *
953
     * Note: The delimiter has to given in the reverse order as
954
     *       it is occurring within the string.
955
     *
956
     * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
957
     *   ==> array('[my][words', 'here]')
958
     *
959
     * @param string $delimiter Delimiter string to explode with
960
     * @param string $string The string to explode
961
     * @param int $count Number of array entries
962
     * @return string[] Exploded values
963
     */
964
    public static function revExplode($delimiter, $string, $count = 0)
965
    {
966
        // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
967
        if ($count === 2) {
968
            $position = strrpos($string, strrev($delimiter));
969
            if ($position !== false) {
970
                return [substr($string, 0, $position), substr($string, $position + strlen($delimiter))];
971
            }
972
            return [$string];
973
        }
974
        if ($count <= 1) {
975
            return [$string];
976
        }
977
        $explodedValues = explode($delimiter, strrev($string), $count) ?: [];
978
        $explodedValues = array_map('strrev', $explodedValues);
979
        return array_reverse($explodedValues);
980
    }
981
982
    /**
983
     * Explodes a string and removes whitespace-only values.
984
     *
985
     * If $removeEmptyValues is set, then all values that contain only whitespace are removed.
986
     *
987
     * Each item will have leading and trailing whitespace removed. However, if the tail items are
988
     * returned as a single array item, their internal whitespace will not be modified.
989
     *
990
     * @param string $delim Delimiter string to explode with
991
     * @param string $string The string to explode
992
     * @param bool $removeEmptyValues If set, all empty values will be removed in output
993
     * @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with
994
     *                   the last element containing the rest of string. If the limit parameter is negative, all components
995
     *                   except the last -limit are returned.
996
     * @return string[] Exploded values
997
     */
998
    public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0): array
999
    {
1000
        $result = explode($delim, $string) ?: [];
1001
        if ($removeEmptyValues) {
1002
            // Remove items that are just whitespace, but leave whitespace intact for the rest.
1003
            $result = array_values(array_filter($result, fn ($item) => trim($item) !== ''));
1004
        }
1005
1006
        if ($limit === 0) {
1007
            // Return everything.
1008
            return array_map('trim', $result);
1009
        }
1010
1011
        if ($limit < 0) {
1012
            // Trim and return just the first $limit elements and ignore the rest.
1013
            return array_map('trim', array_slice($result, 0, $limit));
1014
        }
1015
1016
        // Fold the last length - $limit elements into a single trailing item, then trim and return the result.
1017
        $tail = array_slice($result, $limit - 1);
1018
        $result = array_slice($result, 0, $limit - 1);
1019
        if ($tail) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tail of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

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

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

1287
            libxml_disable_entity_loader(/** @scrutinizer ignore-type */ $previousValueOfEntityLoader);
Loading history...
1288
        }
1289
        if (xml_get_error_code($parser)) {
1290
            return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1291
        }
1292
        xml_parser_free($parser);
1293
        $stack = [[]];
1294
        $stacktop = 0;
1295
        $startPoint = 0;
1296
        $tagi = [];
1297
        foreach ($vals as $key => $val) {
1298
            $type = $val['type'];
1299
            // open tag:
1300
            if ($type === 'open' || $type === 'complete') {
1301
                $stack[$stacktop++] = $tagi;
1302
                if ($depth == $stacktop) {
1303
                    $startPoint = $key;
1304
                }
1305
                $tagi = ['tag' => $val['tag']];
1306
                if (isset($val['attributes'])) {
1307
                    $tagi['attrs'] = $val['attributes'];
1308
                }
1309
                if (isset($val['value'])) {
1310
                    $tagi['values'][] = $val['value'];
1311
                }
1312
            }
1313
            // finish tag:
1314
            if ($type === 'complete' || $type === 'close') {
1315
                $oldtagi = $tagi;
1316
                $tagi = $stack[--$stacktop];
1317
                $oldtag = $oldtagi['tag'];
1318
                unset($oldtagi['tag']);
1319
                if ($depth == $stacktop + 1) {
1320
                    if ($key - $startPoint > 0) {
1321
                        $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
1322
                        $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
1323
                    } else {
1324
                        $oldtagi['XMLvalue'] = $oldtagi['values'][0];
1325
                    }
1326
                }
1327
                $tagi['ch'][$oldtag][] = $oldtagi;
1328
                unset($oldtagi);
1329
            }
1330
            // cdata
1331
            if ($type === 'cdata') {
1332
                $tagi['values'][] = $val['value'];
1333
            }
1334
        }
1335
        return $tagi['ch'];
1336
    }
1337
1338
    /**
1339
     * Converts a PHP array into an XML string.
1340
     * The XML output is optimized for readability since associative keys are used as tag names.
1341
     * 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.
1342
     * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
1343
     * 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
1344
     * 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.
1345
     * 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!
1346
     * 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...
1347
     *
1348
     * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1349
     * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
1350
     * @param int $level Current recursion level. Don't change, stay at zero!
1351
     * @param string $docTag Alternative document tag. Default is "phparray".
1352
     * @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
1353
     * @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')
1354
     * @param array $stackData Stack data. Don't touch.
1355
     * @return string An XML string made from the input content in the array.
1356
     * @see xml2array()
1357
     */
1358
    public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = [], array $stackData = [])
1359
    {
1360
        // 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
1361
        $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);
1362
        // Set indenting mode:
1363
        $indentChar = $spaceInd ? ' ' : "\t";
1364
        $indentN = $spaceInd > 0 ? $spaceInd : 1;
1365
        $nl = $spaceInd >= 0 ? LF : '';
1366
        // Init output variable:
1367
        $output = '';
1368
        // Traverse the input array
1369
        foreach ($array as $k => $v) {
1370
            $attr = '';
1371
            $tagName = $k;
1372
            // Construct the tag name.
1373
            // Use tag based on grand-parent + parent tag name
1374
            if (isset($stackData['grandParentTagName'], $stackData['parentTagName'], $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
1375
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1376
                $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
1377
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) {
1378
                // Use tag based on parent tag name + if current tag is numeric
1379
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1380
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
1381
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
1382
                // Use tag based on parent tag name + current tag
1383
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1384
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
1385
            } elseif (isset($stackData['parentTagName'], $options['parentTagMap'][$stackData['parentTagName']])) {
1386
                // Use tag based on parent tag name:
1387
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1388
                $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
1389
            } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) {
1390
                // If integer...;
1391
                if ($options['useNindex'] ?? false) {
1392
                    // If numeric key, prefix "n"
1393
                    $tagName = 'n' . $tagName;
1394
                } else {
1395
                    // Use special tag for num. keys:
1396
                    $attr .= ' index="' . $tagName . '"';
1397
                    $tagName = ($options['useIndexTagForNum'] ?? false) ?: 'numIndex';
1398
                }
1399
            } elseif (!empty($options['useIndexTagForAssoc'])) {
1400
                // Use tag for all associative keys:
1401
                $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1402
                $tagName = $options['useIndexTagForAssoc'];
1403
            }
1404
            // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
1405
            $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
1406
            // If the value is an array then we will call this function recursively:
1407
            if (is_array($v)) {
1408
                // Sub elements:
1409
                if (isset($options['alt_options']) && ($options['alt_options'][($stackData['path'] ?? '') . '/' . $tagName] ?? false)) {
1410
                    $subOptions = $options['alt_options'][($stackData['path'] ?? '') . '/' . $tagName];
1411
                    $clearStackPath = (bool)($subOptions['clearStackPath'] ?? false);
1412
                } else {
1413
                    $subOptions = $options;
1414
                    $clearStackPath = false;
1415
                }
1416
                if (empty($v)) {
1417
                    $content = '';
1418
                } else {
1419
                    $content = $nl . self::array2xml($v, $NSprefix, $level + 1, '', $spaceInd, $subOptions, [
1420
                            'parentTagName' => $tagName,
1421
                            'grandParentTagName' => $stackData['parentTagName'] ?? '',
1422
                            'path' => $clearStackPath ? '' : ($stackData['path'] ?? '') . '/' . $tagName
1423
                        ]) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
1424
                }
1425
                // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
1426
                if (!isset($options['disableTypeAttrib']) || (int)$options['disableTypeAttrib'] != 2) {
1427
                    $attr .= ' type="array"';
1428
                }
1429
            } else {
1430
                // Just a value:
1431
                // Look for binary chars:
1432
                $vLen = strlen($v);
1433
                // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
1434
                if ($vLen && strcspn($v, $binaryChars) != $vLen) {
1435
                    // If the value contained binary chars then we base64-encode it and set an attribute to notify this situation:
1436
                    $content = $nl . chunk_split(base64_encode($v));
1437
                    $attr .= ' base64="1"';
1438
                } else {
1439
                    // Otherwise, just htmlspecialchar the stuff:
1440
                    $content = htmlspecialchars($v);
1441
                    $dType = gettype($v);
1442
                    if ($dType === 'string') {
1443
                        if (isset($options['useCDATA']) && $options['useCDATA'] && $content != $v) {
1444
                            $content = '<![CDATA[' . $v . ']]>';
1445
                        }
1446
                    } elseif (!($options['disableTypeAttrib'] ?? false)) {
1447
                        $attr .= ' type="' . $dType . '"';
1448
                    }
1449
                }
1450
            }
1451
            if ((string)$tagName !== '') {
1452
                // Add the element to the output string:
1453
                $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
1454
                    . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
1455
            }
1456
        }
1457
        // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
1458
        if (!$level) {
1459
            $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
1460
        }
1461
        return $output;
1462
    }
1463
1464
    /**
1465
     * Converts an XML string to a PHP array.
1466
     * This is the reverse function of array2xml()
1467
     * This is a wrapper for xml2arrayProcess that adds a two-level cache
1468
     *
1469
     * @param string $string XML content to convert into an array
1470
     * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1471
     * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1472
     * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1473
     * @see array2xml()
1474
     * @see xml2arrayProcess()
1475
     */
1476
    public static function xml2array($string, $NSprefix = '', $reportDocTag = false)
1477
    {
1478
        $runtimeCache = static::makeInstance(CacheManager::class)->getCache('runtime');
1479
        $firstLevelCache = $runtimeCache->get('generalUtilityXml2Array') ?: [];
1480
        $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
1481
        // Look up in first level cache
1482
        if (empty($firstLevelCache[$identifier])) {
1483
            $firstLevelCache[$identifier] = self::xml2arrayProcess(trim($string), $NSprefix, $reportDocTag);
1484
            $runtimeCache->set('generalUtilityXml2Array', $firstLevelCache);
1485
        }
1486
        return $firstLevelCache[$identifier];
1487
    }
1488
1489
    /**
1490
     * Converts an XML string to a PHP array.
1491
     * This is the reverse function of array2xml()
1492
     *
1493
     * @param string $string XML content to convert into an array
1494
     * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1495
     * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1496
     * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1497
     * @see array2xml()
1498
     */
1499
    protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = false)
1500
    {
1501
        // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1502
        $previousValueOfEntityLoader = null;
1503
        if (PHP_MAJOR_VERSION < 8) {
1504
            $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1505
        }
1506
        // Create parser:
1507
        $parser = xml_parser_create();
1508
        $vals = [];
1509
        $index = [];
1510
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1511
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1512
        // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
1513
        $match = [];
1514
        preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
1515
        $theCharset = $match[1] ?? 'utf-8';
1516
        // us-ascii / utf-8 / iso-8859-1
1517
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
1518
        // Parse content:
1519
        xml_parse_into_struct($parser, $string, $vals, $index);
1520
        if (PHP_MAJOR_VERSION < 8) {
1521
            libxml_disable_entity_loader($previousValueOfEntityLoader);
0 ignored issues
show
Bug introduced by
It seems like $previousValueOfEntityLoader can also be of type null; however, parameter $disable of libxml_disable_entity_loader() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

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

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