Completed
Push — master ( 8d0509...654480 )
by
unknown
18:58
created

GeneralUtility::xmlRecompileFromStructValArray()   C

Complexity

Conditions 12
Paths 53

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 22
nc 53
nop 1
dl 0
loc 36
rs 6.9666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\RFCValidation;
20
use GuzzleHttp\Exception\RequestException;
21
use Psr\Container\ContainerInterface;
22
use Psr\Log\LoggerAwareInterface;
23
use Psr\Log\LoggerInterface;
24
use TYPO3\CMS\Core\Cache\CacheManager;
25
use TYPO3\CMS\Core\Core\ClassLoadingInformation;
26
use TYPO3\CMS\Core\Core\Environment;
27
use TYPO3\CMS\Core\Http\RequestFactory;
28
use TYPO3\CMS\Core\Log\LogManager;
29
use TYPO3\CMS\Core\SingletonInterface;
30
31
/**
32
 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
33
 * Most of the functions do not relate specifically to TYPO3
34
 * However a section of functions requires certain TYPO3 features available
35
 * See comments in the source.
36
 * You are encouraged to use this library in your own scripts!
37
 *
38
 * USE:
39
 * All methods in this class are meant to be called statically.
40
 * So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'
41
 */
42
class GeneralUtility
43
{
44
    const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*';
45
    const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME';
46
47
    /**
48
     * State of host header value security check
49
     * in order to avoid unnecessary multiple checks during one request
50
     *
51
     * @var bool
52
     */
53
    protected static $allowHostHeaderValue = false;
54
55
    /**
56
     * @var ContainerInterface|null
57
     */
58
    protected static $container;
59
60
    /**
61
     * Singleton instances returned by makeInstance, using the class names as
62
     * array keys
63
     *
64
     * @var array<string, SingletonInterface>
65
     */
66
    protected static $singletonInstances = [];
67
68
    /**
69
     * Instances returned by makeInstance, using the class names as array keys
70
     *
71
     * @var array<string, array<object>>
72
     */
73
    protected static $nonSingletonInstances = [];
74
75
    /**
76
     * Cache for makeInstance with given class name and final class names to reduce number of self::getClassName() calls
77
     *
78
     * @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...
79
     */
80
    protected static $finalClassNameCache = [];
81
82
    /**
83
     * @var array<string, mixed>
84
     */
85
    protected static $indpEnvCache = [];
86
87
    final private function __construct()
88
    {
89
    }
90
91
    /*************************
92
     *
93
     * GET/POST Variables
94
     *
95
     * Background:
96
     * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
97
     * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
98
     * But the clean solution is that quotes are never escaped and that is what the functions below offers.
99
     * Eventually TYPO3 should provide this in the global space as well.
100
     * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
101
     * This functionality was previously needed to normalize between magic quotes logic, which was removed from PHP 5.4,
102
     * so these methods are still in use, but not tackle the slash problem anymore.
103
     *
104
     *************************/
105
    /**
106
     * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST, which is equivalent to 'GP' order
107
     * In case you already know by which method your data is arriving consider using GeneralUtility::_GET or GeneralUtility::_POST.
108
     *
109
     * @param string $var GET/POST var to return
110
     * @return mixed POST var named $var, if not set, the GET var of the same name and if also not set, NULL.
111
     */
112
    public static function _GP($var)
113
    {
114
        if (empty($var)) {
115
            return;
116
        }
117
        if (isset($_POST[$var])) {
118
            $value = $_POST[$var];
119
        } elseif (isset($_GET[$var])) {
120
            $value = $_GET[$var];
121
        } else {
122
            $value = 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
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "?"; newline found
Loading history...
159
            : (empty($var) ? null : ($_GET[$var] ?? null));
0 ignored issues
show
Coding Style introduced by
Expected 1 space before ":"; newline found
Loading history...
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 = '...')
0 ignored issues
show
Coding Style introduced by
Method name "GeneralUtility::fixed_lgd_cs" is not in camel caps format
Loading history...
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
                    // "192.168.3.0/24"
255
                    $lnet = ip2long($test);
256
                    $lip = ip2long($baseIP);
257
                    $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
258
                    $firstpart = substr($binnet, 0, $mask);
0 ignored issues
show
Bug introduced by
$mask of type false|string is incompatible with the type integer expected by parameter $length of substr(). ( Ignorable by Annotation )

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

258
                    $firstpart = substr($binnet, 0, /** @scrutinizer ignore-type */ $mask);
Loading history...
259
                    $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
260
                    $firstip = substr($binip, 0, $mask);
261
                    $yes = $firstpart === $firstip;
262
                } else {
263
                    // "192.168.*.*"
264
                    $IPparts = explode('.', $test);
265
                    $yes = 1;
266
                    foreach ($IPparts as $index => $val) {
267
                        $val = trim($val);
268
                        if ($val !== '*' && $IPpartsReq[$index] !== $val) {
269
                            $yes = 0;
270
                        }
271
                    }
272
                }
273
                if ($yes) {
274
                    return true;
275
                }
276
            }
277
        }
278
        return false;
279
    }
280
281
    /**
282
     * Match IPv6 address with a list of IPv6 prefixes
283
     *
284
     * @param string $baseIP Is the current remote IP address for instance
285
     * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
286
     * @return bool TRUE If a baseIP matches any prefix
287
     */
288
    public static function cmpIPv6($baseIP, $list)
289
    {
290
        // Policy default: Deny connection
291
        $success = false;
292
        $baseIP = self::normalizeIPv6($baseIP);
293
        $values = self::trimExplode(',', $list, true);
294
        foreach ($values as $test) {
295
            $testList = explode('/', $test);
296
            if (count($testList) === 2) {
297
                [$test, $mask] = $testList;
298
            } else {
299
                $mask = false;
300
            }
301
            if (self::validIPv6($test)) {
302
                $test = self::normalizeIPv6($test);
303
                $maskInt = (int)$mask ?: 128;
304
                // Special case; /0 is an allowed mask - equals a wildcard
305
                if ($mask === '0') {
306
                    $success = true;
307
                } elseif ($maskInt == 128) {
308
                    $success = $test === $baseIP;
309
                } else {
310
                    $testBin = inet_pton($test);
311
                    $baseIPBin = inet_pton($baseIP);
312
                    $success = true;
313
                    // Modulo is 0 if this is a 8-bit-boundary
314
                    $maskIntModulo = $maskInt % 8;
315
                    $numFullCharactersUntilBoundary = (int)($maskInt / 8);
316
                    if (strpos($testBin, substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) !== 0) {
317
                        $success = false;
318
                    } elseif ($maskIntModulo > 0) {
319
                        // If not an 8-bit-boundary, check bits of last character
320
                        $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
321
                        $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
322
                        if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
323
                            $success = false;
324
                        }
325
                    }
326
                }
327
            }
328
            if ($success) {
329
                return true;
330
            }
331
        }
332
        return false;
333
    }
334
335
    /**
336
     * Normalize an IPv6 address to full length
337
     *
338
     * @param string $address Given IPv6 address
339
     * @return string Normalized address
340
     */
341
    public static function normalizeIPv6($address)
