Passed
Push — master ( 1afed5...2da5fe )
by
unknown
37:51 queued 18:52
created

GeneralUtility   F

Complexity

Total Complexity 649

Size/Duplication

Total Lines 3534
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 649
eloc 1419
dl 0
loc 3534
rs 0.8
c 0
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 rmFromList() 0 9 3
A validIPv4() 0 3 1
A isOnCurrentHost() 0 3 1
C cmpFQDN() 0 59 15
A md5int() 0 3 1
A shortMD5() 0 3 1
B normalizeIPv6() 0 54 10
B cmpIPv6() 0 47 11
A expandList() 0 20 5
A validIPv6() 0 3 1
A validEmail() 0 17 5
B get_tag_attributes() 0 27 7
A split_fileref() 0 23 4
B intExplode() 0 21 9
A camelCaseToLowerCaseUnderscored() 0 4 1
A isFirstPartOfStr() 0 5 4
A explodeUrl2Array() 0 11 3
B isValidUrl() 0 26 8
A underscoredToUpperCamelCase() 0 3 1
B formatSize() 0 31 9
A compileSelectedGetVarsFromArray() 0 12 4
A splitCalc() 0 13 2
A removeDotsFromTS() 0 12 3
A wrapJS() 0 17 3
A underscoredToLowerCamelCase() 0 3 1
A revExplode() 0 16 5
A dirname() 0 4 2
B implodeArrayForUrl() 0 13 7
B trimExplode() 0 20 8
A split_tag_attributes() 0 26 5
B implodeAttributes() 0 18 7
F array2xml() 0 104 32
A xml2array() 0 11 4
A __construct() 0 2 1
A _GP() 0 13 4
F xml2tree() 0 66 16
A resolveBackPath() 0 22 5
A mkdir_deep() 0 11 5
A minifyJavaScript() 0 18 3
A setIndpEnv() 0 3 1
A fixWindowsFilePath() 0 3 1
A linkThisScript() 0 13 4
D rmdir() 0 47 18
A mkdir() 0 7 2
A getUrl() 0 15 3
A writeFile() 0 18 5
A hmac() 0 22 6
C xmlRecompileFromStructValArray() 0 36 12
C writeFileToTypo3tempDir() 0 67 15
A removePrefixPathFromList() 0 11 3
A writeJavaScriptContentToTemporaryFile() 0 7 2
A uniqueList() 0 13 3
A writeStyleSheetContentToTemporaryFile() 0 7 2
B createVersionNumberedFilename() 0 47 10
B get_dirs() 0 17 7
F xml2arrayProcess() 0 105 21
A createDirectoryPath() 0 18 6
C getFilesInDir() 0 52 14
A locationHeaderUrl() 0 18 4
B getAllFilesAndFoldersInPath() 0 15 8
A getMaxUploadFileSize() 0 12 3
A getBytesFromSizeMeasurement() 0 11 4
D fixPermissions() 0 55 20
C makeInstance() 0 48 15
A hostHeaderValueMatchesTrustedHostsPattern() 0 25 5
A webserverUsesHttps() 0 9 3
A hideIfDefaultLanguage() 0 4 1
F getIndpEnv() 0 283 70
B copyDirectory() 0 21 7
A stdAuthCode() 0 19 4
A makeInstanceForDi() 0 10 2
A makeInstanceService() 0 30 5
A setContainer() 0 3 1
A addInstance() 0 10 3
A upload_copy_move() 0 23 4
A getInstances() 0 3 1
A removeSingletonInstance() 0 10 3
A quoteJSvalue() 0 17 1
A jsonEncodeForHtmlAttribute() 0 4 2
A hideIfNotTranslated() 0 4 1
B callUserFunction() 0 33 8
A validPathStr() 0 4 3
A isAllowedHostHeaderValue() 0 22 5
A flushInternalRuntimeCaches() 0 3 1
A checkInstanceClassName() 0 7 3
B unlink_tempfile() 0 19 7
A upload_to_tempfile() 0 17 5
A isInternalRequestType() 0 6 4
A isAbsPath() 0 9 6
A getLogger() 0 3 1
A getContainer() 0 6 2
A resetSingletonInstances() 0 5 2
A getSingletonInstances() 0 3 1
A purgeInstances() 0 5 1
A getImplementationForClass() 0 3 1
A tempnam() 0 17 4
B isAllowedAbsPath() 0 11 7
A getClassName() 0 8 3
A classHasImplementation() 0 3 1
C sanitizeLocalUrl() 0 29 17
A setSingletonInstance() 0 6 1
B getFileAbsFileName() 0 27 11

