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