342
    {
343
        $normalizedAddress = '';
344
        // According to RFC lowercase-representation is recommended
345
        $address = strtolower($address);
346
        // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
347
        if (strlen($address) === 39) {
348
            // Already in full expanded form
349
            return $address;
350
        }
351
        // Count 2 if if address has hidden zero blocks
352
        $chunks = explode('::', $address);
353
        if (count($chunks) === 2) {
354
            $chunksLeft = explode(':', $chunks[0]);
355
            $chunksRight = explode(':', $chunks[1]);
356
            $left = count($chunksLeft);
357
            $right = count($chunksRight);
358
            // Special case: leading zero-only blocks count to 1, should be 0
359
            if ($left === 1 && strlen($chunksLeft[0]) === 0) {
360
                $left = 0;
361
            }
362
            $hiddenBlocks = 8 - ($left + $right);
363
            $hiddenPart = '';
364
            $h = 0;
365
            while ($h < $hiddenBlocks) {
366
                $hiddenPart .= '0000:';
367
                $h++;
368
            }
369
            if ($left === 0) {
370
                $stageOneAddress = $hiddenPart . $chunks[1];
371
            } else {
372
                $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
373
            }
374
        } else {
375
            $stageOneAddress = $address;
376
        }
377
        // Normalize the blocks:
378
        $blocks = explode(':', $stageOneAddress);
379
        $divCounter = 0;
380
        foreach ($blocks as $block) {
381
            $tmpBlock = '';
382
            $i = 0;
383
            $hiddenZeros = 4 - strlen($block);
384
            while ($i < $hiddenZeros) {
385
                $tmpBlock .= '0';
386
                $i++;
387
            }
388
            $normalizedAddress .= $tmpBlock . $block;
389
            if ($divCounter < 7) {
390
                $normalizedAddress .= ':';
391
                $divCounter++;
392
            }
393
        }
394
        return $normalizedAddress;
395
    }
396
397
    /**
398
     * Validate a given IP address.
399
     *
400
     * Possible format are IPv4 and IPv6.
401
     *
402
     * @param string $ip IP address to be tested
403
     * @return bool TRUE if $ip is either of IPv4 or IPv6 format.
404
     */
405
    public static function validIP($ip)
406
    {
407
        return filter_var($ip, FILTER_VALIDATE_IP) !== false;
408
    }
409
410
    /**
411
     * Validate a given IP address to the IPv4 address format.
412
     *
413
     * Example for possible format: 10.0.45.99
414
     *
415
     * @param string $ip IP address to be tested
416
     * @return bool TRUE if $ip is of IPv4 format.
417
     */
418
    public static function validIPv4($ip)
419
    {
420
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
421
    }
422
423
    /**
424
     * Validate a given IP address to the IPv6 address format.
425
     *
426
     * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
427
     *
428
     * @param string $ip IP address to be tested
429
     * @return bool TRUE if $ip is of IPv6 format.
430
     */
431
    public static function validIPv6($ip)
432
    {
433
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
434
    }
435
436
    /**
437
     * Match fully qualified domain name with list of strings with wildcard
438
     *
439
     * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
440
     * @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)
441
     * @return bool TRUE if a domain name mask from $list matches $baseIP
442
     */
443
    public static function cmpFQDN($baseHost, $list)
444
    {
445
        $baseHost = trim($baseHost);
446
        if (empty($baseHost)) {
447
            return false;
448
        }
449
        if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
450
            // Resolve hostname
451
            // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
452
            // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
453
            $baseHostName = gethostbyaddr($baseHost);
454
            if ($baseHostName === $baseHost) {
455
                // Unable to resolve hostname
456
                return false;
457
            }
458
        } else {
459
            $baseHostName = $baseHost;
460
        }
461
        $baseHostNameParts = explode('.', $baseHostName);
462
        $values = self::trimExplode(',', $list, true);
463
        foreach ($values as $test) {
464
            $hostNameParts = explode('.', $test);
465
            // To match hostNameParts can only be shorter (in case of wildcards) or equal
466
            $hostNamePartsCount = count($hostNameParts);
467
            $baseHostNamePartsCount = count($baseHostNameParts);
468
            if ($hostNamePartsCount > $baseHostNamePartsCount) {
469
                continue;
470
            }
471
            $yes = true;
472
            foreach ($hostNameParts as $index => $val) {
473
                $val = trim($val);
474
                if ($val === '*') {
475
                    // Wildcard valid for one or more hostname-parts
476
                    $wildcardStart = $index + 1;
477
                    // Wildcard as last/only part always matches, otherwise perform recursive checks
478
                    if ($wildcardStart < $hostNamePartsCount) {
479
                        $wildcardMatched = false;
480
                        $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
481
                        while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) {
482
                            $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
483
                            $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
484
                            $wildcardStart++;
485
                        }
486
                        if ($wildcardMatched) {
487
                            // Match found by recursive compare
488
                            return true;
489
                        }
490
                        $yes = false;
491
                    }
492
                } elseif ($baseHostNameParts[$index] !== $val) {
493
                    // In case of no match
494
                    $yes = false;
495
                }
496
            }
497
            if ($yes) {
498
                return true;
499
            }
500
        }
501
        return false;
502
    }
503
504
    /**
505
     * Checks if a given URL matches the host that currently handles this HTTP request.
506
     * Scheme, hostname and (optional) port of the given URL are compared.
507
     *
508
     * @param string $url URL to compare with the TYPO3 request host
509
     * @return bool Whether the URL matches the TYPO3 request host
510
     */
511
    public static function isOnCurrentHost($url)
512
    {
513
        return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
514
    }
515
516
    /**
517
     * Check for item in list
518
     * Check if an item exists in a comma-separated list of items.
519
     *
520
     * @param string $list Comma-separated list of items (string)
521
     * @param string $item Item to check for
522
     * @return bool TRUE if $item is in $list
523
     */
524
    public static function inList($list, $item)
525
    {
526
        return strpos(',' . $list . ',', ',' . $item . ',') !== false;
527
    }
528
529
    /**
530
     * Removes an item from a comma-separated list of items.
531
     *
532
     * If $element contains a comma, the behaviour of this method is undefined.
533
     * Empty elements in the list are preserved.
534
     *
535
     * @param string $element Element to remove
536
     * @param string $list Comma-separated list of items (string)
537
     * @return string New comma-separated list of items
538
     */
539
    public static function rmFromList($element, $list)
540
    {
541
        $items = explode(',', $list);
542
        foreach ($items as $k => $v) {
543
            if ($v == $element) {
544
                unset($items[$k]);
545
            }
546
        }
547
        return implode(',', $items);
548
    }
549
550
    /**
551
     * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
552
     * Ranges are limited to 1000 values per range.
553
     *
554
     * @param string $list Comma-separated list of integers with ranges (string)
555
     * @return string New comma-separated list of items
556
     */
557
    public static function expandList($list)
558
    {
559
        $items = explode(',', $list);
560
        $list = [];
561
        foreach ($items as $item) {
562
            $range = explode('-', $item);
563
            if (isset($range[1])) {
564
                $runAwayBrake = 1000;
565
                for ($n = $range[0]; $n <= $range[1]; $n++) {
566
                    $list[] = $n;
567
                    $runAwayBrake--;
568
                    if ($runAwayBrake <= 0) {
569
                        break;
570
                    }
571
                }
572
            } else {
573
                $list[] = $item;
574
            }
575
        }
576
        return implode(',', $list);
577
    }
578
579
    /**
580
     * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
581
     *
582
     * @param string $str String to md5-hash
583
     * @return int Returns 28bit integer-hash
584
     */
585
    public static function md5int($str)
586
    {
587
        return hexdec(substr(md5($str), 0, 7));
588
    }
589
590
    /**
591
     * Returns the first 10 positions of the MD5-hash		(changed from 6 to 10 recently)
592
     *
593
     * @param string $input Input string to be md5-hashed
594
     * @param int $len The string-length of the output
595
     * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
596
     */
597
    public static function shortMD5($input, $len = 10)
598
    {
599
        return substr(md5($input), 0, $len);
600
    }
601
602
    /**
603
     * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
604
     *
605
     * @param string $input Input string to create HMAC from
606
     * @param string $additionalSecret additionalSecret to prevent hmac being used in a different context
607
     * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
608
     */
609
    public static function hmac($input, $additionalSecret = '')
610
    {
611
        $hashAlgorithm = 'sha1';
612
        $hashBlocksize = 64;
613
        $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
614
        if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
615
            $hmac = hash_hmac($hashAlgorithm, $input, $secret);
616
        } else {
617
            // Outer padding
618
            $opad = str_repeat(chr(92), $hashBlocksize);
619
            // Inner padding
620
            $ipad = str_repeat(chr(54), $hashBlocksize);
621
            if (strlen($secret) > $hashBlocksize) {
622
                // Keys longer than block size are shorten
623
                $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, "\0");
624
            } else {
625
                // Keys shorter than block size are zero-padded
626
                $key = str_pad($secret, $hashBlocksize, "\0");
627
            }
