8b15d06d76f95770a6697d5d3016844f49273aa1
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / GeneralUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Core\ApplicationContext;
18 use TYPO3\CMS\Core\Core\ClassLoadingInformation;
19 use TYPO3\CMS\Core\Imaging\GraphicalFunctions;
20 use TYPO3\CMS\Core\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 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate);
1157 } else {
1158 // Try to use native PHP functions first, precedence has openssl
1159 $bytes .= self::generateRandomBytesOpenSsl($bytesToGenerate);
1160 if (!isset($bytes[($bytesToReturn - 1)])) {
1161 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate);
1162 }
1163 // If openssl and mcrypt failed, try /dev/urandom
1164 if (!isset($bytes[($bytesToReturn - 1)])) {
1165 $bytes .= self::generateRandomBytesUrandom($bytesToGenerate);
1166 }
1167 }
1168 // Fall back if other random byte generation failed until now
1169 if (!isset($bytes[($bytesToReturn - 1)])) {
1170 $bytes .= self::generateRandomBytesFallback($bytesToReturn);
1171 }
1172 }
1173 // get first $bytesToReturn and remove it from the byte cache
1174 $output = substr($bytes, 0, $bytesToReturn);
1175 $bytes = substr($bytes, $bytesToReturn);
1176 return $output;
1177 }
1178
1179 /**
1180 * Generate random bytes using openssl if available
1181 *
1182 * @param string $bytesToGenerate
1183 * @return string
1184 */
1185 static protected function generateRandomBytesOpenSsl($bytesToGenerate) {
1186 if (!function_exists('openssl_random_pseudo_bytes')) {
1187 return '';
1188 }
1189 $isStrong = NULL;
1190 return (string)openssl_random_pseudo_bytes($bytesToGenerate, $isStrong);
1191 }
1192
1193 /**
1194 * Generate random bytes using mcrypt if available
1195 *
1196 * @param $bytesToGenerate
1197 * @return string
1198 */
1199 static protected function generateRandomBytesMcrypt($bytesToGenerate) {
1200 if (!function_exists('mcrypt_create_iv')) {
1201 return '';
1202 }
1203 return (string)(@mcrypt_create_iv($bytesToGenerate, MCRYPT_DEV_URANDOM));
1204 }
1205
1206 /**
1207 * Read random bytes from /dev/urandom if it is accessible
1208 *
1209 * @param $bytesToGenerate
1210 * @return string
1211 */
1212 static protected function generateRandomBytesUrandom($bytesToGenerate) {
1213 $bytes = '';
1214 $fh = @fopen('/dev/urandom', 'rb');
1215 if ($fh) {
1216 // PHP only performs buffered reads, so in reality it will always read
1217 // at least 4096 bytes. Thus, it costs nothing extra to read and store
1218 // that much so as to speed any additional invocations.
1219 $bytes = fread($fh, $bytesToGenerate);
1220 fclose($fh);
1221 }
1222 return $bytes;
1223 }
1224
1225 /**
1226 * Generate pseudo random bytes as last resort
1227 *
1228 * @param $bytesToReturn
1229 * @return string
1230 */
1231 static protected function generateRandomBytesFallback($bytesToReturn) {
1232 $bytes = '';
1233 // We initialize with somewhat random.
1234 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() % pow(10, 6), 10, 2) . microtime() . uniqid('', TRUE) . getmypid();
1235 while (!isset($bytes[($bytesToReturn - 1)])) {
1236 $randomState = sha1(microtime() . mt_rand() . $randomState);
1237 $bytes .= sha1(mt_rand() . $randomState, TRUE);
1238 }
1239 return $bytes;
1240 }
1241
1242 /**
1243 * Returns an ASCII string (punicode) representation of $value
1244 *
1245 * @param string $value
1246 * @return string An ASCII encoded (punicode) string
1247 */
1248 static public function idnaEncode($value) {
1249 if (isset(self::$idnaStringCache[$value])) {
1250 return self::$idnaStringCache[$value];
1251 } else {
1252 if (!self::$idnaConverter) {
1253 self::$idnaConverter = new \idna_convert(array('idn_version' => 2008));
1254 }
1255 self::$idnaStringCache[$value] = self::$idnaConverter->encode($value);
1256 return self::$idnaStringCache[$value];
1257 }
1258 }
1259
1260 /**
1261 * Returns a hex representation of a random byte string.
1262 *
1263 * @param int $count Number of hex characters to return
1264 * @return string Random Bytes
1265 */
1266 static public function getRandomHexString($count) {
1267 return substr(bin2hex(self::generateRandomBytes((int)(($count + 1) / 2))), 0, $count);
1268 }
1269
1270 /**
1271 * Returns a given string with underscores as UpperCamelCase.
1272 * Example: Converts blog_example to BlogExample
1273 *
1274 * @param string $string String to be converted to camel case
1275 * @return string UpperCamelCasedWord
1276 */
1277 static public function underscoredToUpperCamelCase($string) {
1278 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1279 return $upperCamelCase;
1280 }
1281
1282 /**
1283 * Returns a given string with underscores as lowerCamelCase.
1284 * Example: Converts minimal_value to minimalValue
1285 *
1286 * @param string $string String to be converted to camel case
1287 * @return string lowerCamelCasedWord
1288 */
1289 static public function underscoredToLowerCamelCase($string) {
1290 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1291 $lowerCamelCase = self::lcfirst($upperCamelCase);
1292 return $lowerCamelCase;
1293 }
1294
1295 /**
1296 * Returns a given CamelCasedString as an lowercase string with underscores.
1297 * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1298 *
1299 * @param string $string String to be converted to lowercase underscore
1300 * @return string lowercase_and_underscored_string
1301 */
1302 static public function camelCaseToLowerCaseUnderscored($string) {
1303 return self::strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string));
1304 }
1305
1306 /**
1307 * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1308 * Example: Converts "Hello World" to "hello World"
1309 *
1310 * @param string $string The string to be used to lowercase the first character
1311 * @return string The string with the first character as lowercase
1312 */
1313 static public function lcfirst($string) {
1314 return self::strtolower($string[0]) . substr($string, 1);
1315 }
1316
1317 /**
1318 * Checks if a given string is a Uniform Resource Locator (URL).
1319 *
1320 * On seriously malformed URLs, parse_url may return FALSE and emit an
1321 * E_WARNING.
1322 *
1323 * filter_var() requires a scheme to be present.
1324 *
1325 * http://www.faqs.org/rfcs/rfc2396.html
1326 * Scheme names consist of a sequence of characters beginning with a
1327 * lower case letter and followed by any combination of lower case letters,
1328 * digits, plus ("+"), period ("."), or hyphen ("-"). For resiliency,
1329 * programs interpreting URI should treat upper case letters as equivalent to
1330 * lower case in scheme names (e.g., allow "HTTP" as well as "http").
1331 * scheme = alpha *( alpha | digit | "+" | "-" | "." )
1332 *
1333 * Convert the domain part to punicode if it does not look like a regular
1334 * domain name. Only the domain part because RFC3986 specifies the the rest of
1335 * the url may not contain special characters:
1336 * http://tools.ietf.org/html/rfc3986#appendix-A
1337 *
1338 * @param string $url The URL to be validated
1339 * @return bool Whether the given URL is valid
1340 */
1341 static public function isValidUrl($url) {
1342 $parsedUrl = parse_url($url);
1343 if (!$parsedUrl || !isset($parsedUrl['scheme'])) {
1344 return FALSE;
1345 }
1346 // HttpUtility::buildUrl() will always build urls with <scheme>://
1347 // our original $url might only contain <scheme>: (e.g. mail:)
1348 // so we convert that to the double-slashed version to ensure
1349 // our check against the $recomposedUrl is proper
1350 if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
1351 $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
1352 }
1353 $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
1354 if ($recomposedUrl !== $url) {
1355 // The parse_url() had to modify characters, so the URL is invalid
1356 return FALSE;
1357 }
1358 if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
1359 $parsedUrl['host'] = self::idnaEncode($parsedUrl['host']);
1360 }
1361 return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== FALSE;
1362 }
1363
1364 /*************************
1365 *
1366 * ARRAY FUNCTIONS
1367 *
1368 *************************/
1369 /**
1370 * Check if an string item exists in an array.
1371 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1372 *
1373 * Comparison to PHP in_array():
1374 * -> $array = array(0, 1, 2, 3);
1375 * -> variant_a := \TYPO3\CMS\Core\Utility\ArrayUtility::inArray($array, $needle)
1376 * -> variant_b := in_array($needle, $array)
1377 * -> variant_c := in_array($needle, $array, TRUE)
1378 * +---------+-----------+-----------+-----------+
1379 * | $needle | variant_a | variant_b | variant_c |
1380 * +---------+-----------+-----------+-----------+
1381 * | '1a' | FALSE | TRUE | FALSE |
1382 * | '' | FALSE | TRUE | FALSE |
1383 * | '0' | TRUE | TRUE | FALSE |
1384 * | 0 | TRUE | TRUE | TRUE |
1385 * +---------+-----------+-----------+-----------+
1386 *
1387 * @param array $in_array One-dimensional array of items
1388 * @param string $item Item to check for
1389 * @return bool TRUE if $item is in the one-dimensional array $in_array
1390 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::inArray() instead
1391 */
1392 static public function inArray(array $in_array, $item) {
1393 static::logDeprecatedFunction();
1394 return ArrayUtility::inArray($in_array, $item);
1395 }
1396
1397 /**
1398 * Explodes a $string delimited by $delim and casts each item in the array to (int).
1399 * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
1400 *
1401 * @param string $delimiter Delimiter string to explode with
1402 * @param string $string The string to explode
1403 * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
1404 * @param int $limit If positive, the result will contain a maximum of limit elements,
1405 * @return array Exploded values, all converted to integers
1406 */
1407 static public function intExplode($delimiter, $string, $removeEmptyValues = FALSE, $limit = 0) {
1408 $result = explode($delimiter, $string);
1409 foreach ($result as $key => &$value) {
1410 if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
1411 unset($result[$key]);
1412 } else {
1413 $value = (int)$value;
1414 }
1415 }
1416 unset($value);
1417 if ($limit !== 0) {
1418 if ($limit < 0) {
1419 $result = array_slice($result, 0, $limit);
1420 } elseif (count($result) > $limit) {
1421 $lastElements = array_slice($result, $limit - 1);
1422 $result = array_slice($result, 0, $limit - 1);
1423 $result[] = implode($delimiter, $lastElements);
1424 }
1425 }
1426 return $result;
1427 }
1428
1429 /**
1430 * Reverse explode which explodes the string counting from behind.
1431 *
1432 * Note: The delimiter has to given in the reverse order as
1433 * it is occurring within the string.
1434 *
1435 * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
1436 * ==> array('[my][words', 'here]')
1437 *
1438 * @param string $delimiter Delimiter string to explode with
1439 * @param string $string The string to explode
1440 * @param int $count Number of array entries
1441 * @return array Exploded values
1442 */
1443 static public function revExplode($delimiter, $string, $count = 0) {
1444 // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
1445 if ($count === 2) {
1446 $position = strrpos($string, strrev($delimiter));
1447 if ($position !== FALSE) {
1448 return array(substr($string, 0, $position), substr($string, $position + strlen($delimiter)));
1449 } else {
1450 return array($string);
1451 }
1452 } elseif ($count <= 1) {
1453 return array($string);
1454 } else {
1455 $explodedValues = explode($delimiter, strrev($string), $count);
1456 $explodedValues = array_map('strrev', $explodedValues);
1457 return array_reverse($explodedValues);
1458 }
1459 }
1460
1461 /**
1462 * Explodes a string and trims all values for whitespace in the ends.
1463 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1464 *
1465 * @param string $delim Delimiter string to explode with
1466 * @param string $string The string to explode
1467 * @param bool $removeEmptyValues If set, all empty values will be removed in output
1468 * @param int $limit If positive, the result will contain a maximum of
1469 * @return array Exploded values
1470 */
1471 static public function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
1472 $result = array_map('trim', explode($delim, $string));
1473 if ($removeEmptyValues) {
1474 $temp = array();
1475 foreach ($result as $value) {
1476 if ($value !== '') {
1477 $temp[] = $value;
1478 }
1479 }
1480 $result = $temp;
1481 }
1482 if ($limit > 0 && count($result) > $limit) {
1483 $lastElements = array_splice($result, $limit - 1);
1484 $result[] = implode($delim, $lastElements);
1485 } elseif ($limit < 0) {
1486 $result = array_slice($result, 0, $limit);
1487 }
1488 return $result;
1489 }
1490
1491 /**
1492 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1493 *
1494 * @param array $array Array containing the values
1495 * @param string $cmpValue Value to search for and if found remove array entry where found.
1496 * @return array Output array with entries removed if search string is found
1497 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::removeArrayEntryByValue() instead
1498 */
1499 static public function removeArrayEntryByValue(array $array, $cmpValue) {
1500 static::logDeprecatedFunction();
1501 return ArrayUtility::removeArrayEntryByValue($array, $cmpValue);
1502 }
1503
1504 /**
1505 * Filters an array to reduce its elements to match the condition.
1506 * The values in $keepItems can be optionally evaluated by a custom callback function.
1507 *
1508 * Example (arguments used to call this function):
1509 * $array = array(
1510 * array('aa' => array('first', 'second'),
1511 * array('bb' => array('third', 'fourth'),
1512 * array('cc' => array('fifth', 'sixth'),
1513 * );
1514 * $keepItems = array('third');
1515 * $getValueFunc = create_function('$value', 'return $value[0];');
1516 *
1517 * Returns:
1518 * array(
1519 * array('bb' => array('third', 'fourth'),
1520 * )
1521 *
1522 * @param array $array The initial array to be filtered/reduced
1523 * @param mixed $keepItems The items which are allowed/kept in the array - accepts array or csv string
1524 * @param string $getValueFunc (optional) Callback function used to get the value to keep
1525 * @return array The filtered/reduced array with the kept items
1526 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::keepItemsInArray() instead
1527 */
1528 static public function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
1529 static::logDeprecatedFunction();
1530 return ArrayUtility::keepItemsInArray($array, $keepItems, $getValueFunc);
1531 }
1532
1533 /**
1534 * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1535 *
1536 * @param string $name Name prefix for entries. Set to blank if you wish none.
1537 * @param array $theArray The (multidimensional) array to implode
1538 * @param string $str (keep blank)
1539 * @param bool $skipBlank If set, parameters which were blank strings would be removed.
1540 * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1541 * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1542 * @see explodeUrl2Array()
1543 */
1544 static public function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
1545 foreach ($theArray as $Akey => $AVal) {
1546 $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1547 if (is_array($AVal)) {
1548 $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1549 } else {
1550 if (!$skipBlank || (string)$AVal !== '') {
1551 $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1552 }
1553 }
1554 }
1555 return $str;
1556 }
1557
1558 /**
1559 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1560 *
1561 * @param string $string GETvars string
1562 * @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())
1563 * @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!
1564 * @see implodeArrayForUrl()
1565 */
1566 static public function explodeUrl2Array($string, $multidim = FALSE) {
1567 $output = array();
1568 if ($multidim) {
1569 parse_str($string, $output);
1570 } else {
1571 $p = explode('&', $string);
1572 foreach ($p as $v) {
1573 if ($v !== '') {
1574 list($pK, $pV) = explode('=', $v, 2);
1575 $output[rawurldecode($pK)] = rawurldecode($pV);
1576 }
1577 }
1578 }
1579 return $output;
1580 }
1581
1582 /**
1583 * Returns an array with selected keys from incoming data.
1584 * (Better read source code if you want to find out...)
1585 *
1586 * @param string $varList List of variable/key names
1587 * @param array $getArray Array from where to get values based on the keys in $varList
1588 * @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
1589 * @return array Output array with selected variables.
1590 */
1591 static public function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = TRUE) {
1592 $keys = self::trimExplode(',', $varList, TRUE);
1593 $outArr = array();
1594 foreach ($keys as $v) {
1595 if (isset($getArray[$v])) {
1596 $outArr[$v] = $getArray[$v];
1597 } elseif ($GPvarAlt) {
1598 $outArr[$v] = self::_GP($v);
1599 }
1600 }
1601 return $outArr;
1602 }
1603
1604 /**
1605 * AddSlash array
1606 * This function traverses a multidimensional array and adds slashes to the values.
1607 * NOTE that the input array is and argument by reference.!!
1608 * Twin-function to stripSlashesOnArray
1609 *
1610 * @param array $theArray Multidimensional input array, (REFERENCE!)
1611 * @return array
1612 */
1613 static public function addSlashesOnArray(array &$theArray) {
1614 foreach ($theArray as &$value) {
1615 if (is_array($value)) {
1616 self::addSlashesOnArray($value);
1617 } else {
1618 $value = addslashes($value);
1619 }
1620 }
1621 unset($value);
1622 reset($theArray);
1623 }
1624
1625 /**
1626 * StripSlash array
1627 * This function traverses a multidimensional array and strips slashes to the values.
1628 * NOTE that the input array is and argument by reference.!!
1629 * Twin-function to addSlashesOnArray
1630 *
1631 * @param array $theArray Multidimensional input array, (REFERENCE!)
1632 * @return array
1633 */
1634 static public function stripSlashesOnArray(array &$theArray) {
1635 foreach ($theArray as &$value) {
1636 if (is_array($value)) {
1637 self::stripSlashesOnArray($value);
1638 } else {
1639 $value = stripslashes($value);
1640 }
1641 }
1642 unset($value);
1643 reset($theArray);
1644 }
1645
1646 /**
1647 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1648 *
1649 * @param array $arr Multidimensional input array
1650 * @param string $cmd "add" or "strip", depending on usage you wish.
1651 * @return array
1652 */
1653 static public function slashArray(array $arr, $cmd) {
1654 if ($cmd == 'strip') {
1655 self::stripSlashesOnArray($arr);
1656 }
1657 if ($cmd == 'add') {
1658 self::addSlashesOnArray($arr);
1659 }
1660 return $arr;
1661 }
1662
1663 /**
1664 * Rename Array keys with a given mapping table
1665 *
1666 * @param array $array Array by reference which should be remapped
1667 * @param array $mappingTable Array with remap information, array/$oldKey => $newKey)
1668 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::remapArrayKeys() instead
1669 */
1670 static public function remapArrayKeys(&$array, $mappingTable) {
1671 static::logDeprecatedFunction();
1672 ArrayUtility::remapArrayKeys($array, $mappingTable);
1673 }
1674
1675 /**
1676 * 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.
1677 *
1678 * @param array $arr1 First array
1679 * @param array $arr2 Second array
1680 * @return array Merged result.
1681 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - native php '+' operator instead
1682 */
1683 static public function array_merge(array $arr1, array $arr2) {
1684 static::logDeprecatedFunction();
1685 return $arr2 + $arr1;
1686 }
1687
1688 /**
1689 * Filters keys off from first array that also exist in second array. Comparison is done by keys.
1690 * This method is a recursive version of php array_diff_assoc()
1691 *
1692 * @param array $array1 Source array
1693 * @param array $array2 Reduce source array by this array
1694 * @return array Source array reduced by keys also present in second array
1695 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::arrayDiffAssocRecursive() instead
1696 */
1697 static public function arrayDiffAssocRecursive(array $array1, array $array2) {
1698 static::logDeprecatedFunction();
1699 return ArrayUtility::arrayDiffAssocRecursive($array1, $array2);
1700 }
1701
1702 /**
1703 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1704 *
1705 * @param array $row Input array of values
1706 * @param string $delim Delimited, default is comma
1707 * @param string $quote Quote-character to wrap around the values.
1708 * @return string A single line of CSV
1709 */
1710 static public function csvValues(array $row, $delim = ',', $quote = '"') {
1711 $out = array();
1712 foreach ($row as $value) {
1713 $out[] = str_replace($quote, $quote . $quote, $value);
1714 }
1715 $str = $quote . implode(($quote . $delim . $quote), $out) . $quote;
1716 return $str;
1717 }
1718
1719 /**
1720 * Removes dots "." from end of a key identifier of TypoScript styled array.
1721 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1722 *
1723 * @param array $ts TypoScript configuration array
1724 * @return array TypoScript configuration array without dots at the end of all keys
1725 */
1726 static public function removeDotsFromTS(array $ts) {
1727 $out = array();
1728 foreach ($ts as $key => $value) {
1729 if (is_array($value)) {
1730 $key = rtrim($key, '.');
1731 $out[$key] = self::removeDotsFromTS($value);
1732 } else {
1733 $out[$key] = $value;
1734 }
1735 }
1736 return $out;
1737 }
1738
1739 /**
1740 * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1741 *
1742 * @param array $array array to be sorted recursively, passed by reference
1743 * @return bool TRUE if param is an array
1744 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::naturalKeySortRecursive() instead
1745 */
1746 static public function naturalKeySortRecursive(&$array) {
1747 static::logDeprecatedFunction();
1748 return ArrayUtility::naturalKeySortRecursive($array);
1749 }
1750
1751 /*************************
1752 *
1753 * HTML/XML PROCESSING
1754 *
1755 *************************/
1756 /**
1757 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1758 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1759 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1760 *
1761 * @param string $tag HTML-tag string (or attributes only)
1762 * @return array Array with the attribute values.
1763 */
1764 static public function get_tag_attributes($tag) {
1765 $components = self::split_tag_attributes($tag);
1766 // Attribute name is stored here
1767 $name = '';
1768 $valuemode = FALSE;
1769 $attributes = array();
1770 foreach ($components as $key => $val) {
1771 // 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
1772 if ($val != '=') {
1773 if ($valuemode) {
1774 if ($name) {
1775 $attributes[$name] = $val;
1776 $name = '';
1777 }
1778 } else {
1779 if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val))) {
1780 $attributes[$key] = '';
1781 $name = $key;
1782 }
1783 }
1784 $valuemode = FALSE;
1785 } else {
1786 $valuemode = TRUE;
1787 }
1788 }
1789 return $attributes;
1790 }
1791
1792 /**
1793 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1794 * Removes tag-name if found
1795 *
1796 * @param string $tag HTML-tag string (or attributes only)
1797 * @return array Array with the attribute values.
1798 */
1799 static public function split_tag_attributes($tag) {
1800 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
1801 // Removes any > in the end of the string
1802 $tag_tmp = trim(rtrim($tag_tmp, '>'));
1803 $value = array();
1804 // Compared with empty string instead , 030102
1805 while ($tag_tmp !== '') {
1806 $firstChar = $tag_tmp[0];
1807 if ($firstChar === '"' || $firstChar === '\'') {
1808 $reg = explode($firstChar, $tag_tmp, 3);
1809 $value[] = $reg[1];
1810 $tag_tmp = trim($reg[2]);
1811 } elseif ($firstChar === '=') {
1812 $value[] = '=';
1813 // Removes = chars.
1814 $tag_tmp = trim(substr($tag_tmp, 1));
1815 } else {
1816 // There are '' around the value. We look for the next ' ' or '>'
1817 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1818 $value[] = trim($reg[0]);
1819 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
1820 }
1821 }
1822 reset($value);
1823 return $value;
1824 }
1825
1826 /**
1827 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1828 *
1829 * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1830 * @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!
1831 * @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1832 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1833 */
1834 static public function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
1835 if ($xhtmlSafe) {
1836 $newArr = array();
1837 foreach ($arr as $p => $v) {
1838 if (!isset($newArr[strtolower($p)])) {
1839 $newArr[strtolower($p)] = htmlspecialchars($v);
1840 }
1841 }
1842 $arr = $newArr;
1843 }
1844 $list = array();
1845 foreach ($arr as $p => $v) {
1846 if ((string)$v !== '' || $dontOmitBlankAttribs) {
1847 $list[] = $p . '="' . $v . '"';
1848 }
1849 }
1850 return implode(' ', $list);
1851 }
1852
1853 /**
1854 * Wraps JavaScript code XHTML ready with <script>-tags
1855 * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1856 * This is nice for indenting JS code with PHP code on the same level.
1857 *
1858 * @param string $string JavaScript code
1859 * @param bool $linebreak Wrap script element in line breaks? Default is TRUE.
1860 * @return string The wrapped JS code, ready to put into a XHTML page
1861 */
1862 static public function wrapJS($string, $linebreak = TRUE) {
1863 if (trim($string)) {
1864 // <script wrapped in nl?
1865 $cr = $linebreak ? LF : '';
1866 // remove nl from the beginning
1867 $string = preg_replace('/^\\n+/', '', $string);
1868 // re-ident to one tab using the first line as reference
1869 $match = array();
1870 if (preg_match('/^(\\t+)/', $string, $match)) {
1871 $string = str_replace($match[1], TAB, $string);
1872 }
1873 $string = $cr . '<script type="text/javascript">
1874 /*<![CDATA[*/
1875 ' . $string . '
1876 /*]]>*/
1877 </script>' . $cr;
1878 }
1879 return trim($string);
1880 }
1881
1882 /**
1883 * Parses XML input into a PHP array with associative keys
1884 *
1885 * @param string $string XML data input
1886 * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1887 * @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.
1888 * @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
1889 */
1890 static public function xml2tree($string, $depth = 999) {
1891 $parser = xml_parser_create();
1892 $vals = array();
1893 $index = array();
1894 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1895 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1896 xml_parse_into_struct($parser, $string, $vals, $index);
1897 if (xml_get_error_code($parser)) {
1898 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1899 }
1900 xml_parser_free($parser);
1901 $stack = array(array());
1902 $stacktop = 0;
1903 $startPoint = 0;
1904 $tagi = array();
1905 foreach ($vals as $key => $val) {
1906 $type = $val['type'];
1907 // open tag:
1908 if ($type == 'open' || $type == 'complete') {
1909 $stack[$stacktop++] = $tagi;
1910 if ($depth == $stacktop) {
1911 $startPoint = $key;
1912 }
1913 $tagi = array('tag' => $val['tag']);
1914 if (isset($val['attributes'])) {
1915 $tagi['attrs'] = $val['attributes'];
1916 }
1917 if (isset($val['value'])) {
1918 $tagi['values'][] = $val['value'];
1919 }
1920 }
1921 // finish tag:
1922 if ($type == 'complete' || $type == 'close') {
1923 $oldtagi = $tagi;
1924 $tagi = $stack[--$stacktop];
1925 $oldtag = $oldtagi['tag'];
1926 unset($oldtagi['tag']);
1927 if ($depth == $stacktop + 1) {
1928 if ($key - $startPoint > 0) {
1929 $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
1930 $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
1931 } else {
1932 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
1933 }
1934 }
1935 $tagi['ch'][$oldtag][] = $oldtagi;
1936 unset($oldtagi);
1937 }
1938 // cdata
1939 if ($type == 'cdata') {
1940 $tagi['values'][] = $val['value'];
1941 }
1942 }
1943 return $tagi['ch'];
1944 }
1945
1946 /**
1947 * Turns PHP array into XML. See array2xml()
1948 *
1949 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1950 * @param string $docTag Alternative document tag. Default is "phparray".
1951 * @param array $options Options for the compilation. See array2xml() for description.
1952 * @param string $charset Forced charset to prologue
1953 * @return string An XML string made from the input content in the array.
1954 * @see xml2array(),array2xml()
1955 */
1956 static public function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
1957 // Set default charset unless explicitly specified
1958 $charset = $charset ?: 'utf-8';
1959 // Return XML:
1960 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF . self::array2xml($array, '', 0, $docTag, 0, $options);
1961 }
1962
1963 /**
1964 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
1965 *
1966 * Converts a PHP array into an XML string.
1967 * The XML output is optimized for readability since associative keys are used as tag names.
1968 * 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.
1969 * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
1970 * 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
1971 * 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.
1972 * 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!
1973 * 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...
1974 *
1975 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1976 * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
1977 * @param int $level Current recursion level. Don't change, stay at zero!
1978 * @param string $docTag Alternative document tag. Default is "phparray".
1979 * @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
1980 * @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')
1981 * @param array $stackData Stack data. Don't touch.
1982 * @return string An XML string made from the input content in the array.
1983 * @see xml2array()
1984 */
1985 static public function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array()) {
1986 // 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
1987 $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);
1988 // Set indenting mode:
1989 $indentChar = $spaceInd ? ' ' : TAB;
1990 $indentN = $spaceInd > 0 ? $spaceInd : 1;
1991 $nl = $spaceInd >= 0 ? LF : '';
1992 // Init output variable:
1993 $output = '';
1994 // Traverse the input array
1995 foreach ($array as $k => $v) {
1996 $attr = '';
1997 $tagName = $k;
1998 // Construct the tag name.
1999 // Use tag based on grand-parent + parent tag name
2000 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
2001 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2002 $tagName = (string)$options['grandParentTagMap'][($stackData['grandParentTagName'] . '/' . $stackData['parentTagName'])];
2003 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) {
2004 // Use tag based on parent tag name + if current tag is numeric
2005 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2006 $tagName = (string)$options['parentTagMap'][($stackData['parentTagName'] . ':_IS_NUM')];
2007 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
2008 // Use tag based on parent tag name + current tag
2009 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2010 $tagName = (string)$options['parentTagMap'][($stackData['parentTagName'] . ':' . $tagName)];
2011 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) {
2012 // Use tag based on parent tag name:
2013 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2014 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
2015 } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) {
2016 // If integer...;
2017 if ($options['useNindex']) {
2018 // If numeric key, prefix "n"
2019 $tagName = 'n' . $tagName;
2020 } else {
2021 // Use special tag for num. keys:
2022 $attr .= ' index="' . $tagName . '"';
2023 $tagName = $options['useIndexTagForNum'] ?: 'numIndex';
2024 }
2025 } elseif ($options['useIndexTagForAssoc']) {
2026 // Use tag for all associative keys:
2027 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2028 $tagName = $options['useIndexTagForAssoc'];
2029 }
2030 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2031 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2032 // If the value is an array then we will call this function recursively:
2033 if (is_array($v)) {
2034 // Sub elements:
2035 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2036 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2037 $clearStackPath = $subOptions['clearStackPath'];
2038 } else {
2039 $subOptions = $options;
2040 $clearStackPath = FALSE;
2041 }
2042 $content = $nl . self::array2xml($v, $NSprefix, ($level + 1), '', $spaceInd, $subOptions, array(
2043 'parentTagName' => $tagName,
2044 'grandParentTagName' => $stackData['parentTagName'],
2045 'path' => ($clearStackPath ? '' : $stackData['path'] . '/' . $tagName)
2046 )) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
2047 // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2048 if ((int)$options['disableTypeAttrib'] != 2) {
2049 $attr .= ' type="array"';
2050 }
2051 } else {
2052 // Just a value:
2053 // Look for binary chars:
2054 $vLen = strlen($v);
2055 // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
2056 if ($vLen && strcspn($v, $binaryChars) != $vLen) {
2057 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2058 $content = $nl . chunk_split(base64_encode($v));
2059 $attr .= ' base64="1"';
2060 } else {
2061 // Otherwise, just htmlspecialchar the stuff:
2062 $content = htmlspecialchars($v);
2063 $dType = gettype($v);
2064 if ($dType == 'string') {
2065 if ($options['useCDATA'] && $content != $v) {
2066 $content = '<![CDATA[' . $v . ']]>';
2067 }
2068 } elseif (!$options['disableTypeAttrib']) {
2069 $attr .= ' type="' . $dType . '"';
2070 }
2071 }
2072 }
2073 if ((string)$tagName !== '') {
2074 // Add the element to the output string:
2075 $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
2076 . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2077 }
2078 }
2079 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2080 if (!$level) {
2081 $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
2082 }
2083 return $output;
2084 }
2085
2086 /**
2087 * Converts an XML string to a PHP array.
2088 * This is the reverse function of array2xml()
2089 * This is a wrapper for xml2arrayProcess that adds a two-level cache
2090 *
2091 * @param string $string XML content to convert into an array
2092 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2093 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2094 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2095 * @see array2xml(),xml2arrayProcess()
2096 */
2097 static public function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
2098 static $firstLevelCache = array();
2099 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
2100 // Look up in first level cache
2101 if (!empty($firstLevelCache[$identifier])) {
2102 $array = $firstLevelCache[$identifier];
2103 } else {
2104 // Look up in second level cache
2105 $array = PageRepository::getHash($identifier, 0);
2106 if (!is_array($array)) {
2107 $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2108 PageRepository::storeHash($identifier, $array, 'ident_xml2array');
2109 }
2110 // Store content in first level cache
2111 $firstLevelCache[$identifier] = $array;
2112 }
2113 return $array;
2114 }
2115
2116 /**
2117 * Converts an XML string to a PHP array.
2118 * This is the reverse function of array2xml()
2119 *
2120 * @param string $string XML content to convert into an array
2121 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2122 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2123 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2124 * @see array2xml()
2125 */
2126 static protected function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
2127 // Create parser:
2128 $parser = xml_parser_create();
2129 $vals = array();
2130 $index = array();
2131 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2132 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2133 // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2134 $match = array();
2135 preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2136 $theCharset = $match[1] ?: 'utf-8';
2137 // us-ascii / utf-8 / iso-8859-1
2138 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
2139 // Parse content:
2140 xml_parse_into_struct($parser, $string, $vals, $index);
2141 // If error, return error message:
2142 if (xml_get_error_code($parser)) {
2143 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2144 }
2145 xml_parser_free($parser);
2146 // Init vars:
2147 $stack = array(array());
2148 $stacktop = 0;
2149 $current = array();
2150 $tagName = '';
2151 $documentTag = '';
2152 // Traverse the parsed XML structure:
2153 foreach ($vals as $key => $val) {
2154 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2155 $tagName = $val['tag'];
2156 if (!$documentTag) {
2157 $documentTag = $tagName;
2158 }
2159 // Test for name space:
2160 $tagName = $NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix ? substr($tagName, strlen($NSprefix)) : $tagName;
2161 // Test for numeric tag, encoded on the form "nXXX":
2162 $testNtag = substr($tagName, 1);
2163 // Closing tag.
2164 $tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName;
2165 // Test for alternative index value:
2166 if ((string)$val['attributes']['index'] !== '') {
2167 $tagName = $val['attributes']['index'];
2168 }
2169 // Setting tag-values, manage stack:
2170 switch ($val['type']) {
2171 case 'open':
2172 // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2173 // Setting blank place holder
2174 $current[$tagName] = array();
2175 $stack[$stacktop++] = $current;
2176 $current = array();
2177 break;
2178 case 'close':
2179 // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2180 $oldCurrent = $current;
2181 $current = $stack[--$stacktop];
2182 // Going to the end of array to get placeholder key, key($current), and fill in array next:
2183 end($current);
2184 $current[key($current)] = $oldCurrent;
2185 unset($oldCurrent);
2186 break;
2187 case 'complete':
2188 // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2189 if ($val['attributes']['base64']) {
2190 $current[$tagName] = base64_decode($val['value']);
2191 } else {
2192 // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2193 $current[$tagName] = (string)$val['value'];
2194 // Cast type:
2195 switch ((string)$val['attributes']['type']) {
2196 case 'integer':
2197 $current[$tagName] = (int)$current[$tagName];
2198 break;
2199 case 'double':
2200 $current[$tagName] = (double) $current[$tagName];
2201 break;
2202 case 'boolean':
2203 $current[$tagName] = (bool)$current[$tagName];
2204 break;
2205 case 'NULL':
2206 $current[$tagName] = NULL;
2207 break;
2208 case 'array':
2209 // 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...
2210 $current[$tagName] = array();
2211 break;
2212 }
2213 }
2214 break;
2215 }
2216 }
2217 if ($reportDocTag) {
2218 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2219 }
2220 // Finally return the content of the document tag.
2221 return $current[$tagName];
2222 }
2223
2224 /**
2225 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2226 *
2227 * @param array $vals An array of XML parts, see xml2tree
2228 * @return string Re-compiled XML data.
2229 */
2230 static public function xmlRecompileFromStructValArray(array $vals) {
2231 $XMLcontent = '';
2232 foreach ($vals as $val) {
2233 $type = $val['type'];
2234 // Open tag:
2235 if ($type == 'open' || $type == 'complete') {
2236 $XMLcontent .= '<' . $val['tag'];
2237 if (isset($val['attributes'])) {
2238 foreach ($val['attributes'] as $k => $v) {
2239 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2240 }
2241 }
2242 if ($type == 'complete') {
2243 if (isset($val['value'])) {
2244 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2245 } else {
2246 $XMLcontent .= '/>';
2247 }
2248 } else {
2249 $XMLcontent .= '>';
2250 }
2251 if ($type == 'open' && isset($val['value'])) {
2252 $XMLcontent .= htmlspecialchars($val['value']);
2253 }
2254 }
2255 // Finish tag:
2256 if ($type == 'close') {
2257 $XMLcontent .= '</' . $val['tag'] . '>';
2258 }
2259 // Cdata
2260 if ($type == 'cdata') {
2261 $XMLcontent .= htmlspecialchars($val['value']);
2262 }
2263 }
2264 return $XMLcontent;
2265 }
2266
2267 /**
2268 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2269 *
2270 * @param string $xmlData XML data
2271 * @return array Attributes of the xml prologue (header)
2272 */
2273 static public function xmlGetHeaderAttribs($xmlData) {
2274 $match = array();
2275 if (preg_match('/^\\s*<\\?xml([^>]*)\\?\\>/', $xmlData, $match)) {
2276 return self::get_tag_attributes($match[1]);
2277 }
2278 }
2279
2280 /**
2281 * Minifies JavaScript
2282 *
2283 * @param string $script Script to minify
2284 * @param string $error Error message (if any)
2285 * @return string Minified script or source string if error happened
2286 */
2287 static public function minifyJavaScript($script, &$error = '') {
2288 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'])) {
2289 $fakeThis = FALSE;
2290 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] as $hookMethod) {
2291 try {
2292 $parameters = array('script' => $script);
2293 $script = static::callUserFunction($hookMethod, $parameters, $fakeThis);
2294 } catch (\Exception $e) {
2295 $errorMessage = 'Error minifying java script: ' . $e->getMessage();
2296 $error .= $errorMessage;
2297 static::devLog($errorMessage, \TYPO3\CMS\Core\Utility\GeneralUtility::class, 2, array(
2298 'JavaScript' => $script,
2299 'Stack trace' => $e->getTrace(),
2300 'hook' => $hookMethod
2301 ));
2302 }
2303 }
2304 }
2305 return $script;
2306 }
2307
2308 /*************************
2309 *
2310 * FILES FUNCTIONS
2311 *
2312 *************************/
2313 /**
2314 * Reads the file or url $url and returns the content
2315 * 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.
2316 *
2317 * @param string $url File/URL to read
2318 * @param int $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2319 * @param array $requestHeaders HTTP headers to be used in the request
2320 * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2321 * @return mixed The content from the resource given as input. FALSE if an error has occurred.
2322 */
2323 static public function getUrl($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
2324 $content = FALSE;
2325 if (isset($report)) {
2326 $report['error'] = 0;
2327 $report['message'] = '';
2328 }
2329 // Use cURL for: http, https, ftp, ftps, sftp and scp
2330 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2331 if (isset($report)) {
2332 $report['lib'] = 'cURL';
2333 }
2334 // External URL without error checking.
2335 if (!function_exists('curl_init') || !($ch = curl_init())) {
2336 if (isset($report)) {
2337 $report['error'] = -1;
2338 $report['message'] = 'Couldn\'t initialize cURL.';
2339 }
2340 return FALSE;
2341 }
2342
2343 $followLocationSucceeded = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
2344
2345 curl_setopt($ch, CURLOPT_URL, $url);
2346 curl_setopt($ch, CURLOPT_HEADER, !$followLocationSucceeded || $includeHeader ? 1 : 0);
2347 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
2348 curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
2349 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2350 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
2351 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout']));
2352
2353 if (is_array($requestHeaders)) {
2354 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
2355 }
2356 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2357 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2358 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2359 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyNTLM']) {
2360 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
2361 }
2362 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2363 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2364 }
2365 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2366 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2367 }
2368 }
2369 $content = curl_exec($ch);
2370 $curlInfo = curl_getinfo($ch);
2371
2372 if (!$followLocationSucceeded) {
2373 // Check if we need to do redirects
2374 if ($curlInfo['http_code'] >= 300 && $curlInfo['http_code'] < 400) {
2375 $locationUrl = $curlInfo['redirect_url'];
2376 if (!$locationUrl) {
2377 // Some curllib versions do not return redirect_url. Examine headers.
2378 $locationUrl = self::getRedirectUrlFromHttpHeaders($content);
2379 }
2380 if ($locationUrl) {
2381 $content = self::getUrl($locationUrl, $includeHeader, $requestHeaders, $report);
2382 $followLocationSucceeded = TRUE;
2383 } else {
2384 // Failure: we got a redirection status code but not the URL to redirect to.
2385 $content = FALSE;
2386 }
2387 }
2388 if ($content && !$includeHeader) {
2389 $content = self::stripHttpHeaders($content);
2390 }
2391 }
2392
2393 if (isset($report)) {
2394 if (!$followLocationSucceeded && $curlInfo['http_code'] >= 300 && $curlInfo['http_code'] < 400) {
2395 $report['http_code'] = $curlInfo['http_code'];
2396 $report['content_type'] = $curlInfo['content_type'];
2397 $report['error'] = CURLE_GOT_NOTHING;
2398 $report['message'] = 'Expected "Location" header but got nothing.';
2399 } elseif ($content === FALSE) {
2400 $report['error'] = curl_errno($ch);
2401 $report['message'] = curl_error($ch);
2402 } elseif ($includeHeader) {
2403 // Set only for $includeHeader to work exactly like PHP variant
2404 $report['http_code'] = $curlInfo['http_code'];
2405 $report['content_type'] = $curlInfo['content_type'];
2406 }
2407 }
2408 curl_close($ch);
2409 } elseif ($includeHeader) {
2410 if (isset($report)) {
2411 $report['lib'] = 'socket';
2412 }
2413 $parsedURL = parse_url($url);
2414 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2415 if (isset($report)) {
2416 $report['error'] = -1;
2417 $report['message'] = 'Reading headers is not allowed for this protocol.';
2418 }
2419 return FALSE;
2420 }
2421 $port = (int)$parsedURL['port'];
2422 if ($port < 1) {
2423 if ($parsedURL['scheme'] == 'http') {
2424 $port = $port > 0 ? $port : 80;
2425 $scheme = '';
2426 } else {
2427 $port = $port > 0 ? $port : 443;
2428 $scheme = 'ssl://';
2429 }
2430 }
2431 $errno = 0;
2432 $fp = @fsockopen(($scheme . $parsedURL['host']), $port, $errno, $errstr, 2.0);
2433 if (!$fp || $errno > 0) {
2434 if (isset($report)) {
2435 $report['error'] = $errno ?: -1;
2436 $report['message'] = $errno ? ($errstr ?: 'Socket error.') : 'Socket initialization error.';
2437 }
2438 return FALSE;
2439 }
2440 $method = $includeHeader == 2 ? 'HEAD' : 'GET';
2441 $msg = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/') . ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') . ' HTTP/1.0' . CRLF . 'Host: ' . $parsedURL['host'] . '
2442
2443 Connection: close
2444
2445 ';
2446 if (is_array($requestHeaders)) {
2447 $msg .= implode(CRLF, $requestHeaders) . CRLF;
2448 }
2449 $msg .= CRLF;
2450 fputs($fp, $msg);
2451 while (!feof($fp)) {
2452 $line = fgets($fp, 2048);
2453 if (isset($report)) {
2454 if (preg_match('|^HTTP/\\d\\.\\d +(\\d+)|', $line, $status)) {
2455 $report['http_code'] = $status[1];
2456 } elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2457 $report['content_type'] = $type[1];
2458 }
2459 }
2460 $content .= $line;
2461 if (trim($line) === '') {
2462 // Stop at the first empty line (= end of header)
2463 break;
2464 }
2465 }
2466 if ($includeHeader != 2) {
2467 $content .= stream_get_contents($fp);
2468 }
2469 fclose($fp);
2470 } elseif (is_array($requestHeaders)) {
2471 if (isset($report)) {
2472 $report['lib'] = 'file/context';
2473 }
2474 $parsedURL = parse_url($url);
2475 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2476 if (isset($report)) {
2477 $report['error'] = -1;
2478 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2479 }
2480 return FALSE;
2481 }
2482 $ctx = stream_context_create(array(
2483 'http' => array(
2484 'header' => implode(CRLF, $requestHeaders)
2485 )
2486 ));
2487 $content = @file_get_contents($url, FALSE, $ctx);
2488 if ($content === FALSE && isset($report)) {
2489 $report['error'] = -1;
2490 $report['message'] = 'Couldn\'t get URL: ' . (isset($http_response_header) ? implode(LF, $http_response_header) : $url);
2491 }
2492 } else {
2493 if (isset($report)) {
2494 $report['lib'] = 'file';
2495 }
2496 $content = @file_get_contents($url);
2497 if ($content === FALSE && isset($report)) {
2498 $report['error'] = -1;
2499 $report['message'] = 'Couldn\'t get URL: ' . (isset($http_response_header) ? implode(LF, $http_response_header) : $url);
2500 }
2501 }
2502 return $content;
2503 }
2504
2505 /**
2506 * Parses HTTP headers and returns the content of the "Location" header
2507 * or the empty string if no such header found.
2508 *
2509 * @param string $content
2510 * @return string
2511 */
2512 static protected function getRedirectUrlFromHttpHeaders($content) {
2513 $result = '';
2514 $headers = explode("\r\n", $content);
2515 foreach ($headers as $header) {
2516 if ($header == '') {
2517 break;
2518 }
2519 if (preg_match('/^\s*Location\s*:/i', $header)) {
2520 list(, $result) = self::trimExplode(':', $header, FALSE, 2);
2521 if ($result) {
2522 $result = self::locationHeaderUrl($result);
2523 }
2524 break;
2525 }
2526 }
2527 return $result;
2528 }
2529
2530 /**
2531 * Strips HTTP headers from the content.
2532 *
2533 * @param string $content
2534 * @return string
2535 */
2536 static protected function stripHttpHeaders($content) {
2537 $headersEndPos = strpos($content, "\r\n\r\n");
2538 if ($headersEndPos) {
2539 $content = substr($content, $headersEndPos + 4);
2540 }
2541 return $content;
2542 }
2543
2544 /**
2545 * Writes $content to the file $file
2546 *
2547 * @param string $file Filepath to write to
2548 * @param string $content Content to write
2549 * @param bool $changePermissions If TRUE, permissions are forced to be set
2550 * @return bool TRUE if the file was successfully opened and written to.
2551 */
2552 static public function writeFile($file, $content, $changePermissions = FALSE) {
2553 if (!@is_file($file)) {
2554 $changePermissions = TRUE;
2555 }
2556 if ($fd = fopen($file, 'wb')) {
2557 $res = fwrite($fd, $content);
2558 fclose($fd);
2559 if ($res === FALSE) {
2560 return FALSE;
2561 }
2562 // Change the permissions only if the file has just been created
2563 if ($changePermissions) {
2564 self::fixPermissions($file);
2565 }
2566 return TRUE;
2567 }
2568 return FALSE;
2569 }
2570
2571 /**
2572 * Sets the file system mode and group ownership of a file or a folder.
2573 *
2574 * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2575 * @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2576 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2577 */
2578 static public function fixPermissions($path, $recursive = FALSE) {
2579 if (TYPO3_OS != 'WIN') {
2580 $result = FALSE;
2581 // Make path absolute
2582 if (!self::isAbsPath($path)) {
2583 $path = self::getFileAbsFileName($path, FALSE);
2584 }
2585 if (self::isAllowedAbsPath($path)) {
2586 if (@is_file($path)) {
2587 $targetFilePermissions = isset($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])
2588 ? octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])
2589 : octdec('0644');
2590 // "@" is there because file is not necessarily OWNED by the user
2591 $result = @chmod($path, $targetFilePermissions);
2592 } elseif (@is_dir($path)) {
2593 $targetDirectoryPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])
2594 ? octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])
2595 : octdec('0755');
2596 // "@" is there because file is not necessarily OWNED by the user
2597 $result = @chmod($path, $targetDirectoryPermissions);
2598 }
2599 // Set createGroup if not empty
2600 if (
2601 isset($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])
2602 && $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'] !== ''
2603 ) {
2604 // "@" is there because file is not necessarily OWNED by the user
2605 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2606 $result = $changeGroupResult ? $result : FALSE;
2607 }
2608 // Call recursive if recursive flag if set and $path is directory
2609 if ($recursive && @is_dir($path)) {
2610 $handle = opendir($path);
2611 while (($file = readdir($handle)) !== FALSE) {
2612 $recursionResult = NULL;
2613 if ($file !== '.' && $file !== '..') {
2614 if (@is_file(($path . '/' . $file))) {
2615 $recursionResult = self::fixPermissions($path . '/' . $file);
2616 } elseif (@is_dir(($path . '/' . $file))) {
2617 $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
2618 }
2619 if (isset($recursionResult) && !$recursionResult) {
2620 $result = FALSE;
2621 }
2622 }
2623 }
2624 closedir($handle);
2625 }
2626 }
2627 } else {
2628 $result = TRUE;
2629 }
2630 return $result;
2631 }
2632
2633 /**
2634 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2635 * Accepts an additional subdirectory in the file path!
2636 *
2637 * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/
2638 * @param string $content Content string to write
2639 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2640 */
2641 static public function writeFileToTypo3tempDir($filepath, $content) {
2642 // Parse filepath into directory and basename:
2643 $fI = pathinfo($filepath);
2644 $fI['dirname'] .= '/';
2645 // Check parts:
2646 if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
2647 if (defined('PATH_site')) {
2648 // Setting main temporary directory name (standard)
2649 $dirName = PATH_site . 'typo3temp/';
2650 if (@is_dir($dirName)) {
2651 if (self::isFirstPartOfStr($fI['dirname'], $dirName)) {
2652 // Checking if the "subdir" is found:
2653 $subdir = substr($fI['dirname'], strlen($dirName));
2654 if ($subdir) {
2655 if (preg_match('/^[[:alnum:]_]+\\/$/', $subdir) || preg_match('/^[[:alnum:]_]+\\/[[:alnum:]_]+\\/$/', $subdir)) {
2656 $dirName .= $subdir;
2657 if (!@is_dir($dirName)) {
2658 self::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
2659 }
2660 } else {
2661 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2662 }
2663 }
2664 // Checking dir-name again (sub-dir might have been created):
2665 if (@is_dir($dirName)) {
2666 if ($filepath == $dirName . $fI['basename']) {
2667 self::writeFile($filepath, $content);
2668 if (!@is_file($filepath)) {
2669 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2670 }
2671 } else {
2672 return 'Calculated filelocation didn\'t match input $filepath!';
2673 }
2674 } else {
2675 return '"' . $dirName . '" is not a directory!';
2676 }
2677 } else {
2678 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2679 }
2680 } else {
2681 return 'PATH_site + "typo3temp/" was not a directory!';
2682 }
2683 } else {
2684 return 'PATH_site constant was NOT defined!';
2685 }
2686 } else {
2687 return 'Input filepath "' . $filepath . '" was generally invalid!';
2688 }
2689 }
2690
2691 /**
2692 * Wrapper function for mkdir.
2693 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
2694 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2695 *
2696 * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2697 * @return bool TRUE if @mkdir went well!
2698 */
2699 static public function mkdir($newFolder) {
2700 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2701 if ($result) {
2702 self::fixPermissions($newFolder);
2703 }
2704 return $result;
2705 }
2706
2707 /**
2708 * Creates a directory - including parent directories if necessary and
2709 * sets permissions on newly created directories.
2710 *
2711 * @param string $directory Target directory to create. Must a have trailing slash
2712 * @param string $deepDirectory Directory to create. This second parameter
2713 * @return void
2714 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2715 * @throws \RuntimeException If directory could not be created
2716 */
2717 static public function mkdir_deep($directory, $deepDirectory = '') {
2718 if (!is_string($directory)) {
2719 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955);
2720 }
2721 if (!is_string($deepDirectory)) {
2722 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.', 1303662956);
2723 }
2724 // Ensure there is only one slash
2725 $fullPath = rtrim($directory, '/') . '/' . ltrim($deepDirectory, '/');
2726 if ($fullPath !== '' && !is_dir($fullPath)) {
2727 $firstCreatedPath = self::createDirectoryPath($fullPath);
2728 if ($firstCreatedPath !== '') {
2729 self::fixPermissions($firstCreatedPath, TRUE);
2730 }
2731 }
2732 }
2733
2734 /**
2735 * Creates directories for the specified paths if they do not exist. This
2736 * functions sets proper permission mask but does not set proper user and
2737 * group.
2738 *
2739 * @static
2740 * @param string $fullDirectoryPath
2741 * @return string Path to the the first created directory in the hierarchy
2742 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep
2743 * @throws \RuntimeException If directory could not be created
2744 */
2745 static protected function createDirectoryPath($fullDirectoryPath) {
2746 $currentPath = $fullDirectoryPath;
2747 $firstCreatedPath = '';
2748 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']);
2749 if (!@is_dir($currentPath)) {
2750 do {
2751 $firstCreatedPath = $currentPath;
2752 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR);
2753 $currentPath = substr($currentPath, 0, $separatorPosition);
2754 } while (!is_dir($currentPath) && $separatorPosition !== FALSE);
2755 $result = @mkdir($fullDirectoryPath, $permissionMask, TRUE);
2756 // Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir()
2757 if (!$result && !@is_dir($fullDirectoryPath)) {
2758 throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401);
2759 }
2760 }
2761 return $firstCreatedPath;
2762 }
2763
2764 /**
2765 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2766 *
2767 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2768 * @param bool $removeNonEmpty Allow deletion of non-empty directories
2769 * @return bool TRUE if @rmdir went well!
2770 */
2771 static public function rmdir($path, $removeNonEmpty = FALSE) {
2772 $OK = FALSE;
2773 // Remove trailing slash
2774 $path = preg_replace('|/$|', '', $path);
2775 if (file_exists($path)) {
2776 $OK = TRUE;
2777 if (!is_link($path) && is_dir($path)) {
2778 if ($removeNonEmpty == TRUE && ($handle = opendir($path))) {
2779 while ($OK && FALSE !== ($file = readdir($handle))) {
2780 if ($file == '.' || $file == '..') {
2781 continue;
2782 }
2783 $OK = self::rmdir($path . '/' . $file, $removeNonEmpty);
2784 }
2785 closedir($handle);
2786 }
2787 if ($OK) {
2788 $OK = @rmdir($path);
2789 }
2790 } elseif (is_link($path) && is_dir($path) && TYPO3_OS === 'WIN') {
2791 $OK = rmdir($path);
2792 } else {
2793 // If $path is a file, simply remove it
2794 $OK = unlink($path);
2795 }
2796 clearstatcache();
2797 } elseif (is_link($path)) {
2798 $OK = unlink($path);
2799 clearstatcache();
2800 }
2801 return $OK;
2802 }
2803
2804 /**
2805 * Flushes a directory by first moving to a temporary resource, and then
2806 * triggering the remove process. This way directories can be flushed faster
2807 * to prevent race conditions on concurrent processes accessing the same directory.
2808 *
2809 * @param string $directory The directory to be renamed and flushed
2810 * @param bool $keepOriginalDirectory Whether to only empty the directory and not remove it
2811 * @return bool Whether the action was successful
2812 */
2813 static public function flushDirectory($directory, $keepOriginalDirectory = FALSE) {
2814 $result = FALSE;
2815
2816 if (is_dir($directory)) {
2817 $temporaryDirectory = rtrim($directory, '/') . '.' . uniqid('remove', TRUE) . '/';
2818 if (rename($directory, $temporaryDirectory)) {
2819 if ($keepOriginalDirectory) {
2820 self::mkdir($directory);
2821 }
2822 clearstatcache();
2823 $result = self::rmdir($temporaryDirectory, TRUE);
2824 }
2825 }
2826
2827 return $result;
2828 }
2829
2830 /**
2831 * Returns an array with the names of folders in a specific path
2832 * Will return 'error' (string) if there were an error with reading directory content.
2833 *
2834 * @param string $path Path to list directories from
2835 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2836 */
2837 static public function get_dirs($path) {
2838 if ($path) {
2839 if (is_dir($path)) {
2840 $dir = scandir($path);
2841 $dirs = array();
2842 foreach ($dir as $entry) {
2843 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
2844 $dirs[] = $entry;
2845 }
2846 }
2847 } else {
2848 $dirs = 'error';
2849 }
2850 }
2851 return $dirs;
2852 }
2853
2854 /**
2855 * Finds all files in a given path and returns them as an array. Each
2856 * array key is a md5 hash of the full path to the file. This is done because
2857 * 'some' extensions like the import/export extension depend on this.
2858 *
2859 * @param string $path The path to retrieve the files from.
2860 * @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.
2861 * @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned.
2862 * @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time.
2863 * @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 '$/'.
2864 * @return array|string Array of the files found, or an error message in case the path could not be opened.
2865 */
2866 static public function getFilesInDir($path, $extensionList = '', $prependPath = FALSE, $order = '', $excludePattern = '') {
2867 $excludePattern = (string)$excludePattern;
2868 $path = rtrim($path, '/');
2869 if (!@is_dir($path)) {
2870 return array();
2871 }
2872
2873 $rawFileList = scandir($path);
2874 if ($rawFileList === FALSE) {
2875 return 'error opening path: "' . $path . '"';
2876 }
2877
2878 $pathPrefix = $path . '/';
2879 $extensionList = ',' . $extensionList . ',';
2880 $files = array();
2881 foreach ($rawFileList as $entry) {
2882 $completePathToEntry = $pathPrefix . $entry;
2883 if (!@is_file($completePathToEntry)) {
2884 continue;
2885 }
2886
2887 if (
2888 ($extensionList === ',,' || stripos($extensionList, ',' . pathinfo($entry, PATHINFO_EXTENSION) . ',') !== FALSE)
2889 && ($excludePattern === '' || !preg_match(('/^' . $excludePattern . '$/'), $entry))
2890 ) {
2891 if ($order !== 'mtime') {
2892 $files[] = $entry;
2893 } else {
2894 // Store the value in the key so we can do a fast asort later.
2895 $files[$entry] = filemtime($completePathToEntry);
2896 }
2897 }
2898 }
2899
2900 $valueName = 'value';
2901 if ($order === 'mtime') {
2902 asort($files);
2903 $valueName = 'key';
2904 }
2905
2906 $valuePathPrefix = $prependPath ? $pathPrefix : '';
2907 $foundFiles = array();
2908 foreach ($files as $key => $value) {
2909 // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
2910 $foundFiles[md5($pathPrefix . ${$valueName})] = $valuePathPrefix . ${$valueName};
2911 }
2912
2913 return $foundFiles;
2914 }
2915
2916 /**
2917 * Recursively gather all files and folders of a path.
2918 *
2919 * @param array $fileArr Empty input array (will have files added to it)
2920 * @param string $path The path to read recursively from (absolute) (include trailing slash!)
2921 * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2922 * @param bool $regDirs If set, directories are also included in output.
2923 * @param int $recursivityLevels The number of levels to dig down...
2924 * @param string $excludePattern regex pattern of files/directories to exclude
2925 * @return array An array with the found files/directories.
2926 */
2927 static public function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = FALSE, $recursivityLevels = 99, $excludePattern = '') {
2928 if ($regDirs) {
2929 $fileArr[md5($path)] = $path;
2930 }
2931 $fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
2932 $dirs = self::get_dirs($path);
2933 if ($recursivityLevels > 0 && is_array($dirs)) {
2934 foreach ($dirs as $subdirs) {
2935 if ((string)$subdirs !== '' && ($excludePattern === '' || !preg_match(('/^' . $excludePattern . '$/'), $subdirs))) {
2936 $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
2937 }
2938 }
2939 }
2940 return $fileArr;
2941 }
2942
2943 /**