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