628
            $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func(
629
                $hashAlgorithm,
630
                ($key ^ $ipad) . $input
631
            )));
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
     */
644
    public static function uniqueList($in_list, $secondParameter = null)
645
    {
646
        if (is_array($in_list)) {
0 ignored issues
show
introduced by
The condition is_array($in_list) is always false.
Loading history...
647
            throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
648
        }
649
        if (isset($secondParameter)) {
650
            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);
651
        }
652
        return implode(',', array_unique(self::trimExplode(',', $in_list, true)));
653
    }
654
655
    /**
656
     * Splits a reference to a file in 5 parts
657
     *
658
     * @param string $fileNameWithPath File name with path to be analyzed (must exist if open_basedir is set)
659
     * @return array<string, string> Contains keys [path], [file], [filebody], [fileext], [realFileext]
660
     */
661
    public static function split_fileref($fileNameWithPath)
0 ignored issues
show
Coding Style introduced by
Method name "GeneralUtility::split_fileref" is not in camel caps format
Loading history...
662
    {
663
        $info = [];
664
        $reg = [];
665
        if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) {
666
            $info['path'] = $reg[1];
667
            $info['file'] = $reg[2];
668
        } else {
669
            $info['path'] = '';
670
            $info['file'] = $fileNameWithPath;
671
        }
672
        $reg = '';
673
        // If open_basedir is set and the fileName was supplied without a path the is_dir check fails
674
        if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) {
0 ignored issues
show
Bug introduced by
$reg of type string is incompatible with the type array|null expected by parameter $matches of preg_match(). ( Ignorable by Annotation )

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

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

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

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

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

1845
        $result = @mkdir($newFolder, /** @scrutinizer ignore-type */ octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']));
Loading history...
1846
        if ($result) {
1847
            static::fixPermissions($newFolder);
1848
        }
1849
        return $result;
1850
    }
1851
1852
    /**
1853
     * Creates a directory - including parent directories if necessary and
1854
     * sets permissions on newly created directories.
1855
     *
1856
     * @param string $directory Target directory to create. Must a have trailing slash
1857
     * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
1858
     * @throws \RuntimeException If directory could not be created
1859
     */
1860
    public static function mkdir_deep($directory)
0 ignored issues
show
Coding Style introduced by
Method name "GeneralUtility::mkdir_deep" is not in camel caps format
Loading history...
1861
    {
1862
        if (!is_string($directory)) {
0 ignored issues
show
introduced by
The condition is_string($directory) is always true.
Loading history...
1863
            throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955);
1864
        }
1865
        // Ensure there is only one slash
1866
        $fullPath = rtrim($directory, '/') . '/';
1867
        if ($fullPath !== '/' && !is_dir($fullPath)) {
1868
            $firstCreatedPath = static::createDirectoryPath($fullPath);
1869
            if ($firstCreatedPath !== '') {
1870
                static::fixPermissions($firstCreatedPath, true);
1871
            }
1872
        }
1873
    }
1874
1875
    /**
1876
     * Creates directories for the specified paths if they do not exist. This
1877
     * functions sets proper permission mask but does not set proper user and
1878
     * group.
1879
     *
1880
     * @static
1881
     * @param string $fullDirectoryPath
1882
     * @return string Path to the the first created directory in the hierarchy
1883
     * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep
1884
     * @throws \RuntimeException If directory could not be created
1885
     */
1886
    protected static function createDirectoryPath($fullDirectoryPath)
1887
    {
1888
        $currentPath = $fullDirectoryPath;
1889
        $firstCreatedPath = '';
1890
        $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']);
1891
        if (!@is_dir($currentPath)) {
1892
            do {
1893
                $firstCreatedPath = $currentPath;
1894
                $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR);
1895
                $currentPath = substr($currentPath, 0, $separatorPosition);
1896
            } while (!is_dir($currentPath) && $separatorPosition !== false);
1897
            $result = @mkdir($fullDirectoryPath, $permissionMask, true);
0 ignored issues
show
Bug introduced by
It seems like $permissionMask can also be of type double; however, parameter $mode of mkdir() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

1897
            $result = @mkdir($fullDirectoryPath, /** @scrutinizer ignore-type */ $permissionMask, true);
Loading history...
1898
            // Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir()
1899
            if (!$result && !@is_dir($fullDirectoryPath)) {
1900
                throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401);
1901
            }
1902
        }
1903
        return $firstCreatedPath;
1904
    }
1905
1906
    /**
1907
     * Wrapper function for rmdir, allowing recursive deletion of folders and files
1908
     *
1909
     * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
1910
     * @param bool $removeNonEmpty Allow deletion of non-empty directories
1911
     * @return bool TRUE if operation was successful
1912
     */
1913
    public static function rmdir($path, $removeNonEmpty = false)
1914
    {
1915
        $OK = false;
1916
        // Remove trailing slash
1917
        $path = preg_replace('|/$|', '', $path);
1918
        $isWindows = DIRECTORY_SEPARATOR === '\\';
1919
        if (file_exists($path)) {
1920
            $OK = true;
1921
            if (!is_link($path) && is_dir($path)) {
1922
                if ($removeNonEmpty === true && ($handle = @opendir($path))) {
1923
                    $entries = [];
1924
1925
                    while (false !== ($file = readdir($handle))) {
1926
                        if ($file === '.' || $file === '..') {
1927
                            continue;
1928
                        }
1929
1930
                        $entries[] = $path . '/' . $file;
1931
                    }
1932
1933
                    closedir($handle);
1934
1935
                    foreach ($entries as $entry) {
1936
                        if (!static::rmdir($entry, $removeNonEmpty)) {
1937
                            $OK = false;
1938
                        }
1939
                    }
1940
                }
1941
                if ($OK) {
1942
                    $OK = @rmdir($path);
1943
                }
1944
            } elseif (is_link($path) && is_dir($path) && $isWindows) {
1945
                $OK = @rmdir($path);
1946
            } else {
1947
                // If $path is a file, simply remove it
1948
                $OK = @unlink($path);
1949
            }
1950
            clearstatcache();
1951
        } elseif (is_link($path)) {
1952
            $OK = @unlink($path);
1953
            if (!$OK && $isWindows) {
1954
                // Try to delete dead folder links on Windows systems
1955
                $OK = @rmdir($path);
1956
            }
1957
            clearstatcache();
1958
        }
1959
        return $OK;
1960
    }
1961
1962
    /**
1963
     * Returns an array with the names of folders in a specific path
1964
     * Will return 'error' (string) if there were an error with reading directory content.
1965
     * Will return null if provided path is false.
1966
     *
1967
     * @param string $path Path to list directories from
1968
     * @return string[]|string|null Returns an array with the directory entries as values. If no path is provided, the return value will be null.
1969
     */
1970
    public static function get_dirs($path)
0 ignored issues
show
Coding Style introduced by
Method name "GeneralUtility::get_dirs" is not in camel caps format
Loading history...
1971
    {
1972
        $dirs = null;
1973
        if ($path) {
1974
            if (is_dir($path)) {
1975
                $dir = scandir($path);
1976
                $dirs = [];
1977
                foreach ($dir as $entry) {
1978
                    if (is_dir($path . '/' . $entry) && $entry !== '..' && $entry !== '.') {
1979
                        $dirs[] = $entry;
1980
                    }
1981
                }
1982
            } else {
1983
                $dirs = 'error';
1984
            }
1985
        }
1986
        return $dirs;
1987
    }
