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