How to fix   Complexity   

Complex Class

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

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

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

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

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

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

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

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

Loading history...
881
            return false;
882
        }
883
        // HttpUtility::buildUrl() will always build urls with <scheme>://
884
        // our original $url might only contain <scheme>: (e.g. mail:)
885
        // so we convert that to the double-slashed version to ensure
886
        // our check against the $recomposedUrl is proper
887
        if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
888
            $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
889
        }
890
        $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
891
        if ($recomposedUrl !== $url) {
892
            // The parse_url() had to modify characters, so the URL is invalid
893
            return false;
894
        }
895
        if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
896
            $host = (string)idn_to_ascii($parsedUrl['host']);
897
            if ($host === false) {
0 ignored issues
show
introduced by
The condition $host === false is always false.
Loading history...
898
                return false;
899
            }
900
            $parsedUrl['host'] = $host;
901
        }
902
        return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false;
903
    }
904
905
    /*************************
906
     *
907
     * ARRAY FUNCTIONS
908
     *
909
     *************************/
910
911
    /**
912
     * Explodes a $string delimited by $delimiter and casts each item in the array to (int).
913
     * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
914
     *
915
     * @param string $delimiter Delimiter string to explode with
916
     * @param string $string The string to explode
917
     * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
918
     * @param int $limit If positive, the result will contain a maximum of limit elements,
919
     * @return int[] Exploded values, all converted to integers
920
     */
921
    public static function intExplode($delimiter, $string, $removeEmptyValues = false, $limit = 0)
922
    {
923
        $result = explode($delimiter, $string) ?: [];
924
        foreach ($result as $key => &$value) {
925
            if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
926
                unset($result[$key]);
927
            } else {
928
                $value = (int)$value;
929
            }
930
        }
931
        unset($value);
932
        if ($limit !== 0) {
933
            if ($limit < 0) {
934
                $result = array_slice($result, 0, $limit);
935
            } elseif (count($result) > $limit) {
936
                $lastElements = array_slice($result, $limit - 1);
937
                $result = array_slice($result, 0, $limit - 1);
938
                $result[] = implode($delimiter, $lastElements);
939
            }
940
        }
941
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result returns an array which contains values of type string which are incompatible with the documented value type integer.
Loading history...
942
    }
943
944
    /**
945
     * Reverse explode which explodes the string counting from behind.
946
     *
947
     * Note: The delimiter has to given in the reverse order as
948
     *       it is occurring within the string.
949
     *
950
     * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
951
     *   ==> array('[my][words', 'here]')
952
     *
953
     * @param string $delimiter Delimiter string to explode with
954
     * @param string $string The string to explode
955
     * @param int $count Number of array entries
956
     * @return string[] Exploded values
957
     */
958
    public static function revExplode($delimiter, $string, $count = 0)
959
    {
960
        // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
961
        if ($count === 2) {
962
            $position = strrpos($string, strrev($delimiter));
963
            if ($position !== false) {
964
                return [substr($string, 0, $position), substr($string, $position + strlen($delimiter))];
965
            }
966
            return [$string];
967
        }
968
        if ($count <= 1) {
969
            return [$string];
970
        }
971
        $explodedValues = explode($delimiter, strrev($string), $count) ?: [];
972
        $explodedValues = array_map('strrev', $explodedValues);
973
        return array_reverse($explodedValues);
974
    }
975
976
    /**
977
     * Explodes a string and trims all values for whitespace in the end.
978
     * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
979
     *
980
     * @param string $delim Delimiter string to explode with
981
     * @param string $string The string to explode
982
     * @param bool $removeEmptyValues If set, all empty values will be removed in output
983
     * @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with
984
     *                   the last element containing the rest of string. If the limit parameter is negative, all components
985
     *                   except the last -limit are returned.
986
     * @return string[] Exploded values
987
     */
988
    public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0)
989
    {
990
        $result = explode($delim, $string) ?: [];
991
        if ($removeEmptyValues) {
992
            $temp = [];
993
            foreach ($result as $value) {
994
                if (trim($value) !== '') {
995
                    $temp[] = $value;
996
                }
997
            }
998
            $result = $temp;
999
        }
1000
        if ($limit > 0 && count($result) > $limit) {
1001
            $lastElements = array_splice($result, $limit - 1);
1002
            $result[] = implode($delim, $lastElements);
1003
        } elseif ($limit < 0) {
1004
            $result = array_slice($result, 0, $limit);
1005
        }
1006
        $result = array_map('trim', $result);
1007
        return $result;
1008
    }