1988
1989
    /**
1990
     * Finds all files in a given path and returns them as an array. Each
1991
     * array key is a md5 hash of the full path to the file. This is done because
1992
     * 'some' extensions like the import/export extension depend on this.
1993
     *
1994
     * @param string $path The path to retrieve the files from.
1995
     * @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.
1996
     * @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned.
1997
     * @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time.
1998
     * @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 '$/'.
1999
     * @return array<string, string>|string Array of the files found, or an error message in case the path could not be opened.
2000
     */
2001
    public static function getFilesInDir($path, $extensionList = '', $prependPath = false, $order = '', $excludePattern = '')
2002
    {
2003
        $excludePattern = (string)$excludePattern;
2004
        $path = rtrim($path, '/');
2005
        if (!@is_dir($path)) {
2006
            return [];
2007
        }
2008
2009
        $rawFileList = scandir($path);
2010
        if ($rawFileList === false) {
2011
            return 'error opening path: "' . $path . '"';
2012
        }
2013
2014
        $pathPrefix = $path . '/';
2015
        $allowedFileExtensionArray = self::trimExplode(',', $extensionList);
2016
        $extensionList = ',' . str_replace(' ', '', $extensionList) . ',';
2017
        $files = [];
2018
        foreach ($rawFileList as $entry) {
2019
            $completePathToEntry = $pathPrefix . $entry;
2020
            if (!@is_file($completePathToEntry)) {
2021
                continue;
2022
            }
2023
2024
            foreach ($allowedFileExtensionArray as $allowedFileExtension) {
2025
                if (
2026
                    ($extensionList === ',,' || stripos($extensionList, ',' . substr($entry, strlen($allowedFileExtension) * -1, strlen($allowedFileExtension)) . ',') !== false)
2027
                    && ($excludePattern === '' || !preg_match('/^' . $excludePattern . '$/', $entry))
2028
                ) {
2029
                    if ($order !== 'mtime') {
2030
                        $files[] = $entry;
2031
                    } else {
2032
                        // Store the value in the key so we can do a fast asort later.
2033
                        $files[$entry] = filemtime($completePathToEntry);
2034
                    }
2035
                }
2036
            }
2037
        }
2038
2039
        $valueName = 'value';
2040
        if ($order === 'mtime') {
2041
            asort($files);
2042
            $valueName = 'key';
2043
        }
2044
2045
        $valuePathPrefix = $prependPath ? $pathPrefix : '';
2046
        $foundFiles = [];
2047
        foreach ($files as $key => $value) {
2048
            // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
2049
            $foundFiles[md5($pathPrefix . ${$valueName})] = $valuePathPrefix . ${$valueName};
2050
        }
2051
2052
        return $foundFiles;
2053
    }
2054
2055
    /**
2056
     * Recursively gather all files and folders of a path.
2057
     *
2058
     * @param string[] $fileArr Empty input array (will have files added to it)
2059
     * @param string $path The path to read recursively from (absolute) (include trailing slash!)
2060
     * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2061
     * @param bool $regDirs If set, directories are also included in output.
2062
     * @param int $recursivityLevels The number of levels to dig down...
2063
     * @param string $excludePattern regex pattern of files/directories to exclude
2064
     * @return array<string, string> An array with the found files/directories.
2065
     */
2066
    public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = false, $recursivityLevels = 99, $excludePattern = '')
2067
    {
2068
        if ($regDirs) {
2069
            $fileArr[md5($path)] = $path;
2070
        }
2071
        $fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
0 ignored issues
show
Bug introduced by
self::getFilesInDir($pat... 1, 1, $excludePattern) of type string is incompatible with the type array|null expected by parameter $array2 of array_merge(). ( Ignorable by Annotation )

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

2071
        $fileArr = array_merge($fileArr, /** @scrutinizer ignore-type */ self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
Loading history...
2072
        $dirs = self::get_dirs($path);
2073
        if ($recursivityLevels > 0 && is_array($dirs)) {
0 ignored issues
show
introduced by
The condition is_array($dirs) is always false.
Loading history...
2074
            foreach ($dirs as $subdirs) {
2075
                if ((string)$subdirs !== '' && ($excludePattern === '' || !preg_match('/^' . $excludePattern . '$/', $subdirs))) {
2076
                    $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
2077
                }
2078
            }
2079
        }
2080
        return $fileArr;
2081
    }
2082
2083
    /**
2084
     * Removes the absolute part of all files/folders in fileArr
2085
     *
2086
     * @param string[] $fileArr The file array to remove the prefix from
2087
     * @param string $prefixToRemove The prefix path to remove (if found as first part of string!)
2088
     * @return string[]|string The input $fileArr processed, or a string with an error message, when an error occurred.
2089
     */
2090
    public static function removePrefixPathFromList(array $fileArr, $prefixToRemove)
2091
    {
2092
        foreach ($fileArr as $k => &$absFileRef) {
2093
            if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
2094
                $absFileRef = substr($absFileRef, strlen($prefixToRemove));
2095
            } else {
2096
                return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2097
            }
2098
        }
2099
        unset($absFileRef);
2100
        return $fileArr;
2101
    }
2102
2103
    /**
2104
     * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2105
     *
2106
     * @param string $theFile File path to process
2107
     * @return string
2108
     */
2109
    public static function fixWindowsFilePath($theFile)
2110
    {
2111
        return str_replace(['\\', '//'], '/', $theFile);
2112
    }
2113
2114
    /**
2115
     * Resolves "../" sections in the input path string.
2116
     * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2117
     *
2118
     * @param string $pathStr File path in which "/../" is resolved
2119
     * @return string
2120
     */
2121
    public static function resolveBackPath($pathStr)
2122
    {
2123
        if (strpos($pathStr, '..') === false) {
2124
            return $pathStr;
2125
        }
2126
        $parts = explode('/', $pathStr);
2127
        $output = [];
2128
        $c = 0;
2129
        foreach ($parts as $part) {
2130
            if ($part === '..') {
2131
                if ($c) {
2132
                    array_pop($output);
2133
                    --$c;
2134
                } else {
2135
                    $output[] = $part;
2136
                }
2137
            } else {
2138
                ++$c;
2139
                $output[] = $part;
2140
            }
2141
        }
2142
        return implode('/', $output);
2143
    }
2144
2145
    /**
2146
     * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2147
     * - If already having a scheme, nothing is prepended
2148
     * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2149
     * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2150
     *
2151
     * @param string $path URL / path to prepend full URL addressing to.
2152
     * @return string
2153
     */
2154
    public static function locationHeaderUrl($path)
2155
    {
2156
        if (strpos($path, '//') === 0) {
2157
            return $path;
2158
        }
2159
2160
        // relative to HOST
2161
        if (strpos($path, '/') === 0) {
2162
            return self::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
2163
        }
2164
2165
        $urlComponents = parse_url($path);
2166
        if (!($urlComponents['scheme'] ?? false)) {
2167
            // No scheme either
2168
            return self::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
2169
        }
2170
2171
        return $path;
2172
    }
2173
2174
    /**
2175
     * Returns the maximum upload size for a file that is allowed. Measured in KB.
2176
     * This might be handy to find out the real upload limit that is possible for this
2177
     * TYPO3 installation.
2178
     *
2179
     * @return int The maximum size of uploads that are allowed (measured in kilobytes)
2180
     */
2181
    public static function getMaxUploadFileSize()
2182
    {
2183
        // Check for PHP restrictions of the maximum size of one of the $_FILES
2184
        $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
2185
        // Check for PHP restrictions of the maximum $_POST size
2186
        $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
2187
        // If the total amount of post data is smaller (!) than the upload_max_filesize directive,
2188
        // then this is the real limit in PHP
2189
        $phpUploadLimit = $phpPostLimit > 0 && $phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit;
2190
        return floor($phpUploadLimit) / 1024;
2191
    }
2192
2193
    /**
2194
     * Gets the bytes value from a measurement string like "100k".
2195
     *
2196
     * @param string $measurement The measurement (e.g. "100k")
2197
     * @return int The bytes value (e.g. 102400)
2198
     */
