GeneralUtility.php 198 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Core\Utility;

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
Wouter Wolters's avatar
Wouter Wolters committed
16

17
18
use TYPO3\CMS\Core\Core\ApplicationContext;
use TYPO3\CMS\Core\Core\ClassLoader;
19
use TYPO3\CMS\Core\Imaging\GraphicalFunctions;
20
21
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Frontend\Page\PageRepository;
22

23
24
25
26
27
28
29
30
31
/**
 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
 * Most of the functions do not relate specifically to TYPO3
 * However a section of functions requires certain TYPO3 features available
 * See comments in the source.
 * You are encouraged to use this library in your own scripts!
 *
 * USE:
 * The class is intended to be used without creating an instance of it.
32
 * So: Don't instantiate - call functions with "\TYPO3\CMS\Core\Utility\GeneralUtility::" prefixed the function name.
33
 * So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'
34
35
36
37
38
 *
 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
 */
class GeneralUtility {

39
	// Severity constants used by \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
40
41
42
43
44
	const SYSLOG_SEVERITY_INFO = 0;
	const SYSLOG_SEVERITY_NOTICE = 1;
	const SYSLOG_SEVERITY_WARNING = 2;
	const SYSLOG_SEVERITY_ERROR = 3;
	const SYSLOG_SEVERITY_FATAL = 4;
45
46
47
48
49
50
51
52
53
54
55
56

	const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*';
	const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME';

	/**
	 * State of host header value security check
	 * in order to avoid unnecessary multiple checks during one request
	 *
	 * @var bool
	 */
	static protected $allowHostHeaderValue = FALSE;

57
58
59
60
	/**
	 * Singleton instances returned by makeInstance, using the class names as
	 * array keys
	 *
Christian Kuhn's avatar
Christian Kuhn committed
61
	 * @var array<\TYPO3\CMS\Core\SingletonInterface>
62
63
64
65
66
67
68
69
70
71
	 */
	static protected $singletonInstances = array();

	/**
	 * Instances returned by makeInstance, using the class names as array keys
	 *
	 * @var array<array><object>
	 */
	static protected $nonSingletonInstances = array();

72
73
74
75
76
77
78
	/**
	 * Cache for makeInstance with given class name and final class names to reduce number of self::getClassName() calls
	 *
	 * @var array Given class name => final class name
	 */
	static protected $finalClassNameCache = array();

79
80
81
82
83
	/**
	 * The application context
	 *
	 * @var \TYPO3\CMS\Core\Core\ApplicationContext
	 */
84
	static protected $applicationContext = NULL;
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
	/**
	 * IDNA string cache
	 *
	 * @var array<string>
	 */
	static protected $idnaStringCache = array();

	/**
	 * IDNA converter
	 *
	 * @var \idna_convert
	 */
	static protected $idnaConverter = NULL;

100
101
102
103
104
105
106
107
108
109
110
111
112
	/**
	 * A list of supported CGI server APIs
	 * NOTICE: This is a duplicate of the SAME array in SystemEnvironmentBuilder
	 * @var array
	 */
	static protected $supportedCgiServerApis = array(
		'fpm-fcgi',
		'cgi',
		'isapi',
		'cgi-fcgi',
		'srv', // HHVM with fastcgi
	);

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
	/*************************
	 *
	 * GET/POST Variables
	 *
	 * Background:
	 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
	 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
	 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
	 * Eventually TYPO3 should provide this in the global space as well.
	 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
	 *
	 *************************/
	/**
	 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
	 * Strips slashes from all output, both strings and arrays.
128
	 * To enhancement security in your scripts, please consider using \TYPO3\CMS\Core\Utility\GeneralUtility::_GET or \TYPO3\CMS\Core\Utility\GeneralUtility::_POST if you already
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
	 * know by which method your data is arriving to the scripts!
	 *
	 * @param string $var GET/POST var to return
	 * @return mixed POST var named $var and if not set, the GET var of the same name.
	 */
	static public function _GP($var) {
		if (empty($var)) {
			return;
		}
		$value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
		if (isset($value)) {
			if (is_array($value)) {
				self::stripSlashesOnArray($value);
			} else {
				$value = stripslashes($value);
			}
		}
		return $value;
	}

