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