2199
    public static function getBytesFromSizeMeasurement($measurement)
2200
    {
2201
        $bytes = (float)$measurement;
2202
        if (stripos($measurement, 'G')) {
2203
            $bytes *= 1024 * 1024 * 1024;
2204
        } elseif (stripos($measurement, 'M')) {
2205
            $bytes *= 1024 * 1024;
2206
        } elseif (stripos($measurement, 'K')) {
2207
            $bytes *= 1024;
2208
        }
2209
        return $bytes;
2210
    }
2211
2212
    /**
2213
     * Function for static version numbers on files, based on the filemtime
2214
     *
2215
     * This will make the filename automatically change when a file is
2216
     * changed, and by that re-cached by the browser. If the file does not
2217
     * exist physically the original file passed to the function is
2218
     * returned without the timestamp.
2219
     *
2220
     * Behaviour is influenced by the setting
2221
     * TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename]
2222
     * = TRUE (BE) / "embed" (FE) : modify filename
2223
     * = FALSE (BE) / "querystring" (FE) : add timestamp as parameter
2224
     *
2225
     * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
2226
     * @return string Relative path with version filename including the timestamp
2227
     */
2228
    public static function createVersionNumberedFilename($file)
2229
    {
2230
        $lookupFile = explode('?', $file);
2231
        $path = self::resolveBackPath(self::dirname(Environment::getCurrentScript()) . '/' . $lookupFile[0]);
2232
2233
        $doNothing = false;
2234
        if (TYPO3_MODE === 'FE') {
0 ignored issues
show
introduced by
The condition TYPO3\CMS\Core\Utility\TYPO3_MODE === 'FE' is always false.
Loading history...
2235
            $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
2236
            if ($mode === 'embed') {
2237
                $mode = true;
2238
            } else {
2239
                if ($mode === 'querystring') {
2240
                    $mode = false;
2241
                } else {
2242
                    $doNothing = true;
2243
                }
2244
            }
2245
        } else {
2246
            $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
2247
        }
2248
        if ($doNothing || !file_exists($path)) {
2249
            // File not found, return filename unaltered
2250
            $fullName = $file;
2251
        } else {
2252
            if (!$mode) {
2253
                // If use of .htaccess rule is not configured,
2254
                // we use the default query-string method
2255
                if (!empty($lookupFile[1])) {
2256
                    $separator = '&';
2257
                } else {
2258
                    $separator = '?';
2259
                }
2260
                $fullName = $file . $separator . filemtime($path);
2261
            } else {
2262
                // Change the filename
2263
                $name = explode('.', $lookupFile[0]);
2264
                $extension = array_pop($name);
2265
                array_push($name, filemtime($path), $extension);
2266
                $fullName = implode('.', $name);
2267
                // Append potential query string
2268
                $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
2269
            }
2270
        }
2271
        return $fullName;
2272
    }
2273
2274
    /**
2275
     * Writes string to a temporary file named after the md5-hash of the string
2276
     * Quite useful for extensions adding their custom built JavaScript during runtime.
2277
     *
2278
     * @param string $content JavaScript to write to file.
2279
     * @return string filename to include in the <script> tag
2280
     */
2281
    public static function writeJavaScriptContentToTemporaryFile(string $content)
2282
    {
2283
        $script = 'typo3temp/assets/js/' . GeneralUtility::shortMD5($content) . '.js';
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2284
        if (!@is_file(Environment::getPublicPath() . '/' . $script)) {
2285
            self::writeFileToTypo3tempDir(Environment::getPublicPath() . '/' . $script, $content);
2286
        }
2287
        return $script;
2288
    }
2289
2290
    /**
2291
     * Writes string to a temporary file named after the md5-hash of the string
2292
     * Quite useful for extensions adding their custom built StyleSheet during runtime.
2293
     *
2294
     * @param string $content CSS styles to write to file.
2295
     * @return string filename to include in the <link> tag
2296
     */
2297
    public static function writeStyleSheetContentToTemporaryFile(string $content)
2298
    {
2299
        $script = 'typo3temp/assets/css/' . self::shortMD5($content) . '.css';
2300
        if (!@is_file(Environment::getPublicPath() . '/' . $script)) {
2301
            self::writeFileToTypo3tempDir(Environment::getPublicPath() . '/' . $script, $content);
2302
        }
2303
        return $script;
2304
    }
2305
2306
    /*************************
2307
     *
2308
     * SYSTEM INFORMATION
2309
     *
2310
     *************************/
2311
2312
    /**
2313
     * Returns the link-url to the current script.
2314
     * 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.
2315
     * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
2316
     *
2317
     * @param array $getParams Array of GET parameters to include
2318
     * @return string
2319
     */
2320
    public static function linkThisScript(array $getParams = [])
2321
    {
2322
        $parts = self::getIndpEnv('SCRIPT_NAME');
2323
        $params = self::_GET();
2324
        foreach ($getParams as $key => $value) {
2325
            if ($value !== '') {
2326
                $params[$key] = $value;
2327
            } else {
2328
                unset($params[$key]);
2329
            }
2330
        }
2331
        $pString = self::implodeArrayForUrl('', $params);
2332
        return $pString ? $parts . '?' . ltrim($pString, '&') : $parts;
2333
    }
2334
2335
    /**
2336
     * This method is only for testing and should never be used outside tests-
2337
     *
2338
     * @param string $envName
2339
     * @param mixed $value
2340
     * @internal
2341
     */
2342
    public static function setIndpEnv($envName, $value)
2343
    {
2344
        self::$indpEnvCache[$envName] = $value;
2345
    }
2346
2347
    /**
2348
     * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2349
     * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2350
     *
2351
     * @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
2352
     * @return string Value based on the input key, independent of server/os environment.
2353
     * @throws \UnexpectedValueException
2354
     */
2355
    public static function getIndpEnv($getEnvName)