	/**
	 * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
	 *
	 * @param string $parameter Key (variable name) from GET or POST vars
	 * @return array Returns the GET vars merged recursively onto the POST vars.
	 */
	static public function _GPmerged($parameter) {
		$postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : array();
		$getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : array();
158
159
		$mergedParameters = $getParameter;
		ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter);
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
		self::stripSlashesOnArray($mergedParameters);
		return $mergedParameters;
	}

	/**
	 * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
	 * ALWAYS use this API function to acquire the GET variables!
	 *
	 * @param string $var Optional pointer to value in GET array (basically name of GET var)
	 * @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!*
	 * @see _POST(), _GP(), _GETset()
	 */
	static public function _GET($var = NULL) {
		$value = $var === NULL ? $_GET : (empty($var) ? NULL : $_GET[$var]);
		// Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
		if (isset($value)) {
			if (is_array($value)) {
				self::stripSlashesOnArray($value);
			} else {
				$value = stripslashes($value);
			}
		}
		return $value;
	}

	/**
	 * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
	 * ALWAYS use this API function to acquire the $_POST variables!
	 *
	 * @param string $var Optional pointer to value in POST array (basically name of POST var)
	 * @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!*
	 * @see _GET(), _GP()
	 */
	static public function _POST($var = NULL) {
		$value = $var === NULL ? $_POST : (empty($var) ? NULL : $_POST[$var]);
		// Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
		if (isset($value)) {
			if (is_array($value)) {
				self::stripSlashesOnArray($value);
			} else {
				$value = stripslashes($value);
			}
		}
		return $value;
	}

	/**
	 * Writes input value to $_GET.
	 *
	 * @param mixed $inputGet
	 * @param string $key
	 * @return void
	 */
	static public function _GETset($inputGet, $key = '') {
		// Adds slashes since TYPO3 standard currently is that slashes
		// must be applied (regardless of magic_quotes setting)
		if (is_array($inputGet)) {
			self::addSlashesOnArray($inputGet);
		} else {
			$inputGet = addslashes($inputGet);
		}
		if ($key != '') {
			if (strpos($key, '|') !== FALSE) {
				$pieces = explode('|', $key);
				$newGet = array();
225
				$pointer = &$newGet;
226
				foreach ($pieces as $piece) {
227
					$pointer = &$pointer[$piece];
228
229
				}
				$pointer = $inputGet;
230
231
				$mergedGet = $_GET;
				ArrayUtility::mergeRecursiveWithOverrule($mergedGet, $newGet);
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
				$_GET = $mergedGet;
				$GLOBALS['HTTP_GET_VARS'] = $mergedGet;
			} else {
				$_GET[$key] = $inputGet;
				$GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
			}
		} elseif (is_array($inputGet)) {
			$_GET = $inputGet;
			$GLOBALS['HTTP_GET_VARS'] = $inputGet;
		}
	}

	/**
	 * Wrapper for the RemoveXSS function.
	 * Removes potential XSS code from an input string.
	 *
	 * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
	 *
	 * @param string $string Input string
	 * @return string Input string with potential XSS code removed
	 */
	static public function removeXSS($string) {
Benni Mack's avatar
Benni Mack committed
254
		return \RemoveXSS::process($string);
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
	}

	/*************************
	 *
	 * IMAGE FUNCTIONS
	 *
	 *************************/
	/**
	 * Compressing a GIF file if not already LZW compressed.
	 * 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)
	 *
	 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
	 * GIF:
	 * 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!)
	 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
	 * PNG:
	 * No changes.
	 *
	 * $theFile is expected to be a valid GIF-file!
	 * The function returns a code for the operation.
	 *
	 * @param string $theFile Filepath
	 * @param string $type See description of function
	 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
279
	 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Use \TYPO3\CMS\Core\Imaging\GraphicalFunctions::gifCompress() instead.
280
281
	 */
	static public function gif_compress($theFile, $type) {
282
283
		static::logDeprecatedFunction();
		$returnCode = GraphicalFunctions::gifCompress($theFile, $type);
284
285
286
287
288
289
290
291
292
		return $returnCode;
	}

	/**
	 * Converts a png file to gif.
	 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set TRUE.
	 *
	 * @param string $theFile The filename with path
	 * @return string New filename
293
	 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Use \TYPO3\CMS\Core\Imaging\GraphicalFunctions::pngToGifByImagemagick() instead.
294
295
	 */
	static public function png_to_gif_by_imagemagick($theFile) {
296
297
298
		static::logDeprecatedFunction();
		$newFile = GraphicalFunctions::pngToGifByImagemagick($theFile);
		return $newFile;
299
300
301
302
303
304
305
	}

	/**
	 * Returns filename of the png/gif version of the input file (which can be png or gif).
	 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
	 *
	 * @param string $theFile Filepath of image file
306
	 * @param bool $output_png If set, then input file is converted to PNG, otherwise to GIF
307
	 * @return string If the new image file exists, its filepath is returned
308
	 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8. Use \TYPO3\CMS\Core\Imaging\GraphicalFunctions::readPngGif() instead.
309
310
	 */
	static public function read_png_gif($theFile, $output_png = FALSE) {
311
312
313
		static::logDeprecatedFunction();
		$newFile = GraphicalFunctions::readPngGif($theFile, $output_png);
		return $newFile;
314
315
316
317
318
319
320
321
322
323
324
	}

	/*************************
	 *
	 * STRING FUNCTIONS
	 *
	 *************************/
	/**
	 * Truncates a string with appended/prepended "..." and takes current character set into consideration.
	 *
	 * @param string $string String to truncate
325
	 * @param int $chars Must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
326
327
328
329
330
331
332
333
334
335
336
	 * @param string $appendString Appendix to the truncated string
	 * @return string Cropped string
	 */
	static public function fixed_lgd_cs($string, $chars, $appendString = '...') {
		if (is_object($GLOBALS['LANG'])) {
			return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
		} elseif (is_object($GLOBALS['TSFE'])) {
			$charSet = $GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet;
			return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString);
		} else {
			// This case should not happen
337
			$csConvObj = self::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
338
339
340
341
342
343
344
345
346
347
			return $csConvObj->crop('utf-8', $string, $chars, $appendString);
		}
	}

	/**
	 * Match IP number with list of numbers with wildcard
	 * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
	 *
	 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
	 * @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE.
348
	 * @return bool TRUE if an IP-mask from $list matches $baseIP
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
	 */
	static public function cmpIP($baseIP, $list) {
		$list = trim($list);
		if ($list === '') {
			return FALSE;
		} elseif ($list === '*') {
			return TRUE;
		}
		if (strpos($baseIP, ':') !== FALSE && self::validIPv6($baseIP)) {
			return self::cmpIPv6($baseIP, $list);
		} else {
			return self::cmpIPv4($baseIP, $list);
		}
	}

	/**
	 * Match IPv4 number with list of numbers with wildcard
	 *
	 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
	 * @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168), could also contain IPv6 addresses
369
	 * @return bool TRUE if an IP-mask from $list matches $baseIP
370
371
372
373
	 */
	static public function cmpIPv4($baseIP, $list) {
		$IPpartsReq = explode('.', $baseIP);
		if (count($IPpartsReq) == 4) {
374
			$values = self::trimExplode(',', $list, TRUE);
375
376
377
378
379
380
381
			foreach ($values as $test) {
				$testList = explode('/', $test);
				if (count($testList) == 2) {
					list($test, $mask) = $testList;
				} else {
					$mask = FALSE;
				}
382
				if ((int)$mask) {
383
384
385
386
387
388
389
					// "192.168.3.0/24"
					$lnet = ip2long($test);
					$lip = ip2long($baseIP);
					$binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
					$firstpart = substr($binnet, 0, $mask);
					$binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
					$firstip = substr($binip, 0, $mask);
390
					$yes = $firstpart === $firstip;
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
				} else {
					// "192.168.*.*"
					$IPparts = explode('.', $test);
					$yes = 1;
					foreach ($IPparts as $index => $val) {
						$val = trim($val);
						if ($val !== '*' && $IPpartsReq[$index] !== $val) {
							$yes = 0;
						}
					}
				}
				if ($yes) {
					return TRUE;
				}
			}
		}
		return FALSE;
	}

	/**
	 * Match IPv6 address with a list of IPv6 prefixes
	 *
	 * @param string $baseIP Is the current remote IP address for instance
	 * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
415
	 * @return bool TRUE If an baseIP matches any prefix
416
417
418
419
420
	 */
	static public function cmpIPv6($baseIP, $list) {
		// Policy default: Deny connection
		$success = FALSE;
		$baseIP = self::normalizeIPv6($baseIP);
421
		$values = self::trimExplode(',', $list, TRUE);
422
423
424
425
426
427
428
429
430
		foreach ($values as $test) {
			$testList = explode('/', $test);
			if (count($testList) == 2) {
				list($test, $mask) = $testList;
			} else {
				$mask = FALSE;
			}
			if (self::validIPv6($test)) {
				$test = self::normalizeIPv6($test);
431
				$maskInt = (int)$mask ?: 128;
432
433
434
435
436
437
438
439
440
441
442
				// Special case; /0 is an allowed mask - equals a wildcard
				if ($mask === '0') {
					$success = TRUE;
				} elseif ($maskInt == 128) {
					$success = $test === $baseIP;
				} else {
					$testBin = self::IPv6Hex2Bin($test);
					$baseIPBin = self::IPv6Hex2Bin($baseIP);
					$success = TRUE;
					// Modulo is 0 if this is a 8-bit-boundary
					$maskIntModulo = $maskInt % 8;
443
					$numFullCharactersUntilBoundary = (int)($maskInt / 8);
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
					if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) {
						$success = FALSE;
					} elseif ($maskIntModulo > 0) {
						// If not an 8-bit-boundary, check bits of last character
						$testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
						$baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
						if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
							$success = FALSE;
						}
					}
				}
			}
			if ($success) {
				return TRUE;
			}
		}
		return FALSE;
	}

	/**
	 * Transform a regular IPv6 address from hex-representation into binary
	 *
	 * @param string $hex IPv6 address in hex-presentation
	 * @return string Binary representation (16 characters, 128 characters)
	 * @see IPv6Bin2Hex()
	 */
	static public function IPv6Hex2Bin($hex) {
		return inet_pton($hex);
	}

	/**
	 * Transform an IPv6 address from binary to hex-representation
	 *
	 * @param string $bin IPv6 address in hex-presentation
	 * @return string Binary representation (16 characters, 128 characters)
	 * @see IPv6Hex2Bin()
	 */
	static public function IPv6Bin2Hex($bin) {
		return inet_ntop($bin);
	}

	/**
	 * Normalize an IPv6 address to full length
	 *
	 * @param string $address Given IPv6 address
	 * @return string Normalized address
	 * @see compressIPv6()
	 */
	static public function normalizeIPv6($address) {
		$normalizedAddress = '';
		$stageOneAddress = '';
		// According to RFC lowercase-representation is recommended
		$address = strtolower($address);
		// Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
		if (strlen($address) == 39) {
			// Already in full expanded form
			return $address;
		}
		// Count 2 if if address has hidden zero blocks
		$chunks = explode('::', $address);
		if (count($chunks) == 2) {
			$chunksLeft = explode(':', $chunks[0]);
			$chunksRight = explode(':', $chunks[1]);
			$left = count($chunksLeft);
			$right = count($chunksRight);
			// Special case: leading zero-only blocks count to 1, should be 0
			if ($left == 1 && strlen($chunksLeft[0]) == 0) {
				$left = 0;
			}
			$hiddenBlocks = 8 - ($left + $right);
			$hiddenPart = '';
			$h = 0;
			while ($h < $hiddenBlocks) {
				$hiddenPart .= '0000:';
				$h++;
			}
			if ($left == 0) {
				$stageOneAddress = $hiddenPart . $chunks[1];
			} else {
523
				$stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
			}
		} else {
			$stageOneAddress = $address;
		}
		// Normalize the blocks:
		$blocks = explode(':', $stageOneAddress);
		$divCounter = 0;
		foreach ($blocks as $block) {
			$tmpBlock = '';
			$i = 0;
			$hiddenZeros = 4 - strlen($block);
			while ($i < $hiddenZeros) {
				$tmpBlock .= '0';
				$i++;
			}
			$normalizedAddress .= $tmpBlock . $block;
			if ($divCounter < 7) {
				$normalizedAddress .= ':';
				$divCounter++;
			}
		}
		return $normalizedAddress;
	}

	/**
	 * Compress an IPv6 address to the shortest notation
	 *
	 * @param string $address Given IPv6 address
	 * @return string Compressed address
	 * @see normalizeIPv6()
	 */
	static public function compressIPv6($address) {
		return inet_ntop(inet_pton($address));
	}

	/**
	 * Validate a given IP address.
	 *
	 * Possible format are IPv4 and IPv6.
	 *
	 * @param string $ip IP address to be tested
565
	 * @return bool TRUE if $ip is either of IPv4 or IPv6 format.
566
567
568
569
570
571
572
573
574
575
576
	 */
	static public function validIP($ip) {
		return filter_var($ip, FILTER_VALIDATE_IP) !== FALSE;
	}

	/**
	 * Validate a given IP address to the IPv4 address format.
	 *
	 * Example for possible format: 10.0.45.99
	 *
	 * @param string $ip IP address to be tested
577
	 * @return bool TRUE if $ip is of IPv4 format.
578
579
580
581
582
583
584
585
586
587
588
	 */
	static public function validIPv4($ip) {
		return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE;
	}

	/**
	 * Validate a given IP address to the IPv6 address format.
	 *
	 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
	 *
	 * @param string $ip IP address to be tested
589
	 * @return bool TRUE if $ip is of IPv6 format.
590
591
592
593
594
595
596
597
598
599
	 */
	static public function validIPv6($ip) {
		return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE;
	}

	/**
	 * Match fully qualified domain name with list of strings with wildcard
	 *
	 * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
	 * @param string $list A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
600
	 * @return bool TRUE if a domain name mask from $list matches $baseIP
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
	 */
	static public function cmpFQDN($baseHost, $list) {
		$baseHost = trim($baseHost);
		if (empty($baseHost)) {
			return FALSE;
		}
		if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
			// Resolve hostname
			// Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
			// the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
			$baseHostName = gethostbyaddr($baseHost);
			if ($baseHostName === $baseHost) {
				// Unable to resolve hostname
				return FALSE;
			}
		} else {
			$baseHostName = $baseHost;
		}
		$baseHostNameParts = explode('.', $baseHostName);