1009
1010
    /**
1011
     * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1012
     *
1013
     * @param string $name Name prefix for entries. Set to blank if you wish none.
1014
     * @param array $theArray The (multidimensional) array to implode
1015
     * @param string $str (keep blank)
1016
     * @param bool $skipBlank If set, parameters which were blank strings would be removed.
1017
     * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1018
     * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1019
     * @see explodeUrl2Array()
1020
     */
1021
    public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false)
1022
    {
1023
        foreach ($theArray as $Akey => $AVal) {
1024
            $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1025
            if (is_array($AVal)) {
1026
                $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1027
            } else {
1028
                if (!$skipBlank || (string)$AVal !== '') {
1029
                    $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1030
                }
1031
            }
1032
        }
1033
        return $str;
1034
    }
1035
1036
    /**
1037
     * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array.
1038
     *
1039
     * Note! If you want to use a multi-dimensional string, consider this plain simple PHP code instead:
1040
     *
1041
     * $result = [];
1042
     * parse_str($queryParametersAsString, $result);
1043
     *
1044
     * However, if you do magic with a flat structure (e.g. keeping "ext[mykey]" as flat key in a one-dimensional array)
1045
     * then this method is for you.
1046
     *
1047
     * @param string $string GETvars string
1048
     * @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!
1049
     * @see implodeArrayForUrl()
1050
     */
1051
    public static function explodeUrl2Array($string)
1052
    {
1053
        $output = [];
1054
        $p = explode('&', $string);
1055
        foreach ($p as $v) {
1056
            if ($v !== '') {
1057
                [$pK, $pV] = explode('=', $v, 2);
1058
                $output[rawurldecode($pK)] = rawurldecode($pV);
1059
            }
1060
        }
1061
        return $output;
1062
    }
1063
1064
    /**
1065
     * Returns an array with selected keys from incoming data.
1066
     * (Better read source code if you want to find out...)
1067
     *
1068
     * @param string $varList List of variable/key names
1069
     * @param array $getArray Array from where to get values based on the keys in $varList
1070
     * @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
1071
     * @return array Output array with selected variables.
1072
     */
1073
    public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = true)
1074
    {
1075
        $keys = self::trimExplode(',', $varList, true);
1076
        $outArr = [];
1077
        foreach ($keys as $v) {
1078
            if (isset($getArray[$v])) {
1079
                $outArr[$v] = $getArray[$v];
1080
            } elseif ($GPvarAlt) {
1081
                $outArr[$v] = self::_GP($v);
1082
            }
1083
        }
1084
        return $outArr;
1085
    }
1086
1087
    /**
1088
     * Removes dots "." from end of a key identifier of TypoScript styled array.
1089
     * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1090
     *
1091
     * @param array $ts TypoScript configuration array
1092
     * @return array TypoScript configuration array without dots at the end of all keys
1093
     */
1094
    public static function removeDotsFromTS(array $ts)
1095
    {
1096
        $out = [];
1097
        foreach ($ts as $key => $value) {
1098
            if (is_array($value)) {
1099
                $key = rtrim($key, '.');
1100
                $out[$key] = self::removeDotsFromTS($value);
1101
            } else {
1102
                $out[$key] = $value;
1103
            }
1104
        }
1105
        return $out;
1106
    }
1107
1108
    /*************************
1109
     *
1110
     * HTML/XML PROCESSING
1111
     *
1112
     *************************/
1113
    /**
1114
     * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1115
     * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1116
     * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1117
     *
1118
     * @param string $tag HTML-tag string (or attributes only)
1119
     * @param bool $decodeEntities Whether to decode HTML entities
1120
     * @return array<string, string> Array with the attribute values.
1121
     */
1122
    public static function get_tag_attributes($tag, bool $decodeEntities = false)
1123
    {
1124
        $components = self::split_tag_attributes($tag);
1125
        // Attribute name is stored here
1126
        $name = '';
1127
        $valuemode = false;
1128
        $attributes = [];
1129
        foreach ($components as $key => $val) {
1130
            // 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
1131
            if ($val !== '=') {
1132
                if ($valuemode) {
1133
                    if ($name) {
1134
                        $attributes[$name] = $decodeEntities ? htmlspecialchars_decode($val) : $val;
1135
                        $name = '';
1136
                    }
1137
                } else {
1138
                    if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val) ?? '')) {
1139
                        $attributes[$key] = '';
1140
                        $name = $key;
1141
                    }
1142
                }