2356
    {
2357
        if (array_key_exists($getEnvName, self::$indpEnvCache)) {
2358
            return self::$indpEnvCache[$getEnvName];
2359
        }
2360
2361
        /*
2362
        Conventions:
2363
        output from parse_url():
2364
        URL:	http://username:[email protected]:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
2365
        [scheme] => 'http'
2366
        [user] => 'username'
2367
        [pass] => 'password'
2368
        [host] => '192.168.1.4'
2369
        [port] => '8080'
2370
        [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2371
        [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2372
        [fragment] => 'link1'Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2373
        [path_dir] = '/typo3/32/temp/phpcheck/'
2374
        [path_info] = '/arg1/arg2/arg3/'
2375
        [path] = [path_script/path_dir][path_info]Keys supported:URI______:
2376
        REQUEST_URI		=	[path]?[query]		= /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2377
        HTTP_HOST		=	[host][:[port]]		= 192.168.1.4:8080
2378
        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')!
2379
        PATH_INFO		=	[path_info]			= /arg1/arg2/arg3/
2380
        QUERY_STRING	=	[query]				= arg1,arg2,arg3&p1=parameter1&p2[key]=value
2381
        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
2382
        (Notice: NO username/password + NO fragment)CLIENT____:
2383
        REMOTE_ADDR		=	(client IP)
2384
        REMOTE_HOST		=	(client host)
2385
        HTTP_USER_AGENT	=	(client user agent)
2386
        HTTP_ACCEPT_LANGUAGE	= (client accept language)SERVER____:
2387
        SCRIPT_FILENAME	=	Absolute filename of script		(Differs between windows/unix). On windows 'C:\\some\\path\\' will be converted to 'C:/some/path/'Special extras:
2388
        TYPO3_HOST_ONLY =		[host] = 192.168.1.4
2389
        TYPO3_PORT =			[port] = 8080 (blank if 80, taken from host value)
2390
        TYPO3_REQUEST_HOST = 		[scheme]://[host][:[port]]
2391
        TYPO3_REQUEST_URL =		[scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
2392
        TYPO3_REQUEST_SCRIPT =  	[scheme]://[host][:[port]][path_script]
2393
        TYPO3_REQUEST_DIR =		[scheme]://[host][:[port]][path_dir]
2394
        TYPO3_SITE_URL = 		[scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2395
        TYPO3_SITE_PATH = 		[path_dir] of the TYPO3 website frontend
2396
        TYPO3_SITE_SCRIPT = 		[script / Speaking URL] of the TYPO3 website
2397
        TYPO3_DOCUMENT_ROOT =		Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2398
        TYPO3_SSL = 			Returns TRUE if this session uses SSL/TLS (https)
2399
        TYPO3_PROXY = 			Returns TRUE if this session runs over a well known proxyNotice: [fragment] is apparently NEVER available to the script!Testing suggestions:
2400
        - Output all the values.
2401
        - 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
2402
        - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2403
         */
2404
        $retVal = '';
2405
        switch ((string)$getEnvName) {
2406
            case 'SCRIPT_NAME':
2407
                $retVal = Environment::isRunningOnCgiServer()
2408
                    && (($_SERVER['ORIG_PATH_INFO'] ?? false) ?: ($_SERVER['PATH_INFO'] ?? false))
2409
                        ? (($_SERVER['ORIG_PATH_INFO'] ?? '') ?: ($_SERVER['PATH_INFO'] ?? ''))
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "?"; newline found
Loading history...
2410
                        : (($_SERVER['ORIG_SCRIPT_NAME'] ?? '') ?: ($_SERVER['SCRIPT_NAME'] ?? ''));
0 ignored issues
show
Coding Style introduced by
Expected 1 space before ":"; newline found
Loading history...
2411
                // Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
2412
                if (self::cmpIP($_SERVER['REMOTE_ADDR'] ?? '', $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'] ?? '')) {
2413
                    if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
2414
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
2415
                    } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
2416
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
2417
                    }
2418
                }
2419
                break;
2420
            case 'SCRIPT_FILENAME':
2421
                $retVal = Environment::getCurrentScript();
2422
                break;
2423
            case 'REQUEST_URI':
2424
                // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('REQUEST_URI'))
2425
                if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar'])) {
2426
                    // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
2427
                    [$v, $n] = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
2428
                    $retVal = $GLOBALS[$v][$n];
2429
                } elseif (empty($_SERVER['REQUEST_URI'])) {
2430
                    // This is for ISS/CGI which does not have the REQUEST_URI available.
2431
                    $retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '');
2432
                } else {
2433
                    $retVal = '/' . ltrim($_SERVER['REQUEST_URI'], '/');
2434
                }
2435
                // Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
2436
                if (isset($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])
2437
                    && self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])
2438
                ) {
2439
                    if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
2440
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
2441
                    } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
2442
                        $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
2443
                    }
2444
                }
2445
                break;
2446
            case 'PATH_INFO':
2447
                // $_SERVER['PATH_INFO'] != $_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI)
2448
                // are seen to set PATH_INFO equal to script_name
2449
                // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2450
                // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers,
2451
                // then 'PHP_SAPI=='cgi'' might be a better check.
2452
                // Right now strcmp($_SERVER['PATH_INFO'], GeneralUtility::getIndpEnv('SCRIPT_NAME')) will always
2453
                // return FALSE for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO
2454
                // because of PHP_SAPI=='cgi' (see above)
2455
                if (!Environment::isRunningOnCgiServer()) {
2456
                    $retVal = $_SERVER['PATH_INFO'];
2457
                }
2458
                break;
2459
            case 'TYPO3_REV_PROXY':
2460
                $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
2461
                break;
2462
            case 'REMOTE_ADDR':
2463
                $retVal = $_SERVER['REMOTE_ADDR'] ?? null;
2464
                if (self::cmpIP($retVal, $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'] ?? '')) {
2465
                    $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
2466
                    // Choose which IP in list to use
2467
                    if (!empty($ip)) {
2468
                        switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
2469
                            case 'last':
2470
                                $ip = array_pop($ip);
2471
                                break;
2472
                            case 'first':
2473
                                $ip = array_shift($ip);
2474
                                break;
2475
                            case 'none':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2476
2477
                            default:
2478
                                $ip = '';
2479
                        }
2480
                    }
2481
                    if (self::validIP($ip)) {
2482
                        $retVal = $ip;
2483
                    }
2484
                }
2485
                break;
2486
            case 'HTTP_HOST':
2487
                // if it is not set we're most likely on the cli
2488
                $retVal = $_SERVER['HTTP_HOST'] ?? null;
2489
                if (isset($_SERVER['REMOTE_ADDR']) && static::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
2490
                    $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
2491
                    // Choose which host in list to use
2492
                    if (!empty($host)) {
2493
                        switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
2494
                            case 'last':
2495
                                $host = array_pop($host);
2496
                                break;
2497
                            case 'first':
2498
                                $host = array_shift($host);
2499
                                break;
2500
                            case 'none':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2501
2502
                            default:
2503
                                $host = '';
2504
                        }
2505
                    }
2506
                    if ($host) {
2507
                        $retVal = $host;
2508
                    }
2509
                }
2510
                if (!static::isAllowedHostHeaderValue($retVal)) {
2511
                    throw new \UnexpectedValueException(
2512
                        '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.',
2513
                        1396795884
2514
                    );
2515
                }
2516
                break;
2517
            case 'HTTP_REFERER':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2518
2519
            case 'HTTP_USER_AGENT':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2520
2521
            case 'HTTP_ACCEPT_ENCODING':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2522
2523
            case 'HTTP_ACCEPT_LANGUAGE':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2524
2525
            case 'REMOTE_HOST':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2526
2527
            case 'QUERY_STRING':
2528
                $retVal = $_SERVER[$getEnvName] ?? '';
2529
                break;
2530
            case 'TYPO3_DOCUMENT_ROOT':
2531
                // Get the web root (it is not the root of the TYPO3 installation)
2532
                // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
2533
                // 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.
2534
                // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2535
                $SFN = self::getIndpEnv('SCRIPT_FILENAME');
2536
                $SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME')));
2537
                $SFN_A = explode('/', strrev($SFN));
2538
                $acc = [];
2539
                foreach ($SN_A as $kk => $vv) {
2540
                    if ((string)$SFN_A[$kk] === (string)$vv) {
2541
                        $acc[] = $vv;
2542
                    } else {
2543
                        break;
2544
                    }
2545
                }
2546
                $commonEnd = strrev(implode('/', $acc));
2547
                if ((string)$commonEnd !== '') {
2548
                    $retVal = substr($SFN, 0, -(strlen($commonEnd) + 1));
2549
                }
2550
                break;
2551
            case 'TYPO3_HOST_ONLY':
2552
                $httpHost = self::getIndpEnv('HTTP_HOST');
2553
                $httpHostBracketPosition = strpos($httpHost, ']');
2554
                $httpHostParts = explode(':', $httpHost);
2555
                $retVal = $httpHostBracketPosition !== false ? substr($httpHost, 0, $httpHostBracketPosition + 1) : array_shift($httpHostParts);
2556
                break;
2557
            case 'TYPO3_PORT':
2558
                $httpHost = self::getIndpEnv('HTTP_HOST');
2559
                $httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY');
2560
                $retVal = strlen($httpHost) > strlen($httpHostOnly) ? substr($httpHost, strlen($httpHostOnly) + 1) : '';
2561
                break;
2562
            case 'TYPO3_REQUEST_HOST':
2563
                $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') . self::getIndpEnv('HTTP_HOST');
2564
                break;
2565
            case 'TYPO3_REQUEST_URL':
2566
                $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI');
2567
                break;
2568
            case 'TYPO3_REQUEST_SCRIPT':
2569
                $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME');
2570
                break;
2571
            case 'TYPO3_REQUEST_DIR':
2572
                $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/';
2573
                break;
2574
            case 'TYPO3_SITE_URL':
