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