Revert "[TASK] Update mso/idna-convert to 1.1.0"
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / GeneralUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Core\ApplicationContext;
18 use TYPO3\CMS\Core\Core\ClassLoadingInformation;
19 use TYPO3\CMS\Core\Imaging\GraphicalFunctions;
20 use TYPO3\CMS\Core\Service\OpcodeCacheService;
21 use TYPO3\CMS\Core\SingletonInterface;
22 use TYPO3\CMS\Frontend\Page\PageRepository;
23
24 /**
25 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
26 * Most of the functions do not relate specifically to TYPO3
27 * However a section of functions requires certain TYPO3 features available
28 * See comments in the source.
29 * You are encouraged to use this library in your own scripts!
30 *
31 * USE:
32 * The class is intended to be used without creating an instance of it.
33 * So: Don't instantiate - call functions with "\TYPO3\CMS\Core\Utility\GeneralUtility::" prefixed the function name.
34 * So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'
35 */
36 class GeneralUtility
37 {
38 // Severity constants used by \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
39 const SYSLOG_SEVERITY_INFO = 0;
40 const SYSLOG_SEVERITY_NOTICE = 1;
41 const SYSLOG_SEVERITY_WARNING = 2;
42 const SYSLOG_SEVERITY_ERROR = 3;
43 const SYSLOG_SEVERITY_FATAL = 4;
44
45 const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*';
46 const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME';
47
48 /**
49 * State of host header value security check
50 * in order to avoid unnecessary multiple checks during one request
51 *
52 * @var bool
53 */
54 protected static $allowHostHeaderValue = false;
55
56 /**
57 * Singleton instances returned by makeInstance, using the class names as
58 * array keys
59 *
60 * @var array<\TYPO3\CMS\Core\SingletonInterface>
61 */
62 protected static $singletonInstances = array();
63
64 /**
65 * Instances returned by makeInstance, using the class names as array keys
66 *
67 * @var array<array><object>
68 */
69 protected static $nonSingletonInstances = array();
70
71 /**
72 * Cache for makeInstance with given class name and final class names to reduce number of self::getClassName() calls
73 *
74 * @var array Given class name => final class name
75 */
76 protected static $finalClassNameCache = array();
77
78 /**
79 * The application context
80 *
81 * @var \TYPO3\CMS\Core\Core\ApplicationContext
82 */
83 protected static $applicationContext = null;
84
85 /**
86 * IDNA string cache
87 *
88 * @var array<string>
89 */
90 protected static $idnaStringCache = array();
91
92 /**
93 * IDNA converter
94 *
95 * @var \idna_convert
96 */
97 protected static $idnaConverter = null;
98
99 /**
100 * A list of supported CGI server APIs
101 * NOTICE: This is a duplicate of the SAME array in SystemEnvironmentBuilder
102 * @var array
103 */
104 protected static $supportedCgiServerApis = array(
105 'fpm-fcgi',
106 'cgi',
107 'isapi',
108 'cgi-fcgi',
109 'srv', // HHVM with fastcgi
110 );
111
112 /**
113 * @var array
114 */
115 protected static $indpEnvCache = [];
116
117 /*************************
118 *
119 * GET/POST Variables
120 *
121 * Background:
122 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
123 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
124 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
125 * Eventually TYPO3 should provide this in the global space as well.
126 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
127 * This functionality was previously needed to normalize between magic quotes logic, which was removed from PHP 5.4,
128 * so these methods are still in use, but not tackle the slash problem anymore.
129 *
130 *************************/
131 /**
132 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
133 * To enhance security in your scripts, please consider using GeneralUtility::_GET or GeneralUtility::_POST if you already
134 * know by which method your data is arriving to the scripts!
135 *
136 * @param string $var GET/POST var to return
137 * @return mixed POST var named $var and if not set, the GET var of the same name.
138 */
139 public static function _GP($var)
140 {
141 if (empty($var)) {
142 return;
143 }
144 if (isset($_POST[$var])) {
145 $value = $_POST[$var];
146 } elseif (isset($_GET[$var])) {
147 $value = $_GET[$var];
148 } else {
149 $value = null;
150 }
151 // This is there for backwards-compatibility, in order to avoid NULL
152 if (isset($value) && !is_array($value)) {
153 $value = (string)$value;
154 }
155 return $value;
156 }
157
158 /**
159 * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
160 *
161 * @param string $parameter Key (variable name) from GET or POST vars
162 * @return array Returns the GET vars merged recursively onto the POST vars.
163 */
164 public static function _GPmerged($parameter)
165 {
166 $postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : array();
167 $getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : array();
168 $mergedParameters = $getParameter;
169 ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter);
170 return $mergedParameters;
171 }
172
173 /**
174 * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
175 * ALWAYS use this API function to acquire the GET variables!
176 * This function was previously used to normalize between magic quotes logic, which was removed from PHP 5.5
177 *
178 * @param string $var Optional pointer to value in GET array (basically name of GET var)
179 * @return mixed If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself. In any case *slashes are stipped from the output!*
180 * @see _POST(), _GP(), _GETset()
181 */
182 public static function _GET($var = null)
183 {
184 $value = $var === null ? $_GET : (empty($var) ? null : $_GET[$var]);
185 // This is there for backwards-compatibility, in order to avoid NULL
186 if (isset($value) && !is_array($value)) {
187 $value = (string)$value;
188 }
189 return $value;
190 }
191
192 /**
193 * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
194 * ALWAYS use this API function to acquire the $_POST variables!
195 *
196 * @param string $var Optional pointer to value in POST array (basically name of POST var)
197 * @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself. In any case *slashes are stipped from the output!*
198 * @see _GET(), _GP()
199 */
200 public static function _POST($var = null)
201 {
202 $value = $var === null ? $_POST : (empty($var) ? null : $_POST[$var]);
203 // This is there for backwards-compatibility, in order to avoid NULL
204 if (isset($value) && !is_array($value)) {
205 $value = (string)$value;
206 }
207 return $value;
208 }
209
210 /**
211 * Writes input value to $_GET.
212 *
213 * @param mixed $inputGet
214 * @param string $key
215 * @return void
216 */
217 public static function _GETset($inputGet, $key = '')
218 {
219 if ($key != '') {
220 if (strpos($key, '|') !== false) {
221 $pieces = explode('|', $key);
222 $newGet = array();
223 $pointer = &$newGet;
224 foreach ($pieces as $piece) {
225 $pointer = &$pointer[$piece];
226 }
227 $pointer = $inputGet;
228 $mergedGet = $_GET;
229 ArrayUtility::mergeRecursiveWithOverrule($mergedGet, $newGet);
230 $_GET = $mergedGet;
231 $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
232 } else {
233 $_GET[$key] = $inputGet;
234 $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
235 }
236 } elseif (is_array($inputGet)) {
237 $_GET = $inputGet;
238 $GLOBALS['HTTP_GET_VARS'] = $inputGet;
239 }
240 }
241
242 /**
243 * Wrapper for the RemoveXSS function.
244 * Removes potential XSS code from an input string.
245 *
246 * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
247 *
248 * @param string $string Input string
249 * @return string Input string with potential XSS code removed
250 */
251 public static function removeXSS($string)
252 {
253 return \RemoveXSS::process($string);
254 }
255
256 /*************************
257 *
258 * IMAGE FUNCTIONS
259 *
260 *************************/
261 /**
262 * Compressing a GIF file if not already LZW compressed.
263 * This function is a workaround for the fact that ImageMagick and/or GD does not compress GIF-files to their minimun size (that is RLE or no compression used)
264 *
265 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
266 * GIF:
267 * If $type is not set, the compression is done with ImageMagick (provided that $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] is pointing to the path of a lzw-enabled version of 'convert') else with GD (should be RLE-enabled!)
268 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
269 * PNG:
270 * No changes.
271 *
272 * $theFile is expected to be a valid GIF-file!
273 * The function returns a code for the operation.
274 *
275 * @param string $theFile Filepath
276 * @param string $type See description of function
277 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
278 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Use \TYPO3\CMS\Core\Imaging\GraphicalFunctions::gifCompress() instead.
279 */
280 public static function gif_compress($theFile, $type)
281 {
282 static::logDeprecatedFunction();
283 $returnCode = GraphicalFunctions::gifCompress($theFile, $type);
284 return $returnCode;
285 }
286
287 /**
288 * Converts a png file to gif.
289 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set TRUE.
290 *
291 * @param string $theFile The filename with path
292 * @return string New filename
293 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Use \TYPO3\CMS\Core\Imaging\GraphicalFunctions::pngToGifByImagemagick() instead.
294 */
295 public static function png_to_gif_by_imagemagick($theFile)
296 {
297 static::logDeprecatedFunction();
298 $newFile = GraphicalFunctions::pngToGifByImagemagick($theFile);
299 return $newFile;
300 }
301
302 /**
303 * Returns filename of the png/gif version of the input file (which can be png or gif).
304 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
305 *
306 * @param string $theFile Filepath of image file
307 * @param bool $output_png If set, then input file is converted to PNG, otherwise to GIF
308 * @return string If the new image file exists, its filepath is returned
309 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Use \TYPO3\CMS\Core\Imaging\GraphicalFunctions::readPngGif() instead.
310 */
311 public static function read_png_gif($theFile, $output_png = false)
312 {
313 static::logDeprecatedFunction();
314 $newFile = GraphicalFunctions::readPngGif($theFile, $output_png);
315 return $newFile;
316 }
317
318 /*************************
319 *
320 * STRING FUNCTIONS
321 *
322 *************************/
323 /**
324 * Truncates a string with appended/prepended "..." and takes current character set into consideration.
325 *
326 * @param string $string String to truncate
327 * @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.
328 * @param string $appendString Appendix to the truncated string
329 * @return string Cropped string
330 */
331 public static function fixed_lgd_cs($string, $chars, $appendString = '...')
332 {
333 if (is_object($GLOBALS['LANG'])) {
334 return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
335 } elseif (is_object($GLOBALS['TSFE']) && is_object($GLOBALS['TSFE']->csConvObj)) {
336 $charSet = $GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet;
337 return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString);
338 } else {
339 // This case should not happen
340 $csConvObj = self::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
341 return $csConvObj->crop('utf-8', $string, $chars, $appendString);
342 }
343 }
344
345 /**
346 * Match IP number with list of numbers with wildcard
347 * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
348 *
349 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
350 * @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.
351 * @return bool TRUE if an IP-mask from $list matches $baseIP
352 */
353 public static function cmpIP($baseIP, $list)
354 {
355 $list = trim($list);
356 if ($list === '') {
357 return false;
358 } elseif ($list === '*') {
359 return true;
360 }
361 if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
362 return self::cmpIPv6($baseIP, $list);
363 } else {
364 return self::cmpIPv4($baseIP, $list);
365 }
366 }
367
368 /**
369 * Match IPv4 number with list of numbers with wildcard
370 *
371 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
372 * @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
373 * @return bool TRUE if an IP-mask from $list matches $baseIP
374 */
375 public static function cmpIPv4($baseIP, $list)
376 {
377 $IPpartsReq = explode('.', $baseIP);
378 if (count($IPpartsReq) === 4) {
379 $values = self::trimExplode(',', $list, true);
380 foreach ($values as $test) {
381 $testList = explode('/', $test);
382 if (count($testList) === 2) {
383 list($test, $mask) = $testList;
384 } else {
385 $mask = false;
386 }
387 if ((int)$mask) {
388 // "192.168.3.0/24"
389 $lnet = ip2long($test);
390 $lip = ip2long($baseIP);
391 $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
392 $firstpart = substr($binnet, 0, $mask);
393 $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
394 $firstip = substr($binip, 0, $mask);
395 $yes = $firstpart === $firstip;
396 } else {
397 // "192.168.*.*"
398 $IPparts = explode('.', $test);
399 $yes = 1;
400 foreach ($IPparts as $index => $val) {
401 $val = trim($val);
402 if ($val !== '*' && $IPpartsReq[$index] !== $val) {
403 $yes = 0;
404 }
405 }
406 }
407 if ($yes) {
408 return true;
409 }
410 }
411 }
412 return false;
413 }
414
415 /**
416 * Match IPv6 address with a list of IPv6 prefixes
417 *
418 * @param string $baseIP Is the current remote IP address for instance
419 * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
420 * @return bool TRUE If an baseIP matches any prefix
421 */
422 public static function cmpIPv6($baseIP, $list)
423 {
424 // Policy default: Deny connection
425 $success = false;
426 $baseIP = self::normalizeIPv6($baseIP);
427 $values = self::trimExplode(',', $list, true);
428 foreach ($values as $test) {
429 $testList = explode('/', $test);
430 if (count($testList) === 2) {
431 list($test, $mask) = $testList;
432 } else {
433 $mask = false;
434 }
435 if (self::validIPv6($test)) {
436 $test = self::normalizeIPv6($test);
437 $maskInt = (int)$mask ?: 128;
438 // Special case; /0 is an allowed mask - equals a wildcard
439 if ($mask === '0') {
440 $success = true;
441 } elseif ($maskInt == 128) {
442 $success = $test === $baseIP;
443 } else {
444 $testBin = self::IPv6Hex2Bin($test);
445 $baseIPBin = self::IPv6Hex2Bin($baseIP);
446 $success = true;
447 // Modulo is 0 if this is a 8-bit-boundary
448 $maskIntModulo = $maskInt % 8;
449 $numFullCharactersUntilBoundary = (int)($maskInt / 8);
450 if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) {
451 $success = false;
452 } elseif ($maskIntModulo > 0) {
453 // If not an 8-bit-boundary, check bits of last character
454 $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
455 $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
456 if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
457 $success = false;
458 }
459 }
460 }
461 }
462 if ($success) {
463 return true;
464 }
465 }
466 return false;
467 }
468
469 /**
470 * Transform a regular IPv6 address from hex-representation into binary
471 *
472 * @param string $hex IPv6 address in hex-presentation
473 * @return string Binary representation (16 characters, 128 characters)
474 * @see IPv6Bin2Hex()
475 */
476 public static function IPv6Hex2Bin($hex)
477 {
478 return inet_pton($hex);
479 }
480
481 /**
482 * Transform an IPv6 address from binary to hex-representation
483 *
484 * @param string $bin IPv6 address in hex-presentation
485 * @return string Binary representation (16 characters, 128 characters)
486 * @see IPv6Hex2Bin()
487 */
488 public static function IPv6Bin2Hex($bin)
489 {
490 return inet_ntop($bin);
491 }
492
493 /**
494 * Normalize an IPv6 address to full length
495 *
496 * @param string $address Given IPv6 address
497 * @return string Normalized address
498 * @see compressIPv6()
499 */
500 public static function normalizeIPv6($address)
501 {
502 $normalizedAddress = '';
503 $stageOneAddress = '';
504 // According to RFC lowercase-representation is recommended
505 $address = strtolower($address);
506 // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
507 if (strlen($address) == 39) {
508 // Already in full expanded form
509 return $address;
510 }
511 // Count 2 if if address has hidden zero blocks
512 $chunks = explode('::', $address);
513 if (count($chunks) === 2) {
514 $chunksLeft = explode(':', $chunks[0]);
515 $chunksRight = explode(':', $chunks[1]);
516 $left = count($chunksLeft);
517 $right = count($chunksRight);
518 // Special case: leading zero-only blocks count to 1, should be 0
519 if ($left == 1 && strlen($chunksLeft[0]) == 0) {
520 $left = 0;
521 }
522 $hiddenBlocks = 8 - ($left + $right);
523 $hiddenPart = '';
524 $h = 0;
525 while ($h < $hiddenBlocks) {
526 $hiddenPart .= '0000:';
527 $h++;
528 }
529 if ($left == 0) {
530 $stageOneAddress = $hiddenPart . $chunks[1];
531 } else {
532 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
533 }
534 } else {
535 $stageOneAddress = $address;
536 }
537 // Normalize the blocks:
538 $blocks = explode(':', $stageOneAddress);
539 $divCounter = 0;
540 foreach ($blocks as $block) {
541 $tmpBlock = '';
542 $i = 0;
543 $hiddenZeros = 4 - strlen($block);
544 while ($i < $hiddenZeros) {
545 $tmpBlock .= '0';
546 $i++;
547 }
548 $normalizedAddress .= $tmpBlock . $block;
549 if ($divCounter < 7) {
550 $normalizedAddress .= ':';
551 $divCounter++;
552 }
553 }
554 return $normalizedAddress;
555 }
556
557 /**
558 * Compress an IPv6 address to the shortest notation
559 *
560 * @param string $address Given IPv6 address
561 * @return string Compressed address
562 * @see normalizeIPv6()
563 */
564 public static function compressIPv6($address)
565 {
566 return inet_ntop(inet_pton($address));
567 }
568
569 /**
570 * Validate a given IP address.
571 *
572 * Possible format are IPv4 and IPv6.
573 *
574 * @param string $ip IP address to be tested
575 * @return bool TRUE if $ip is either of IPv4 or IPv6 format.
576 */
577 public static function validIP($ip)
578 {
579 return filter_var($ip, FILTER_VALIDATE_IP) !== false;
580 }
581
582 /**
583 * Validate a given IP address to the IPv4 address format.
584 *
585 * Example for possible format: 10.0.45.99
586 *
587 * @param string $ip IP address to be tested
588 * @return bool TRUE if $ip is of IPv4 format.
589 */
590 public static function validIPv4($ip)
591 {
592 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
593 }
594
595 /**
596 * Validate a given IP address to the IPv6 address format.
597 *
598 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
599 *
600 * @param string $ip IP address to be tested
601 * @return bool TRUE if $ip is of IPv6 format.
602 */
603 public static function validIPv6($ip)
604 {
605 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
606 }
607
608 /**
609 * Match fully qualified domain name with list of strings with wildcard
610 *
611 * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
612 * @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)
613 * @return bool TRUE if a domain name mask from $list matches $baseIP
614 */
615 public static function cmpFQDN($baseHost, $list)
616 {
617 $baseHost = trim($baseHost);
618 if (empty($baseHost)) {
619 return false;
620 }
621 if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
622 // Resolve hostname
623 // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
624 // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
625 $baseHostName = gethostbyaddr($baseHost);
626 if ($baseHostName === $baseHost) {
627 // Unable to resolve hostname
628 return false;
629 }
630 } else {
631 $baseHostName = $baseHost;
632 }
633 $baseHostNameParts = explode('.', $baseHostName);
634 $values = self::trimExplode(',', $list, true);
635 foreach ($values as $test) {
636 $hostNameParts = explode('.', $test);
637 // To match hostNameParts can only be shorter (in case of wildcards) or equal
638 $hostNamePartsCount = count($hostNameParts);
639 $baseHostNamePartsCount = count($baseHostNameParts);
640 if ($hostNamePartsCount > $baseHostNamePartsCount) {
641 continue;
642 }
643 $yes = true;
644 foreach ($hostNameParts as $index => $val) {
645 $val = trim($val);
646 if ($val === '*') {
647 // Wildcard valid for one or more hostname-parts
648 $wildcardStart = $index + 1;
649 // Wildcard as last/only part always matches, otherwise perform recursive checks
650 if ($wildcardStart < $hostNamePartsCount) {
651 $wildcardMatched = false;
652 $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
653 while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) {
654 $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
655 $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
656 $wildcardStart++;
657 }
658 if ($wildcardMatched) {
659 // Match found by recursive compare
660 return true;
661 } else {
662 $yes = false;
663 }
664 }
665 } elseif ($baseHostNameParts[$index] !== $val) {
666 // In case of no match
667 $yes = false;
668 }
669 }
670 if ($yes) {
671 return true;
672 }
673 }
674 return false;
675 }
676
677 /**
678 * Checks if a given URL matches the host that currently handles this HTTP request.
679 * Scheme, hostname and (optional) port of the given URL are compared.
680 *
681 * @param string $url URL to compare with the TYPO3 request host
682 * @return bool Whether the URL matches the TYPO3 request host
683 */
684 public static function isOnCurrentHost($url)
685 {
686 return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
687 }
688
689 /**
690 * Check for item in list
691 * Check if an item exists in a comma-separated list of items.
692 *
693 * @param string $list Comma-separated list of items (string)
694 * @param string $item Item to check for
695 * @return bool TRUE if $item is in $list
696 */
697 public static function inList($list, $item)
698 {
699 return strpos(',' . $list . ',', ',' . $item . ',') !== false;
700 }
701
702 /**
703 * Removes an item from a comma-separated list of items.
704 *
705 * If $element contains a comma, the behaviour of this method is undefined.
706 * Empty elements in the list are preserved.
707 *
708 * @param string $element Element to remove
709 * @param string $list Comma-separated list of items (string)
710 * @return string New comma-separated list of items
711 */
712 public static function rmFromList($element, $list)
713 {
714 $items = explode(',', $list);
715 foreach ($items as $k => $v) {
716 if ($v == $element) {
717 unset($items[$k]);
718 }
719 }
720 return implode(',', $items);
721 }
722
723 /**
724 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
725 * Ranges are limited to 1000 values per range.
726 *
727 * @param string $list Comma-separated list of integers with ranges (string)
728 * @return string New comma-separated list of items
729 */
730 public static function expandList($list)
731 {
732 $items = explode(',', $list);
733 $list = array();
734 foreach ($items as $item) {
735 $range = explode('-', $item);
736 if (isset($range[1])) {
737 $runAwayBrake = 1000;
738 for ($n = $range[0]; $n <= $range[1]; $n++) {
739 $list[] = $n;
740 $runAwayBrake--;
741 if ($runAwayBrake <= 0) {
742 break;
743 }
744 }
745 } else {
746 $list[] = $item;
747 }
748 }
749 return implode(',', $list);
750 }
751
752 /**
753 * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
754 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
755 *
756 * @param string $verNumberStr Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
757 * @return bool Returns TRUE if this setup is compatible with the provided version number
758 * @todo Still needs a function to convert versions to branches
759 */
760 public static function compat_version($verNumberStr)
761 {
762 return VersionNumberUtility::convertVersionNumberToInteger(TYPO3_branch) >= VersionNumberUtility::convertVersionNumberToInteger($verNumberStr);
763 }
764
765 /**
766 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
767 *
768 * @param string $str String to md5-hash
769 * @return int Returns 28bit integer-hash
770 */
771 public static function md5int($str)
772 {
773 return hexdec(substr(md5($str), 0, 7));
774 }
775
776 /**
777 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
778 *
779 * @param string $input Input string to be md5-hashed
780 * @param int $len The string-length of the output
781 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
782 */
783 public static function shortMD5($input, $len = 10)
784 {
785 return substr(md5($input), 0, $len);
786 }
787
788 /**
789 * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
790 *
791 * @param string $input Input string to create HMAC from
792 * @param string $additionalSecret additionalSecret to prevent hmac beeing used in a different context
793 * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
794 */
795 public static function hmac($input, $additionalSecret = '')
796 {
797 $hashAlgorithm = 'sha1';
798 $hashBlocksize = 64;
799 $hmac = '';
800 $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
801 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
802 $hmac = hash_hmac($hashAlgorithm, $input, $secret);
803 } else {
804 // Outer padding
805 $opad = str_repeat(chr(92), $hashBlocksize);
806 // Inner padding
807 $ipad = str_repeat(chr(54), $hashBlocksize);
808 if (strlen($secret) > $hashBlocksize) {
809 // Keys longer than block size are shorten
810 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, chr(0));
811 } else {
812 // Keys shorter than block size are zero-padded
813 $key = str_pad($secret, $hashBlocksize, chr(0));
814 }
815 $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, (($key ^ $ipad) . $input))));
816 }
817 return $hmac;
818 }
819
820 /**
821 * Takes comma-separated lists and arrays and removes all duplicates
822 * If a value in the list is trim(empty), the value is ignored.
823 *
824 * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
825 * @param mixed $secondParameter Dummy field, which if set will show a warning!
826 * @return string Returns the list without any duplicates of values, space around values are trimmed
827 */
828 public static function uniqueList($in_list, $secondParameter = null)
829 {
830 if (is_array($in_list)) {
831 throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
832 }
833 if (isset($secondParameter)) {
834 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);
835 }
836 return implode(',', array_unique(self::trimExplode(',', $in_list, true)));
837 }
838
839 /**
840 * Splits a reference to a file in 5 parts
841 *
842 * @param string $fileNameWithPath File name with path to be analysed (must exist if open_basedir is set)
843 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
844 */
845 public static function split_fileref($fileNameWithPath)
846 {
847 $reg = array();
848 if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) {
849 $info['path'] = $reg[1];
850 $info['file'] = $reg[2];
851 } else {
852 $info['path'] = '';
853 $info['file'] = $fileNameWithPath;
854 }
855 $reg = '';
856 // If open_basedir is set and the fileName was supplied without a path the is_dir check fails
857 if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) {
858 $info['filebody'] = $reg[1];
859 $info['fileext'] = strtolower($reg[2]);
860 $info['realFileext'] = $reg[2];
861 } else {
862 $info['filebody'] = $info['file'];
863 $info['fileext'] = '';
864 }
865 reset($info);
866 return $info;
867 }
868
869 /**
870 * Returns the directory part of a path without trailing slash
871 * If there is no dir-part, then an empty string is returned.
872 * Behaviour:
873 *
874 * '/dir1/dir2/script.php' => '/dir1/dir2'
875 * '/dir1/' => '/dir1'
876 * 'dir1/script.php' => 'dir1'
877 * 'd/script.php' => 'd'
878 * '/script.php' => ''
879 * '' => ''
880 *
881 * @param string $path Directory name / path
882 * @return string Processed input value. See function description.
883 */
884 public static function dirname($path)
885 {
886 $p = self::revExplode('/', $path, 2);
887 return count($p) === 2 ? $p[0] : '';
888 }
889
890 /**
891 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
892 *
893 * @param string $color A hexadecimal color code, #xxxxxx
894 * @param int $R Offset value 0-255
895 * @param int $G Offset value 0-255
896 * @param int $B Offset value 0-255
897 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
898 * @see modifyHTMLColorAll()
899 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
900 */
901 public static function modifyHTMLColor($color, $R, $G, $B)
902 {
903 self::logDeprecatedFunction();
904 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
905 $nR = MathUtility::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
906 $nG = MathUtility::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
907 $nB = MathUtility::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
908 return '#' . substr(('0' . dechex($nR)), -2) . substr(('0' . dechex($nG)), -2) . substr(('0' . dechex($nB)), -2);
909 }
910
911 /**
912 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
913 *
914 * @param string $color A hexadecimal color code, #xxxxxx
915 * @param int $all Offset value 0-255 for all three channels.
916 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
917 * @see modifyHTMLColor()
918 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
919 */
920 public static function modifyHTMLColorAll($color, $all)
921 {
922 self::logDeprecatedFunction();
923 return self::modifyHTMLColor($color, $all, $all, $all);
924 }
925
926 /**
927 * Returns TRUE if the first part of $str matches the string $partStr
928 *
929 * @param string $str Full string to check
930 * @param string $partStr Reference string which must be found as the "first part" of the full string
931 * @return bool TRUE if $partStr was found to be equal to the first part of $str
932 */
933 public static function isFirstPartOfStr($str, $partStr)
934 {
935 return $partStr != '' && strpos((string)$str, (string)$partStr, 0) === 0;
936 }
937
938 /**
939 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
940 *
941 * @param int $sizeInBytes Number of bytes to format.
942 * @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".
943 * @param int $base The unit base if not using a unit name. Defaults to 1024.
944 * @return string Formatted representation of the byte number, for output.
945 */
946 public static function formatSize($sizeInBytes, $labels = '', $base = 0)
947 {
948 $defaultFormats = array(
949 'iec' => array('base' => 1024, 'labels' => array(' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi')),
950 'si' => array('base' => 1000, 'labels' => array(' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y')),
951 );
952 // Set labels and base:
953 if (empty($labels)) {
954 $labels = 'iec';
955 }
956 if (isset($defaultFormats[$labels])) {
957 $base = $defaultFormats[$labels]['base'];
958 $labelArr = $defaultFormats[$labels]['labels'];
959 } else {
960 $base = (int)$base;
961 if ($base !== 1000 && $base !== 1024) {
962 $base = 1024;
963 }
964 $labelArr = explode('|', str_replace('"', '', $labels));
965 }
966 // @todo find out which locale is used for current BE user to cover the BE case as well
967 $oldLocale = setlocale(LC_NUMERIC, 0);
968 $newLocale = isset($GLOBALS['TSFE']) ? $GLOBALS['TSFE']->config['config']['locale_all'] : '';
969 if ($newLocale) {
970 setlocale(LC_NUMERIC, $newLocale);
971 }
972 $localeInfo = localeconv();
973 if ($newLocale) {
974 setlocale(LC_NUMERIC, $oldLocale);
975 }
976 $sizeInBytes = max($sizeInBytes, 0);
977 $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base));
978 $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
979 if ($sizeInUnits > ($base * .9)) {
980 $multiplier++;
981 }
982 $multiplier = min($multiplier, count($labelArr) - 1);
983 $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
984 return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier];
985 }
986
987 /**
988 * Returns microtime input to milliseconds
989 *
990 * @param string $microtime Microtime
991 * @return int Microtime input string converted to an integer (milliseconds)
992 */
993 public static function convertMicrotime($microtime)
994 {
995 $parts = explode(' ', $microtime);
996 return round(($parts[0] + $parts[1]) * 1000);
997 }
998
999 /**
1000 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
1001 *
1002 * @param string $string Input string, eg "123 + 456 / 789 - 4
1003 * @param string $operators Operators to split by, typically "/+-*
1004 * @return array Array with operators and operands separated.
1005 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc(), \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
1006 */
1007 public static function splitCalc($string, $operators)
1008 {
1009 $res = array();
1010 $sign = '+';
1011 while ($string) {
1012 $valueLen = strcspn($string, $operators);
1013 $value = substr($string, 0, $valueLen);
1014 $res[] = array($sign, trim($value));
1015 $sign = substr($string, $valueLen, 1);
1016 $string = substr($string, $valueLen + 1);
1017 }
1018 reset($res);
1019 return $res;
1020 }
1021
1022 /**
1023 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1024 * Note: Use htmlspecialchars($str, ENT_COMPAT, 'UTF-8', FALSE) to avoid double encoding.
1025 * This makes the call to this method obsolete.
1026 *
1027 * @param string $str String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;
1028 * @return string Converted result.
1029 *
1030 */
1031 public static function deHSCentities($str)
1032 {
1033 return preg_replace('/&amp;([#[:alnum:]]*;)/', '&\\1', $str);
1034 }
1035
1036 /**
1037 * This function is used to escape any ' -characters when transferring text to JavaScript!
1038 *
1039 * @param string $string String to escape
1040 * @param bool $extended If set, also backslashes are escaped.
1041 * @param string $char The character to escape, default is ' (single-quote)
1042 * @return string Processed input string
1043 */
1044 public static function slashJS($string, $extended = false, $char = '\'')
1045 {
1046 if ($extended) {
1047 $string = str_replace('\\', '\\\\', $string);
1048 }
1049 return str_replace($char, '\\' . $char, $string);
1050 }
1051
1052 /**
1053 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1054 * Useful when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1055 *
1056 * @param string $str String to raw-url-encode with spaces preserved
1057 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1058 */
1059 public static function rawUrlEncodeJS($str)
1060 {
1061 return str_replace('%20', ' ', rawurlencode($str));
1062 }
1063
1064 /**
1065 * rawurlencode which preserves "/" chars
1066 * Useful when file paths should keep the "/" chars, but have all other special chars encoded.
1067 *
1068 * @param string $str Input string
1069 * @return string Output string
1070 */
1071 public static function rawUrlEncodeFP($str)
1072 {
1073 return str_replace('%2F', '/', rawurlencode($str));
1074 }
1075
1076 /**
1077 * Checking syntax of input email address
1078 *
1079 * http://tools.ietf.org/html/rfc3696
1080 * International characters are allowed in email. So the whole address needs
1081 * to be converted to punicode before passing it to filter_var(). We convert
1082 * the user- and domain part separately to increase the chance of hitting an
1083 * entry in self::$idnaStringCache.
1084 *
1085 * Also the @ sign may appear multiple times in an address. If not used as
1086 * a boundary marker between the user- and domain part, it must be escaped
1087 * with a backslash: \@. This mean we can not just explode on the @ sign and
1088 * expect to get just two parts. So we pop off the domain and then glue the
1089 * rest together again.
1090 *
1091 * @param string $email Input string to evaluate
1092 * @return bool Returns TRUE if the $email address (input string) is valid
1093 */
1094 public static function validEmail($email)
1095 {
1096 // Early return in case input is not a string
1097 if (!is_string($email)) {
1098 return false;
1099 }
1100 $atPosition = strrpos($email, '@');
1101 if (!$atPosition || $atPosition + 1 === strlen($email)) {
1102 // Return if no @ found or it is placed at the very beginning or end of the email
1103 return false;
1104 }
1105 $domain = substr($email, $atPosition + 1);
1106 $user = substr($email, 0, $atPosition);
1107 if (!preg_match('/^[a-z0-9.\\-]*$/i', $domain)) {
1108 $domain = self::idnaEncode($domain);
1109 }
1110 return filter_var($user . '@' . $domain, FILTER_VALIDATE_EMAIL) !== false;
1111 }
1112
1113 /**
1114 * Checks if current e-mail sending method does not accept recipient/sender name
1115 * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
1116 * program are known not to process such input correctly and they cause SMTP
1117 * errors. This function will return TRUE if current mail sending method has
1118 * problem with recipient name in recipient/sender argument for mail().
1119 *
1120 * @todo 4.3 should have additional configuration variable, which is combined
1121 * by || with the rest in this function.
1122 *
1123 * @return bool TRUE if mail() does not accept recipient name
1124 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1125 */
1126 public static function isBrokenEmailEnvironment()
1127 {
1128 self::logDeprecatedFunction();
1129 return TYPO3_OS == 'WIN' || false !== strpos(ini_get('sendmail_path'), 'mini_sendmail');
1130 }
1131
1132 /**
1133 * Changes from/to arguments for mail() function to work in any environment.
1134 *
1135 * @param string $address Address to adjust
1136 * @return string Adjusted address
1137 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1138 */
1139 public static function normalizeMailAddress($address)
1140 {
1141 self::logDeprecatedFunction();
1142 if (self::isBrokenEmailEnvironment() && false !== ($pos1 = strrpos($address, '<'))) {
1143 $pos2 = strpos($address, '>', $pos1);
1144 $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
1145 }
1146 return $address;
1147 }
1148
1149 /**
1150 * Formats a string for output between <textarea>-tags
1151 * All content outputted in a textarea form should be passed through this function
1152 * Not only is the content htmlspecialchar'ed on output but there is also a single newline added in the top. The newline is necessary because browsers will ignore the first newline after <textarea> if that is the first character. Therefore better set it!
1153 *
1154 * @param string $content Input string to be formatted.
1155 * @return string Formatted for <textarea>-tags
1156 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1157 */
1158 public static function formatForTextarea($content)
1159 {
1160 self::logDeprecatedFunction();
1161 return LF . htmlspecialchars($content);
1162 }
1163
1164 /**
1165 * Converts string to uppercase
1166 * The function converts all Latin characters (a-z, but no accents, etc) to
1167 * uppercase. It is safe for all supported character sets (incl. utf-8).
1168 * Unlike strtoupper() it does not honour the locale.
1169 *
1170 * @param string $str Input string
1171 * @return string Uppercase String
1172 */
1173 public static function strtoupper($str)
1174 {
1175 return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1176 }
1177
1178 /**
1179 * Converts string to lowercase
1180 * The function converts all Latin characters (A-Z, but no accents, etc) to
1181 * lowercase. It is safe for all supported character sets (incl. utf-8).
1182 * Unlike strtolower() it does not honour the locale.
1183 *
1184 * @param string $str Input string
1185 * @return string Lowercase String
1186 */
1187 public static function strtolower($str)
1188 {
1189 return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1190 }
1191
1192 /**
1193 * Returns a string of highly randomized bytes (over the full 8-bit range).
1194 *
1195 * Note: Returned values are not guaranteed to be crypto-safe,
1196 * most likely they are not, depending on the used retrieval method.
1197 *
1198 * @param int $bytesToReturn Number of characters (bytes) to return
1199 * @return string Random Bytes
1200 * @see http://bugs.php.net/bug.php?id=52523
1201 * @see http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/index.html
1202 */
1203 public static function generateRandomBytes($bytesToReturn)
1204 {
1205 // Cache 4k of the generated bytestream.
1206 static $bytes = '';
1207 $bytesToGenerate = max(4096, $bytesToReturn);
1208 // if we have not enough random bytes cached, we generate new ones
1209 if (!isset($bytes[$bytesToReturn - 1])) {
1210 if (TYPO3_OS === 'WIN') {
1211 // Openssl seems to be deadly slow on Windows, so try to use mcrypt
1212 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate);
1213 } else {
1214 // Try to use native PHP functions first, precedence has openssl
1215 $bytes .= self::generateRandomBytesOpenSsl($bytesToGenerate);
1216 if (!isset($bytes[$bytesToReturn - 1])) {
1217 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate);
1218 }
1219 // If openssl and mcrypt failed, try /dev/urandom
1220 if (!isset($bytes[$bytesToReturn - 1])) {
1221 $bytes .= self::generateRandomBytesUrandom($bytesToGenerate);
1222 }
1223 }
1224 // Fall back if other random byte generation failed until now
1225 if (!isset($bytes[$bytesToReturn - 1])) {
1226 $bytes .= self::generateRandomBytesFallback($bytesToReturn);
1227 }
1228 }
1229 // get first $bytesToReturn and remove it from the byte cache
1230 $output = substr($bytes, 0, $bytesToReturn);
1231 $bytes = substr($bytes, $bytesToReturn);
1232 return $output;
1233 }
1234
1235 /**
1236 * Generate random bytes using openssl if available
1237 *
1238 * @param string $bytesToGenerate
1239 * @return string
1240 */
1241 protected static function generateRandomBytesOpenSsl($bytesToGenerate)
1242 {
1243 if (!function_exists('openssl_random_pseudo_bytes')) {
1244 return '';
1245 }
1246 $isStrong = null;
1247 return (string)openssl_random_pseudo_bytes($bytesToGenerate, $isStrong);
1248 }
1249
1250 /**
1251 * Generate random bytes using mcrypt if available
1252 *
1253 * @param $bytesToGenerate
1254 * @return string
1255 */
1256 protected static function generateRandomBytesMcrypt($bytesToGenerate)
1257 {
1258 if (!function_exists('mcrypt_create_iv')) {
1259 return '';
1260 }
1261 return (string)(@mcrypt_create_iv($bytesToGenerate, MCRYPT_DEV_URANDOM));
1262 }
1263
1264 /**
1265 * Read random bytes from /dev/urandom if it is accessible
1266 *
1267 * @param $bytesToGenerate
1268 * @return string
1269 */
1270 protected static function generateRandomBytesUrandom($bytesToGenerate)
1271 {
1272 $bytes = '';
1273 $fh = @fopen('/dev/urandom', 'rb');
1274 if ($fh) {
1275 // PHP only performs buffered reads, so in reality it will always read
1276 // at least 4096 bytes. Thus, it costs nothing extra to read and store
1277 // that much so as to speed any additional invocations.
1278 $bytes = fread($fh, $bytesToGenerate);
1279 fclose($fh);
1280 }
1281 return $bytes;
1282 }
1283
1284 /**
1285 * Generate pseudo random bytes as last resort
1286 *
1287 * @param $bytesToReturn
1288 * @return string
1289 */
1290 protected static function generateRandomBytesFallback($bytesToReturn)
1291 {
1292 $bytes = '';
1293 // We initialize with somewhat random.
1294 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() % pow(10, 6), 10, 2) . microtime() . StringUtility::getUniqueId() . getmypid();
1295 while (!isset($bytes[$bytesToReturn - 1])) {
1296 $randomState = sha1(microtime() . mt_rand() . $randomState);
1297 $bytes .= sha1(mt_rand() . $randomState, true);
1298 }
1299 return $bytes;
1300 }
1301
1302 /**
1303 * Returns an ASCII string (punicode) representation of $value
1304 *
1305 * @param string $value
1306 * @return string An ASCII encoded (punicode) string
1307 */
1308 public static function idnaEncode($value)
1309 {
1310 if (isset(self::$idnaStringCache[$value])) {
1311 return self::$idnaStringCache[$value];
1312 } else {
1313 if (!self::$idnaConverter) {
1314 self::$idnaConverter = new \idna_convert(array('idn_version' => 2008));
1315 }
1316 self::$idnaStringCache[$value] = self::$idnaConverter->encode($value);
1317 return self::$idnaStringCache[$value];
1318 }
1319 }
1320
1321 /**
1322 * Returns a hex representation of a random byte string.
1323 *
1324 * @param int $count Number of hex characters to return
1325 * @return string Random Bytes
1326 */
1327 public static function getRandomHexString($count)
1328 {
1329 return substr(bin2hex(self::generateRandomBytes((int)(($count + 1) / 2))), 0, $count);
1330 }
1331
1332 /**
1333 * Returns a given string with underscores as UpperCamelCase.
1334 * Example: Converts blog_example to BlogExample
1335 *
1336 * @param string $string String to be converted to camel case
1337 * @return string UpperCamelCasedWord
1338 */
1339 public static function underscoredToUpperCamelCase($string)
1340 {
1341 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1342 return $upperCamelCase;
1343 }
1344
1345 /**
1346 * Returns a given string with underscores as lowerCamelCase.
1347 * Example: Converts minimal_value to minimalValue
1348 *
1349 * @param string $string String to be converted to camel case
1350 * @return string lowerCamelCasedWord
1351 */
1352 public static function underscoredToLowerCamelCase($string)
1353 {
1354 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1355 $lowerCamelCase = self::lcfirst($upperCamelCase);
1356 return $lowerCamelCase;
1357 }
1358
1359 /**
1360 * Returns a given CamelCasedString as an lowercase string with underscores.
1361 * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1362 *
1363 * @param string $string String to be converted to lowercase underscore
1364 * @return string lowercase_and_underscored_string
1365 */
1366 public static function camelCaseToLowerCaseUnderscored($string)
1367 {
1368 return self::strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string));
1369 }
1370
1371 /**
1372 * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1373 * Example: Converts "Hello World" to "hello World"
1374 *
1375 * @param string $string The string to be used to lowercase the first character
1376 * @return string The string with the first character as lowercase
1377 */
1378 public static function lcfirst($string)
1379 {
1380 return self::strtolower($string[0]) . substr($string, 1);
1381 }
1382
1383 /**
1384 * Checks if a given string is a Uniform Resource Locator (URL).
1385 *
1386 * On seriously malformed URLs, parse_url may return FALSE and emit an
1387 * E_WARNING.
1388 *
1389 * filter_var() requires a scheme to be present.
1390 *
1391 * http://www.faqs.org/rfcs/rfc2396.html
1392 * Scheme names consist of a sequence of characters beginning with a
1393 * lower case letter and followed by any combination of lower case letters,
1394 * digits, plus ("+"), period ("."), or hyphen ("-"). For resiliency,
1395 * programs interpreting URI should treat upper case letters as equivalent to
1396 * lower case in scheme names (e.g., allow "HTTP" as well as "http").
1397 * scheme = alpha *( alpha | digit | "+" | "-" | "." )
1398 *
1399 * Convert the domain part to punicode if it does not look like a regular
1400 * domain name. Only the domain part because RFC3986 specifies the the rest of
1401 * the url may not contain special characters:
1402 * http://tools.ietf.org/html/rfc3986#appendix-A
1403 *
1404 * @param string $url The URL to be validated
1405 * @return bool Whether the given URL is valid
1406 */
1407 public static function isValidUrl($url)
1408 {
1409 $parsedUrl = parse_url($url);
1410 if (!$parsedUrl || !isset($parsedUrl['scheme'])) {
1411 return false;
1412 }
1413 // HttpUtility::buildUrl() will always build urls with <scheme>://
1414 // our original $url might only contain <scheme>: (e.g. mail:)
1415 // so we convert that to the double-slashed version to ensure
1416 // our check against the $recomposedUrl is proper
1417 if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
1418 $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
1419 }
1420 $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
1421 if ($recomposedUrl !== $url) {
1422 // The parse_url() had to modify characters, so the URL is invalid
1423 return false;
1424 }
1425 if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
1426 $parsedUrl['host'] = self::idnaEncode($parsedUrl['host']);
1427 }
1428 return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false;
1429 }
1430
1431 /*************************
1432 *
1433 * ARRAY FUNCTIONS
1434 *
1435 *************************/
1436 /**
1437 * Check if an string item exists in an array.
1438 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1439 *
1440 * Comparison to PHP in_array():
1441 * -> $array = array(0, 1, 2, 3);
1442 * -> variant_a := \TYPO3\CMS\Core\Utility\ArrayUtility::inArray($array, $needle)
1443 * -> variant_b := in_array($needle, $array)
1444 * -> variant_c := in_array($needle, $array, TRUE)
1445 * +---------+-----------+-----------+-----------+
1446 * | $needle | variant_a | variant_b | variant_c |
1447 * +---------+-----------+-----------+-----------+
1448 * | '1a' | FALSE | TRUE | FALSE |
1449 * | '' | FALSE | TRUE | FALSE |
1450 * | '0' | TRUE | TRUE | FALSE |
1451 * | 0 | TRUE | TRUE | TRUE |
1452 * +---------+-----------+-----------+-----------+
1453 *
1454 * @param array $in_array One-dimensional array of items
1455 * @param string $item Item to check for
1456 * @return bool TRUE if $item is in the one-dimensional array $in_array
1457 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::inArray() instead
1458 */
1459 public static function inArray(array $in_array, $item)
1460 {
1461 static::logDeprecatedFunction();
1462 return ArrayUtility::inArray($in_array, $item);
1463 }
1464
1465 /**
1466 * Explodes a $string delimited by $delim and casts each item in the array to (int).
1467 * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
1468 *
1469 * @param string $delimiter Delimiter string to explode with
1470 * @param string $string The string to explode
1471 * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
1472 * @param int $limit If positive, the result will contain a maximum of limit elements,
1473 * @return array Exploded values, all converted to integers
1474 */
1475 public static function intExplode($delimiter, $string, $removeEmptyValues = false, $limit = 0)
1476 {
1477 $result = explode($delimiter, $string);
1478 foreach ($result as $key => &$value) {
1479 if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
1480 unset($result[$key]);
1481 } else {
1482 $value = (int)$value;
1483 }
1484 }
1485 unset($value);
1486 if ($limit !== 0) {
1487 if ($limit < 0) {
1488 $result = array_slice($result, 0, $limit);
1489 } elseif (count($result) > $limit) {
1490 $lastElements = array_slice($result, $limit - 1);
1491 $result = array_slice($result, 0, $limit - 1);
1492 $result[] = implode($delimiter, $lastElements);
1493 }
1494 }
1495 return $result;
1496 }
1497
1498 /**
1499 * Reverse explode which explodes the string counting from behind.
1500 *
1501 * Note: The delimiter has to given in the reverse order as
1502 * it is occurring within the string.
1503 *
1504 * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
1505 * ==> array('[my][words', 'here]')
1506 *
1507 * @param string $delimiter Delimiter string to explode with
1508 * @param string $string The string to explode
1509 * @param int $count Number of array entries
1510 * @return array Exploded values
1511 */
1512 public static function revExplode($delimiter, $string, $count = 0)
1513 {
1514 // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
1515 if ($count === 2) {
1516 $position = strrpos($string, strrev($delimiter));
1517 if ($position !== false) {
1518 return array(substr($string, 0, $position), substr($string, $position + strlen($delimiter)));
1519 } else {
1520 return array($string);
1521 }
1522 } elseif ($count <= 1) {
1523 return array($string);
1524 } else {
1525 $explodedValues = explode($delimiter, strrev($string), $count);
1526 $explodedValues = array_map('strrev', $explodedValues);
1527 return array_reverse($explodedValues);
1528 }
1529 }
1530
1531 /**
1532 * Explodes a string and trims all values for whitespace in the end.
1533 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1534 *
1535 * @param string $delim Delimiter string to explode with
1536 * @param string $string The string to explode
1537 * @param bool $removeEmptyValues If set, all empty values will be removed in output
1538 * @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with
1539 * the last element containing the rest of string. If the limit parameter is negative, all components
1540 * except the last -limit are returned.
1541 * @return array Exploded values
1542 */
1543 public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0)
1544 {
1545 $result = explode($delim, $string);
1546 if ($removeEmptyValues) {
1547 $temp = array();
1548 foreach ($result as $value) {
1549 if (trim($value) !== '') {
1550 $temp[] = $value;
1551 }
1552 }
1553 $result = $temp;
1554 }
1555 if ($limit > 0 && count($result) > $limit) {
1556 $lastElements = array_splice($result, $limit - 1);
1557 $result[] = implode($delim, $lastElements);
1558 } elseif ($limit < 0) {
1559 $result = array_slice($result, 0, $limit);
1560 }
1561 $result = array_map('trim', $result);
1562 return $result;
1563 }
1564
1565 /**
1566 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1567 *
1568 * @param array $array Array containing the values
1569 * @param string $cmpValue Value to search for and if found remove array entry where found.
1570 * @return array Output array with entries removed if search string is found
1571 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::removeArrayEntryByValue() instead
1572 */
1573 public static function removeArrayEntryByValue(array $array, $cmpValue)
1574 {
1575 static::logDeprecatedFunction();
1576 return ArrayUtility::removeArrayEntryByValue($array, $cmpValue);
1577 }
1578
1579 /**
1580 * Filters an array to reduce its elements to match the condition.
1581 * The values in $keepItems can be optionally evaluated by a custom callback function.
1582 *
1583 * Example (arguments used to call this function):
1584 * $array = array(
1585 * array('aa' => array('first', 'second'),
1586 * array('bb' => array('third', 'fourth'),
1587 * array('cc' => array('fifth', 'sixth'),
1588 * );
1589 * $keepItems = array('third');
1590 * $getValueFunc = function($value) { return $value[0]; }
1591 *
1592 * Returns:
1593 * array(
1594 * array('bb' => array('third', 'fourth'),
1595 * )
1596 *
1597 * @param array $array The initial array to be filtered/reduced
1598 * @param mixed $keepItems The items which are allowed/kept in the array - accepts array or csv string
1599 * @param string $getValueFunc (optional) Callback function used to get the value to keep
1600 * @return array The filtered/reduced array with the kept items
1601 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::keepItemsInArray() instead
1602 */
1603 public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = null)
1604 {
1605 static::logDeprecatedFunction();
1606 return ArrayUtility::keepItemsInArray($array, $keepItems, $getValueFunc);
1607 }
1608
1609 /**
1610 * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1611 *
1612 * @param string $name Name prefix for entries. Set to blank if you wish none.
1613 * @param array $theArray The (multidimensional) array to implode
1614 * @param string $str (keep blank)
1615 * @param bool $skipBlank If set, parameters which were blank strings would be removed.
1616 * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1617 * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1618 * @see explodeUrl2Array()
1619 */
1620 public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false)
1621 {
1622 foreach ($theArray as $Akey => $AVal) {
1623 $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1624 if (is_array($AVal)) {
1625 $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1626 } else {
1627 if (!$skipBlank || (string)$AVal !== '') {
1628 $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1629 }
1630 }
1631 }
1632 return $str;
1633 }
1634
1635 /**
1636 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1637 *
1638 * @param string $string GETvars string
1639 * @param bool $multidim If set, the string will be parsed into a multidimensional array if square brackets are used in variable names (using PHP function parse_str())
1640 * @return array 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!
1641 * @see implodeArrayForUrl()
1642 */
1643 public static function explodeUrl2Array($string, $multidim = false)
1644 {
1645 $output = array();
1646 if ($multidim) {
1647 parse_str($string, $output);
1648 } else {
1649 $p = explode('&', $string);
1650 foreach ($p as $v) {
1651 if ($v !== '') {
1652 list($pK, $pV) = explode('=', $v, 2);
1653 $output[rawurldecode($pK)] = rawurldecode($pV);
1654 }
1655 }
1656 }
1657 return $output;
1658 }
1659
1660 /**
1661 * Returns an array with selected keys from incoming data.
1662 * (Better read source code if you want to find out...)
1663 *
1664 * @param string $varList List of variable/key names
1665 * @param array $getArray Array from where to get values based on the keys in $varList
1666 * @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
1667 * @return array Output array with selected variables.
1668 */
1669 public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = true)
1670 {
1671 $keys = self::trimExplode(',', $varList, true);
1672 $outArr = array();
1673 foreach ($keys as $v) {
1674 if (isset($getArray[$v])) {
1675 $outArr[$v] = $getArray[$v];
1676 } elseif ($GPvarAlt) {
1677 $outArr[$v] = self::_GP($v);
1678 }
1679 }
1680 return $outArr;
1681 }
1682
1683 /**
1684 * AddSlash array
1685 * This function traverses a multidimensional array and adds slashes to the values.
1686 * NOTE that the input array is and argument by reference.!!
1687 * Twin-function to stripSlashesOnArray
1688 *
1689 * @param array $theArray Multidimensional input array, (REFERENCE!)
1690 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1691 * @return array
1692 */
1693 public static function addSlashesOnArray(array &$theArray)
1694 {
1695 self::logDeprecatedFunction();
1696 foreach ($theArray as &$value) {
1697 if (is_array($value)) {
1698 self::addSlashesOnArray($value);
1699 } else {
1700 $value = addslashes($value);
1701 }
1702 }
1703 unset($value);
1704 reset($theArray);
1705 }
1706
1707 /**
1708 * StripSlash array
1709 * This function traverses a multidimensional array and strips slashes to the values.
1710 * NOTE that the input array is and argument by reference.!!
1711 * Twin-function to addSlashesOnArray
1712 *
1713 * @param array $theArray Multidimensional input array, (REFERENCE!)
1714 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1715 * @return array
1716 */
1717 public static function stripSlashesOnArray(array &$theArray)
1718 {
1719 foreach ($theArray as &$value) {
1720 if (is_array($value)) {
1721 self::stripSlashesOnArray($value);
1722 } else {
1723 $value = stripslashes($value);
1724 }
1725 }
1726 unset($value);
1727 reset($theArray);
1728 }
1729
1730 /**
1731 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1732 *
1733 * @param array $arr Multidimensional input array
1734 * @param string $cmd "add" or "strip", depending on usage you wish.
1735 * @return array
1736 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1737 */
1738 public static function slashArray(array $arr, $cmd)
1739 {
1740 self::logDeprecatedFunction();
1741 if ($cmd == 'strip') {
1742 self::stripSlashesOnArray($arr);
1743 }
1744 if ($cmd == 'add') {
1745 self::addSlashesOnArray($arr);
1746 }
1747 return $arr;
1748 }
1749
1750 /**
1751 * Rename Array keys with a given mapping table
1752 *
1753 * @param array $array Array by reference which should be remapped
1754 * @param array $mappingTable Array with remap information, array/$oldKey => $newKey)
1755 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::remapArrayKeys() instead
1756 */
1757 public static function remapArrayKeys(&$array, $mappingTable)
1758 {
1759 static::logDeprecatedFunction();
1760 ArrayUtility::remapArrayKeys($array, $mappingTable);
1761 }
1762
1763 /**
1764 * An array_merge function where the keys are NOT renumbered as they happen to be with the real php-array_merge function. It is "binary safe" in the sense that integer keys are overridden as well.
1765 *
1766 * @param array $arr1 First array
1767 * @param array $arr2 Second array
1768 * @return array Merged result.
1769 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - native php '+' operator instead
1770 */
1771 public static function array_merge(array $arr1, array $arr2)
1772 {
1773 static::logDeprecatedFunction();
1774 return $arr2 + $arr1;
1775 }
1776
1777 /**
1778 * Filters keys off from first array that also exist in second array. Comparison is done by keys.
1779 * This method is a recursive version of php array_diff_assoc()
1780 *
1781 * @param array $array1 Source array
1782 * @param array $array2 Reduce source array by this array
1783 * @return array Source array reduced by keys also present in second array
1784 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::arrayDiffAssocRecursive() instead
1785 */
1786 public static function arrayDiffAssocRecursive(array $array1, array $array2)
1787 {
1788 static::logDeprecatedFunction();
1789 return ArrayUtility::arrayDiffAssocRecursive($array1, $array2);
1790 }
1791
1792 /**
1793 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1794 *
1795 * @param array $row Input array of values
1796 * @param string $delim Delimited, default is comma
1797 * @param string $quote Quote-character to wrap around the values.
1798 * @return string A single line of CSV
1799 */
1800 public static function csvValues(array $row, $delim = ',', $quote = '"')
1801 {
1802 $out = array();
1803 foreach ($row as $value) {
1804 $out[] = str_replace($quote, $quote . $quote, $value);
1805 }
1806 $str = $quote . implode(($quote . $delim . $quote), $out) . $quote;
1807 return $str;
1808 }
1809
1810 /**
1811 * Removes dots "." from end of a key identifier of TypoScript styled array.
1812 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1813 *
1814 * @param array $ts TypoScript configuration array
1815 * @return array TypoScript configuration array without dots at the end of all keys
1816 */
1817 public static function removeDotsFromTS(array $ts)
1818 {
1819 $out = array();
1820 foreach ($ts as $key => $value) {
1821 if (is_array($value)) {
1822 $key = rtrim($key, '.');
1823 $out[$key] = self::removeDotsFromTS($value);
1824 } else {
1825 $out[$key] = $value;
1826 }
1827 }
1828 return $out;
1829 }
1830
1831 /**
1832 * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1833 *
1834 * @param array $array array to be sorted recursively, passed by reference
1835 * @return bool TRUE if param is an array
1836 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::naturalKeySortRecursive() instead
1837 */
1838 public static function naturalKeySortRecursive(&$array)
1839 {
1840 static::logDeprecatedFunction();
1841 return ArrayUtility::naturalKeySortRecursive($array);
1842 }
1843
1844 /*************************
1845 *
1846 * HTML/XML PROCESSING
1847 *
1848 *************************/
1849 /**
1850 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1851 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1852 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1853 *
1854 * @param string $tag HTML-tag string (or attributes only)
1855 * @return array Array with the attribute values.
1856 */
1857 public static function get_tag_attributes($tag)
1858 {
1859 $components = self::split_tag_attributes($tag);
1860 // Attribute name is stored here
1861 $name = '';
1862 $valuemode = false;
1863 $attributes = array();
1864 foreach ($components as $key => $val) {
1865 // 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
1866 if ($val != '=') {
1867 if ($valuemode) {
1868 if ($name) {
1869 $attributes[$name] = $val;
1870 $name = '';
1871 }
1872 } else {
1873 if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val))) {
1874 $attributes[$key] = '';
1875 $name = $key;
1876 }
1877 }
1878 $valuemode = false;
1879 } else {
1880 $valuemode = true;
1881 }
1882 }
1883 return $attributes;
1884 }
1885
1886 /**
1887 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1888 * Removes tag-name if found
1889 *
1890 * @param string $tag HTML-tag string (or attributes only)
1891 * @return array Array with the attribute values.
1892 */
1893 public static function split_tag_attributes($tag)
1894 {
1895 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
1896 // Removes any > in the end of the string
1897 $tag_tmp = trim(rtrim($tag_tmp, '>'));
1898 $value = array();
1899 // Compared with empty string instead , 030102
1900 while ($tag_tmp !== '') {
1901 $firstChar = $tag_tmp[0];
1902 if ($firstChar === '"' || $firstChar === '\'') {
1903 $reg = explode($firstChar, $tag_tmp, 3);
1904 $value[] = $reg[1];
1905 $tag_tmp = trim($reg[2]);
1906 } elseif ($firstChar === '=') {
1907 $value[] = '=';
1908 // Removes = chars.
1909 $tag_tmp = trim(substr($tag_tmp, 1));
1910 } else {
1911 // There are '' around the value. We look for the next ' ' or '>'
1912 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1913 $value[] = trim($reg[0]);
1914 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
1915 }
1916 }
1917 reset($value);
1918 return $value;
1919 }
1920
1921 /**
1922 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1923 *
1924 * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1925 * @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!
1926 * @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1927 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1928 */
1929 public static function implodeAttributes(array $arr, $xhtmlSafe = false, $dontOmitBlankAttribs = false)
1930 {
1931 if ($xhtmlSafe) {
1932 $newArr = array();
1933 foreach ($arr as $p => $v) {
1934 if (!isset($newArr[strtolower($p)])) {
1935 $newArr[strtolower($p)] = htmlspecialchars($v);
1936 }
1937 }
1938 $arr = $newArr;
1939 }
1940 $list = array();
1941 foreach ($arr as $p => $v) {
1942 if ((string)$v !== '' || $dontOmitBlankAttribs) {
1943 $list[] = $p . '="' . $v . '"';
1944 }
1945 }
1946 return implode(' ', $list);
1947 }
1948
1949 /**
1950 * Wraps JavaScript code XHTML ready with <script>-tags
1951 * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1952 * This is nice for indenting JS code with PHP code on the same level.
1953 *
1954 * @param string $string JavaScript code
1955 * @param bool $linebreak Wrap script element in line breaks? Default is TRUE.
1956 * @return string The wrapped JS code, ready to put into a XHTML page
1957 */
1958 public static function wrapJS($string, $linebreak = true)
1959 {
1960 if (trim($string)) {
1961 // <script wrapped in nl?
1962 $cr = $linebreak ? LF : '';
1963 // remove nl from the beginning
1964 $string = preg_replace('/^\\n+/', '', $string);
1965 // re-ident to one tab using the first line as reference
1966 $match = array();
1967 if (preg_match('/^(\\t+)/', $string, $match)) {
1968 $string = str_replace($match[1], TAB, $string);
1969 }
1970 $string = $cr . '<script type="text/javascript">
1971 /*<![CDATA[*/
1972 ' . $string . '
1973 /*]]>*/
1974 </script>' . $cr;
1975 }
1976 return trim($string);
1977 }
1978
1979 /**
1980 * Parses XML input into a PHP array with associative keys
1981 *
1982 * @param string $string XML data input
1983 * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1984 * @param array $parserOptions Options that will be passed to PHP's xml_parser_set_option()
1985 * @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.
1986 */
1987 public static function xml2tree($string, $depth = 999, $parserOptions = array())
1988 {
1989 // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1990 $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1991 $parser = xml_parser_create();
1992 $vals = array();
1993 $index = array();
1994 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1995 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1996 foreach ($parserOptions as $option => $value) {
1997 xml_parser_set_option($parser, $option, $value);
1998 }
1999 xml_parse_into_struct($parser, $string, $vals, $index);
2000 libxml_disable_entity_loader($previousValueOfEntityLoader);
2001 if (xml_get_error_code($parser)) {
2002 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2003 }
2004 xml_parser_free($parser);
2005 $stack = array(array());
2006 $stacktop = 0;
2007 $startPoint = 0;
2008 $tagi = array();
2009 foreach ($vals as $key => $val) {
2010 $type = $val['type'];
2011 // open tag:
2012 if ($type == 'open' || $type == 'complete') {
2013 $stack[$stacktop++] = $tagi;
2014 if ($depth == $stacktop) {
2015 $startPoint = $key;
2016 }
2017 $tagi = array('tag' => $val['tag']);
2018 if (isset($val['attributes'])) {
2019 $tagi['attrs'] = $val['attributes'];
2020 }
2021 if (isset($val['value'])) {
2022 $tagi['values'][] = $val['value'];
2023 }
2024 }
2025 // finish tag:
2026 if ($type == 'complete' || $type == 'close') {
2027 $oldtagi = $tagi;
2028 $tagi = $stack[--$stacktop];
2029 $oldtag = $oldtagi['tag'];
2030 unset($oldtagi['tag']);
2031 if ($depth == $stacktop + 1) {
2032 if ($key - $startPoint > 0) {
2033 $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
2034 $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
2035 } else {
2036 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
2037 }
2038 }
2039 $tagi['ch'][$oldtag][] = $oldtagi;
2040 unset($oldtagi);
2041 }
2042 // cdata
2043 if ($type == 'cdata') {
2044 $tagi['values'][] = $val['value'];
2045 }
2046 }
2047 return $tagi['ch'];
2048 }
2049
2050 /**
2051 * Turns PHP array into XML. See array2xml()
2052 *
2053 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2054 * @param string $docTag Alternative document tag. Default is "phparray".
2055 * @param array $options Options for the compilation. See array2xml() for description.
2056 * @param string $charset Forced charset to prologue
2057 * @return string An XML string made from the input content in the array.
2058 * @see xml2array(),array2xml()
2059 */
2060 public static function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '')
2061 {
2062 // Set default charset unless explicitly specified
2063 $charset = $charset ?: 'utf-8';
2064 // Return XML:
2065 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF . self::array2xml($array, '', 0, $docTag, 0, $options);
2066 }
2067
2068 /**
2069 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2070 *
2071 * Converts a PHP array into an XML string.
2072 * The XML output is optimized for readability since associative keys are used as tag names.
2073 * 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.
2074 * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
2075 * 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
2076 * 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.
2077 * 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 suchs 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!
2078 * 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...
2079 *
2080 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2081 * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
2082 * @param int $level Current recursion level. Don't change, stay at zero!
2083 * @param string $docTag Alternative document tag. Default is "phparray".
2084 * @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
2085 * @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')
2086 * @param array $stackData Stack data. Don't touch.
2087 * @return string An XML string made from the input content in the array.
2088 * @see xml2array()
2089 */
2090 public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array())
2091 {
2092 // 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
2093 $binaryChars = chr(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);
2094 // Set indenting mode:
2095 $indentChar = $spaceInd ? ' ' : TAB;
2096 $indentN = $spaceInd > 0 ? $spaceInd : 1;
2097 $nl = $spaceInd >= 0 ? LF : '';
2098 // Init output variable:
2099 $output = '';
2100 // Traverse the input array
2101 foreach ($array as $k => $v) {
2102 $attr = '';
2103 $tagName = $k;
2104 // Construct the tag name.
2105 // Use tag based on grand-parent + parent tag name
2106 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
2107 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2108 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
2109 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) {
2110 // Use tag based on parent tag name + if current tag is numeric
2111 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2112 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
2113 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
2114 // Use tag based on parent tag name + current tag
2115 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2116 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
2117 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) {
2118 // Use tag based on parent tag name:
2119 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2120 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
2121 } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) {
2122 // If integer...;
2123 if ($options['useNindex']) {
2124 // If numeric key, prefix "n"
2125 $tagName = 'n' . $tagName;
2126 } else {
2127 // Use special tag for num. keys:
2128 $attr .= ' index="' . $tagName . '"';
2129 $tagName = $options['useIndexTagForNum'] ?: 'numIndex';
2130 }
2131 } elseif ($options['useIndexTagForAssoc']) {
2132 // Use tag for all associative keys:
2133 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2134 $tagName = $options['useIndexTagForAssoc'];
2135 }
2136 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2137 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2138 // If the value is an array then we will call this function recursively:
2139 if (is_array($v)) {
2140 // Sub elements:
2141 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2142 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2143 $clearStackPath = $subOptions['clearStackPath'];
2144 } else {
2145 $subOptions = $options;
2146 $clearStackPath = false;
2147 }
2148 if (empty($v)) {
2149 $content = '';
2150 } else {
2151 $content = $nl . self::array2xml($v, $NSprefix, ($level + 1), '', $spaceInd, $subOptions, array(
2152 'parentTagName' => $tagName,
2153 'grandParentTagName' => $stackData['parentTagName'],
2154 'path' => ($clearStackPath ? '' : $stackData['path'] . '/' . $tagName)
2155 )) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
2156 }
2157 // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2158 if ((int)$options['disableTypeAttrib'] != 2) {
2159 $attr .= ' type="array"';
2160 }
2161 } else {
2162 // Just a value:
2163 // Look for binary chars:
2164 $vLen = strlen($v);
2165 // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
2166 if ($vLen && strcspn($v, $binaryChars) != $vLen) {
2167 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2168 $content = $nl . chunk_split(base64_encode($v));
2169 $attr .= ' base64="1"';
2170 } else {
2171 // Otherwise, just htmlspecialchar the stuff:
2172 $content = htmlspecialchars($v);
2173 $dType = gettype($v);
2174 if ($dType == 'string') {
2175 if ($options['useCDATA'] && $content != $v) {
2176 $content = '<![CDATA[' . $v . ']]>';
2177 }
2178 } elseif (!$options['disableTypeAttrib']) {
2179 $attr .= ' type="' . $dType . '"';
2180 }
2181 }
2182 }
2183 if ((string)$tagName !== '') {
2184 // Add the element to the output string:
2185 $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
2186 . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2187 }
2188 }
2189 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2190 if (!$level) {
2191 $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
2192 }
2193 return $output;
2194 }
2195
2196 /**
2197 * Converts an XML string to a PHP array.
2198 * This is the reverse function of array2xml()
2199 * This is a wrapper for xml2arrayProcess that adds a two-level cache
2200 *
2201 * @param string $string XML content to convert into an array
2202 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2203 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2204 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2205 * @see array2xml(),xml2arrayProcess()
2206 */
2207 public static function xml2array($string, $NSprefix = '', $reportDocTag = false)
2208 {
2209 static $firstLevelCache = array();
2210 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
2211 // Look up in first level cache
2212 if (!empty($firstLevelCache[$identifier])) {
2213 $array = $firstLevelCache[$identifier];
2214 } else {
2215 // Look up in second level cache
2216 // @todo: Is this cache really required? It basically substitutes a little cpu work with a db query?
2217 $array = PageRepository::getHash($identifier, 0);
2218 if (!is_array($array)) {
2219 $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2220 PageRepository::storeHash($identifier, $array, 'ident_xml2array');
2221 }
2222 // Store content in first level cache
2223 $firstLevelCache[$identifier] = $array;
2224 }
2225 return $array;
2226 }
2227
2228 /**
2229 * Converts an XML string to a PHP array.
2230 * This is the reverse function of array2xml()
2231 *
2232 * @param string $string XML content to convert into an array
2233 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2234 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2235 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2236 * @see array2xml()
2237 */
2238 protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = false)
2239 {
2240 // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
2241 $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
2242 // Create parser:
2243 $parser = xml_parser_create();
2244 $vals = array();
2245 $index = array();
2246 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2247 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2248 // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2249 $match = array();
2250 preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2251 $theCharset = $match[1] ?: 'utf-8';
2252 // us-ascii / utf-8 / iso-8859-1
2253 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
2254 // Parse content:
2255 xml_parse_into_struct($parser, $string, $vals, $index);
2256 libxml_disable_entity_loader($previousValueOfEntityLoader);
2257 // If error, return error message:
2258 if (xml_get_error_code($parser)) {
2259 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2260 }
2261 xml_parser_free($parser);
2262 // Init vars:
2263 $stack = array(array());
2264 $stacktop = 0;
2265 $current = array();
2266 $tagName = '';
2267 $documentTag = '';
2268 // Traverse the parsed XML structure:
2269 foreach ($vals as $key => $val) {
2270 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2271 $tagName = $val['tag'];
2272 if (!$documentTag) {
2273 $documentTag = $tagName;
2274 }
2275 // Test for name space:
2276 $tagName = $NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix ? substr($tagName, strlen($NSprefix)) : $tagName;
2277 // Test for numeric tag, encoded on the form "nXXX":
2278 $testNtag = substr($tagName, 1);
2279 // Closing tag.
2280 $tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName;
2281 // Test for alternative index value:
2282 if ((string)$val['attributes']['index'] !== '') {
2283 $tagName = $val['attributes']['index'];
2284 }
2285 // Setting tag-values, manage stack:
2286 switch ($val['type']) {
2287 case 'open':
2288 // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2289 // Setting blank place holder
2290 $current[$tagName] = array();
2291 $stack[$stacktop++] = $current;
2292 $current = array();
2293 break;
2294 case 'close':
2295 // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2296 $oldCurrent = $current;
2297 $current = $stack[--$stacktop];
2298 // Going to the end of array to get placeholder key, key($current), and fill in array next:
2299 end($current);
2300 $current[key($current)] = $oldCurrent;
2301 unset($oldCurrent);
2302 break;
2303 case 'complete':
2304 // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2305 if ($val['attributes']['base64']) {
2306 $current[$tagName] = base64_decode($val['value']);
2307 } else {
2308 // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2309 $current[$tagName] = (string)$val['value'];
2310 // Cast type:
2311 switch ((string)$val['attributes']['type']) {
2312 case 'integer':
2313 $current[$tagName] = (int)$current[$tagName];
2314 break;
2315 case 'double':
2316 $current[$tagName] = (double) $current[$tagName];
2317 break;
2318 case 'boolean':
2319 $current[$tagName] = (bool)$current[$tagName];
2320 break;
2321 case 'NULL':
2322 $current[$tagName] = null;
2323 break;
2324 case 'array':
2325 // 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...
2326 $current[$tagName] = array();
2327 break;
2328 }
2329 }
2330 break;
2331 }
2332 }
2333 if ($reportDocTag) {
2334 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2335 }
2336 // Finally return the content of the document tag.
2337 return $current[$tagName];
2338 }
2339
2340 /**
2341 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2342 *
2343 * @param array $vals An array of XML parts, see xml2tree
2344 * @return string Re-compiled XML data.
2345 */
2346 public static function xmlRecompileFromStructValArray(array $vals)
2347 {
2348 $XMLcontent = '';
2349 foreach ($vals as $val) {
2350 $type = $val['type'];
2351 // Open tag:
2352 if ($type == 'open' || $type == 'complete') {
2353 $XMLcontent .= '<' . $val['tag'];
2354 if (isset($val['attributes'])) {
2355 foreach ($val['attributes'] as $k => $v) {
2356 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2357 }
2358 }
2359 if ($type == 'complete') {
2360 if (isset($val['value'])) {
2361 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2362 } else {
2363 $XMLcontent .= '/>';
2364 }
2365 } else {
2366 $XMLcontent .= '>';
2367 }
2368 if ($type == 'open' && isset($val['value'])) {
2369 $XMLcontent .= htmlspecialchars($val['value']);
2370 }
2371 }
2372 // Finish tag:
2373 if ($type == 'close') {
2374 $XMLcontent .= '</' . $val['tag'] . '>';
2375 }
2376 // Cdata
2377 if ($type == 'cdata') {
2378 $XMLcontent .= htmlspecialchars($val['value']);
2379 }
2380 }
2381 return $XMLcontent;
2382 }
2383
2384 /**
2385 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2386 *
2387 * @param string $xmlData XML data
2388 * @return array Attributes of the xml prologue (header)
2389 */
2390 public static function xmlGetHeaderAttribs($xmlData)
2391 {
2392 $match = array();
2393 if (preg_match('/^\\s*<\\?xml([^>]*)\\?\\>/', $xmlData, $match)) {
2394 return self::get_tag_attributes($match[1]);
2395 }
2396 }
2397
2398 /**
2399 * Minifies JavaScript
2400 *
2401 * @param string $script Script to minify
2402 * @param string $error Error message (if any)
2403 * @return string Minified script or source string if error happened
2404 */
2405 public static function minifyJavaScript($script, &$error = '')
2406 {
2407 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'])) {
2408 $fakeThis = false;
2409 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] as $hookMethod) {
2410 try {
2411 $parameters = array('script' => $script);
2412 $script = static::callUserFunction($hookMethod, $parameters, $fakeThis);
2413 } catch (\Exception $e) {
2414 $errorMessage = 'Error minifying java script: ' . $e->getMessage();
2415 $error .= $errorMessage;
2416 static::devLog($errorMessage, \TYPO3\CMS\Core\Utility\GeneralUtility::class, 2, array(
2417 'JavaScript' => $script,
2418 'Stack trace' => $e->getTrace(),
2419 'hook' => $hookMethod
2420 ));
2421 }
2422 }
2423 }
2424 return $script;
2425 }
2426
2427 /*************************
2428 *
2429 * FILES FUNCTIONS
2430 *
2431 *************************/
2432 /**
2433 * Reads the file or url $url and returns the content
2434 * If you are having trouble with proxys when reading URLs you can configure your way out of that with settings like $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] etc.
2435 *
2436 * @param string $url File/URL to read
2437 * @param int $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2438 * @param array $requestHeaders HTTP headers to be used in the request
2439 * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2440 * @return mixed The content from the resource given as input. FALSE if an error has occurred.
2441 */
2442 public static function getUrl($url, $includeHeader = 0, $requestHeaders = false, &$report = null)
2443 {
2444 $content = false;
2445 if (isset($report)) {
2446 $report['error'] = 0;
2447 $report['message'] = '';
2448 }
2449 // Use cURL for: http, https, ftp, ftps, sftp and scp
2450 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2451 if (isset($report)) {
2452 $report['lib'] = 'cURL';
2453 }
2454 // External URL without error checking.
2455 if (!function_exists('curl_init') || !($ch = curl_init())) {
2456 if (isset($report)) {
2457 $report['error'] = -1;
2458 $report['message'] = 'Couldn\'t initialize cURL.';
2459 }
2460 return false;
2461 }
2462
2463 $followLocationSucceeded = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
2464
2465 $curlIncludeHeaders = !$followLocationSucceeded || $includeHeader;
2466 curl_setopt($ch, CURLOPT_URL, $url);
2467 curl_setopt($ch, CURLOPT_HEADER, $curlIncludeHeaders ? 1 : 0);
2468 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
2469 curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
2470 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2471 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
2472 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout']));
2473
2474 if (is_array($requestHeaders)) {
2475 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
2476 }
2477 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2478 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2479 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2480 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (bool)$GLOBALS['TYPO3_CONF_VARS']['HTTP']['ssl_verify_host']);
2481 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (bool)$GLOBALS['TYPO3_CONF_VARS']['HTTP']['ssl_verify_peer']);
2482 if ($GLOBALS['TYPO3_CONF_VARS']['HTTP']['ssl_verify_peer']) {
2483 if ($GLOBALS['TYPO3_CONF_VARS']['HTTP']['ssl_cafile']) {
2484 curl_setopt($ch, CURLOPT_CAINFO, $GLOBALS['TYPO3_CONF_VARS']['HTTP']['ssl_cafile']);
2485 }
2486 if ($GLOBALS['TYPO3_CONF_VARS']['HTTP']['ssl_capath']) {
2487 curl_setopt($ch, CURLOPT_CAPATH, $GLOBALS['TYPO3_CONF_VARS']['HTTP']['ssl_capath']);
2488 }
2489 }
2490 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyNTLM']) {
2491 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
2492 }
2493 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2494 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2495 }
2496 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2497 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2498 }
2499 }
2500 $content = curl_exec($ch);
2501 $curlInfo = curl_getinfo($ch);
2502
2503 // Remove additional proxy header block, when proxy is used for https request and CURL_HEADER is enabled.
2504 // Most HTTPS proxies add a second header before the actual server headers in their response, as a
2505 // response to the CONNECT message sent by the client to the proxy. cURL does not strip this since 2005,
2506 // so there are two headers arriving here, of which the first is not of interest to us—therefore, we can
2507 // safely strip it.
2508 // Detecting two linebreaks followed by a "HTTP/" (as done here) is the only reliable way to detect the
2509 // proxy headers, as the relevant RFCs do not specify the exact status code (it might be any of 2xx) or
2510 // the status message. Therefore, we check if there is a second HTTP headers block and then strip the
2511 // first one.
2512 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']
2513 && $curlIncludeHeaders
2514 && preg_match('/^https:/', $url)
2515 && strpos($content, "\r\n\r\nHTTP/") !== false
2516 ) {
2517 $content = self::stripHttpHeaders($content);
2518 }
2519
2520 if (!$followLocationSucceeded) {
2521 // Check if we need to do redirects
2522 if ($curlInfo['http_code'] >= 300 && $curlInfo['http_code'] < 400) {
2523 $locationUrl = $curlInfo['redirect_url'];
2524 if (!$locationUrl) {
2525 // Some curllib versions do not return redirect_url. Examine headers.
2526 $locationUrl = self::getRedirectUrlFromHttpHeaders($content);
2527 }
2528 if ($locationUrl) {
2529 $content = self::getUrl($locationUrl, $includeHeader, $requestHeaders, $report);
2530 $followLocationSucceeded = true;
2531 } else {
2532 // Failure: we got a redirection status code but not the URL to redirect to.
2533 $content = false;
2534 }
2535 }
2536 if ($content && !$includeHeader) {
2537 $content = self::stripHttpHeaders($content);
2538 }
2539 }
2540
2541 if (isset($report)) {
2542 if (!$followLocationSucceeded && $curlInfo['http_code'] >= 300 && $curlInfo['http_code'] < 400) {
2543 $report['http_code'] = $curlInfo['http_code'];
2544 $report['content_type'] = $curlInfo['content_type'];
2545 $report['error'] = CURLE_GOT_NOTHING;
2546 $report['message'] = 'Expected "Location" header but got nothing.';
2547 } elseif ($content === false) {
2548 $report['error'] = curl_errno($ch);
2549 $report['message'] = curl_error($ch);
2550 } elseif ($includeHeader) {
2551 // Set only for $includeHeader to work exactly like PHP variant
2552 $report['http_code'] = $curlInfo['http_code'];
2553 $report['content_type'] = $curlInfo['content_type'];
2554 }
2555 }
2556 curl_close($ch);
2557 } elseif ($includeHeader) {
2558 if (isset($report)) {
2559 $report['lib'] = 'socket';
2560 }
2561 $parsedURL = parse_url($url);
2562 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2563 if (isset($report)) {
2564 $report['error'] = -1;
2565 $report['message'] = 'Reading headers is not allowed for this protocol.';
2566 }
2567 return false;
2568 }
2569 $port = (int)$parsedURL['port'];
2570 if ($port < 1) {
2571 if ($parsedURL['scheme'] == 'http') {
2572 $port = $port > 0 ? $port : 80;
2573 $scheme = '';
2574 } else {
2575 $port = $port > 0 ? $port : 443;
2576 $scheme = 'ssl://';
2577 }
2578 }
2579 $errno = 0;
2580 $fp = @fsockopen(($scheme . $parsedURL['host']), $port, $errno, $errstr, 2.0);
2581 if (!$fp || $errno > 0) {
2582 if (isset($report)) {
2583 $report['error'] = $errno ?: -1;
2584 $report['message'] = $errno ? ($errstr ?: 'Socket error.') : 'Socket initialization error.';
2585 }
2586 return false;
2587 }
2588 $method = $includeHeader == 2 ? 'HEAD' : 'GET';
2589 $msg = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/')
2590 . ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') . ' HTTP/1.0' . CRLF
2591 . 'Host: ' . $parsedURL['host'] . CRLF
2592 . 'Connection: close' . CRLF;
2593 if (is_array($requestHeaders)) {
2594 $msg .= implode(CRLF, $requestHeaders) . CRLF;
2595 }
2596 $msg .= CRLF;
2597 fputs($fp, $msg);
2598 while (!feof($fp)) {
2599 $line = fgets($fp, 2048);
2600 if (isset($report)) {
2601 if (preg_match('|^HTTP/\\d\\.\\d +(\\d+)|', $line, $status)) {
2602 $report['http_code'] = $status[1];
2603 } elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2604 $report['content_type'] = $type[1];
2605 }
2606 }
2607 $content .= $line;
2608 if (trim($line) === '') {
2609 // Stop at the first empty line (= end of header)
2610 break;
2611 }
2612 }
2613 if ($includeHeader != 2) {
2614 $content .= stream_get_contents($fp);
2615 }
2616 fclose($fp);
2617 } elseif (is_array($requestHeaders)) {
2618 if (isset($report)) {
2619 $report['lib'] = 'file/context';
2620 }
2621 $parsedURL = parse_url($url);
2622 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2623 if (isset($report)) {
2624 $report['error'] = -1;
2625 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2626 }
2627 return false;
2628 }
2629 $ctx = stream_context_get_default(array(
2630 'http' => array(
2631 'header' => implode(CRLF, $requestHeaders)
2632 )
2633 ));
2634 $content = @file_get_contents($url, false, $ctx);
2635 if ($content === false && isset($report)) {
2636 $report['error'] = -1;
2637 $report['message'] = 'Couldn\'t get URL: ' . (isset($http_response_header) ? implode(LF, $http_response_header) : $url);
2638 }
2639 } else {
2640 if (isset($report)) {
2641 $report['lib'] = 'file';
2642 }
2643 $content = @file_get_contents($url);
2644 if ($content === false && isset($report)) {
2645 $report['error'] = -1;
2646 $report['message'] = 'Couldn\'t get URL: ' . (isset($http_response_header) ? implode(LF, $http_response_header) : $url);
2647 }
2648 }
2649 return $content;
2650 }
2651
2652 /**
2653 * Parses HTTP headers and returns the content of the "Location" header
2654 * or the empty string if no such header found.
2655 *
2656 * @param string $content
2657 * @return string
2658 */
2659 protected static function getRedirectUrlFromHttpHeaders($content)
2660 {
2661 $result = '';
2662 $headers = explode("\r\n", $content);
2663 foreach ($headers as $header) {
2664 if ($header == '') {
2665 break;
2666 }
2667 if (preg_match('/^\s*Location\s*:/i', $header)) {
2668 list(, $result) = self::trimExplode(':', $header, false, 2);
2669 if ($result) {
2670 $result = self::locationHeaderUrl($result);
2671 }
2672 break;
2673 }
2674 }
2675 return $result;
2676 }
2677
2678 /**
2679 * Strips HTTP headers from the content.
2680 *
2681 * @param string $content
2682 * @return string
2683 */
2684 protected static function stripHttpHeaders($content)
2685 {
2686 $headersEndPos = strpos($content, "\r\n\r\n");
2687 if ($headersEndPos) {
2688 $content = substr($content, $headersEndPos + 4);
2689 }
2690 return $content;
2691 }
2692
2693 /**
2694 * Writes $content to the file $file
2695 *
2696 * @param string $file Filepath to write to
2697 * @param string $content Content to write
2698 * @param bool $changePermissions If TRUE, permissions are forced to be set
2699 * @return bool TRUE if the file was successfully opened and written to.
2700 */
2701 public static function writeFile($file, $content, $changePermissions = false)
2702 {
2703 if (!@is_file($file)) {
2704 $changePermissions = true;
2705 }
2706 if ($fd = fopen($file, 'wb')) {
2707 $res = fwrite($fd, $content);
2708 fclose($fd);
2709 if ($res === false) {
2710 return false;
2711 }
2712 // Change the permissions only if the file has just been created
2713 if ($changePermissions) {
2714 static::fixPermissions($file);
2715 }
2716 return true;
2717 }
2718 return false;
2719 }
2720
2721 /**
2722 * Sets the file system mode and group ownership of a file or a folder.
2723 *
2724 * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2725 * @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2726 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2727 */
2728 public static function fixPermissions($path, $recursive = false)
2729 {
2730 if (TYPO3_OS === 'WIN') {
2731 return true;
2732 }
2733 $result = false;
2734 // Make path absolute
2735 if (!static::isAbsPath($path)) {
2736 $path = static::getFileAbsFileName($path, false);
2737 }
2738 if (static::isAllowedAbsPath($path)) {
2739 if (@is_file($path)) {
2740 $targetPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'])
2741 ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask']
2742 : '0644';
2743 } elseif (@is_dir($path)) {
2744 $targetPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'])
2745 ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']
2746 : '0755';
2747 }
2748 if (!empty($targetPermissions)) {
2749 // make sure it's always 4 digits
2750 $targetPermissions = str_pad($targetPermissions, 4, 0, STR_PAD_LEFT);
2751 $targetPermissions = octdec($targetPermissions);
2752 // "@" is there because file is not necessarily OWNED by the user
2753 $result = @chmod($path, $targetPermissions);
2754 }
2755 // Set createGroup if not empty
2756 if (
2757 isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'])
2758 && $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] !== ''
2759 ) {
2760 // "@" is there because file is not necessarily OWNED by the user
2761 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']);
2762 $result = $changeGroupResult ? $result : false;
2763 }
2764 // Call recursive if recursive flag if set and $path is directory
2765 if ($recursive && @is_dir($path)) {
2766 $handle = opendir($path);
2767 while (($file = readdir($handle)) !== false) {
2768 $recursionResult = null;
2769 if ($file !== '.' && $file !== '..') {
2770 if (@is_file(($path . '/' . $file))) {
2771 $recursionResult = static::fixPermissions($path . '/' . $file);
2772 } elseif (@is_dir(($path . '/' . $file))) {
2773 $recursionResult = static::fixPermissions($path . '/' . $file, true);
2774 }
2775 if (isset($recursionResult) && !$recursionResult) {
2776 $result = false;
2777 }
2778 }
2779 }
2780 closedir($handle);
2781 }
2782 }
2783 return $result;
2784 }
2785
2786 /**
2787 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2788 * Accepts an additional subdirectory in the file path!
2789 *
2790 * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2791 * @param string $content Content string to write
2792 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2793 */
2794 public static function writeFileToTypo3tempDir($filepath, $content)
2795 {
2796 if (!defined('PATH_site')) {
2797 return 'PATH_site constant was NOT defined!';
2798 }
2799
2800 // Parse filepath into directory and basename:
2801 $fI = pathinfo($filepath);
2802 $fI['dirname'] .= '/';
2803 // Check parts:
2804 if (!static::validPathStr($filepath) || !$fI['basename'] || strlen($fI['basename']) >= 60) {
2805 return 'Input filepath "' . $filepath . '" was generally invalid!';
2806 }
2807 // Setting main temporary directory name (standard)
2808 $dirName = PATH_site . 'typo3temp/';
2809 if (!@is_dir($dirName)) {
2810 return 'PATH_site + "typo3temp/" was not a directory!';
2811 }
2812 if (!static::isFirstPartOfStr($fI['dirname'], $dirName)) {
2813 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2814 }
2815 // Checking if the "subdir" is found:
2816 $subdir = substr($fI['dirname'], strlen($dirName));
2817 if ($subdir) {
2818 if (preg_match('/^[[:alnum:]_]+\\/$/', $subdir) || preg_match('/^[[:alnum:]_]+\\/[[:alnum:]_]+\\/$/', $subdir)) {
2819 $dirName .= $subdir;
2820 if (!@is_dir($dirName)) {
2821 static::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
2822 }
2823 } else {
2824 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2825 }
2826 }
2827 // Checking dir-name again (sub-dir might have been created):
2828 if (@is_dir($dirName)) {
2829 if ($filepath == $dirName . $fI['basename']) {
2830 static::writeFile($filepath, $content);
2831 if (!@is_file($filepath)) {
2832 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2833 }
2834 } else {
2835 return 'Calculated filelocation didn\'t match input "' . $filepath . '".';
2836 }
2837 } else {
2838 return '"' . $dirName . '" is not a directory!';
2839 }
2840 return null;
2841 }
2842
2843 /**
2844 * Wrapper function for mkdir.
2845 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']
2846 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']
2847 *
2848 * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2849 * @return bool TRUE if @mkdir went well!
2850 */
2851 public static function mkdir($newFolder)
2852 {
2853 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']));
2854 if ($result) {
2855 static::fixPermissions($newFolder);
2856 }
2857 return $result;
2858 }
2859
2860 /**
2861 * Creates a directory - including parent directories if necessary and
2862 * sets permissions on newly created directories.
2863 *
2864 * @param string $directory Target directory to create. Must a have trailing slash
2865 * @param string $deepDirectory Directory to create. This second parameter
2866 * @return void
2867 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2868 * @throws \RuntimeException If directory could not be created
2869 */
2870 public static function mkdir_deep($directory, $deepDirectory = '')
2871 {
2872 if (!is_string($directory)) {
2873 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955);
2874 }
2875 if (!is_string($deepDirectory)) {
2876 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.', 1303662956);
2877 }
2878 // Ensure there is only one slash
2879 $fullPath = rtrim($directory, '/') . '/' . ltrim($deepDirectory, '/');
2880 if ($fullPath !== '' && !is_dir($fullPath)) {
2881 $firstCreatedPath = static::createDirectoryPath($fullPath);
2882 if ($firstCreatedPath !== '') {
2883 static::fixPermissions($firstCreatedPath, true);
2884 }
2885 }
2886 }
2887
2888 /**
2889 * Creates directories for the specified paths if they do not exist. This
2890 * functions sets proper permission mask but does not set proper user and
2891 * group.
2892 *
2893 * @static
2894 * @param string $fullDirectoryPath
2895 * @return string Path to the the first created directory in the hierarchy
2896 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep
2897 * @throws \RuntimeException If directory could not be created
2898 */
2899 protected static function createDirectoryPath($fullDirectoryPath)
2900 {
2901 $currentPath = $fullDirectoryPath;
2902 $firstCreatedPath = '';
2903 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']);
2904 if (!@is_dir($currentPath)) {
2905 do {
2906 $firstCreatedPath = $currentPath;
2907 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR);
2908 $currentPath = substr($currentPath, 0, $separatorPosition);
2909 } while (!is_dir($currentPath) && $separatorPosition !== false);
2910 $result = @mkdir($fullDirectoryPath, $permissionMask, true);
2911 // Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir()
2912 if (!$result && !@is_dir($fullDirectoryPath)) {
2913 throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401);
2914 }
2915 }
2916 return $firstCreatedPath;
2917 }
2918
2919 /**
2920 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2921 *
2922 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2923 * @param bool $removeNonEmpty Allow deletion of non-empty directories
2924 * @return bool TRUE if @rmdir went well!
2925 */
2926 public static function rmdir($path, $removeNonEmpty = false)
2927 {
2928 $OK = false;
2929 // Remove trailing slash
2930 $path = preg_replace('|/$|', '', $path);
2931 if (file_exists($path)) {
2932 $OK = true;
2933 if (!is_link($path) && is_dir($path)) {
2934 if ($removeNonEmpty == true && ($handle = @opendir($path))) {
2935 while ($OK && false !== ($file = readdir($handle))) {
2936 if ($file == '.' || $file == '..') {
2937 continue;
2938 }
2939 $OK = static::rmdir($path . '/' . $file, $removeNonEmpty);
2940 }
2941 closedir($handle);
2942 }
2943 if ($OK) {
2944 $OK = @rmdir($path);
2945 }
2946 } elseif (is_link($path) && is_dir($path) && TYPO3_OS === 'WIN') {
2947 $OK = @rmdir($path);
2948 } else {
2949 // If $path is a file, simply remove it
2950 $OK = @unlink($path);
2951 }
2952 clearstatcache();
2953 } elseif (is_link($path)) {
2954 $OK = @unlink($path);
2955 clearstatcache();
2956 }
2957 return $OK;
2958 }
2959
2960 /**
2961 * Flushes a directory by first moving to a temporary resource, and then
2962 * triggering the remove process. This way directories can be flushed faster
2963 * to prevent race conditions on concurrent processes accessing the same directory.
2964 *
2965 * @param string $directory The directory to be renamed and flushed
2966 * @param bool $keepOriginalDirectory Whether to only empty the directory and not remove it
2967 * @param bool $flushOpcodeCache Also flush the opcode cache right after renaming the directory.
2968 * @return bool Whether the action was successful
2969 */
2970 public static function flushDirectory($directory, $keepOriginalDirectory = false, $flushOpcodeCache = false)
2971 {
2972 $result = false;
2973
2974 if (is_dir($directory)) {
2975 $temporaryDirectory = rtrim($directory, '/') . '.' . StringUtility::getUniqueId('remove') . '/';
2976 if (rename($directory, $temporaryDirectory)) {
2977 if ($flushOpcodeCache) {
2978 GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive($directory);
2979 }
2980 if ($keepOriginalDirectory) {
2981 static::mkdir($directory);
2982 }
2983 clearstatcache();
2984 $result = static::rmdir($temporaryDirectory, true);
2985 }
2986 }
2987
2988 return $result;
2989 }
2990
2991 /**
2992 * Returns an array with the names of folders in a specific path
2993 * Will return 'error' (string) if there were an error with reading directory content.
2994 *
2995 * @param string $path Path to list directories from
2996 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2997 */
2998 public static function get_dirs($path)
2999 {
3000 if ($path) {
3001 if (is_dir($path)) {
3002 $dir = scandir($path);
3003 $dirs = array();
3004 foreach ($dir as $entry) {
3005 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
3006 $dirs[] = $entry;
3007 }
3008 }
3009 } else {
3010 $dirs = 'error';
3011 }
3012 }
3013 return $dirs;
3014 }
3015
3016 /**
3017 * Finds all files in a given path and returns them as an array. Each
3018 * array key is a md5 hash of the full path to the file. This is done because
3019 * 'some' extensions like the import/export extension depend on this.
3020 *
3021 * @param string $path The path to retrieve the files from.
3022 * @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.
3023 * @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned.
3024 * @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time.
3025 * @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 '$/'.
3026 * @return array|string Array of the files found, or an error message in case the path could not be opened.
3027 */
3028 public static function getFilesInDir($path, $extensionList = '', $prependPath = false, $order = '', $excludePattern = '')
3029 {
3030 $excludePattern = (string)$excludePattern;
3031 $path = rtrim($path, '/');
3032 if (!@is_dir($path)) {
3033 return array();
3034 }
3035
3036 $rawFileList = scandir($path);
3037 if ($rawFileList === false) {
3038 return 'error opening path: "' . $path . '"';
3039 }
3040
3041 $pathPrefix = $path . '/';
3042 $extensionList = ',' . $extensionList . ',';
3043 $files = array();
3044 foreach ($rawFileList as $entry) {
3045 $completePathToEntry = $pathPrefix . $entry;
3046 if (!@is_file($completePathToEntry)) {
3047 continue;
3048 }
3049
3050 if (