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