620
		$values = self::trimExplode(',', $list, TRUE);
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
		foreach ($values as $test) {
			$hostNameParts = explode('.', $test);
			// To match hostNameParts can only be shorter (in case of wildcards) or equal
			if (count($hostNameParts) > count($baseHostNameParts)) {
				continue;
			}
			$yes = TRUE;
			foreach ($hostNameParts as $index => $val) {
				$val = trim($val);
				if ($val === '*') {
					// Wildcard valid for one or more hostname-parts
					$wildcardStart = $index + 1;
					// Wildcard as last/only part always matches, otherwise perform recursive checks
					if ($wildcardStart < count($hostNameParts)) {
						$wildcardMatched = FALSE;
						$tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
						while ($wildcardStart < count($baseHostNameParts) && !$wildcardMatched) {
							$tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
							$wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
							$wildcardStart++;
						}
						if ($wildcardMatched) {
							// Match found by recursive compare
							return TRUE;
						} else {
							$yes = FALSE;
						}
					}
				} elseif ($baseHostNameParts[$index] !== $val) {
					// In case of no match
					$yes = FALSE;
				}
			}
			if ($yes) {
				return TRUE;
			}
		}
		return FALSE;
	}

	/**
	 * Checks if a given URL matches the host that currently handles this HTTP request.
	 * Scheme, hostname and (optional) port of the given URL are compared.
	 *
	 * @param string $url URL to compare with the TYPO3 request host
666
	 * @return bool Whether the URL matches the TYPO3 request host
667
668
669
670
671
672
673
674
675
676
677
	 */
	static public function isOnCurrentHost($url) {
		return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
	}

	/**
	 * Check for item in list
	 * Check if an item exists in a comma-separated list of items.
	 *
	 * @param string $list Comma-separated list of items (string)
	 * @param string $item Item to check for
678
	 * @return bool TRUE if $item is in $list
679
680
	 */
	static public function inList($list, $item) {
681
		return strpos(',' . $list . ',', ',' . $item . ',') !== FALSE;
682
683
684
685
686
	}

	/**
	 * Removes an item from a comma-separated list of items.
	 *
687
	 * If $element contains a comma, the behaviour of this method is undefined.
688
	 * Empty elements in the list are preserved.
689
	 *
690
691
692
693
694
	 * @param string $element Element to remove
	 * @param string $list Comma-separated list of items (string)
	 * @return string New comma-separated list of items
	 */
	static public function rmFromList($element, $list) {
695
696
697
698
699
700
701
		$items = explode(',', $list);
		foreach ($items as $k => $v) {
			if ($v == $element) {
				unset($items[$k]);
			}
		}
		return implode(',', $items);
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
	}

	/**
	 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
	 * Ranges are limited to 1000 values per range.
	 *
	 * @param string $list Comma-separated list of integers with ranges (string)
	 * @return string New comma-separated list of items
	 */
	static public function expandList($list) {
		$items = explode(',', $list);
		$list = array();
		foreach ($items as $item) {
			$range = explode('-', $item);
			if (isset($range[1])) {
				$runAwayBrake = 1000;
				for ($n = $range[0]; $n <= $range[1]; $n++) {
					$list[] = $n;
					$runAwayBrake--;
					if ($runAwayBrake <= 0) {
						break;
					}
				}
			} else {
				$list[] = $item;
			}
		}
		return implode(',', $list);
	}

	/**
	 * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
	 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
	 *
	 * @param string $verNumberStr Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
737
	 * @return bool Returns TRUE if this setup is compatible with the provided version number
738
739
740
	 * @todo Still needs a function to convert versions to branches
	 */
	static public function compat_version($verNumberStr) {
741
		return VersionNumberUtility::convertVersionNumberToInteger(TYPO3_branch) >= VersionNumberUtility::convertVersionNumberToInteger($verNumberStr);
742
743
744
745
746
747
	}

	/**
	 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
	 *
	 * @param string $str String to md5-hash
748
	 * @return int Returns 28bit integer-hash
749
750
751
752
753
754
755
756
757
	 */
	static public function md5int($str) {
		return hexdec(substr(md5($str), 0, 7));
	}

	/**
	 * Returns the first 10 positions of the MD5-hash		(changed from 6 to 10 recently)
	 *
	 * @param string $input Input string to be md5-hashed
758
	 * @param int $len The string-length of the output
759
760
761
762
763
764
765
766
767
768
	 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
	 */
	static public function shortMD5($input, $len = 10) {
		return substr(md5($input), 0, $len);
	}

	/**
	 * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
	 *
	 * @param string $input Input string to create HMAC from
769
	 * @param string $additionalSecret additionalSecret to prevent hmac beeing used in a different context
770
771
	 * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
	 */
