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