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