1143
                $valuemode = false;
1144
            } else {
1145
                $valuemode = true;
1146
            }
1147
        }
1148
        return $attributes;
1149
    }
1150
1151
    /**
1152
     * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1153
     * Removes tag-name if found
1154
     *
1155
     * @param string $tag HTML-tag string (or attributes only)
1156
     * @return string[] Array with the attribute values.
1157
     */
1158
    public static function split_tag_attributes($tag)
1159
    {
1160
        $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)) ?? '');
1161
        // Removes any > in the end of the string
1162
        $tag_tmp = trim(rtrim($tag_tmp, '>'));
1163
        $value = [];
1164
        // Compared with empty string instead , 030102
1165
        while ($tag_tmp !== '') {
1166
            $firstChar = $tag_tmp[0];
1167
            if ($firstChar === '"' || $firstChar === '\'') {
1168
                $reg = explode($firstChar, $tag_tmp, 3);
1169
                $value[] = $reg[1];
1170
                $tag_tmp = trim($reg[2]);
1171
            } elseif ($firstChar === '=') {
1172
                $value[] = '=';
1173
                // Removes = chars.
1174
                $tag_tmp = trim(substr($tag_tmp, 1));
1175
            } else {
1176
                // There are '' around the value. We look for the next ' ' or '>'
1177
                $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1178
                $value[] = trim($reg[0]);
1179
                $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . ($reg[1] ?? ''));
1180
            }
1181
        }
1182
        reset($value);
1183
        return $value;
1184
    }
1185
1186
    /**
1187
     * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1188
     *
1189
     * @param array<string, string> $arr Array with attribute key/value pairs, eg. "bgcolor" => "red", "border" => "0"
1190
     * @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!
1191
     * @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1192
     * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1193
     */
1194
    public static function implodeAttributes(array $arr, $xhtmlSafe = false, $dontOmitBlankAttribs = false)
1195
    {
1196
        if ($xhtmlSafe) {
1197
            $newArr = [];
1198
            foreach ($arr as $p => $v) {
1199
                if (!isset($newArr[strtolower($p)])) {
1200
                    $newArr[strtolower($p)] = htmlspecialchars($v);
1201
                }
1202
            }
1203
            $arr = $newArr;
1204
        }
1205
        $list = [];
1206
        foreach ($arr as $p => $v) {
1207
            if ((string)$v !== '' || $dontOmitBlankAttribs) {
1208
                $list[] = $p . '="' . $v . '"';
1209
            }
1210
        }
1211
        return implode(' ', $list);
1212
    }
1213
1214
    /**
1215
     * Wraps JavaScript code XHTML ready with <script>-tags
1216
     * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1217
     * This is nice for indenting JS code with PHP code on the same level.
1218
     *
1219
     * @param string $string JavaScript code
1220
     * @return string The wrapped JS code, ready to put into a XHTML page
1221
     */
1222
    public static function wrapJS($string)
1223
    {
1224
        if (trim($string)) {
1225
            // remove nl from the beginning
1226
            $string = ltrim($string, LF);
1227
            // re-ident to one tab using the first line as reference
1228
            $match = [];
1229
            if (preg_match('/^(\\t+)/', $string, $match)) {
1230
                $string = str_replace($match[1], "\t", $string);
1231
            }
1232
            return '<script>
1233
/*<![CDATA[*/
1234
' . $string . '
1235
/*]]>*/
1236
</script>';
1237
        }
1238
        return '';
1239
    }
1240
1241
    /**
1242
     * Parses XML input into a PHP array with associative keys
1243
     *
1244
     * @param string $string XML data input
1245
     * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1246
     * @param array $parserOptions Options that will be passed to PHP's xml_parser_set_option()
1247
     * @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.
1248
     */
1249
    public static function xml2tree($string, $depth = 999, $parserOptions = [])
1250
    {
1251
        // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1252
        $previousValueOfEntityLoader = null;
1253
        if (PHP_MAJOR_VERSION < 8) {
1254
            $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1255
        }
1256
        $parser = xml_parser_create();
1257
        $vals = [];
1258
        $index = [];
1259
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1260
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1261
        foreach ($parserOptions as $option => $value) {
1262
            xml_parser_set_option($parser, $option, $value);
1263
        }
1264
        xml_parse_into_struct($parser, $string, $vals, $index);
1265
        if (PHP_MAJOR_VERSION < 8) {
1266
            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

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

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

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

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