772
	static public function hmac($input, $additionalSecret = '') {
773
774
775
		$hashAlgorithm = 'sha1';
		$hashBlocksize = 64;
		$hmac = '';
776
		$secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
777
		if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
778
			$hmac = hash_hmac($hashAlgorithm, $input, $secret);
779
780
781
782
783
		} else {
			// Outer padding
			$opad = str_repeat(chr(92), $hashBlocksize);
			// Inner padding
			$ipad = str_repeat(chr(54), $hashBlocksize);
784
			if (strlen($secret) > $hashBlocksize) {
785
				// Keys longer than block size are shorten
786
				$key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, chr(0));
787
788
			} else {
				// Keys shorter than block size are zero-padded
789
				$key = str_pad($secret, $hashBlocksize, chr(0));
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
			}
			$hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, (($key ^ $ipad) . $input))));
		}
		return $hmac;
	}

	/**
	 * Takes comma-separated lists and arrays and removes all duplicates
	 * If a value in the list is trim(empty), the value is ignored.
	 *
	 * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
	 * @param mixed $secondParameter Dummy field, which if set will show a warning!
	 * @return string Returns the list without any duplicates of values, space around values are trimmed
	 */
	static public function uniqueList($in_list, $secondParameter = NULL) {
		if (is_array($in_list)) {
			throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
		}
		if (isset($secondParameter)) {
			throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!', 1270853886);
		}
811
		return implode(',', array_unique(self::trimExplode(',', $in_list, TRUE)));
812
813
814
815
816
	}

	/**
	 * Splits a reference to a file in 5 parts
	 *
817
	 * @param string $fileNameWithPath File name with path to be analysed (must exist if open_basedir is set)
818
819
	 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
	 */