2575
                if (Environment::getCurrentScript()) {
2576
                    $lPath = PathUtility::stripPathSitePrefix(PathUtility::dirnameDuringBootstrap(Environment::getCurrentScript())) . '/';
2577
                    $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
2578
                    $siteUrl = substr($url, 0, -strlen($lPath));
2579
                    if (substr($siteUrl, -1) !== '/') {
2580
                        $siteUrl .= '/';
2581
                    }
2582
                    $retVal = $siteUrl;
2583
                }
2584
                break;
2585
            case 'TYPO3_SITE_PATH':
2586
                $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
2587
                break;
2588
            case 'TYPO3_SITE_SCRIPT':
2589
                $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL')));
2590
                break;
2591
            case 'TYPO3_SSL':
2592
                $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL'] ?? null);
2593
                if ($proxySSL === '*') {
2594
                    $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
2595
                }
2596
                if (self::cmpIP($_SERVER['REMOTE_ADDR'] ?? '', $proxySSL)) {
2597
                    $retVal = true;
2598
                } else {
2599
                    // https://secure.php.net/manual/en/reserved.variables.server.php
2600
                    // "Set to a non-empty value if the script was queried through the HTTPS protocol."
2601
                    $retVal = !empty($_SERVER['SSL_SESSION_ID'])
2602
                        || (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off');
2603
                }
2604
                break;
2605
            case '_ARRAY':
2606
                $out = [];
2607
                // Here, list ALL possible keys to this function for debug display.
2608
                $envTestVars = [
2609
                    'HTTP_HOST',
2610
                    'TYPO3_HOST_ONLY',
2611
                    'TYPO3_PORT',
2612
                    'PATH_INFO',
2613
                    'QUERY_STRING',
2614
                    'REQUEST_URI',
2615
                    'HTTP_REFERER',
2616
                    'TYPO3_REQUEST_HOST',
2617
                    'TYPO3_REQUEST_URL',
2618
                    'TYPO3_REQUEST_SCRIPT',
2619
                    'TYPO3_REQUEST_DIR',
2620
                    'TYPO3_SITE_URL',
2621
                    'TYPO3_SITE_SCRIPT',
2622
                    'TYPO3_SSL',
2623
                    'TYPO3_REV_PROXY',
2624
                    'SCRIPT_NAME',
2625
                    'TYPO3_DOCUMENT_ROOT',
2626
                    'SCRIPT_FILENAME',
2627
                    'REMOTE_ADDR',
2628
                    'REMOTE_HOST',
2629
                    'HTTP_USER_AGENT',
2630
                    'HTTP_ACCEPT_LANGUAGE'
2631
                ];
2632
                foreach ($envTestVars as $v) {
2633
                    $out[$v] = self::getIndpEnv($v);
2634
                }
2635
                reset($out);
2636
                $retVal = $out;
2637
                break;
2638
        }
2639
        self::$indpEnvCache[$getEnvName] = $retVal;
2640
        return $retVal;
2641
    }
2642
2643
    /**
2644
     * Checks if the provided host header value matches the trusted hosts pattern.
2645
     * If the pattern is not defined (which only can happen early in the bootstrap), deny any value.
2646
     * The result is saved, so the check needs to be executed only once.
2647
     *
2648
     * @param string $hostHeaderValue HTTP_HOST header value as sent during the request (may include port)
2649
     * @return bool
2650
     */
2651
    public static function isAllowedHostHeaderValue($hostHeaderValue)
2652
    {
2653
        if (static::$allowHostHeaderValue === true) {
2654
            return true;
2655
        }
2656
2657
        if (static::isInternalRequestType()) {
2658
            return static::$allowHostHeaderValue = true;
2659
        }
2660
2661
        // Deny the value if trusted host patterns is empty, which means we are early in the bootstrap
2662
        if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'])) {
2663
            return false;
2664
        }
2665
2666
        if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL) {
2667
            static::$allowHostHeaderValue = true;
2668
        } else {
2669
            static::$allowHostHeaderValue = static::hostHeaderValueMatchesTrustedHostsPattern($hostHeaderValue);
2670
        }
2671
2672
        return static::$allowHostHeaderValue;
2673
    }
2674
2675
    /**
2676
     * Checks if the provided host header value matches the trusted hosts pattern without any preprocessing.
2677
     *
2678
     * @param string $hostHeaderValue
2679
     * @return bool
2680
     * @internal
2681
     */
2682
    public static function hostHeaderValueMatchesTrustedHostsPattern($hostHeaderValue)
2683
    {
2684
        if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME) {
2685
            // Allow values that equal the server name
2686
            // Note that this is only secure if name base virtual host are configured correctly in the webserver
2687
            $defaultPort = self::getIndpEnv('TYPO3_SSL') ? '443' : '80';
2688
            $parsedHostValue = parse_url('http://' . $hostHeaderValue);
2689
            if (isset($parsedHostValue['port'])) {
2690
                $hostMatch = (strtolower($parsedHostValue['host']) === strtolower($_SERVER['SERVER_NAME']) && (string)$parsedHostValue['port'] === $_SERVER['SERVER_PORT']);
2691
            } else {
2692
                $hostMatch = (strtolower($hostHeaderValue) === strtolower($_SERVER['SERVER_NAME']) && $defaultPort === $_SERVER['SERVER_PORT']);
2693
            }
2694
        } else {
2695
            // In case name based virtual hosts are not possible, we allow setting a trusted host pattern
2696
            // See https://typo3.org/teams/security/security-bulletins/typo3-core/typo3-core-sa-2014-001/ for further details
2697
            $hostMatch = (bool)preg_match('/^' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] . '$/i', $hostHeaderValue);
2698
        }
2699
2700
        return $hostMatch;
2701
    }
2702
2703
    /**
2704
     * Allows internal requests to the install tool and from the command line.
2705
     * We accept this risk to have the install tool always available.
2706
     * Also CLI needs to be allowed as unfortunately AbstractUserAuthentication::getAuthInfoArray()
2707
     * accesses HTTP_HOST without reason on CLI
2708
     * Additionally, allows requests when no REQUESTTYPE is set, which can happen quite early in the
2709
     * Bootstrap. See Application.php in EXT:backend/Classes/Http/.
2710
     *
2711
     * @return bool
2712
     */
2713
    protected static function isInternalRequestType()
2714
    {
2715
        return Environment::isCli() || !defined('TYPO3_REQUESTTYPE') || (defined('TYPO3_REQUESTTYPE') && TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_INSTALL);
2716
    }
2717
2718
    /*************************
2719
     *
2720
     * TYPO3 SPECIFIC FUNCTIONS
2721
     *
2722
     *************************/
2723
    /**
2724
     * Returns the absolute filename of a relative reference, resolves the "EXT:" prefix
2725
     * (way of referring to files inside extensions) and checks that the file is inside
2726
     * the TYPO3's base folder and implies a check with
2727
     * \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr().
2728
     *
2729
     * @param string $filename The input filename/filepath to evaluate
2730
     * @return string Returns the absolute filename of $filename if valid, otherwise blank string.
2731
     */
2732
    public static function getFileAbsFileName($filename)
2733
    {
2734
        if ((string)$filename === '') {
2735
            return '';
2736
        }
2737
        // Extension
2738
        if (strpos($filename, 'EXT:') === 0) {
2739
            [$extKey, $local] = explode('/', substr($filename, 4), 2);
2740
            $filename = '';
2741
            if ((string)$extKey !== '' && ExtensionManagementUtility::isLoaded($extKey) && (string)$local !== '') {
2742
                $filename = ExtensionManagementUtility::extPath($extKey) . $local;
2743
            }
2744
        } elseif (!static::isAbsPath($filename)) {
2745
            // is relative. Prepended with the public web folder
2746
            $filename = Environment::getPublicPath() . '/' . $filename;
2747
        } elseif (!(
2748
            static::isFirstPartOfStr($filename, Environment::getProjectPath())
2749
                  || static::isFirstPartOfStr($filename, Environment::getPublicPath())
2750
        )) {
2751
            // absolute, but set to blank if not allowed
2752
            $filename = '';
2753
        }
2754
        if ((string)$filename !== '' && static::validPathStr($filename)) {
2755
            // checks backpath.
2756
            return $filename;
2757
        }
2758
        return '';
2759
    }
