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