820
	static public function split_fileref($fileNameWithPath) {
821
		$reg = array();
822
		if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) {
823
824
825
826
			$info['path'] = $reg[1];
			$info['file'] = $reg[2];
		} else {
			$info['path'] = '';
827
			$info['file'] = $fileNameWithPath;
828
829
		}
		$reg = '';
830
831
		// If open_basedir is set and the fileName was supplied without a path the is_dir check fails
		if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) {
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
			$info['filebody'] = $reg[1];
			$info['fileext'] = strtolower($reg[2]);
			$info['realFileext'] = $reg[2];
		} else {
			$info['filebody'] = $info['file'];
			$info['fileext'] = '';
		}
		reset($info);
		return $info;
	}

	/**
	 * Returns the directory part of a path without trailing slash
	 * If there is no dir-part, then an empty string is returned.
	 * Behaviour:
	 *
	 * '/dir1/dir2/script.php' => '/dir1/dir2'
	 * '/dir1/' => '/dir1'
	 * 'dir1/script.php' => 'dir1'
	 * 'd/script.php' => 'd'
	 * '/script.php' => ''
	 * '' => ''
	 *
	 * @param string $path Directory name / path
	 * @return string Processed input value. See function description.
	 */
	static public function dirname($path) {
		$p = self::revExplode('/', $path, 2);
		return count($p) == 2 ? $p[0] : '';
	}

	/**
	 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
	 *
	 * @param string $color A hexadecimal color code, #xxxxxx
867
868
869
	 * @param int $R Offset value 0-255
	 * @param int $G Offset value 0-255
	 * @param int $B Offset value 0-255
870
871
872
873
874
	 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
	 * @see modifyHTMLColorAll()
	 */
	static public function modifyHTMLColor($color, $R, $G, $B) {
		// This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
875
876
877
		$nR = MathUtility::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
		$nG = MathUtility::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
		$nB = MathUtility::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
878
		return '#' . substr(('0' . dechex($nR)), -2) . substr(('0' . dechex($nG)), -2) . substr(('0' . dechex($nB)), -2);
879
880
881
882
883
884
	}

	/**
	 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
	 *
	 * @param string $color A hexadecimal color code, #xxxxxx
885
	 * @param int $all Offset value 0-255 for all three channels.
886
887
888
889
890
891
892
893
894
895
896
897
	 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
	 * @see modifyHTMLColor()
	 */
	static public function modifyHTMLColorAll($color, $all) {
		return self::modifyHTMLColor($color, $all, $all, $all);
	}

	/**
	 * Returns TRUE if the first part of $str matches the string $partStr
	 *
	 * @param string $str Full string to check
	 * @param string $partStr Reference string which must be found as the "first part" of the full string
898
	 * @return bool TRUE if $partStr was found to be equal to the first part of $str
899
900
	 */
	static public function isFirstPartOfStr($str, $partStr) {
901
		return $partStr != '' && strpos((string)$str, (string)$partStr, 0) === 0;
902
903
904
905
906
	}

	/**
	 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
	 *
907
	 * @param int $sizeInBytes Number of bytes to format.
908
909
910
911
912
	 * @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)
	 * @return string Formatted representation of the byte number, for output.
	 */
	static public function formatSize($sizeInBytes, $labels = '') {
		// Set labels:
913
		if ($labels === '') {
914
915
916
917
918
919
920
			$labels = ' | K| M| G';
		} else {
			$labels = str_replace('"', '', $labels);
		}
		$labelArr = explode('|', $labels);
		// Find size:
		if ($sizeInBytes > 900) {
921
			// @todo find out which locale is used for current BE user to cover the BE case as well
922
923
924
925
926
927
928
929
930
			$locale = is_object($GLOBALS['TSFE']) ? $GLOBALS['TSFE']->config['config']['locale_all'] : '';
			$oldLocale = setlocale(LC_NUMERIC, 0);
			if ($locale) {
				setlocale(LC_NUMERIC, $locale);
			}
			$localeInfo = localeconv();
			if ($locale) {
				setlocale(LC_NUMERIC, $oldLocale);
			}
931
932
			// GB
			if ($sizeInBytes > 900000000) {
933
				$val = $sizeInBytes / (1024 * 1024 * 1024);
934
				return number_format($val, ($val < 20 ? 1 : 0), $localeInfo['decimal_point'], '') . $labelArr[3];
935
936
937
			} elseif ($sizeInBytes > 900000) {
				// MB
				$val = $sizeInBytes / (1024 * 1024);
938
				return number_format($val, ($val < 20 ? 1 : 0), $localeInfo['decimal_point'], '') . $labelArr[2];
939
940
941
			} else {
				// KB
				$val = $sizeInBytes / 1024;
942
				return number_format($val, ($val < 20 ? 1 : 0), $localeInfo['decimal_point'], '') . $labelArr[1];
943
944
945
946
947
948
949
950
951
952
953
			}
		} else {
			// Bytes
			return $sizeInBytes . $labelArr[0];
		}
	}

	/**
	 * Returns microtime input to milliseconds
	 *
	 * @param string $microtime Microtime
954
	 * @return int Microtime input string converted to an integer (milliseconds)
955
956
	 */
	static public function convertMicrotime($microtime) {
957
958
		$parts = explode(' ', $microtime);
		return round(($parts[0] + $parts[1]) * 1000);
959
960
961
962
963
964
965
966
	}

	/**
	 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
	 *
	 * @param string $string Input string, eg "123 + 456 / 789 - 4
	 * @param string $operators Operators to split by, typically "/+-*
	 * @return array Array with operators and operands separated.
967
	 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc(), \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
	 */
	static public function splitCalc($string, $operators) {
		$res = array();
		$sign = '+';
		while ($string) {
			$valueLen = strcspn($string, $operators);
			$value = substr($string, 0, $valueLen);
			$res[] = array($sign, trim($value));
			$sign = substr($string, $valueLen, 1);
			$string = substr($string, $valueLen + 1);
		}
		reset($res);
		return $res;
	}

	/**
	 * Re-converts HTML entities if they have been converted by htmlspecialchars()
985
986
	 * Note: Use htmlspecialchars($str, ENT_COMPAT, 'UTF-8', FALSE) to avoid double encoding.
	 *       This makes the call to this method obsolete.
987
988
989
	 *
	 * @param string $str String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;
	 * @return string Converted result.
990
	 *
991
992
993
994
995
996
997
998
999
	 */
	static public function deHSCentities($str) {
		return preg_replace('/&amp;([#[:alnum:]]*;)/', '&\\1', $str);
	}

	/**
	 * This function is used to escape any ' -characters when transferring text to JavaScript!
	 *
	 * @param string $string String to escape
1000
	 * @param bool $extended If set, also backslashes are escaped.