2760
2761
    /**
2762
     * Checks for malicious file paths.
2763
     *
2764
     * Returns TRUE if no '//', '..', '\' or control characters are found in the $theFile.
2765
     * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2766
     * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2767
     *
2768
     * @param string $theFile File path to evaluate
2769
     * @return bool TRUE, $theFile is allowed path string, FALSE otherwise
2770
     * @see http://php.net/manual/en/security.filesystem.nullbytes.php
2771
     */
2772
    public static function validPathStr($theFile)
2773
    {
2774
        return strpos($theFile, '//') === false && strpos($theFile, '\\') === false
2775
            && preg_match('#(?:^\\.\\.|/\\.\\./|[[:cntrl:]])#u', $theFile) === 0;
2776
    }
2777
2778
    /**
2779
     * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns TRUE if so.
2780
     *
2781
     * @param string $path File path to evaluate
2782
     * @return bool
2783
     */
2784
    public static function isAbsPath($path)
2785
    {
2786
        if (substr($path, 0, 6) === 'vfs://') {
2787
            return true;
2788
        }
2789
        return isset($path[0]) && $path[0] === '/' || Environment::isWindows() && (strpos($path, ':/') === 1 || strpos($path, ':\\') === 1);
2790
    }
2791
2792
    /**
2793
     * Returns TRUE if the path is absolute, without backpath '..' and within TYPO3s project or public folder OR within the lockRootPath
2794
     *
2795
     * @param string $path File path to evaluate
2796
     * @return bool
2797
     */
2798
    public static function isAllowedAbsPath($path)
2799
    {
2800
        if (substr($path, 0, 6) === 'vfs://') {
2801
            return true;
2802
        }
2803
        $lockRootPath = $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'];
2804
        return static::isAbsPath($path) && static::validPathStr($path)
2805
            && (
2806
                static::isFirstPartOfStr($path, Environment::getProjectPath())
2807
                || static::isFirstPartOfStr($path, Environment::getPublicPath())
2808
                || $lockRootPath && static::isFirstPartOfStr($path, $lockRootPath)
2809
            );
2810
    }
2811
2812
    /**
2813
     * Low level utility function to copy directories and content recursive
2814
     *
2815
     * @param string $source Path to source directory, relative to document root or absolute
2816
     * @param string $destination Path to destination directory, relative to document root or absolute
2817
     */
2818
    public static function copyDirectory($source, $destination)
2819
    {
2820
        if (strpos($source, Environment::getProjectPath() . '/') === false) {
2821
            $source = Environment::getPublicPath() . '/' . $source;
2822
        }
2823
        if (strpos($destination, Environment::getProjectPath() . '/') === false) {
2824
            $destination = Environment::getPublicPath() . '/' . $destination;
2825
        }
2826
        if (static::isAllowedAbsPath($source) && static::isAllowedAbsPath($destination)) {
2827
            static::mkdir_deep($destination);
2828
            $iterator = new \RecursiveIteratorIterator(
2829
                new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
2830
                \RecursiveIteratorIterator::SELF_FIRST
2831
            );
2832
            /** @var \SplFileInfo $item */
2833
            foreach ($iterator as $item) {
2834
                $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

2834
                $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...
2835
                if ($item->isDir()) {
2836
                    static::mkdir($target);
2837
                } else {
2838
                    static::upload_copy_move(static::fixWindowsFilePath($item->getPathname()), $target);
2839
                }
2840
            }
2841
        }
2842
    }
2843
2844
    /**
2845
     * Checks if a given string is a valid frame URL to be loaded in the
2846
     * backend.
2847
     *
2848
     * If the given url is empty or considered to be harmless, it is returned
2849
     * as is, else the event is logged and an empty string is returned.
2850
     *
2851
     * @param string $url potential URL to check
2852
     * @return string $url or empty string
2853
     */
2854
    public static function sanitizeLocalUrl($url = '')
2855
    {
2856
        $sanitizedUrl = '';
2857
        if (!empty($url)) {
2858
            $decodedUrl = rawurldecode($url);
2859
            $parsedUrl = parse_url($decodedUrl);
2860
            $testAbsoluteUrl = self::resolveBackPath($decodedUrl);
2861
            $testRelativeUrl = self::resolveBackPath(self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl);
2862
            // Pass if URL is on the current host:
2863
            if (self::isValidUrl($decodedUrl)) {
2864
                if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) {
2865
                    $sanitizedUrl = $url;
2866
                }
2867
            } elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) {
2868
                $sanitizedUrl = $url;
2869
            } elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && $decodedUrl[0] === '/') {
2870
                $sanitizedUrl = $url;
2871
            } elseif (empty($parsedUrl['scheme']) && strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0
2872
                && $decodedUrl[0] !== '/' && strpbrk($decodedUrl, '*:|"<>') === false && strpos($decodedUrl, '\\\\') === false
2873
            ) {
2874
                $sanitizedUrl = $url;
2875
            }
2876
        }
2877
        if (!empty($url) && empty($sanitizedUrl)) {
2878
            static::getLogger()->notice('The URL "' . $url . '" is not considered to be local and was denied.');
2879
        }
2880
        return $sanitizedUrl;
2881
    }
2882
2883
    /**
2884
     * Moves $source file to $destination if uploaded, otherwise try to make a copy
2885
     *
2886
     * @param string $source Source file, absolute path
2887
     * @param string $destination Destination file, absolute path
2888
     * @return bool Returns TRUE if the file was moved.
2889
     * @see upload_to_tempfile()
2890
     */
2891
    public static function upload_copy_move($source, $destination)
0 ignored issues
show
Coding Style introduced by
Method name "GeneralUtility::upload_copy_move" is not in camel caps format
Loading history...
2892
    {
2893
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] ?? null)) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2894
            $params = ['source' => $source, 'destination' => $destination, 'method' => 'upload_copy_move'];
2895
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] as $hookMethod) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2896
                $fakeThis = null;
2897
                self::callUserFunction($hookMethod, $params, $fakeThis);
2898
            }
2899
        }
2900
2901
        $result = false;
2902
        if (is_uploaded_file($source)) {
2903
            // Return the value of move_uploaded_file, and if FALSE the temporary $source is still
2904
            // around so the user can use unlink to delete it:
2905
            $result = move_uploaded_file($source, $destination);
2906
        } else {
2907
            @copy($source, $destination);
2908
        }
2909
        // Change the permissions of the file
2910
        self::fixPermissions($destination);
2911
        // If here the file is copied and the temporary $source is still around,
2912
        // so when returning FALSE the user can try unlink to delete the $source
2913
        return $result;
2914
    }
2915
2916
    /**
2917
     * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in Environment::getProjectPath() . "var/" from where TYPO3 can use it.
2918
     * Use this function to move uploaded files to where you can work on them.
2919
     * 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!
2920
     *
2921
     * @param string $uploadedFileName The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
2922
     * @return string If a new file was successfully created, return its filename, otherwise blank string.
2923
     * @see unlink_tempfile()
2924
     * @see upload_copy_move()
2925
     */
2926
    public static function upload_to_tempfile($uploadedFileName)
0 ignored issues
show
Coding Style introduced by
Method name "GeneralUtility::upload_to_tempfile" is not in camel caps format
Loading history...
2927
    {
2928
        if (is_uploaded_file($uploadedFileName)) {
2929
            $tempFile = self::tempnam('upload_temp_');
2930
            if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] ?? null)) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2931
                $params = ['source' => $uploadedFileName, 'destination' => $tempFile, 'method' => 'upload_to_tempfile'];
2932
                foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Utility\GeneralUtility::class]['moveUploadedFile'] as $hookMethod) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

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