Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
   1  <?php
   2  /***************************************************************
   3   *  Copyright notice
   4   *
   5   *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
   6   *  All rights reserved
   7   *
   8   *  This script is part of the TYPO3 project. The TYPO3 project is
   9   *  free software; you can redistribute it and/or modify
  10   *  it under the terms of the GNU General Public License as published by
  11   *  the Free Software Foundation; either version 2 of the License, or
  12   *  (at your option) any later version.
  13   *
  14   *  The GNU General Public License can be found at
  15   *  http://www.gnu.org/copyleft/gpl.html.
  16   *  A copy is found in the textfile GPL.txt and important notices to the license
  17   *  from the author is found in LICENSE.txt distributed with these scripts.
  18   *
  19   *
  20   *  This script is distributed in the hope that it will be useful,
  21   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  22   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  23   *  GNU General Public License for more details.
  24   *
  25   *  This copyright notice MUST APPEAR in all copies of the script!
  26   ***************************************************************/
  27  
  28  	 // a tabulator
  29  define('TAB', chr(9));
  30  	 // a linefeed
  31  define('LF', chr(10));
  32  	 // a carriage return
  33  define('CR', chr(13));
  34  	 // a CR-LF combination
  35  define('CRLF', CR . LF);
  36  
  37  /**
  38   * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
  39   * Most of the functions do not relate specifically to TYPO3
  40   * However a section of functions requires certain TYPO3 features available
  41   * See comments in the source.
  42   * You are encouraged to use this library in your own scripts!
  43   *
  44   * USE:
  45   * The class is intended to be used without creating an instance of it.
  46   * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
  47   * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
  48   *
  49   * @author Kasper Skårhøj <kasperYYYY@typo3.com>
  50   * @package TYPO3
  51   * @subpackage t3lib
  52   */
  53  final class t3lib_div {
  54  
  55  	 	 // Severity constants used by t3lib_div::sysLog()
  56  	 const SYSLOG_SEVERITY_INFO = 0;
  57  	 const SYSLOG_SEVERITY_NOTICE = 1;
  58  	 const SYSLOG_SEVERITY_WARNING = 2;
  59  	 const SYSLOG_SEVERITY_ERROR = 3;
  60  	 const SYSLOG_SEVERITY_FATAL = 4;
  61  
  62  	 const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*';
  63  	 const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME';
  64  
  65  	 /**
  66  	  * State of host header value security check
  67  	  * in order to avoid unnecessary multiple checks during one request
  68  	  *
  69  	  * @var bool
  70  	  */
  71  	 static protected $allowHostHeaderValue = FALSE;
  72  
  73  	 /**
  74  	  * Singleton instances returned by makeInstance, using the class names as
  75  	  * array keys
  76  	  *
  77  	  * @var array<t3lib_Singleton>
  78  	  */
  79  	 protected static $singletonInstances = array();
  80  
  81  	 /**
  82  	  * Instances returned by makeInstance, using the class names as array keys
  83  	  *
  84  	  * @var array<array><object>
  85  	  */
  86  	 protected static $nonSingletonInstances = array();
  87  
  88  	 /**
  89  	  * Register for makeInstance with given class name and final class names to reduce number of class_exists() calls
  90  	  *
  91  	  * @var array Given class name => final class name
  92  	  */
  93  	 protected static $finalClassNameRegister = array();
  94  
  95  	 /*************************
  96  	  *
  97  	  * GET/POST Variables
  98  	  *
  99  	  * Background:
 100  	  * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
 101  	  * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
 102  	  * But the clean solution is that quotes are never escaped and that is what the functions below offers.
 103  	  * Eventually TYPO3 should provide this in the global space as well.
 104  	  * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
 105  	  *
 106  	  *************************/
 107  
 108  	 /**
 109  	  * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
 110  	  * Strips slashes from all output, both strings and arrays.
 111  	  * To enhancement security in your scripts, please consider using t3lib_div::_GET or t3lib_div::_POST if you already
 112  	  * know by which method your data is arriving to the scripts!
 113  	  *
 114  	  * @param string $var GET/POST var to return
 115  	  * @return mixed POST var named $var and if not set, the GET var of the same name.
 116  	  */
 117  	public static function _GP($var) {
 118  	 	 if (empty($var)) {
 119  	 	 	 return;
 120  	 	 }
 121  	 	 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
 122  	 	 if (isset($value)) {
 123  	 	 	 if (is_array($value)) {
 124  	 	 	 	 self::stripSlashesOnArray($value);
 125  	 	 	 } else {
 126  	 	 	 	 $value = stripslashes($value);
 127  	 	 	 }
 128  	 	 }
 129  	 	 return $value;
 130  	 }
 131  
 132  	 /**
 133  	  * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
 134  	  *
 135  	  * @param string $parameter Key (variable name) from GET or POST vars
 136  	  * @return array Returns the GET vars merged recursively onto the POST vars.
 137  	  */
 138  	public static function _GPmerged($parameter) {
 139  	 	 $postParameter = (isset($_POST[$parameter]) && is_array($_POST[$parameter])) ? $_POST[$parameter] : array();
 140  	 	 $getParameter = (isset($_GET[$parameter]) && is_array($_GET[$parameter])) ? $_GET[$parameter] : array();
 141  
 142  	 	 $mergedParameters = self::array_merge_recursive_overrule($getParameter, $postParameter);
 143  	 	 self::stripSlashesOnArray($mergedParameters);
 144  
 145  	 	 return $mergedParameters;
 146  	 }
 147  
 148  	 /**
 149  	  * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
 150  	  * ALWAYS use this API function to acquire the GET variables!
 151  	  *
 152  	  * @param string $var Optional pointer to value in GET array (basically name of GET var)
 153  	  * @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!*
 154  	  * @see _POST(), _GP(), _GETset()
 155  	  */
 156  	public static function _GET($var = NULL) {
 157  	 	 $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
 158  	 	 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
 159  	 	 	 if (is_array($value)) {
 160  	 	 	 	 self::stripSlashesOnArray($value);
 161  	 	 	 } else {
 162  	 	 	 	 $value = stripslashes($value);
 163  	 	 	 }
 164  	 	 }
 165  	 	 return $value;
 166  	 }
 167  
 168  	 /**
 169  	  * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
 170  	  * ALWAYS use this API function to acquire the $_POST variables!
 171  	  *
 172  	  * @param string $var Optional pointer to value in POST array (basically name of POST var)
 173  	  * @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!*
 174  	  * @see _GET(), _GP()
 175  	  */
 176  	public static function _POST($var = NULL) {
 177  	 	 $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
 178  	 	 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
 179  	 	 	 if (is_array($value)) {
 180  	 	 	 	 self::stripSlashesOnArray($value);
 181  	 	 	 } else {
 182  	 	 	 	 $value = stripslashes($value);
 183  	 	 	 }
 184  	 	 }
 185  	 	 return $value;
 186  	 }
 187  
 188  	 /**
 189  	  * Writes input value to $_GET.
 190  	  *
 191  	  * @param mixed $inputGet
 192  	  *	 	 array or single value to write to $_GET. Values should NOT be
 193  	  *	 	 escaped at input time (but will be escaped before writing
 194  	  *	 	 according to TYPO3 standards).
 195  	  * @param string $key
 196  	  *	 	 alternative key; If set, this will not set the WHOLE GET array,
 197  	  *	 	 but only the key in it specified by this value!
 198  	  *	 	 You can specify to replace keys on deeper array levels by
 199  	  *	 	 separating the keys with a pipe.
 200  	  *	 	 Example: 'parentKey|childKey' will result in
 201  	  *	 	 array('parentKey' => array('childKey' => $inputGet))
 202  	  *
 203  	  * @return void
 204  	  */
 205  	public static function _GETset($inputGet, $key = '') {
 206  	 	 	 // adds slashes since TYPO3 standard currently is that slashes
 207  	 	 	 // must be applied (regardless of magic_quotes setting)
 208  	 	 if (is_array($inputGet)) {
 209  	 	 	 self::addSlashesOnArray($inputGet);
 210  	 	 } else {
 211  	 	 	 $inputGet = addslashes($inputGet);
 212  	 	 }
 213  
 214  	 	 if ($key != '') {
 215  	 	 	 if (strpos($key, '|') !== FALSE) {
 216  	 	 	 	 $pieces = explode('|', $key);
 217  	 	 	 	 $newGet = array();
 218  	 	 	 	 $pointer =& $newGet;
 219  	 	 	 	 foreach ($pieces as $piece) {
 220  	 	 	 	 	 $pointer =& $pointer[$piece];
 221  	 	 	 	 }
 222  	 	 	 	 $pointer = $inputGet;
 223  	 	 	 	 $mergedGet = self::array_merge_recursive_overrule(
 224  	 	 	 	 	 $_GET, $newGet
 225  	 	 	 	 );
 226  
 227  	 	 	 	 $_GET = $mergedGet;
 228  	 	 	 	 $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
 229  	 	 	 } else {
 230  	 	 	 	 $_GET[$key] = $inputGet;
 231  	 	 	 	 $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
 232  	 	 	 }
 233  	 	 } elseif (is_array($inputGet)) {
 234  	 	 	 $_GET = $inputGet;
 235  	 	 	 $GLOBALS['HTTP_GET_VARS'] = $inputGet;
 236  	 	 }
 237  	 }
 238  
 239  	 /**
 240  	  * Wrapper for the RemoveXSS function.
 241  	  * Removes potential XSS code from an input string.
 242  	  *
 243  	  * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
 244  	  *
 245  	  * @param string $string Input string
 246  	  * @return string Input string with potential XSS code removed
 247  	  */
 248  	public static function removeXSS($string) {
 249  	 	 require_once(PATH_typo3 . 'contrib/RemoveXSS/RemoveXSS.php');
 250  	 	 $string = RemoveXSS::process($string);
 251  	 	 return $string;
 252  	 }
 253  
 254  
 255  	 /*************************
 256  	  *
 257  	  * IMAGE FUNCTIONS
 258  	  *
 259  	  *************************/
 260  
 261  
 262  	 /**
 263  	  * Compressing a GIF file if not already LZW compressed.
 264  	  * 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)
 265  	  *
 266  	  *	 	  The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
 267  	  *	 	  GIF:
 268  	  *	 	  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!)
 269  	  *	 	  If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
 270  	  *	 	  PNG:
 271  	  *	 	  No changes.
 272  	  *
 273  	  *	 	  $theFile is expected to be a valid GIF-file!
 274  	  *	 	  The function returns a code for the operation.
 275  	  *
 276  	  * @param string $theFile Filepath
 277  	  * @param string $type See description of function
 278  	  * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
 279  	  */
 280  	public static function gif_compress($theFile, $type) {
 281  	 	 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
 282  	 	 $returnCode = '';
 283  	 	 if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') { // GIF...
 284  	 	 	 if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
 285  	 	 	 	 	 // use temporary file to prevent problems with read and write lock on same file on network file systems
 286  	 	 	 	 $temporaryName  =  dirname($theFile) . '/' . md5(uniqid()) . '.gif';
 287  	 	 	 	 	 // rename could fail, if a simultaneous thread is currently working on the same thing
 288  	 	 	 	 if (@rename($theFile, $temporaryName)) {
 289  	 	 	 	 	 $cmd = self::imageMagickCommand('convert', '"' . $temporaryName . '" "' . $theFile . '"', $gfxConf['im_path_lzw']);
 290  	 	 	 	 	 t3lib_utility_Command::exec($cmd);
 291  	 	 	 	 	 unlink($temporaryName);
 292  	 	 	 	 }
 293  
 294  	 	 	 	 $returnCode = 'IM';
 295  	 	 	 	 if (@is_file($theFile)) {
 296  	 	 	 	 	 self::fixPermissions($theFile);
 297  	 	 	 	 }
 298  	 	 	 } elseif (($type == 'GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
 299  	 	 	 	 $tempImage = imageCreateFromGif($theFile);
 300  	 	 	 	 imageGif($tempImage, $theFile);
 301  	 	 	 	 imageDestroy($tempImage);
 302  	 	 	 	 $returnCode = 'GD';
 303  	 	 	 	 if (@is_file($theFile)) {
 304  	 	 	 	 	 self::fixPermissions($theFile);
 305  	 	 	 	 }
 306  	 	 	 }
 307  	 	 }
 308  	 	 return $returnCode;
 309  	 }
 310  
 311  	 /**
 312  	  * Converts a png file to gif.
 313  	  * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set TRUE.
 314  	  *
 315  	  * @param string $theFile the filename with path
 316  	  * @return string new filename
 317  	  */
 318  	public static function png_to_gif_by_imagemagick($theFile) {
 319  	 	 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
 320  	 	 	 	 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
 321  	 	 	 	 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
 322  	 	 	 	 && strtolower(substr($theFile, -4, 4)) == '.png'
 323  	 	 	 	 && @is_file($theFile)) { // IM
 324  	 	 	 $newFile = substr($theFile, 0, -4) . '.gif';
 325  	 	 	 $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
 326  	 	 	 t3lib_utility_Command::exec($cmd);
 327  	 	 	 $theFile = $newFile;
 328  	 	 	 if (@is_file($newFile)) {
 329  	 	 	 	 self::fixPermissions($newFile);
 330  	 	 	 }
 331  	 	 	 	 // unlink old file?? May be bad idea because TYPO3 would then recreate the file every time as
 332  	 	 	 	 // TYPO3 thinks the file is not generated because it's missing!! So do not unlink $theFile here!!
 333  	 	 }
 334  	 	 return $theFile;
 335  	 }
 336  
 337  	 /**
 338  	  * Returns filename of the png/gif version of the input file (which can be png or gif).
 339  	  * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
 340  	  *
 341  	  * @param string $theFile Filepath of image file
 342  	  * @param boolean $output_png If set, then input file is converted to PNG, otherwise to GIF
 343  	  * @return string If the new image file exists, its filepath is returned
 344  	  */
 345  	public static function read_png_gif($theFile, $output_png = FALSE) {
 346  	 	 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) {
 347  	 	 	 $ext = strtolower(substr($theFile, -4, 4));
 348  	 	 	 if (
 349  	 	 	 	 ((string) $ext == '.png' && $output_png) ||
 350  	 	 	 	 ((string) $ext == '.gif' && !$output_png)
 351  	 	 	 ) {
 352  	 	 	 	 return $theFile;
 353  	 	 	 } else {
 354  	 	 	 	 $newFile = PATH_site . 'typo3temp/readPG_' . md5($theFile . '|' . filemtime($theFile)) . ($output_png ? '.png' : '.gif');
 355  	 	 	 	 $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
 356  	 	 	 	 t3lib_utility_Command::exec($cmd);
 357  	 	 	 	 if (@is_file($newFile)) {
 358  	 	 	 	 	 self::fixPermissions($newFile);
 359  	 	 	 	 	 return $newFile;
 360  	 	 	 	 }
 361  	 	 	 }
 362  	 	 }
 363  	 }
 364  
 365  
 366  	 /*************************
 367  	  *
 368  	  * STRING FUNCTIONS
 369  	  *
 370  	  *************************/
 371  
 372  	 /**
 373  	  * Truncates a string with appended/prepended "..." and takes current character set into consideration.
 374  	  *
 375  	  * @param string $string string to truncate
 376  	  * @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.
 377  	  * @param string $appendString appendix to the truncated string
 378  	  * @return string cropped string
 379  	  */
 380  	public static function fixed_lgd_cs($string, $chars, $appendString = '...') {
 381  	 	 if (is_object($GLOBALS['LANG'])) {
 382  	 	 	 return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
 383  	 	 } elseif (is_object($GLOBALS['TSFE'])) {
 384  	 	 	 $charSet = ($GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet);
 385  	 	 	 return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString);
 386  	 	 } else {
 387  	 	 	 	 // this case should not happen
 388  	 	 	 $csConvObj = self::makeInstance('t3lib_cs');
 389  	 	 	 return $csConvObj->crop('utf-8', $string, $chars, $appendString);
 390  	 	 }
 391  	 }
 392  
 393  	 /**
 394  	  * Breaks up a single line of text for emails
 395  	  *
 396  	  * @param string $str The string to break up
 397  	  * @param string $newlineChar The string to implode the broken lines with (default/typically \n)
 398  	  * @param integer $lineWidth The line width
 399  	  * @return string reformatted text
 400  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Mail::breakLinesForEmail()
 401  	  */
 402  	public static function breakLinesForEmail($str, $newlineChar = LF, $lineWidth = 76) {
 403  	 	 self::logDeprecatedFunction();
 404  	 	 return t3lib_utility_Mail::breakLinesForEmail($str, $newlineChar, $lineWidth);
 405  	 }
 406  
 407  	 /**
 408  	  * Match IP number with list of numbers with wildcard
 409  	  * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
 410  	  *
 411  	  * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
 412  	  * @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.
 413  	  * @return boolean TRUE if an IP-mask from $list matches $baseIP
 414  	  */
 415  	public static function cmpIP($baseIP, $list) {
 416  	 	 $list = trim($list);
 417  	 	 if ($list === '') {
 418  	 	 	 return FALSE;
 419  	 	 } elseif ($list === '*') {
 420  	 	 	 return TRUE;
 421  	 	 }
 422  	 	 if (strpos($baseIP, ':') !== FALSE && self::validIPv6($baseIP)) {
 423  	 	 	 return self::cmpIPv6($baseIP, $list);
 424  	 	 } else {
 425  	 	 	 return self::cmpIPv4($baseIP, $list);
 426  	 	 }
 427  	 }
 428  
 429  	 /**
 430  	  * Match IPv4 number with list of numbers with wildcard
 431  	  *
 432  	  * @param	 string	 	 $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
 433  	  * @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
 434  	  * @return	 boolean	 	 TRUE if an IP-mask from $list matches $baseIP
 435  	  */
 436  	public static function cmpIPv4($baseIP, $list) {
 437  	 	 $IPpartsReq = explode('.', $baseIP);
 438  	 	 if (count($IPpartsReq) == 4) {
 439  	 	 	 $values = self::trimExplode(',', $list, 1);
 440  
 441  	 	 	 foreach ($values as $test) {
 442  	 	 	 	 $testList = explode('/', $test);
 443  	 	 	 	 if (count($testList) == 2) {
 444  	 	 	 	 	 list($test, $mask) = $testList;
 445  	 	 	 	 } else {
 446  	 	 	 	 	 $mask = FALSE;
 447  	 	 	 	 }
 448  
 449  	 	 	 	 if (intval($mask)) {
 450  	 	 	 	 	 	 // "192.168.3.0/24"
 451  	 	 	 	 	 $lnet = ip2long($test);
 452  	 	 	 	 	 $lip = ip2long($baseIP);
 453  	 	 	 	 	 $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
 454  	 	 	 	 	 $firstpart = substr($binnet, 0, $mask);
 455  	 	 	 	 	 $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
 456  	 	 	 	 	 $firstip = substr($binip, 0, $mask);
 457  	 	 	 	 	 $yes = (strcmp($firstpart, $firstip) == 0);
 458  	 	 	 	 } else {
 459  	 	 	 	 	 	 // "192.168.*.*"
 460  	 	 	 	 	 $IPparts = explode('.', $test);
 461  	 	 	 	 	 $yes = 1;
 462  	 	 	 	 	 foreach ($IPparts as $index => $val) {
 463  	 	 	 	 	 	 $val = trim($val);
 464  	 	 	 	 	 	 if (($val !== '*') && ($IPpartsReq[$index] !== $val)) {
 465  	 	 	 	 	 	 	 $yes = 0;
 466  	 	 	 	 	 	 }
 467  	 	 	 	 	 }
 468  	 	 	 	 }
 469  	 	 	 	 if ($yes) {
 470  	 	 	 	 	 return TRUE;
 471  	 	 	 	 }
 472  	 	 	 }
 473  	 	 }
 474  	 	 return FALSE;
 475  	 }
 476  
 477  	 /**
 478  	  * Match IPv6 address with a list of IPv6 prefixes
 479  	  *
 480  	  * @param string $baseIP is the current remote IP address for instance
 481  	  * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
 482  	  * @return boolean TRUE if an baseIP matches any prefix
 483  	  */
 484  	public static function cmpIPv6($baseIP, $list) {
 485  	 	 $success = FALSE; // Policy default: Deny connection
 486  	 	 $baseIP = self::normalizeIPv6($baseIP);
 487  
 488  	 	 $values = self::trimExplode(',', $list, 1);
 489  	 	 foreach ($values as $test) {
 490  	 	 	 $testList = explode('/', $test);
 491  	 	 	 if (count($testList) == 2) {
 492  	 	 	 	 list($test, $mask) = $testList;
 493  	 	 	 } else {
 494  	 	 	 	 $mask = FALSE;
 495  	 	 	 }
 496  
 497  	 	 	 if (self::validIPv6($test)) {
 498  	 	 	 	 $test = self::normalizeIPv6($test);
 499  	 	 	 	 $maskInt = intval($mask) ? intval($mask) : 128;
 500  	 	 	 	 if ($mask === '0') { // special case; /0 is an allowed mask - equals a wildcard
 501  	 	 	 	 	 $success = TRUE;
 502  	 	 	 	 } elseif ($maskInt == 128) {
 503  	 	 	 	 	 $success = ($test === $baseIP);
 504  	 	 	 	 } else {
 505  	 	 	 	 	 $testBin = self::IPv6Hex2Bin($test);
 506  	 	 	 	 	 $baseIPBin = self::IPv6Hex2Bin($baseIP);
 507  	 	 	 	 	 $success = TRUE;
 508  
 509  	 	 	 	 	 // modulo is 0 if this is a 8-bit-boundary
 510  	 	 	 	 	 $maskIntModulo = $maskInt % 8;
 511  	 	 	 	 	 $numFullCharactersUntilBoundary = intval($maskInt / 8);
 512  
 513  	 	 	 	 	 if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) {
 514  	 	 	 	 	 	 $success = FALSE;
 515  	 	 	 	 	 } elseif ($maskIntModulo > 0) {
 516  	 	 	 	 	 	 // if not an 8-bit-boundary, check bits of last character
 517  	 	 	 	 	 	 $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
 518  	 	 	 	 	 	 $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
 519  	 	 	 	 	 	 if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
 520  	 	 	 	 	 	 	 $success = FALSE;
 521  	 	 	 	 	 	 }
 522  	 	 	 	 	 }
 523  	 	 	 	 }
 524  	 	 	 }
 525  	 	 	 if ($success) {
 526  	 	 	 	 return TRUE;
 527  	 	 	 }
 528  	 	 }
 529  	 	 return FALSE;
 530  	 }
 531  
 532  	 /**
 533  	  * Transform a regular IPv6 address from hex-representation into binary
 534  	  *
 535  	  * @param string $hex IPv6 address in hex-presentation
 536  	  * @return string Binary representation (16 characters, 128 characters)
 537  	  * @see IPv6Bin2Hex()
 538  	  */
 539  	public static function IPv6Hex2Bin($hex) {
 540  	 	 	 // use PHP-function if PHP was compiled with IPv6-support
 541  	 	 if (defined('AF_INET6')) {
 542  	 	 	 $bin = inet_pton($hex);
 543  	 	 } else {
 544  	 	 	 $hex = self::normalizeIPv6($hex);
 545  	 	 	 $hex = str_replace(':', '', $hex); // Replace colon to nothing
 546  	 	 	 $bin = pack("H*" , $hex);
 547  	 	 }
 548  	 	 return $bin;
 549  	 }
 550  
 551  	 /**
 552  	  * Transform an IPv6 address from binary to hex-representation
 553  	  *
 554  	  * @param string $bin IPv6 address in hex-presentation
 555  	  * @return string Binary representation (16 characters, 128 characters)
 556  	  * @see IPv6Hex2Bin()
 557  	  */
 558  	public static function IPv6Bin2Hex($bin) {
 559  	 	 	 // use PHP-function if PHP was compiled with IPv6-support
 560  	 	 if (defined('AF_INET6')) {
 561  	 	 	 $hex = inet_ntop($bin);
 562  	 	 } else {
 563  	 	 	 $hex = unpack("H*" , $bin);
 564  	 	 	 $hex = chunk_split($hex[1], 4, ':');
 565  	 	 	 	 // strip last colon (from chunk_split)
 566  	 	 	 $hex = substr($hex, 0, -1);
 567  	 	 	 	 // IPv6 is now in normalized form
 568  	 	 	 	 // compress it for easier handling and to match result from inet_ntop()
 569  	 	 	 $hex = self::compressIPv6($hex);
 570  	 	 }
 571  	 	 return $hex;
 572  
 573  	 }
 574  
 575  	 /**
 576  	  * Normalize an IPv6 address to full length
 577  	  *
 578  	  * @param string $address Given IPv6 address
 579  	  * @return string Normalized address
 580  	  * @see compressIPv6()
 581  	  */
 582  	public static function normalizeIPv6($address) {
 583  	 	 $normalizedAddress = '';
 584  	 	 $stageOneAddress = '';
 585  
 586  	 	 	 // according to RFC lowercase-representation is recommended
 587  	 	 $address = strtolower($address);
 588  
 589  	 	 	 // normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
 590  	 	 if (strlen($address) == 39) {
 591  	 	 	 	 // already in full expanded form
 592  	 	 	 return $address;
 593  	 	 }
 594  
 595  	 	 $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks
 596  	 	 if (count($chunks) == 2) {
 597  	 	 	 $chunksLeft = explode(':', $chunks[0]);
 598  	 	 	 $chunksRight = explode(':', $chunks[1]);
 599  	 	 	 $left = count($chunksLeft);
 600  	 	 	 $right = count($chunksRight);
 601  
 602  	 	 	 	 // Special case: leading zero-only blocks count to 1, should be 0
 603  	 	 	 if ($left == 1 && strlen($chunksLeft[0]) == 0) {
 604  	 	 	 	 $left = 0;
 605  	 	 	 }
 606  
 607  	 	 	 $hiddenBlocks = 8 - ($left + $right);
 608  	 	 	 $hiddenPart = '';
 609  	 	 	 $h = 0;
 610  	 	 	 while ($h < $hiddenBlocks) {
 611  	 	 	 	 $hiddenPart .= '0000:';
 612  	 	 	 	 $h++;
 613  	 	 	 }
 614  
 615  	 	 	 if ($left == 0) {
 616  	 	 	 	 $stageOneAddress = $hiddenPart . $chunks[1];
 617  	 	 	 } else {
 618  	 	 	 	 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
 619  	 	 	 }
 620  	 	 } else {
 621  	 	 	 $stageOneAddress = $address;
 622  	 	 }
 623  
 624  	 	 	 // normalize the blocks:
 625  	 	 $blocks = explode(':', $stageOneAddress);
 626  	 	 $divCounter = 0;
 627  	 	 foreach ($blocks as $block) {
 628  	 	 	 $tmpBlock = '';
 629  	 	 	 $i = 0;
 630  	 	 	 $hiddenZeros = 4 - strlen($block);
 631  	 	 	 while ($i < $hiddenZeros) {
 632  	 	 	 	 $tmpBlock .= '0';
 633  	 	 	 	 $i++;
 634  	 	 	 }
 635  	 	 	 $normalizedAddress .= $tmpBlock . $block;
 636  	 	 	 if ($divCounter < 7) {
 637  	 	 	 	 $normalizedAddress .= ':';
 638  	 	 	 	 $divCounter++;
 639  	 	 	 }
 640  	 	 }
 641  	 	 return $normalizedAddress;
 642  	 }
 643  
 644  
 645  	 /**
 646  	  * Compress an IPv6 address to the shortest notation
 647  	  *
 648  	  * @param string $address Given IPv6 address
 649  	  * @return string Compressed address
 650  	  * @see normalizeIPv6()
 651  	  */
 652  	public static function compressIPv6($address) {
 653  	 	 	 // use PHP-function if PHP was compiled with IPv6-support
 654  	 	 if (defined('AF_INET6')) {
 655  	 	 	 $bin = inet_pton($address);
 656  	 	 	 $address = inet_ntop($bin);
 657  	 	 } else {
 658  	 	 	 $address = self::normalizeIPv6($address);
 659  
 660  	 	 	 	 // append one colon for easier handling
 661  	 	 	 	 // will be removed later
 662  	 	 	 $address .= ':';
 663  
 664  	 	 	 	 // according to IPv6-notation the longest match
 665  	 	 	 	 // of a package of '0000:' may be replaced with ':'
 666  	 	 	 	 // (resulting in something like '1234::abcd')
 667  	 	 	 for ($counter = 8; $counter > 1; $counter--) {
 668  	 	 	 	 $search = str_repeat('0000:', $counter);
 669  	 	 	 	 if (($pos = strpos($address, $search)) !== FALSE) {
 670  	 	 	 	 	 $address = substr($address, 0, $pos) . ':' . substr($address, $pos + ($counter*5));
 671  	 	 	 	 	 break;
 672  	 	 	 	 }
 673  	 	 	 }
 674  
 675  	 	 	 	 // up to 3 zeros in the first part may be removed
 676  	 	 	 $address = preg_replace('/^0{1,3}/', '', $address);
 677  	 	 	 	 // up to 3 zeros at the beginning of other parts may be removed
 678  	 	 	 $address = preg_replace('/:0{1,3}/', ':', $address);
 679  
 680  	 	 	 	 // strip last colon (from chunk_split)
 681  	 	 	 $address = substr($address, 0, -1);
 682  	 	 }
 683  	 	 return $address;
 684  	 }
 685  
 686  	 /**
 687  	  * Validate a given IP address.
 688  	  *
 689  	  * Possible format are IPv4 and IPv6.
 690  	  *
 691  	  * @param string $ip IP address to be tested
 692  	  * @return boolean TRUE if $ip is either of IPv4 or IPv6 format.
 693  	  */
 694  	public static function validIP($ip) {
 695  	 	 return (filter_var($ip, FILTER_VALIDATE_IP) !== FALSE);
 696  	 }
 697  
 698  	 /**
 699  	  * Validate a given IP address to the IPv4 address format.
 700  	  *
 701  	  * Example for possible format: 10.0.45.99
 702  	  *
 703  	  * @param string $ip IP address to be tested
 704  	  * @return boolean TRUE if $ip is of IPv4 format.
 705  	  */
 706  	public static function validIPv4($ip) {
 707  	 	 return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE);
 708  	 }
 709  
 710  	 /**
 711  	  * Validate a given IP address to the IPv6 address format.
 712  	  *
 713  	  * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
 714  	  *
 715  	  * @param string $ip IP address to be tested
 716  	  * @return boolean TRUE if $ip is of IPv6 format.
 717  	  */
 718  	public static function validIPv6($ip) {
 719  	 	 return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE);
 720  	 }
 721  
 722  	 /**
 723  	  * Match fully qualified domain name with list of strings with wildcard
 724  	  *
 725  	  * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
 726  	  * @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)
 727  	  * @return boolean TRUE if a domain name mask from $list matches $baseIP
 728  	  */
 729  	public static function cmpFQDN($baseHost, $list) {
 730  	 	 $baseHost = trim($baseHost);
 731  	 	 if (empty($baseHost)) {
 732  	 	 	 return FALSE;
 733  	 	 }
 734  	 	 if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
 735  	 	 	 	 // resolve hostname
 736  	 	 	 	 // note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
 737  	 	 	 	 // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
 738  	 	 	 $baseHostName = gethostbyaddr($baseHost);
 739  	 	 	 if ($baseHostName === $baseHost) {
 740  	 	 	 	 	 // unable to resolve hostname
 741  	 	 	 	 return FALSE;
 742  	 	 	 }
 743  	 	 } else {
 744  	 	 	 $baseHostName = $baseHost;
 745  	 	 }
 746  	 	 $baseHostNameParts = explode('.', $baseHostName);
 747  
 748  	 	 $values = self::trimExplode(',', $list, 1);
 749  
 750  	 	 foreach ($values as $test) {
 751  	 	 	 $hostNameParts = explode('.', $test);
 752  
 753  	 	 	 	 // to match hostNameParts can only be shorter (in case of wildcards) or equal
 754  	 	 	 if (count($hostNameParts) > count($baseHostNameParts)) {
 755  	 	 	 	 continue;
 756  	 	 	 }
 757  
 758  	 	 	 $yes = TRUE;
 759  	 	 	 foreach ($hostNameParts as $index => $val) {
 760  	 	 	 	 $val = trim($val);
 761  	 	 	 	 if ($val === '*') {
 762  	 	 	 	 	 	 // wildcard valid for one or more hostname-parts
 763  
 764  	 	 	 	 	 $wildcardStart = $index + 1;
 765  	 	 	 	 	 	 // wildcard as last/only part always matches, otherwise perform recursive checks
 766  	 	 	 	 	 if ($wildcardStart < count($hostNameParts)) {
 767  	 	 	 	 	 	 $wildcardMatched = FALSE;
 768  	 	 	 	 	 	 $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
 769  	 	 	 	 	 	 while (($wildcardStart < count($baseHostNameParts)) && (!$wildcardMatched)) {
 770  	 	 	 	 	 	 	 $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
 771  	 	 	 	 	 	 	 $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
 772  	 	 	 	 	 	 	 $wildcardStart++;
 773  	 	 	 	 	 	 }
 774  	 	 	 	 	 	 if ($wildcardMatched) {
 775  	 	 	 	 	 	 	 	 // match found by recursive compare
 776  	 	 	 	 	 	 	 return TRUE;
 777  	 	 	 	 	 	 } else {
 778  	 	 	 	 	 	 	 $yes = FALSE;
 779  	 	 	 	 	 	 }
 780  	 	 	 	 	 }
 781  	 	 	 	 } elseif ($baseHostNameParts[$index] !== $val) {
 782  	 	 	 	 	 	 // in case of no match
 783  	 	 	 	 	 $yes = FALSE;
 784  	 	 	 	 }
 785  	 	 	 }
 786  	 	 	 if ($yes) {
 787  	 	 	 	 return TRUE;
 788  	 	 	 }
 789  	 	 }
 790  	 	 return FALSE;
 791  	 }
 792  
 793  	 /**
 794  	  * Checks if a given URL matches the host that currently handles this HTTP request.
 795  	  * Scheme, hostname and (optional) port of the given URL are compared.
 796  	  *
 797  	  * @param string $url: URL to compare with the TYPO3 request host
 798  	  * @return boolean Whether the URL matches the TYPO3 request host
 799  	  */
 800  	public static function isOnCurrentHost($url) {
 801  	 	 return (stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0);
 802  	 }
 803  
 804  	 /**
 805  	  * Check for item in list
 806  	  * Check if an item exists in a comma-separated list of items.
 807  	  *
 808  	  * @param string $list comma-separated list of items (string)
 809  	  * @param string $item item to check for
 810  	  * @return boolean TRUE if $item is in $list
 811  	  */
 812  	public static function inList($list, $item) {
 813  	 	 return (strpos(',' . $list . ',', ',' . $item . ',') !== FALSE ? TRUE : FALSE);
 814  	 }
 815  
 816  	 /**
 817  	  * Removes an item from a comma-separated list of items.
 818  	  *
 819  	  * @param string $element element to remove
 820  	  * @param string $list comma-separated list of items (string)
 821  	  * @return string new comma-separated list of items
 822  	  */
 823  	public static function rmFromList($element, $list) {
 824  	 	 $items = explode(',', $list);
 825  	 	 foreach ($items as $k => $v) {
 826  	 	 	 if ($v == $element) {
 827  	 	 	 	 unset($items[$k]);
 828  	 	 	 }
 829  	 	 }
 830  	 	 return implode(',', $items);
 831  	 }
 832  
 833  	 /**
 834  	  * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
 835  	  * Ranges are limited to 1000 values per range.
 836  	  *
 837  	  * @param string $list comma-separated list of integers with ranges (string)
 838  	  * @return string new comma-separated list of items
 839  	  */
 840  	public static function expandList($list) {
 841  	 	 $items = explode(',', $list);
 842  	 	 $list = array();
 843  	 	 foreach ($items as $item) {
 844  	 	 	 $range = explode('-', $item);
 845  	 	 	 if (isset($range[1])) {
 846  	 	 	 	 $runAwayBrake = 1000;
 847  	 	 	 	 for ($n = $range[0]; $n <= $range[1]; $n++) {
 848  	 	 	 	 	 $list[] = $n;
 849  
 850  	 	 	 	 	 $runAwayBrake--;
 851  	 	 	 	 	 if ($runAwayBrake <= 0) {
 852  	 	 	 	 	 	 break;
 853  	 	 	 	 	 }
 854  	 	 	 	 }
 855  	 	 	 } else {
 856  	 	 	 	 $list[] = $item;
 857  	 	 	 }
 858  	 	 }
 859  	 	 return implode(',', $list);
 860  	 }
 861  
 862  	 /**
 863  	  * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'FALSE' then the $zeroValue is applied.
 864  	  *
 865  	  * @param integer $theInt Input value
 866  	  * @param integer $min Lower limit
 867  	  * @param integer $max Higher limit
 868  	  * @param integer $zeroValue Default value if input is FALSE.
 869  	  * @return integer The input value forced into the boundaries of $min and $max
 870  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::forceIntegerInRange() instead
 871  	  */
 872  	public static function intInRange($theInt, $min, $max = 2000000000, $zeroValue = 0) {
 873  	 	 self::logDeprecatedFunction();
 874  	 	 return t3lib_utility_Math::forceIntegerInRange($theInt, $min, $max, $zeroValue);
 875  	 }
 876  
 877  	 /**
 878  	  * Returns the $integer if greater than zero, otherwise returns zero.
 879  	  *
 880  	  * @param integer $theInt Integer string to process
 881  	  * @return integer
 882  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::convertToPositiveInteger() instead
 883  	  */
 884  	public static function intval_positive($theInt) {
 885  	 	 self::logDeprecatedFunction();
 886  	 	 return t3lib_utility_Math::convertToPositiveInteger($theInt);
 887  	 }
 888  
 889  	 /**
 890  	  * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
 891  	  *
 892  	  * @param string $verNumberStr Version number on format x.x.x
 893  	  * @return integer Integer version of version number (where each part can count to 999)
 894  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.1 - Use t3lib_utility_VersionNumber::convertVersionNumberToInteger() instead
 895  	  */
 896  	public static function int_from_ver($verNumberStr) {
 897  	 	 	 // Deprecation log is activated only for TYPO3 4.7 and above
 898  	 	 if (t3lib_utility_VersionNumber::convertVersionNumberToInteger(TYPO3_version) >= 4007000) {
 899  	 	 	 self::logDeprecatedFunction();
 900  	 	 }
 901  	 	 return t3lib_utility_VersionNumber::convertVersionNumberToInteger($verNumberStr);
 902  	 }
 903  
 904  	 /**
 905  	  * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
 906  	  * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
 907  	  *
 908  	  * @param string $verNumberStr	 Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
 909  	  * @return boolean Returns TRUE if this setup is compatible with the provided version number
 910  	  * @todo Still needs a function to convert versions to branches
 911  	  */
 912  	public static function compat_version($verNumberStr) {
 913  	 	 $currVersionStr = $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] : TYPO3_branch;
 914  
 915  	 	 if (t3lib_utility_VersionNumber::convertVersionNumberToInteger($currVersionStr) < t3lib_utility_VersionNumber::convertVersionNumberToInteger($verNumberStr)) {
 916  	 	 	 return FALSE;
 917  	 	 } else {
 918  	 	 	 return TRUE;
 919  	 	 }
 920  	 }
 921  
 922  	 /**
 923  	  * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
 924  	  *
 925  	  * @param string $str String to md5-hash
 926  	  * @return integer Returns 28bit integer-hash
 927  	  */
 928  	public static function md5int($str) {
 929  	 	 return hexdec(substr(md5($str), 0, 7));
 930  	 }
 931  
 932  	 /**
 933  	  * Returns the first 10 positions of the MD5-hash	 	 (changed from 6 to 10 recently)
 934  	  *
 935  	  * @param string $input Input string to be md5-hashed
 936  	  * @param integer $len The string-length of the output
 937  	  * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
 938  	  */
 939  	public static function shortMD5($input, $len = 10) {
 940  	 	 return substr(md5($input), 0, $len);
 941  	 }
 942  
 943  	 /**
 944  	  * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
 945  	  *
 946  	  * @param string $input Input string to create HMAC from
 947  	  * @param string $additionalSecret additionalSecret to prevent hmac beeing used in a different context
 948  	  * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
 949  	  */
 950  	public static function hmac($input, $additionalSecret = '') {
 951  	 	 $hashAlgorithm = 'sha1';
 952  	 	 $hashBlocksize = 64;
 953  	 	 $hmac = '';
 954  	 	 $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
 955  	 	 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
 956  	 	 	 $hmac = hash_hmac($hashAlgorithm, $input, $secret);
 957  	 	 } else {
 958  	 	 	 	 // outer padding
 959  	 	 	 $opad = str_repeat(chr(0x5C), $hashBlocksize);
 960  	 	 	 	 // inner padding
 961  	 	 	 $ipad = str_repeat(chr(0x36), $hashBlocksize);
 962  	 	 	 if (strlen($secret) > $hashBlocksize) {
 963  	 	 	 	 	 // keys longer than block size are shorten
 964  	 	 	 	 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, chr(0));
 965  	 	 	 } else {
 966  	 	 	 	 	 // keys shorter than block size are zero-padded
 967  	 	 	 	 $key = str_pad($secret, $hashBlocksize, chr(0));
 968  	 	 	 }
 969  	 	 	 $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, ($key ^ $ipad) . $input)));
 970  	 	 }
 971  	 	 return $hmac;
 972  	 }
 973  
 974  	 /**
 975  	  * Takes comma-separated lists and arrays and removes all duplicates
 976  	  * If a value in the list is trim(empty), the value is ignored.
 977  	  *
 978  	  * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
 979  	  * @param mixed $secondParameter: Dummy field, which if set will show a warning!
 980  	  * @return string Returns the list without any duplicates of values, space around values are trimmed
 981  	  */
 982  	public static function uniqueList($in_list, $secondParameter = NULL) {
 983  	 	 if (is_array($in_list)) {
 984  	 	 	 throw new InvalidArgumentException(
 985  	 	 	 	 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
 986  	 	 	 	 1270853885
 987  	 	 	 );
 988  	 	 }
 989  	 	 if (isset($secondParameter)) {
 990  	 	 	 throw new InvalidArgumentException(
 991  	 	 	 	 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!',
 992  	 	 	 	 1270853886
 993  	 	 	 );
 994  	 	 }
 995  
 996  	 	 return implode(',', array_unique(self::trimExplode(',', $in_list, 1)));
 997  	 }
 998  
 999  	 /**
1000  	  * Splits a reference to a file in 5 parts
1001  	  *
1002  	  * @param string $fileref Filename/filepath to be analysed
1003  	  * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
1004  	  */
1005  	public static function split_fileref($fileref) {
1006  	 	 $reg = array();
1007  	 	 if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
1008  	 	 	 $info['path'] = $reg[1];
1009  	 	 	 $info['file'] = $reg[2];
1010  	 	 } else {
1011  	 	 	 $info['path'] = '';
1012  	 	 	 $info['file'] = $fileref;
1013  	 	 }
1014  
1015  	 	 $reg = '';
1016  	 	 if (!is_dir($fileref) && preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
1017  	 	 	 $info['filebody'] = $reg[1];
1018  	 	 	 $info['fileext'] = strtolower($reg[2]);
1019  	 	 	 $info['realFileext'] = $reg[2];
1020  	 	 } else {
1021  	 	 	 $info['filebody'] = $info['file'];
1022  	 	 	 $info['fileext'] = '';
1023  	 	 }
1024  	 	 reset($info);
1025  	 	 return $info;
1026  	 }
1027  
1028  	 /**
1029  	  * Returns the directory part of a path without trailing slash
1030  	  * If there is no dir-part, then an empty string is returned.
1031  	  * Behaviour:
1032  	  *
1033  	  * '/dir1/dir2/script.php' => '/dir1/dir2'
1034  	  * '/dir1/' => '/dir1'
1035  	  * 'dir1/script.php' => 'dir1'
1036  	  * 'd/script.php' => 'd'
1037  	  * '/script.php' => ''
1038  	  * '' => ''
1039  	  *
1040  	  * @param string $path Directory name / path
1041  	  * @return string Processed input value. See function description.
1042  	  */
1043  	public static function dirname($path) {
1044  	 	 $p = self::revExplode('/', $path, 2);
1045  	 	 return count($p) == 2 ? $p[0] : '';
1046  	 }
1047  
1048  	 /**
1049  	  * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
1050  	  *
1051  	  * @param string $color A hexadecimal color code, #xxxxxx
1052  	  * @param integer $R Offset value 0-255
1053  	  * @param integer $G Offset value 0-255
1054  	  * @param integer $B Offset value 0-255
1055  	  * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1056  	  * @see modifyHTMLColorAll()
1057  	  */
1058  	public static function modifyHTMLColor($color, $R, $G, $B) {
1059  	 	 	 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
1060  	 	 $nR = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
1061  	 	 $nG = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
1062  	 	 $nB = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
1063  	 	 return '#' .
1064  	 	 	 	 substr('0' . dechex($nR), -2) .
1065  	 	 	 	 substr('0' . dechex($nG), -2) .
1066  	 	 	 	 substr('0' . dechex($nB), -2);
1067  	 }
1068  
1069  	 /**
1070  	  * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
1071  	  *
1072  	  * @param string $color A hexadecimal color code, #xxxxxx
1073  	  * @param integer $all Offset value 0-255 for all three channels.
1074  	  * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1075  	  * @see modifyHTMLColor()
1076  	  */
1077  	public static function modifyHTMLColorAll($color, $all) {
1078  	 	 return self::modifyHTMLColor($color, $all, $all, $all);
1079  	 }
1080  
1081  	 /**
1082  	  * Tests if the input can be interpreted as integer.
1083  	  *
1084  	  * @param mixed $var Any input variable to test
1085  	  * @return boolean Returns TRUE if string is an integer
1086  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::canBeInterpretedAsInteger() instead
1087  	  */
1088  	public static function testInt($var) {
1089  	 	 self::logDeprecatedFunction();
1090  
1091  	 	 return t3lib_utility_Math::canBeInterpretedAsInteger($var);
1092  	 }
1093  
1094  	 /**
1095  	  * Returns TRUE if the first part of $str matches the string $partStr
1096  	  *
1097  	  * @param string $str Full string to check
1098  	  * @param string $partStr Reference string which must be found as the "first part" of the full string
1099  	  * @return boolean TRUE if $partStr was found to be equal to the first part of $str
1100  	  */
1101  	public static function isFirstPartOfStr($str, $partStr) {
1102  	 	 return $partStr != '' && strpos((string) $str, (string) $partStr, 0) === 0;
1103  	 }
1104  
1105  	 /**
1106  	  * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
1107  	  *
1108  	  * @param integer $sizeInBytes Number of bytes to format.
1109  	  * @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)
1110  	  * @return string Formatted representation of the byte number, for output.
1111  	  */
1112  	public static function formatSize($sizeInBytes, $labels = '') {
1113  
1114  	 	 	 // Set labels:
1115  	 	 if (strlen($labels) == 0) {
1116  	 	 	 $labels = ' | K| M| G';
1117  	 	 } else {
1118  	 	 	 $labels = str_replace('"', '', $labels);
1119  	 	 }
1120  	 	 $labelArr = explode('|', $labels);
1121  
1122  	 	 	 // Find size:
1123  	 	 if ($sizeInBytes > 900) {
1124  	 	 	 if ($sizeInBytes > 900000000) { // GB
1125  	 	 	 	 $val = $sizeInBytes / (1024 * 1024 * 1024);
1126  	 	 	 	 return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[3];
1127  	 	 	 }
1128  	 	 	 elseif ($sizeInBytes > 900000) { // MB
1129  	 	 	 	 $val = $sizeInBytes / (1024 * 1024);
1130  	 	 	 	 return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[2];
1131  	 	 	 } else { // KB
1132  	 	 	 	 $val = $sizeInBytes / (1024);
1133  	 	 	 	 return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[1];
1134  	 	 	 }
1135  	 	 } else { // Bytes
1136  	 	 	 return $sizeInBytes . $labelArr[0];
1137  	 	 }
1138  	 }
1139  
1140  	 /**
1141  	  * Returns microtime input to milliseconds
1142  	  *
1143  	  * @param string $microtime Microtime
1144  	  * @return integer Microtime input string converted to an integer (milliseconds)
1145  	  */
1146  	public static function convertMicrotime($microtime) {
1147  	 	 $parts = explode(' ', $microtime);
1148  	 	 return round(($parts[0] + $parts[1]) * 1000);
1149  	 }
1150  
1151  	 /**
1152  	  * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
1153  	  *
1154  	  * @param string $string Input string, eg "123 + 456 / 789 - 4"
1155  	  * @param string $operators Operators to split by, typically "/+-*"
1156  	  * @return array Array with operators and operands separated.
1157  	  * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
1158  	  */
1159  	public static function splitCalc($string, $operators) {
1160  	 	 $res = Array();
1161  	 	 $sign = '+';
1162  	 	 while ($string) {
1163  	 	 	 $valueLen = strcspn($string, $operators);
1164  	 	 	 $value = substr($string, 0, $valueLen);
1165  	 	 	 $res[] = Array($sign, trim($value));
1166  	 	 	 $sign = substr($string, $valueLen, 1);
1167  	 	 	 $string = substr($string, $valueLen + 1);
1168  	 	 }
1169  	 	 reset($res);
1170  	 	 return $res;
1171  	 }
1172  
1173  	 /**
1174  	  * Calculates the input by +,-,*,/,%,^ with priority to + and -
1175  	  *
1176  	  * @param string $string Input string, eg "123 + 456 / 789 - 4"
1177  	  * @return integer Calculated value. Or error string.
1178  	  * @see calcParenthesis()
1179  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::calculateWithPriorityToAdditionAndSubtraction() instead
1180  	  */
1181  	public static function calcPriority($string) {
1182  	 	 self::logDeprecatedFunction();
1183  
1184  	 	 return t3lib_utility_Math::calculateWithPriorityToAdditionAndSubtraction($string);
1185  	 }
1186  
1187  	 /**
1188  	  * Calculates the input with parenthesis levels
1189  	  *
1190  	  * @param string $string Input string, eg "(123 + 456) / 789 - 4"
1191  	  * @return integer Calculated value. Or error string.
1192  	  * @see calcPriority(), tslib_cObj::stdWrap()
1193  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::calculateWithParentheses() instead
1194  	  */
1195  	public static function calcParenthesis($string) {
1196  	 	 self::logDeprecatedFunction();
1197  
1198  	 	 return t3lib_utility_Math::calculateWithParentheses($string);
1199  	 }
1200  
1201  	 /**
1202  	  * Inverse version of htmlspecialchars()
1203  	  *
1204  	  * @param string $value Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
1205  	  * @return string Converted result.
1206  	  */
1207  	public static function htmlspecialchars_decode($value) {
1208  	 	 $value = str_replace('&gt;', '>', $value);
1209  	 	 $value = str_replace('&lt;', '<', $value);
1210  	 	 $value = str_replace('&quot;', '"', $value);
1211  	 	 $value = str_replace('&amp;', '&', $value);
1212  	 	 return $value;
1213  	 }
1214  
1215  	 /**
1216  	  * Re-converts HTML entities if they have been converted by htmlspecialchars()
1217  	  *
1218  	  * @param string $str String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;"
1219  	  * @return string Converted result.
1220  	  */
1221  	public static function deHSCentities($str) {
1222  	 	 return preg_replace('/&amp;([#[:alnum:]]*;)/', '&\1', $str);
1223  	 }
1224  
1225  	 /**
1226  	  * This function is used to escape any ' -characters when transferring text to JavaScript!
1227  	  *
1228  	  * @param string $string String to escape
1229  	  * @param boolean $extended If set, also backslashes are escaped.
1230  	  * @param string $char The character to escape, default is ' (single-quote)
1231  	  * @return string Processed input string
1232  	  */
1233  	public static function slashJS($string, $extended = FALSE, $char = "'") {
1234  	 	 if ($extended) {
1235  	 	 	 $string = str_replace("\\", "\\\\", $string);
1236  	 	 }
1237  	 	 return str_replace($char, "\\" . $char, $string);
1238  	 }
1239  
1240  	 /**
1241  	  * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1242  	  * Useful when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1243  	  *
1244  	  * @param string $str String to raw-url-encode with spaces preserved
1245  	  * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1246  	  */
1247  	public static function rawUrlEncodeJS($str) {
1248  	 	 return str_replace('%20', ' ', rawurlencode($str));
1249  	 }
1250  
1251  	 /**
1252  	  * rawurlencode which preserves "/" chars
1253  	  * Useful when file paths should keep the "/" chars, but have all other special chars encoded.
1254  	  *
1255  	  * @param string $str Input string
1256  	  * @return string Output string
1257  	  */
1258  	public static function rawUrlEncodeFP($str) {
1259  	 	 return str_replace('%2F', '/', rawurlencode($str));
1260  	 }
1261  
1262  	 /**
1263  	  * Checking syntax of input email address
1264  	  *
1265  	  * @param string $email Input string to evaluate
1266  	  * @return boolean Returns TRUE if the $email address (input string) is valid
1267  	  */
1268  	public static function validEmail($email) {
1269  	 	 	 // enforce maximum length to prevent libpcre recursion crash bug #52929 in PHP
1270  	 	 	 // fixed in PHP 5.3.4; length restriction per SMTP RFC 2821
1271  	 	 if (strlen($email) > 320) {
1272  	 	 	 return FALSE;
1273  	 	 }
1274  	 	 require_once(PATH_typo3 . 'contrib/idna/idna_convert.class.php');
1275  	 	 $IDN = new idna_convert(array('idn_version' => 2008));
1276  
1277  	 	 return (filter_var($IDN->encode($email), FILTER_VALIDATE_EMAIL) !== FALSE);
1278  	 }
1279  
1280  	 /**
1281  	  * Checks if current e-mail sending method does not accept recipient/sender name
1282  	  * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
1283  	  * program are known not to process such input correctly and they cause SMTP
1284  	  * errors. This function will return TRUE if current mail sending method has
1285  	  * problem with recipient name in recipient/sender argument for mail().
1286  	  *
1287  	  * TODO: 4.3 should have additional configuration variable, which is combined
1288  	  * by || with the rest in this function.
1289  	  *
1290  	  * @return boolean TRUE if mail() does not accept recipient name
1291  	  */
1292  	public static function isBrokenEmailEnvironment() {
1293  	 	 return TYPO3_OS == 'WIN' || (FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
1294  	 }
1295  
1296  	 /**
1297  	  * Changes from/to arguments for mail() function to work in any environment.
1298  	  *
1299  	  * @param string $address Address to adjust
1300  	  * @return string Adjusted address
1301  	  * @see	 t3lib_::isBrokenEmailEnvironment()
1302  	  */
1303  	public static function normalizeMailAddress($address) {
1304  	 	 if (self::isBrokenEmailEnvironment() && FALSE !== ($pos1 = strrpos($address, '<'))) {
1305  	 	 	 $pos2 = strpos($address, '>', $pos1);
1306  	 	 	 $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
1307  	 	 }
1308  	 	 return $address;
1309  	 }
1310  
1311  	 /**
1312  	  * Formats a string for output between <textarea>-tags
1313  	  * All content outputted in a textarea form should be passed through this function
1314  	  * 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!
1315  	  *
1316  	  * @param string $content Input string to be formatted.
1317  	  * @return string Formatted for <textarea>-tags
1318  	  */
1319  	public static function formatForTextarea($content) {
1320  	 	 return LF . htmlspecialchars($content);
1321  	 }
1322  
1323  	 /**
1324  	  * Converts string to uppercase
1325  	  * The function converts all Latin characters (a-z, but no accents, etc) to
1326  	  * uppercase. It is safe for all supported character sets (incl. utf-8).
1327  	  * Unlike strtoupper() it does not honour the locale.
1328  	  *
1329  	  * @param string $str Input string
1330  	  * @return string Uppercase String
1331  	  */
1332  	public static function strtoupper($str) {
1333  	 	 return strtr((string) $str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1334  	 }
1335  
1336  	 /**
1337  	  * Converts string to lowercase
1338  	  * The function converts all Latin characters (A-Z, but no accents, etc) to
1339  	  * lowercase. It is safe for all supported character sets (incl. utf-8).
1340  	  * Unlike strtolower() it does not honour the locale.
1341  	  *
1342  	  * @param string $str Input string
1343  	  * @return string Lowercase String
1344  	  */
1345  	public static function strtolower($str) {
1346  	 	 return strtr((string) $str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1347  	 }
1348  
1349  	 /**
1350  	  * Returns a string of highly randomized bytes (over the full 8-bit range).
1351  	  *
1352  	  * Note: Returned values are not guaranteed to be crypto-safe,
1353  	  * most likely they are not, depending on the used retrieval method.
1354  	  *
1355  	  * @param integer $bytesToReturn Number of characters (bytes) to return
1356  	  * @return string Random Bytes
1357  	  * @see http://bugs.php.net/bug.php?id=52523
1358  	  * @see http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/index.html
1359  	  */
1360  	public static function generateRandomBytes($bytesToReturn) {
1361  	 	 	 // Cache 4k of the generated bytestream.
1362  	 	 static $bytes = '';
1363  	 	 $bytesToGenerate = max(4096, $bytesToReturn);
1364  
1365  	 	 	 // if we have not enough random bytes cached, we generate new ones
1366  	 	 if (!isset($bytes[$bytesToReturn - 1])) {
1367  	 	 	 if (TYPO3_OS === 'WIN') {
1368  	 	 	 	 	 // Openssl seems to be deadly slow on Windows, so try to use mcrypt
1369  	 	 	 	 	 // Windows PHP versions have a bug when using urandom source (see #24410)
1370  	 	 	 	 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_RAND);
1371  	 	 	 } else {
1372  	 	 	 	 	 // Try to use native PHP functions first, precedence has openssl
1373  	 	 	 	 $bytes .= self::generateRandomBytesOpenSsl($bytesToGenerate);
1374  
1375  	 	 	 	 if (!isset($bytes[$bytesToReturn - 1])) {
1376  	 	 	 	 	 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_DEV_URANDOM);
1377  	 	 	 	 }
1378  
1379  	 	 	 	 	 // If openssl and mcrypt failed, try /dev/urandom
1380  	 	 	 	 if (!isset($bytes[$bytesToReturn - 1])) {
1381  	 	 	 	 	 $bytes .= self::generateRandomBytesUrandom($bytesToGenerate);
1382  	 	 	 	 }
1383  	 	 	 }
1384  
1385  	 	 	 	 // Fall back if other random byte generation failed until now
1386  	 	 	 if (!isset($bytes[$bytesToReturn - 1])) {
1387  	 	 	 	 $bytes .= self::generateRandomBytesFallback($bytesToReturn);
1388  	 	 	 }
1389  	 	 }
1390  
1391  	 	 	 // get first $bytesToReturn and remove it from the byte cache
1392  	 	 $output = substr($bytes, 0, $bytesToReturn);
1393  	 	 $bytes = substr($bytes, $bytesToReturn);
1394  
1395  	 	 return $output;
1396  	 }
1397  
1398  	 /**
1399  	  * Generate random bytes using openssl if available
1400  	  *
1401  	  * @param string $bytesToGenerate
1402  	  * @return string
1403  	  */
1404  	protected static function generateRandomBytesOpenSsl($bytesToGenerate) {
1405  	 	 if (!function_exists('openssl_random_pseudo_bytes')) {
1406  	 	 	 return '';
1407  	 	 }
1408  	 	 $isStrong = NULL;
1409  	 	 return (string) openssl_random_pseudo_bytes($bytesToGenerate, $isStrong);
1410  	 }
1411  
1412  	 /**
1413  	  * Generate random bytes using mcrypt if available
1414  	  *
1415  	  * @param $bytesToGenerate
1416  	  * @param $randomSource
1417  	  * @return string
1418  	  */
1419  	protected static function generateRandomBytesMcrypt($bytesToGenerate, $randomSource) {
1420  	 	 if (!function_exists('mcrypt_create_iv')) {
1421  	 	 	 return '';
1422  	 	 }
1423  	 	 return (string) @mcrypt_create_iv($bytesToGenerate, $randomSource);
1424  	 }
1425  
1426  	 /**
1427  	  * Read random bytes from /dev/urandom if it is accessible
1428  	  *
1429  	  * @param $bytesToGenerate
1430  	  * @return string
1431  	  */
1432  	protected static function generateRandomBytesUrandom($bytesToGenerate) {
1433  	 	 $bytes = '';
1434  	 	 $fh = @fopen('/dev/urandom', 'rb');
1435  	 	 if ($fh) {
1436  	 	 	 	 // PHP only performs buffered reads, so in reality it will always read
1437  	 	 	 	 // at least 4096 bytes. Thus, it costs nothing extra to read and store
1438  	 	 	 	 // that much so as to speed any additional invocations.
1439  	 	 	 $bytes = fread($fh, $bytesToGenerate);
1440  	 	 	 fclose($fh);
1441  	 	 }
1442  
1443  	 	 return $bytes;
1444  	 }
1445  
1446  	 /**
1447  	  * Generate pseudo random bytes as last resort
1448  	  *
1449  	  * @param $bytesToReturn
1450  	  * @return string
1451  	  */
1452  	protected static function generateRandomBytesFallback($bytesToReturn) {
1453  	 	 $bytes = '';
1454  	 	 	 // We initialize with somewhat random.
1455  	 	 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() % pow(10, 6), 10, 2) . microtime() . uniqid('') . getmypid();
1456  	 	 while (!isset($bytes[$bytesToReturn - 1])) {
1457  	 	 	 $randomState = sha1(microtime() . mt_rand() . $randomState);
1458  	 	 	 $bytes .= sha1(mt_rand() . $randomState, TRUE);
1459  	 	 }
1460  	 	 return $bytes;
1461  	 }
1462  
1463  	 /**
1464  	  * Returns a hex representation of a random byte string.
1465  	  *
1466  	  * @param integer $count Number of hex characters to return
1467  	  * @return string Random Bytes
1468  	  */
1469  	public static function getRandomHexString($count) {
1470  	 	 return substr(bin2hex(self::generateRandomBytes(intval(($count + 1) / 2))), 0, $count);
1471  	 }
1472  
1473  	 /**
1474  	  * Returns a given string with underscores as UpperCamelCase.
1475  	  * Example: Converts blog_example to BlogExample
1476  	  *
1477  	  * @param string $string: String to be converted to camel case
1478  	  * @return string UpperCamelCasedWord
1479  	  */
1480  	public static function underscoredToUpperCamelCase($string) {
1481  	 	 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1482  	 	 return $upperCamelCase;
1483  	 }
1484  
1485  	 /**
1486  	  * Returns a given string with underscores as lowerCamelCase.
1487  	  * Example: Converts minimal_value to minimalValue
1488  	  *
1489  	  * @param string $string: String to be converted to camel case
1490  	  * @return string lowerCamelCasedWord
1491  	  */
1492  	public static function underscoredToLowerCamelCase($string) {
1493  	 	 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1494  	 	 $lowerCamelCase = self::lcfirst($upperCamelCase);
1495  	 	 return $lowerCamelCase;
1496  	 }
1497  
1498  	 /**
1499  	  * Returns a given CamelCasedString as an lowercase string with underscores.
1500  	  * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1501  	  *
1502  	  * @param string $string String to be converted to lowercase underscore
1503  	  * @return string lowercase_and_underscored_string
1504  	  */
1505  	public static function camelCaseToLowerCaseUnderscored($string) {
1506  	 	 return self::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
1507  	 }
1508  
1509  	 /**
1510  	  * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1511  	  * Example: Converts "Hello World" to "hello World"
1512  	  *
1513  	  * @param string $string The string to be used to lowercase the first character
1514  	  * @return string The string with the first character as lowercase
1515  	  */
1516  	public static function lcfirst($string) {
1517  	 	 return self::strtolower(substr($string, 0, 1)) . substr($string, 1);
1518  	 }
1519  
1520  	 /**
1521  	  * Checks if a given string is a Uniform Resource Locator (URL).
1522  	  *
1523  	  * @param string $url The URL to be validated
1524  	  * @return boolean Whether the given URL is valid
1525  	  */
1526  	public static function isValidUrl($url) {
1527  	 	 require_once(PATH_typo3 . 'contrib/idna/idna_convert.class.php');
1528  	 	 $IDN = new idna_convert(array('idn_version' => 2008));
1529  
1530  	 	 return (filter_var($IDN->encode($url), FILTER_VALIDATE_URL) !== FALSE);
1531  	 }
1532  
1533  
1534  	 /*************************
1535  	  *
1536  	  * ARRAY FUNCTIONS
1537  	  *
1538  	  *************************/
1539  
1540  	 /**
1541  	  * Check if an string item exists in an array.
1542  	  * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1543  	  *
1544  	  * Comparison to PHP in_array():
1545  	  * -> $array = array(0, 1, 2, 3);
1546  	  * -> variant_a := t3lib_div::inArray($array, $needle)
1547  	  * -> variant_b := in_array($needle, $array)
1548  	  * -> variant_c := in_array($needle, $array, TRUE)
1549  	  * +---------+-----------+-----------+-----------+
1550  	  * | $needle | variant_a | variant_b | variant_c |
1551  	  * +---------+-----------+-----------+-----------+
1552  	  * | '1a'	 | FALSE	  | TRUE	   | FALSE	  |
1553  	  * | ''	   | FALSE	  | TRUE	   | FALSE	  |
1554  	  * | '0'	  | TRUE	   | TRUE	   | FALSE	  |
1555  	  * | 0	    | TRUE	   | TRUE	   | TRUE	   |
1556  	  * +---------+-----------+-----------+-----------+
1557  	  *
1558  	  * @param array $in_array one-dimensional array of items
1559  	  * @param string $item item to check for
1560  	  * @return boolean TRUE if $item is in the one-dimensional array $in_array
1561  	  */
1562  	public static function inArray(array $in_array, $item) {
1563  	 	 foreach ($in_array as $val) {
1564  	 	 	 if (!is_array($val) && !strcmp($val, $item)) {
1565  	 	 	 	 return TRUE;
1566  	 	 	 }
1567  	 	 }
1568  	 	 return FALSE;
1569  	 }
1570  
1571  	 /**
1572  	  * Explodes a $string delimited by $delim and passes each item in the array through intval().
1573  	  * Corresponds to t3lib_div::trimExplode(), but with conversion to integers for all values.
1574  	  *
1575  	  * @param string $delimiter Delimiter string to explode with
1576  	  * @param string $string The string to explode
1577  	  * @param boolean $onlyNonEmptyValues If set, all empty values (='') will NOT be set in output
1578  	  * @param integer $limit If positive, the result will contain a maximum of limit elements,
1579  	  *	 	 	 	 	 	  if negative, all components except the last -limit are returned,
1580  	  *	 	 	 	 	 	  if zero (default), the result is not limited at all
1581  	  * @return array Exploded values, all converted to integers
1582  	  */
1583  	public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
1584  	 	 $explodedValues = self::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
1585  	 	 return array_map('intval', $explodedValues);
1586  	 }
1587  
1588  	 /**
1589  	  * Reverse explode which explodes the string counting from behind.
1590  	  * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1591  	  *
1592  	  * @param string $delimiter Delimiter string to explode with
1593  	  * @param string $string The string to explode
1594  	  * @param integer $count Number of array entries
1595  	  * @return array Exploded values
1596  	  */
1597  	public static function revExplode($delimiter, $string, $count = 0) {
1598  	 	 $explodedValues = explode($delimiter, strrev($string), $count);
1599  	 	 $explodedValues = array_map('strrev', $explodedValues);
1600  	 	 return array_reverse($explodedValues);
1601  	 }
1602  
1603  	 /**
1604  	  * Explodes a string and trims all values for whitespace in the ends.
1605  	  * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1606  	  *
1607  	  * @param string $delim Delimiter string to explode with
1608  	  * @param string $string The string to explode
1609  	  * @param boolean $removeEmptyValues If set, all empty values will be removed in output
1610  	  * @param integer $limit If positive, the result will contain a maximum of
1611  	  *	 	 	 	 	 	  $limit elements, if negative, all components except
1612  	  *	 	 	 	 	 	  the last -$limit are returned, if zero (default),
1613  	  *	 	 	 	 	 	  the result is not limited at all. Attention though
1614  	  *	 	 	 	 	 	  that the use of this parameter can slow down this
1615  	  *	 	 	 	 	 	  function.
1616  	  * @return array Exploded values
1617  	  */
1618  	public static function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
1619  	 	 $explodedValues = explode($delim, $string);
1620  
1621  	 	 $result = array_map('trim', $explodedValues);
1622  
1623  	 	 if ($removeEmptyValues) {
1624  	 	 	 $temp = array();
1625  	 	 	 foreach ($result as $value) {
1626  	 	 	 	 if ($value !== '') {
1627  	 	 	 	 	 $temp[] = $value;
1628  	 	 	 	 }
1629  	 	 	 }
1630  	 	 	 $result = $temp;
1631  	 	 }
1632  
1633  	 	 if ($limit != 0) {
1634  	 	 	 if ($limit < 0) {
1635  	 	 	 	 $result = array_slice($result, 0, $limit);
1636  	 	 	 } elseif (count($result) > $limit) {
1637  	 	 	 	 $lastElements = array_slice($result, $limit - 1);
1638  	 	 	 	 $result = array_slice($result, 0, $limit - 1);
1639  	 	 	 	 $result[] = implode($delim, $lastElements);
1640  	 	 	 }
1641  	 	 }
1642  
1643  	 	 return $result;
1644  	 }
1645  
1646  	 /**
1647  	  * Removes the value $cmpValue from the $array if found there. Returns the modified array
1648  	  *
1649  	  * @param array $array Array containing the values
1650  	  * @param string $cmpValue Value to search for and if found remove array entry where found.
1651  	  * @return array Output array with entries removed if search string is found
1652  	  */
1653  	public static function removeArrayEntryByValue(array $array, $cmpValue) {
1654  	 	 foreach ($array as $k => $v) {
1655  	 	 	 if (is_array($v)) {
1656  	 	 	 	 $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
1657  	 	 	 } elseif (!strcmp($v, $cmpValue)) {
1658  	 	 	 	 unset($array[$k]);
1659  	 	 	 }
1660  	 	 }
1661  	 	 return $array;
1662  	 }
1663  
1664  	 /**
1665  	  * Filters an array to reduce its elements to match the condition.
1666  	  * The values in $keepItems can be optionally evaluated by a custom callback function.
1667  	  *
1668  	  * Example (arguments used to call this function):
1669  	  * $array = array(
1670  	  *	 	  array('aa' => array('first', 'second'),
1671  	  *	 	  array('bb' => array('third', 'fourth'),
1672  	  *	 	  array('cc' => array('fifth', 'sixth'),
1673  	  * );
1674  	  * $keepItems = array('third');
1675  	  * $getValueFunc = create_function('$value', 'return $value[0];');
1676  	  *
1677  	  * Returns:
1678  	  * array(
1679  	  *	 	  array('bb' => array('third', 'fourth'),
1680  	  * )
1681  	  *
1682  	  * @param array $array: The initial array to be filtered/reduced
1683  	  * @param mixed $keepItems: The items which are allowed/kept in the array - accepts array or csv string
1684  	  * @param string $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
1685  	  * @return array The filtered/reduced array with the kept items
1686  	  */
1687  	public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
1688  	 	 if ($array) {
1689  	 	 	 	 // Convert strings to arrays:
1690  	 	 	 if (is_string($keepItems)) {
1691  	 	 	 	 $keepItems = self::trimExplode(',', $keepItems);
1692  	 	 	 }
1693  	 	 	 	 // create_function() returns a string:
1694  	 	 	 if (!is_string($getValueFunc)) {
1695  	 	 	 	 $getValueFunc = NULL;
1696  	 	 	 }
1697  	 	 	 	 // Do the filtering:
1698  	 	 	 if (is_array($keepItems) && count($keepItems)) {
1699  	 	 	 	 foreach ($array as $key => $value) {
1700  	 	 	 	 	 	 // Get the value to compare by using the callback function:
1701  	 	 	 	 	 $keepValue = (isset($getValueFunc) ? $getValueFunc($value) : $value);
1702  	 	 	 	 	 if (!in_array($keepValue, $keepItems)) {
1703  	 	 	 	 	 	 unset($array[$key]);
1704  	 	 	 	 	 }
1705  	 	 	 	 }
1706  	 	 	 }
1707  	 	 }
1708  	 	 return $array;
1709  	 }
1710  
1711  	 /**
1712  	  * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1713  	  *
1714  	  * @param string $name Name prefix for entries. Set to blank if you wish none.
1715  	  * @param array $theArray The (multidimensional) array to implode
1716  	  * @param string $str (keep blank)
1717  	  * @param boolean $skipBlank If set, parameters which were blank strings would be removed.
1718  	  * @param boolean $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1719  	  * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1720  	  * @see explodeUrl2Array()
1721  	  */
1722  	public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
1723  	 	 foreach ($theArray as $Akey => $AVal) {
1724  	 	 	 $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1725  	 	 	 if (is_array($AVal)) {
1726  	 	 	 	 $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1727  	 	 	 } else {
1728  	 	 	 	 if (!$skipBlank || strcmp($AVal, '')) {
1729  	 	 	 	 	 $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) .
1730  	 	 	 	 	 	 	 '=' . rawurlencode($AVal);
1731  	 	 	 	 }
1732  	 	 	 }
1733  	 	 }
1734  	 	 return $str;
1735  	 }
1736  
1737  	 /**
1738  	  * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1739  	  *
1740  	  * @param string $string GETvars string
1741  	  * @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())
1742  	  * @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!
1743  	  * @see implodeArrayForUrl()
1744  	  */
1745  	public static function explodeUrl2Array($string, $multidim = FALSE) {
1746  	 	 $output = array();
1747  	 	 if ($multidim) {
1748  	 	 	 parse_str($string, $output);
1749  	 	 } else {
1750  	 	 	 $p = explode('&', $string);
1751  	 	 	 foreach ($p as $v) {
1752  	 	 	 	 if (strlen($v)) {
1753  	 	 	 	 	 list($pK, $pV) = explode('=', $v, 2);
1754  	 	 	 	 	 $output[rawurldecode($pK)] = rawurldecode($pV);
1755  	 	 	 	 }
1756  	 	 	 }
1757  	 	 }
1758  	 	 return $output;
1759  	 }
1760  
1761  	 /**
1762  	  * Returns an array with selected keys from incoming data.
1763  	  * (Better read source code if you want to find out...)
1764  	  *
1765  	  * @param string $varList List of variable/key names
1766  	  * @param array $getArray Array from where to get values based on the keys in $varList
1767  	  * @param boolean $GPvarAlt If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1768  	  * @return array Output array with selected variables.
1769  	  */
1770  	public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = TRUE) {
1771  	 	 $keys = self::trimExplode(',', $varList, 1);
1772  	 	 $outArr = array();
1773  	 	 foreach ($keys as $v) {
1774  	 	 	 if (isset($getArray[$v])) {
1775  	 	 	 	 $outArr[$v] = $getArray[$v];
1776  	 	 	 } elseif ($GPvarAlt) {
1777  	 	 	 	 $outArr[$v] = self::_GP($v);
1778  	 	 	 }
1779  	 	 }
1780  	 	 return $outArr;
1781  	 }
1782  
1783  	 /**
1784  	  * AddSlash array
1785  	  * This function traverses a multidimensional array and adds slashes to the values.
1786  	  * NOTE that the input array is and argument by reference.!!
1787  	  * Twin-function to stripSlashesOnArray
1788  	  *
1789  	  * @param array $theArray Multidimensional input array, (REFERENCE!)
1790  	  * @return array
1791  	  */
1792  	public static function addSlashesOnArray(array &$theArray) {
1793  	 	 foreach ($theArray as &$value) {
1794  	 	 	 if (is_array($value)) {
1795  	 	 	 	 self::addSlashesOnArray($value);
1796  	 	 	 } else {
1797  	 	 	 	 $value = addslashes($value);
1798  	 	 	 }
1799  	 	 }
1800  	 	 unset($value);
1801  	 	 reset($theArray);
1802  	 }
1803  
1804  	 /**
1805  	  * StripSlash array
1806  	  * This function traverses a multidimensional array and strips slashes to the values.
1807  	  * NOTE that the input array is and argument by reference.!!
1808  	  * Twin-function to addSlashesOnArray
1809  	  *
1810  	  * @param array $theArray Multidimensional input array, (REFERENCE!)
1811  	  * @return array
1812  	  */
1813  	public static function stripSlashesOnArray(array &$theArray) {
1814  	 	 foreach ($theArray as &$value) {
1815  	 	 	 if (is_array($value)) {
1816  	 	 	 	 self::stripSlashesOnArray($value);
1817  	 	 	 } else {
1818  	 	 	 	 $value = stripslashes($value);
1819  	 	 	 }
1820  	 	 }
1821  	 	 unset($value);
1822  	 	 reset($theArray);
1823  	 }
1824  
1825  	 /**
1826  	  * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1827  	  *
1828  	  * @param array $arr Multidimensional input array
1829  	  * @param string $cmd "add" or "strip", depending on usage you wish.
1830  	  * @return array
1831  	  */
1832  	public static function slashArray(array $arr, $cmd) {
1833  	 	 if ($cmd == 'strip') {
1834  	 	 	 self::stripSlashesOnArray($arr);
1835  	 	 }
1836  	 	 if ($cmd == 'add') {
1837  	 	 	 self::addSlashesOnArray($arr);
1838  	 	 }
1839  	 	 return $arr;
1840  	 }
1841  
1842  	 /**
1843  	  * Rename Array keys with a given mapping table
1844  	  *
1845  	  * @param array	 $array Array by reference which should be remapped
1846  	  * @param array	 $mappingTable Array with remap information, array/$oldKey => $newKey)
1847  	  */
1848  	public static function remapArrayKeys(&$array, $mappingTable) {
1849  	 	 if (is_array($mappingTable)) {
1850  	 	 	 foreach ($mappingTable as $old => $new) {
1851  	 	 	 	 if ($new && isset($array[$old])) {
1852  	 	 	 	 	 $array[$new] = $array[$old];
1853  	 	 	 	 	 unset ($array[$old]);
1854  	 	 	 	 }
1855  	 	 	 }
1856  	 	 }
1857  	 }
1858  
1859  
1860  	 /**
1861  	  * Merges two arrays recursively and "binary safe" (integer keys are
1862  	  * overridden as well), overruling similar values in the first array
1863  	  * ($arr0) with the values of the second array ($arr1)
1864  	  * In case of identical keys, ie. keeping the values of the second.
1865  	  *
1866  	  * @param array $arr0 First array
1867  	  * @param array $arr1 Second array, overruling the first array
1868  	  * @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.
1869  	  * @param boolean $includeEmptyValues If set, values from $arr1 will overrule if they are empty or zero. Default: TRUE
1870  	  * @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.
1871  	  * @return array Resulting array where $arr1 values has overruled $arr0 values
1872  	  */
1873  	public static function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = FALSE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) {
1874  	 	 foreach ($arr1 as $key => $val) {
1875  	 	 	 if ($enableUnsetFeature && $val === '__UNSET') {
1876  	 	 	 	 unset($arr0[$key]);
1877  	 	 	 	 continue;
1878  	 	 	 }
1879  	 	 	 if (is_array($arr0[$key])) {
1880  	 	 	 	 if (is_array($arr1[$key])) {
1881  	 	 	 	 	 $arr0[$key] = self::array_merge_recursive_overrule(
1882  	 	 	 	 	 	 $arr0[$key],
1883  	 	 	 	 	 	 $arr1[$key],
1884  	 	 	 	 	 	 $notAddKeys,
1885  	 	 	 	 	 	 $includeEmptyValues,
1886  	 	 	 	 	 	 $enableUnsetFeature
1887  	 	 	 	 	 );
1888  	 	 	 	 }
1889  	 	 	 } elseif (
1890  	 	 	 	 (!$notAddKeys || isset($arr0[$key])) &&
1891  	 	 	 	 ($includeEmptyValues || $val)
1892  	 	 	 ) {
1893  	 	 	 	 $arr0[$key] = $val;
1894  	 	 	 }
1895  	 	 }
1896  
1897  	 	 reset($arr0);
1898  	 	 return $arr0;
1899  	 }
1900  
1901  	 /**
1902  	  * 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.
1903  	  *
1904  	  * @param array $arr1 First array
1905  	  * @param array $arr2 Second array
1906  	  * @return array Merged result.
1907  	  */
1908  	public static function array_merge(array $arr1, array $arr2) {
1909  	 	 return $arr2 + $arr1;
1910  	 }
1911  
1912  	 /**
1913  	  * Filters keys off from first array that also exist in second array. Comparison is done by keys.
1914  	  * This method is a recursive version of php array_diff_assoc()
1915  	  *
1916  	  * @param array $array1 Source array
1917  	  * @param array $array2 Reduce source array by this array
1918  	  * @return array Source array reduced by keys also present in second array
1919  	  */
1920  	public static function arrayDiffAssocRecursive(array $array1, array $array2) {
1921  	 	 $differenceArray = array();
1922  	 	 foreach ($array1 as $key => $value) {
1923  	 	 	 if (!array_key_exists($key, $array2)) {
1924  	 	 	 	 $differenceArray[$key] = $value;
1925  	 	 	 } elseif (is_array($value)) {
1926  	 	 	 	 if (is_array($array2[$key])) {
1927  	 	 	 	 	 $differenceArray[$key] = self::arrayDiffAssocRecursive($value, $array2[$key]);
1928  	 	 	 	 }
1929  	 	 	 }
1930  	 	 }
1931  
1932  	 	 return $differenceArray;
1933  	 }
1934  
1935  	 /**
1936  	  * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1937  	  *
1938  	  * @param array $row Input array of values
1939  	  * @param string $delim Delimited, default is comma
1940  	  * @param string $quote Quote-character to wrap around the values.
1941  	  * @return string A single line of CSV
1942  	  */
1943  	public static function csvValues(array $row, $delim = ',', $quote = '"') {
1944  	 	 $out = array();
1945  	 	 foreach ($row as $value) {
1946  	 	 	 $out[] = str_replace($quote, $quote . $quote, $value);
1947  	 	 }
1948  	 	 $str = $quote . implode($quote . $delim . $quote, $out) . $quote;
1949  	 	 return $str;
1950  	 }
1951  
1952  	 /**
1953  	  * Removes dots "." from end of a key identifier of TypoScript styled array.
1954  	  * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1955  	  *
1956  	  * @param array $ts: TypoScript configuration array
1957  	  * @return array TypoScript configuration array without dots at the end of all keys
1958  	  */
1959  	public static function removeDotsFromTS(array $ts) {
1960  	 	 $out = array();
1961  	 	 foreach ($ts as $key => $value) {
1962  	 	 	 if (is_array($value)) {
1963  	 	 	 	 $key = rtrim($key, '.');
1964  	 	 	 	 $out[$key] = self::removeDotsFromTS($value);
1965  	 	 	 } else {
1966  	 	 	 	 $out[$key] = $value;
1967  	 	 	 }
1968  	 	 }
1969  	 	 return $out;
1970  	 }
1971  
1972  	 /**
1973  	  * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1974  	  *
1975  	  * @param array $array array to be sorted recursively, passed by reference
1976  	  * @return boolean TRUE if param is an array
1977  	  */
1978  	public static function naturalKeySortRecursive(&$array) {
1979  	 	 if (!is_array($array)) {
1980  	 	 	 return FALSE;
1981  	 	 }
1982  	 	 uksort($array, 'strnatcasecmp');
1983  	 	 foreach ($array as $key => $value) {
1984  	 	 	 self::naturalKeySortRecursive($array[$key]);
1985  	 	 }
1986  	 	 return TRUE;
1987  	 }
1988  
1989  
1990  	 /*************************
1991  	  *
1992  	  * HTML/XML PROCESSING
1993  	  *
1994  	  *************************/
1995  
1996  	 /**
1997  	  * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1998  	  * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1999  	  * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
2000  	  *
2001  	  * @param string $tag HTML-tag string (or attributes only)
2002  	  * @return array Array with the attribute values.
2003  	  */
2004  	public static function get_tag_attributes($tag) {
2005  	 	 $components = self::split_tag_attributes($tag);
2006  	 	 $name = ''; // attribute name is stored here
2007  	 	 $valuemode = FALSE;
2008  	 	 $attributes = array();
2009  	 	 foreach ($components as $key => $val) {
2010  	 	 	 if ($val != '=') { // 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
2011  	 	 	 	 if ($valuemode) {
2012  	 	 	 	 	 if ($name) {
2013  	 	 	 	 	 	 $attributes[$name] = $val;
2014  	 	 	 	 	 	 $name = '';
2015  	 	 	 	 	 }
2016  	 	 	 	 } else {
2017  	 	 	 	 	 if ($key = strtolower(preg_replace('/[^[:alnum:]_\:\-]/', '', $val))) {
2018  	 	 	 	 	 	 $attributes[$key] = '';
2019  	 	 	 	 	 	 $name = $key;
2020  	 	 	 	 	 }
2021  	 	 	 	 }
2022  	 	 	 	 $valuemode = FALSE;
2023  	 	 	 } else {
2024  	 	 	 	 $valuemode = TRUE;
2025  	 	 	 }
2026  	 	 }
2027  	 	 return $attributes;
2028  	 }
2029  
2030  	 /**
2031  	  * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
2032  	  * Removes tag-name if found
2033  	  *
2034  	  * @param string $tag HTML-tag string (or attributes only)
2035  	  * @return array Array with the attribute values.
2036  	  */
2037  	public static function split_tag_attributes($tag) {
2038  	 	 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
2039  	 	 	 // Removes any > in the end of the string
2040  	 	 $tag_tmp = trim(rtrim($tag_tmp, '>'));
2041  
2042  	 	 $value = array();
2043  	 	 while (strcmp($tag_tmp, '')) { // Compared with empty string instead , 030102
2044  	 	 	 $firstChar = substr($tag_tmp, 0, 1);
2045  	 	 	 if (!strcmp($firstChar, '"') || !strcmp($firstChar, "'")) {
2046  	 	 	 	 $reg = explode($firstChar, $tag_tmp, 3);
2047  	 	 	 	 $value[] = $reg[1];
2048  	 	 	 	 $tag_tmp = trim($reg[2]);
2049  	 	 	 } elseif (!strcmp($firstChar, '=')) {
2050  	 	 	 	 $value[] = '=';
2051  	 	 	 	 $tag_tmp = trim(substr($tag_tmp, 1)); // Removes = chars.
2052  	 	 	 } else {
2053  	 	 	 	 	 // There are '' around the value. We look for the next ' ' or '>'
2054  	 	 	 	 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
2055  	 	 	 	 $value[] = trim($reg[0]);
2056  	 	 	 	 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
2057  	 	 	 }
2058  	 	 }
2059  	 	 reset($value);
2060  	 	 return $value;
2061  	 }
2062  
2063  	 /**
2064  	  * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
2065  	  *
2066  	  * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
2067  	  * @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!
2068  	  * @param boolean $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
2069  	  * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
2070  	  */
2071  	public static function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
2072  	 	 if ($xhtmlSafe) {
2073  	 	 	 $newArr = array();
2074  	 	 	 foreach ($arr as $p => $v) {
2075  	 	 	 	 if (!isset($newArr[strtolower($p)])) {
2076  	 	 	 	 	 $newArr[strtolower($p)] = htmlspecialchars($v);
2077  	 	 	 	 }
2078  	 	 	 }
2079  	 	 	 $arr = $newArr;
2080  	 	 }
2081  	 	 $list = array();
2082  	 	 foreach ($arr as $p => $v) {
2083  	 	 	 if (strcmp($v, '') || $dontOmitBlankAttribs) {
2084  	 	 	 	 $list[] = $p . '="' . $v . '"';
2085  	 	 	 }
2086  	 	 }
2087  	 	 return implode(' ', $list);
2088  	 }
2089  
2090  	 /**
2091  	  * Wraps JavaScript code XHTML ready with <script>-tags
2092  	  * Automatic re-indenting of the JS code is done by using the first line as indent reference.
2093  	  * This is nice for indenting JS code with PHP code on the same level.
2094  	  *
2095  	  * @param string $string JavaScript code
2096  	  * @param boolean $linebreak Wrap script element in line breaks? Default is TRUE.
2097  	  * @return string The wrapped JS code, ready to put into a XHTML page
2098  	  */
2099  	public static function wrapJS($string, $linebreak = TRUE) {
2100  	 	 if (trim($string)) {
2101  	 	 	 	 // <script wrapped in nl?
2102  	 	 	 $cr = $linebreak ? LF : '';
2103  
2104  	 	 	 	 // remove nl from the beginning
2105  	 	 	 $string = preg_replace('/^\n+/', '', $string);
2106  	 	 	 	 // re-ident to one tab using the first line as reference
2107  	 	 	 $match = array();
2108  	 	 	 if (preg_match('/^(\t+)/', $string, $match)) {
2109  	 	 	 	 $string = str_replace($match[1], TAB, $string);
2110  	 	 	 }
2111  	 	 	 $string = $cr . '<script type="text/javascript">
2112  /*<![CDATA[*/
2113  ' . $string . '
2114  /*]]>*/
2115  </script>' . $cr;
2116  	 	 }
2117  	 	 return trim($string);
2118  	 }
2119  
2120  
2121  	 /**
2122  	  * Parses XML input into a PHP array with associative keys
2123  	  *
2124  	  * @param string $string XML data input
2125  	  * @param integer $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
2126  	  * @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.
2127  	  * @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
2128  	  */
2129  	public static function xml2tree($string, $depth = 999) {
2130  	 	 $parser = xml_parser_create();
2131  	 	 $vals = array();
2132  	 	 $index = array();
2133  
2134  	 	 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2135  	 	 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2136  	 	 xml_parse_into_struct($parser, $string, $vals, $index);
2137  
2138  	 	 if (xml_get_error_code($parser)) {
2139  	 	 	 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2140  	 	 }
2141  	 	 xml_parser_free($parser);
2142  
2143  	 	 $stack = array(array());
2144  	 	 $stacktop = 0;
2145  	 	 $startPoint = 0;
2146  
2147  	 	 $tagi = array();
2148  	 	 foreach ($vals as $key => $val) {
2149  	 	 	 $type = $val['type'];
2150  
2151  	 	 	 	 // open tag:
2152  	 	 	 if ($type == 'open' || $type == 'complete') {
2153  	 	 	 	 $stack[$stacktop++] = $tagi;
2154  
2155  	 	 	 	 if ($depth == $stacktop) {
2156  	 	 	 	 	 $startPoint = $key;
2157  	 	 	 	 }
2158  
2159  	 	 	 	 $tagi = array('tag' => $val['tag']);
2160  
2161  	 	 	 	 if (isset($val['attributes'])) {
2162  	 	 	 	 	 $tagi['attrs'] = $val['attributes'];
2163  	 	 	 	 }
2164  	 	 	 	 if (isset($val['value'])) {
2165  	 	 	 	 	 $tagi['values'][] = $val['value'];
2166  	 	 	 	 }
2167  	 	 	 }
2168  	 	 	 	 // finish tag:
2169  	 	 	 if ($type == 'complete' || $type == 'close') {
2170  	 	 	 	 $oldtagi = $tagi;
2171  	 	 	 	 $tagi = $stack[--$stacktop];
2172  	 	 	 	 $oldtag = $oldtagi['tag'];
2173  	 	 	 	 unset($oldtagi['tag']);
2174  
2175  	 	 	 	 if ($depth == ($stacktop + 1)) {
2176  	 	 	 	 	 if ($key - $startPoint > 0) {
2177  	 	 	 	 	 	 $partArray = array_slice(
2178  	 	 	 	 	 	 	 $vals,
2179  	 	 	 	 	 	 	 	 $startPoint + 1,
2180  	 	 	 	 	 	 	 	 $key - $startPoint - 1
2181  	 	 	 	 	 	 );
2182  	 	 	 	 	 	 $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
2183  	 	 	 	 	 } else {
2184  	 	 	 	 	 	 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
2185  	 	 	 	 	 }
2186  	 	 	 	 }
2187  
2188  	 	 	 	 $tagi['ch'][$oldtag][] = $oldtagi;
2189  	 	 	 	 unset($oldtagi);
2190  	 	 	 }
2191  	 	 	 	 // cdata
2192  	 	 	 if ($type == 'cdata') {
2193  	 	 	 	 $tagi['values'][] = $val['value'];
2194  	 	 	 }
2195  	 	 }
2196  	 	 return $tagi['ch'];
2197  	 }
2198  
2199  	 /**
2200  	  * Turns PHP array into XML. See array2xml()
2201  	  *
2202  	  * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2203  	  * @param string $docTag Alternative document tag. Default is "phparray".
2204  	  * @param array $options Options for the compilation. See array2xml() for description.
2205  	  * @param string $charset Forced charset to prologue
2206  	  * @return string An XML string made from the input content in the array.
2207  	  * @see xml2array(),array2xml()
2208  	  */
2209  	public static function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
2210  
2211  	 	 	 // Set default charset unless explicitly specified
2212  	 	 $charset = $charset ? $charset : 'utf-8';
2213  
2214  	 	 	 // Return XML:
2215  	 	 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF .
2216  	 	 	 	 self::array2xml($array, '', 0, $docTag, 0, $options);
2217  	 }
2218  
2219  	 /**
2220  	  * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2221  	  *
2222  	  * Converts a PHP array into an XML string.
2223  	  * The XML output is optimized for readability since associative keys are used as tag names.
2224  	  * 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.
2225  	  * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
2226  	  * 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
2227  	  * 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.
2228  	  * 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!
2229  	  * 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...
2230  	  *
2231  	  * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2232  	  * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
2233  	  * @param integer $level Current recursion level. Don't change, stay at zero!
2234  	  * @param string $docTag Alternative document tag. Default is "phparray".
2235  	  * @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
2236  	  * @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')
2237  	  * @param array $stackData Stack data. Don't touch.
2238  	  * @return string An XML string made from the input content in the array.
2239  	  * @see xml2array()
2240  	  */
2241  	public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array()) {
2242  	 	 	 // 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
2243  	 	 $binaryChars = chr(0) . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) .
2244  	 	 	 	 chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) .
2245  	 	 	 	 chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) .
2246  	 	 	 	 chr(30) . chr(31);
2247  	 	 	 // Set indenting mode:
2248  	 	 $indentChar = $spaceInd ? ' ' : TAB;
2249  	 	 $indentN = $spaceInd > 0 ? $spaceInd : 1;
2250  	 	 $nl = ($spaceInd >= 0 ? LF : '');
2251  
2252  	 	 	 // Init output variable:
2253  	 	 $output = '';
2254  
2255  	 	 	 // Traverse the input array
2256  	 	 foreach ($array as $k => $v) {
2257  	 	 	 $attr = '';
2258  	 	 	 $tagName = $k;
2259  
2260  	 	 	 	 // Construct the tag name.
2261  	 	 	 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
2262  	 	 	 	 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2263  	 	 	 	 $tagName = (string) $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
2264  	 	 	 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && t3lib_utility_Math::canBeInterpretedAsInteger($tagName)) { // Use tag based on parent tag name + if current tag is numeric
2265  	 	 	 	 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2266  	 	 	 	 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
2267  	 	 	 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) { // Use tag based on parent tag name + current tag
2268  	 	 	 	 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2269  	 	 	 	 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
2270  	 	 	 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
2271  	 	 	 	 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2272  	 	 	 	 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName']];
2273  	 	 	 } elseif (!strcmp(intval($tagName), $tagName)) { // If integer...;
2274  	 	 	 	 if ($options['useNindex']) { // If numeric key, prefix "n"
2275  	 	 	 	 	 $tagName = 'n' . $tagName;
2276  	 	 	 	 } else { // Use special tag for num. keys:
2277  	 	 	 	 	 $attr .= ' index="' . $tagName . '"';
2278  	 	 	 	 	 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
2279  	 	 	 	 }
2280  	 	 	 } elseif ($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
2281  	 	 	 	 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2282  	 	 	 	 $tagName = $options['useIndexTagForAssoc'];
2283  	 	 	 }
2284  
2285  	 	 	 	 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2286  	 	 	 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2287  
2288  	 	 	 	 // If the value is an array then we will call this function recursively:
2289  	 	 	 if (is_array($v)) {
2290  
2291  	 	 	 	 	 // Sub elements:
2292  	 	 	 	 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2293  	 	 	 	 	 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2294  	 	 	 	 	 $clearStackPath = $subOptions['clearStackPath'];
2295  	 	 	 	 } else {
2296  	 	 	 	 	 $subOptions = $options;
2297  	 	 	 	 	 $clearStackPath = FALSE;
2298  	 	 	 	 }
2299  
2300  	 	 	 	 $content = $nl .
2301  	 	 	 	 	 	 self::array2xml(
2302  	 	 	 	 	 	 	 $v,
2303  	 	 	 	 	 	 	 $NSprefix,
2304  	 	 	 	 	 	 	 	 $level + 1,
2305  	 	 	 	 	 	 	 '',
2306  	 	 	 	 	 	 	 $spaceInd,
2307  	 	 	 	 	 	 	 $subOptions,
2308  	 	 	 	 	 	 	 array(
2309  	 	 	 	 	 	 	 	 'parentTagName' => $tagName,
2310  	 	 	 	 	 	 	 	 'grandParentTagName' => $stackData['parentTagName'],
2311  	 	 	 	 	 	 	 	 'path' => $clearStackPath ? '' : $stackData['path'] . '/' . $tagName,
2312  	 	 	 	 	 	 	 )
2313  	 	 	 	 	 	 ) .
2314  	 	 	 	 	 	 ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
2315  	 	 	 	 if ((int) $options['disableTypeAttrib'] != 2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2316  	 	 	 	 	 $attr .= ' type="array"';
2317  	 	 	 	 }
2318  	 	 	 } else { // Just a value:
2319  
2320  	 	 	 	 	 // Look for binary chars:
2321  	 	 	 	 $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2322  	 	 	 	 if ($vLen && strcspn($v, $binaryChars) != $vLen) { // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
2323  	 	 	 	 	 	 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2324  	 	 	 	 	 $content = $nl . chunk_split(base64_encode($v));
2325  	 	 	 	 	 $attr .= ' base64="1"';
2326  	 	 	 	 } else {
2327  	 	 	 	 	 	 // Otherwise, just htmlspecialchar the stuff:
2328  	 	 	 	 	 $content = htmlspecialchars($v);
2329  	 	 	 	 	 $dType = gettype($v);
2330  	 	 	 	 	 if ($dType == 'string') {
2331  	 	 	 	 	 	 if ($options['useCDATA'] && $content != $v) {
2332  	 	 	 	 	 	 	 $content = '<![CDATA[' . $v . ']]>';
2333  	 	 	 	 	 	 }
2334  	 	 	 	 	 } elseif (!$options['disableTypeAttrib']) {
2335  	 	 	 	 	 	 $attr .= ' type="' . $dType . '"';
2336  	 	 	 	 	 }
2337  	 	 	 	 }
2338  	 	 	 }
2339  
2340  	 	 	 	 // Add the element to the output string:
2341  	 	 	 $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '') . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2342  	 	 }
2343  
2344  	 	 	 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2345  	 	 if (!$level) {
2346  	 	 	 $output =
2347  	 	 	 	 	 '<' . $docTag . '>' . $nl .
2348  	 	 	 	 	 	 	 $output .
2349  	 	 	 	 	 	 	 '</' . $docTag . '>';
2350  	 	 }
2351  
2352  	 	 return $output;
2353  	 }
2354  
2355  	 /**
2356  	  * Converts an XML string to a PHP array.
2357  	  * This is the reverse function of array2xml()
2358  	  * This is a wrapper for xml2arrayProcess that adds a two-level cache
2359  	  *
2360  	  * @param string $string XML content to convert into an array
2361  	  * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2362  	  * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2363  	  * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2364  	  * @see array2xml(),xml2arrayProcess()
2365  	  */
2366  	public static function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
2367  	 	 static $firstLevelCache = array();
2368  
2369  	 	 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
2370  
2371  	 	 	 // look up in first level cache
2372  	 	 if (!empty($firstLevelCache[$identifier])) {
2373  	 	 	 $array = $firstLevelCache[$identifier];
2374  	 	 } else {
2375  	 	 	 	 // look up in second level cache
2376  	 	 	 $cacheContent = t3lib_pageSelect::getHash($identifier, 0);
2377  	 	 	 $array = unserialize($cacheContent);
2378  
2379  	 	 	 if ($array === FALSE) {
2380  	 	 	 	 $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2381  	 	 	 	 t3lib_pageSelect::storeHash($identifier, serialize($array), 'ident_xml2array');
2382  	 	 	 }
2383  	 	 	 	 // store content in first level cache
2384  	 	 	 $firstLevelCache[$identifier] = $array;
2385  	 	 }
2386  	 	 return $array;
2387  	 }
2388  
2389  	 /**
2390  	  * Converts an XML string to a PHP array.
2391  	  * This is the reverse function of array2xml()
2392  	  *
2393  	  * @param string $string XML content to convert into an array
2394  	  * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2395  	  * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2396  	  * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2397  	  * @see array2xml()
2398  	  */
2399  	protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
2400  	 	 	 // Create parser:
2401  	 	 $parser = xml_parser_create();
2402  	 	 $vals = array();
2403  	 	 $index = array();
2404  
2405  	 	 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2406  	 	 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2407  
2408  	 	 	 // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2409  	 	 $match = array();
2410  	 	 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2411  	 	 $theCharset = $match[1] ? $match[1] : 'utf-8';
2412  	 	 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
2413  
2414  	 	 	 // Parse content:
2415  	 	 xml_parse_into_struct($parser, $string, $vals, $index);
2416  
2417  	 	 	 // If error, return error message:
2418  	 	 if (xml_get_error_code($parser)) {
2419  	 	 	 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2420  	 	 }
2421  	 	 xml_parser_free($parser);
2422  
2423  	 	 	 // Init vars:
2424  	 	 $stack = array(array());
2425  	 	 $stacktop = 0;
2426  	 	 $current = array();
2427  	 	 $tagName = '';
2428  	 	 $documentTag = '';
2429  
2430  	 	 	 // Traverse the parsed XML structure:
2431  	 	 foreach ($vals as $key => $val) {
2432  
2433  	 	 	 	 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2434  	 	 	 $tagName = $val['tag'];
2435  	 	 	 if (!$documentTag) {
2436  	 	 	 	 $documentTag = $tagName;
2437  	 	 	 }
2438  
2439  	 	 	 	 // Test for name space:
2440  	 	 	 $tagName = ($NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix) ? substr($tagName, strlen($NSprefix)) : $tagName;
2441  
2442  	 	 	 	 // Test for numeric tag, encoded on the form "nXXX":
2443  	 	 	 $testNtag = substr($tagName, 1); // Closing tag.
2444  	 	 	 $tagName = (substr($tagName, 0, 1) == 'n' && !strcmp(intval($testNtag), $testNtag)) ? intval($testNtag) : $tagName;
2445  
2446  	 	 	 	 // Test for alternative index value:
2447  	 	 	 if (strlen($val['attributes']['index'])) {
2448  	 	 	 	 $tagName = $val['attributes']['index'];
2449  	 	 	 }
2450  
2451  	 	 	 	 // Setting tag-values, manage stack:
2452  	 	 	 switch ($val['type']) {
2453  	 	 	 	 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2454  	 	 	 	 	 $current[$tagName] = array(); // Setting blank place holder
2455  	 	 	 	 	 $stack[$stacktop++] = $current;
2456  	 	 	 	 	 $current = array();
2457  	 	 	 	 	 break;
2458  	 	 	 	 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2459  	 	 	 	 	 $oldCurrent = $current;
2460  	 	 	 	 	 $current = $stack[--$stacktop];
2461  	 	 	 	 	 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
2462  	 	 	 	 	 $current[key($current)] = $oldCurrent;
2463  	 	 	 	 	 unset($oldCurrent);
2464  	 	 	 	 	 break;
2465  	 	 	 	 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2466  	 	 	 	 	 if ($val['attributes']['base64']) {
2467  	 	 	 	 	 	 $current[$tagName] = base64_decode($val['value']);
2468  	 	 	 	 	 } else {
2469  	 	 	 	 	 	 $current[$tagName] = (string) $val['value']; // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2470  
2471  	 	 	 	 	 	 	 // Cast type:
2472  	 	 	 	 	 	 switch ((string) $val['attributes']['type']) {
2473  	 	 	 	 	 	 	 case 'integer':
2474  	 	 	 	 	 	 	 	 $current[$tagName] = (integer) $current[$tagName];
2475  	 	 	 	 	 	 	 	 break;
2476  	 	 	 	 	 	 	 case 'double':
2477  	 	 	 	 	 	 	 	 $current[$tagName] = (double) $current[$tagName];
2478  	 	 	 	 	 	 	 	 break;
2479  	 	 	 	 	 	 	 case 'boolean':
2480  	 	 	 	 	 	 	 	 $current[$tagName] = (bool) $current[$tagName];
2481  	 	 	 	 	 	 	 	 break;
2482  	 	 	 	 	 	 	 case 'array':
2483  	 	 	 	 	 	 	 	 $current[$tagName] = array(); // 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...
2484  	 	 	 	 	 	 	 	 break;
2485  	 	 	 	 	 	 }
2486  	 	 	 	 	 }
2487  	 	 	 	 	 break;
2488  	 	 	 }
2489  	 	 }
2490  
2491  	 	 if ($reportDocTag) {
2492  	 	 	 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2493  	 	 }
2494  
2495  	 	 	 // Finally return the content of the document tag.
2496  	 	 return $current[$tagName];
2497  	 }
2498  
2499  	 /**
2500  	  * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2501  	  *
2502  	  * @param array $vals An array of XML parts, see xml2tree
2503  	  * @return string Re-compiled XML data.
2504  	  */
2505  	public static function xmlRecompileFromStructValArray(array $vals) {
2506  	 	 $XMLcontent = '';
2507  
2508  	 	 foreach ($vals as $val) {
2509  	 	 	 $type = $val['type'];
2510  
2511  	 	 	 	 // open tag:
2512  	 	 	 if ($type == 'open' || $type == 'complete') {
2513  	 	 	 	 $XMLcontent .= '<' . $val['tag'];
2514  	 	 	 	 if (isset($val['attributes'])) {
2515  	 	 	 	 	 foreach ($val['attributes'] as $k => $v) {
2516  	 	 	 	 	 	 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2517  	 	 	 	 	 }
2518  	 	 	 	 }
2519  	 	 	 	 if ($type == 'complete') {
2520  	 	 	 	 	 if (isset($val['value'])) {
2521  	 	 	 	 	 	 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2522  	 	 	 	 	 } else {
2523  	 	 	 	 	 	 $XMLcontent .= '/>';
2524  	 	 	 	 	 }
2525  	 	 	 	 } else {
2526  	 	 	 	 	 $XMLcontent .= '>';
2527  	 	 	 	 }
2528  
2529  	 	 	 	 if ($type == 'open' && isset($val['value'])) {
2530  	 	 	 	 	 $XMLcontent .= htmlspecialchars($val['value']);
2531  	 	 	 	 }
2532  	 	 	 }
2533  	 	 	 	 // finish tag:
2534  	 	 	 if ($type == 'close') {
2535  	 	 	 	 $XMLcontent .= '</' . $val['tag'] . '>';
2536  	 	 	 }
2537  	 	 	 	 // cdata
2538  	 	 	 if ($type == 'cdata') {
2539  	 	 	 	 $XMLcontent .= htmlspecialchars($val['value']);
2540  	 	 	 }
2541  	 	 }
2542  
2543  	 	 return $XMLcontent;
2544  	 }
2545  
2546  	 /**
2547  	  * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2548  	  *
2549  	  * @param string $xmlData XML data
2550  	  * @return array Attributes of the xml prologue (header)
2551  	  */
2552  	public static function xmlGetHeaderAttribs($xmlData) {
2553  	 	 $match = array();
2554  	 	 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
2555  	 	 	 return self::get_tag_attributes($match[1]);
2556  	 	 }
2557  	 }
2558  
2559  	 /**
2560  	  * Minifies JavaScript
2561  	  *
2562  	  * @param string $script Script to minify
2563  	  * @param string $error Error message (if any)
2564  	  * @return string Minified script or source string if error happened
2565  	  */
2566  	public static function minifyJavaScript($script, &$error = '') {
2567  	 	 require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
2568  	 	 try {
2569  	 	 	 $error = '';
2570  	 	 	 $script = trim(JSMin::minify(str_replace(CR, '', $script)));
2571  	 	 }
2572  	 	 catch (JSMinException $e) {
2573  	 	 	 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
2574  	 	 	 self::devLog($error, 't3lib_div', 2,
2575  	 	 	 	 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
2576  	 	 }
2577  	 	 return $script;
2578  	 }
2579  
2580  
2581  	 /*************************
2582  	  *
2583  	  * FILES FUNCTIONS
2584  	  *
2585  	  *************************/
2586  
2587  	 /**
2588  	  * Reads the file or url $url and returns the content
2589  	  * 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.
2590  	  *
2591  	  * @param string $url File/URL to read
2592  	  * @param integer $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2593  	  * @param array $requestHeaders HTTP headers to be used in the request
2594  	  * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2595  	  * @return mixed The content from the resource given as input. FALSE if an error has occured.
2596  	  */
2597  	public static function getUrl($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
2598  	 	 $content = FALSE;
2599  
2600  	 	 if (isset($report)) {
2601  	 	 	 $report['error'] = 0;
2602  	 	 	 $report['message'] = '';
2603  	 	 }
2604  
2605  	 	 	 // use cURL for: http, https, ftp, ftps, sftp and scp
2606  	 	 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2607  	 	 	 if (isset($report)) {
2608  	 	 	 	 $report['lib'] = 'cURL';
2609  	 	 	 }
2610  
2611  	 	 	 	 // External URL without error checking.
2612  	 	 	 if (!function_exists('curl_init') || !($ch = curl_init())) {
2613  	 	 	 	 if (isset($report)) {
2614  	 	 	 	 	 $report['error'] = -1;
2615  	 	 	 	 	 $report['message'] = 'Couldn\'t initialize cURL.';
2616  	 	 	 	 }
2617  	 	 	 	 return FALSE;
2618  	 	 	 }
2619  
2620  	 	 	 curl_setopt($ch, CURLOPT_URL, $url);
2621  	 	 	 curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
2622  	 	 	 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
2623  	 	 	 curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
2624  	 	 	 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2625  	 	 	 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
2626  	 	 	 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout'])));
2627  
2628  	 	 	 $followLocation = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
2629  
2630  	 	 	 if (is_array($requestHeaders)) {
2631  	 	 	 	 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
2632  	 	 	 }
2633  
2634  	 	 	 	 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2635  	 	 	 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2636  	 	 	 	 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2637  
2638  	 	 	 	 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2639  	 	 	 	 	 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2640  	 	 	 	 }
2641  	 	 	 	 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2642  	 	 	 	 	 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2643  	 	 	 	 }
2644  	 	 	 }
2645  	 	 	 $content = curl_exec($ch);
2646  	 	 	 if (isset($report)) {
2647  	 	 	 	 if ($content === FALSE) {
2648  	 	 	 	 	 $report['error'] = curl_errno($ch);
2649  	 	 	 	 	 $report['message'] = curl_error($ch);
2650  	 	 	 	 } else {
2651  	 	 	 	 	 $curlInfo = curl_getinfo($ch);
2652  	 	 	 	 	 	 // We hit a redirection but we couldn't follow it
2653  	 	 	 	 	 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
2654  	 	 	 	 	 	 $report['error'] = -1;
2655  	 	 	 	 	 	 $report['message'] = 'Couldn\'t follow location redirect (PHP configuration option open_basedir is in effect).';
2656  	 	 	 	 	 } elseif ($includeHeader) {
2657  	 	 	 	 	 	 	 // Set only for $includeHeader to work exactly like PHP variant
2658  	 	 	 	 	 	 $report['http_code'] = $curlInfo['http_code'];
2659  	 	 	 	 	 	 $report['content_type'] = $curlInfo['content_type'];
2660  	 	 	 	 	 }
2661  	 	 	 	 }
2662  	 	 	 }
2663  	 	 	 curl_close($ch);
2664  
2665  	 	 } elseif ($includeHeader) {
2666  	 	 	 if (isset($report)) {
2667  	 	 	 	 $report['lib'] = 'socket';
2668  	 	 	 }
2669  	 	 	 $parsedURL = parse_url($url);
2670  	 	 	 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2671  	 	 	 	 if (isset($report)) {
2672  	 	 	 	 	 $report['error'] = -1;
2673  	 	 	 	 	 $report['message'] = 'Reading headers is not allowed for this protocol.';
2674  	 	 	 	 }
2675  	 	 	 	 return FALSE;
2676  	 	 	 }
2677  	 	 	 $port = intval($parsedURL['port']);
2678  	 	 	 if ($port < 1) {
2679  	 	 	 	 if ($parsedURL['scheme'] == 'http') {
2680  	 	 	 	 	 $port = ($port > 0 ? $port : 80);
2681  	 	 	 	 	 $scheme = '';
2682  	 	 	 	 } else {
2683  	 	 	 	 	 $port = ($port > 0 ? $port : 443);
2684  	 	 	 	 	 $scheme = 'ssl://';
2685  	 	 	 	 }
2686  	 	 	 }
2687  	 	 	 $errno = 0;
2688  	 	 	 	 // $errstr = '';
2689  	 	 	 $fp = @fsockopen($scheme . $parsedURL['host'], $port, $errno, $errstr, 2.0);
2690  	 	 	 if (!$fp || $errno > 0) {
2691  	 	 	 	 if (isset($report)) {
2692  	 	 	 	 	 $report['error'] = $errno ? $errno : -1;
2693  	 	 	 	 	 $report['message'] = $errno ? ($errstr ? $errstr : 'Socket error.') : 'Socket initialization error.';
2694  	 	 	 	 }
2695  	 	 	 	 return FALSE;
2696  	 	 	 }
2697  	 	 	 $method = ($includeHeader == 2) ? 'HEAD' : 'GET';
2698  	 	 	 $msg = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/') .
2699  	 	 	 	 	 ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
2700  	 	 	 	 	 ' HTTP/1.0' . CRLF . 'Host: ' .
2701  	 	 	 	 	 $parsedURL['host'] . "\r\nConnection: close\r\n";
2702  	 	 	 if (is_array($requestHeaders)) {
2703  	 	 	 	 $msg .= implode(CRLF, $requestHeaders) . CRLF;
2704  	 	 	 }
2705  	 	 	 $msg .= CRLF;
2706  
2707  	 	 	 fputs($fp, $msg);
2708  	 	 	 while (!feof($fp)) {
2709  	 	 	 	 $line = fgets($fp, 2048);
2710  	 	 	 	 if (isset($report)) {
2711  	 	 	 	 	 if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
2712  	 	 	 	 	 	 $report['http_code'] = $status[1];
2713  	 	 	 	 	 }
2714  	 	 	 	 	 elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2715  	 	 	 	 	 	 $report['content_type'] = $type[1];
2716  	 	 	 	 	 }
2717  	 	 	 	 }
2718  	 	 	 	 $content .= $line;
2719  	 	 	 	 if (!strlen(trim($line))) {
2720  	 	 	 	 	 break; // Stop at the first empty line (= end of header)
2721  	 	 	 	 }
2722  	 	 	 }
2723  	 	 	 if ($includeHeader != 2) {
2724  	 	 	 	 $content .= stream_get_contents($fp);
2725  	 	 	 }
2726  	 	 	 fclose($fp);
2727  
2728  	 	 } elseif (is_array($requestHeaders)) {
2729  	 	 	 if (isset($report)) {
2730  	 	 	 	 $report['lib'] = 'file/context';
2731  	 	 	 }
2732  	 	 	 $parsedURL = parse_url($url);
2733  	 	 	 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2734  	 	 	 	 if (isset($report)) {
2735  	 	 	 	 	 $report['error'] = -1;
2736  	 	 	 	 	 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2737  	 	 	 	 }
2738  	 	 	 	 return FALSE;
2739  	 	 	 }
2740  	 	 	 $ctx = stream_context_create(array(
2741  	 	 	 	 'http' => array(
2742  	 	 	 	 	 'header' => implode(CRLF, $requestHeaders)
2743  	 	 	 	 )
2744  	 	 	 )
2745  	 	 	 );
2746  
2747  	 	 	 $content = @file_get_contents($url, FALSE, $ctx);
2748  
2749  	 	 	 if ($content === FALSE && isset($report)) {
2750  	 	 	 	 $report['error'] = -1;
2751  	 	 	 	 $report['message'] = 'Couldn\'t get URL: ' . implode(LF, $http_response_header);
2752  	 	 	 }
2753  	 	 } else {
2754  	 	 	 if (isset($report)) {
2755  	 	 	 	 $report['lib'] = 'file';
2756  	 	 	 }
2757  
2758  	 	 	 $content = @file_get_contents($url);
2759  
2760  	 	 	 if ($content === FALSE && isset($report)) {
2761  	 	 	 	 $report['error'] = -1;
2762  	 	 	 	 $report['message'] = 'Couldn\'t get URL: ' . implode(LF, $http_response_header);
2763  	 	 	 }
2764  	 	 }
2765  
2766  	 	 return $content;
2767  	 }
2768  
2769  	 /**
2770  	  * Writes $content to the file $file
2771  	  *
2772  	  * @param string $file Filepath to write to
2773  	  * @param string $content Content to write
2774  	  * @return boolean TRUE if the file was successfully opened and written to.
2775  	  */
2776  	public static function writeFile($file, $content) {
2777  	 	 if (!@is_file($file)) {
2778  	 	 	 $changePermissions = TRUE;
2779  	 	 }
2780  
2781  	 	 if ($fd = fopen($file, 'wb')) {
2782  	 	 	 $res = fwrite($fd, $content);
2783  	 	 	 fclose($fd);
2784  
2785  	 	 	 if ($res === FALSE) {
2786  	 	 	 	 return FALSE;
2787  	 	 	 }
2788  
2789  	 	 	 if ($changePermissions) { // Change the permissions only if the file has just been created
2790  	 	 	 	 self::fixPermissions($file);
2791  	 	 	 }
2792  
2793  	 	 	 return TRUE;
2794  	 	 }
2795  
2796  	 	 return FALSE;
2797  	 }
2798  
2799  	 /**
2800  	  * Sets the file system mode and group ownership of a file or a folder.
2801  	  *
2802  	  * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2803  	  * @param boolean $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2804  	  * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2805  	  */
2806  	public static function fixPermissions($path, $recursive = FALSE) {
2807  	 	 if (TYPO3_OS != 'WIN') {
2808  	 	 	 $result = FALSE;
2809  
2810  	 	 	 	 // Make path absolute
2811  	 	 	 if (!self::isAbsPath($path)) {
2812  	 	 	 	 $path = self::getFileAbsFileName($path, FALSE);
2813  	 	 	 }
2814  
2815  	 	 	 if (self::isAllowedAbsPath($path)) {
2816  	 	 	 	 if (@is_file($path)) {
2817  	 	 	 	 	 	 // "@" is there because file is not necessarily OWNED by the user
2818  	 	 	 	 	 $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
2819  	 	 	 	 } elseif (@is_dir($path)) {
2820  	 	 	 	 	 	 // "@" is there because file is not necessarily OWNED by the user
2821  	 	 	 	 	 $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2822  	 	 	 	 }
2823  
2824  	 	 	 	 	 // Set createGroup if not empty
2825  	 	 	 	 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
2826  	 	 	 	 	 	 // "@" is there because file is not necessarily OWNED by the user
2827  	 	 	 	 	 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2828  	 	 	 	 	 $result = $changeGroupResult ? $result : FALSE;
2829  	 	 	 	 }
2830  
2831  	 	 	 	 	 // Call recursive if recursive flag if set and $path is directory
2832  	 	 	 	 if ($recursive && @is_dir($path)) {
2833  	 	 	 	 	 $handle = opendir($path);
2834  	 	 	 	 	 while (($file = readdir($handle)) !== FALSE) {
2835  	 	 	 	 	 	 $recursionResult = NULL;
2836  	 	 	 	 	 	 if ($file !== '.' && $file !== '..') {
2837  	 	 	 	 	 	 	 if (@is_file($path . '/' . $file)) {
2838  	 	 	 	 	 	 	 	 $recursionResult = self::fixPermissions($path . '/' . $file);
2839  	 	 	 	 	 	 	 } elseif (@is_dir($path . '/' . $file)) {
2840  	 	 	 	 	 	 	 	 $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
2841  	 	 	 	 	 	 	 }
2842  	 	 	 	 	 	 	 if (isset($recursionResult) && !$recursionResult) {
2843  	 	 	 	 	 	 	 	 $result = FALSE;
2844  	 	 	 	 	 	 	 }
2845  	 	 	 	 	 	 }
2846  	 	 	 	 	 }
2847  	 	 	 	 	 closedir($handle);
2848  	 	 	 	 }
2849  	 	 	 }
2850  	 	 } else {
2851  	 	 	 $result = TRUE;
2852  	 	 }
2853  	 	 return $result;
2854  	 }
2855  
2856  	 /**
2857  	  * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2858  	  * Accepts an additional subdirectory in the file path!
2859  	  *
2860  	  * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2861  	  * @param string $content Content string to write
2862  	  * @return string Returns NULL on success, otherwise an error string telling about the problem.
2863  	  */
2864  	public static function writeFileToTypo3tempDir($filepath, $content) {
2865  
2866  	 	 	 // Parse filepath into directory and basename:
2867  	 	 $fI = pathinfo($filepath);
2868  	 	 $fI['dirname'] .= '/';
2869  
2870  	 	 	 // Check parts:
2871  	 	 if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
2872  	 	 	 if (defined('PATH_site')) {
2873  	 	 	 	 $dirName = PATH_site . 'typo3temp/'; // Setting main temporary directory name (standard)
2874  	 	 	 	 if (@is_dir($dirName)) {
2875  	 	 	 	 	 if (self::isFirstPartOfStr($fI['dirname'], $dirName)) {
2876  
2877  	 	 	 	 	 	 	 // Checking if the "subdir" is found:
2878  	 	 	 	 	 	 $subdir = substr($fI['dirname'], strlen($dirName));
2879  	 	 	 	 	 	 if ($subdir) {
2880  	 	 	 	 	 	 	 if (preg_match('/^[[:alnum:]_]+\/$/', $subdir) || preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/', $subdir)) {
2881  	 	 	 	 	 	 	 	 $dirName .= $subdir;
2882  	 	 	 	 	 	 	 	 if (!@is_dir($dirName)) {
2883  	 	 	 	 	 	 	 	 	 self::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
2884  	 	 	 	 	 	 	 	 }
2885  	 	 	 	 	 	 	 } else {
2886  	 	 	 	 	 	 	 	 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or  "[[:alnum:]_]/[[:alnum:]_]/"';
2887  	 	 	 	 	 	 	 }
2888  	 	 	 	 	 	 }
2889  	 	 	 	 	 	 	 // Checking dir-name again (sub-dir might have been created):
2890  	 	 	 	 	 	 if (@is_dir($dirName)) {
2891  	 	 	 	 	 	 	 if ($filepath == $dirName . $fI['basename']) {
2892  	 	 	 	 	 	 	 	 self::writeFile($filepath, $content);
2893  	 	 	 	 	 	 	 	 if (!@is_file($filepath)) {
2894  	 	 	 	 	 	 	 	 	 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2895  	 	 	 	 	 	 	 	 }
2896  	 	 	 	 	 	 	 } else {
2897  	 	 	 	 	 	 	 	 return 'Calculated filelocation didn\'t match input $filepath!';
2898  	 	 	 	 	 	 	 }
2899  	 	 	 	 	 	 } else {
2900  	 	 	 	 	 	 	 return '"' . $dirName . '" is not a directory!';
2901  	 	 	 	 	 	 }
2902  	 	 	 	 	 } else {
2903  	 	 	 	 	 	 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2904  	 	 	 	 	 }
2905  	 	 	 	 } else {
2906  	 	 	 	 	 return 'PATH_site + "typo3temp/" was not a directory!';
2907  	 	 	 	 }
2908  	 	 	 } else {
2909  	 	 	 	 return 'PATH_site constant was NOT defined!';
2910  	 	 	 }
2911  	 	 } else {
2912  	 	 	 return 'Input filepath "' . $filepath . '" was generally invalid!';
2913  	 	 }
2914  	 }
2915  
2916  	 /**
2917  	  * Wrapper function for mkdir.
2918  	  * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
2919  	  * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2920  	  *
2921  	  * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2922  	  * @return boolean TRUE if @mkdir went well!
2923  	  */
2924  	public static function mkdir($newFolder) {
2925  	 	 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2926  	 	 if ($result) {
2927  	 	 	 self::fixPermissions($newFolder);
2928  	 	 }
2929  	 	 return $result;
2930  	 }
2931  
2932  	 /**
2933  	  * Creates a directory - including parent directories if necessary and
2934  	  * sets permissions on newly created directories.
2935  	  *
2936  	  * @param string $directory Target directory to create. Must a have trailing slash
2937  	  * 	 	 if second parameter is given!
2938  	  * 	 	 Example: "/root/typo3site/typo3temp/foo/"
2939  	  * @param string $deepDirectory Directory to create. This second parameter
2940  	  * 	 	 is kept for backwards compatibility since 4.6 where this method
2941  	  * 	 	 was split into a base directory and a deep directory to be created.
2942  	  * 	 	 Example: "xx/yy/" which creates "/root/typo3site/xx/yy/" if $directory is "/root/typo3site/"
2943  	  * @return void
2944  	  * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2945  	  * @throws \RuntimeException If directory could not be created
2946  	  */
2947  	public static function mkdir_deep($directory, $deepDirectory = '') {
2948  	 	 if (!is_string($directory)) {
2949  	 	 	 throw new \InvalidArgumentException(
2950  	 	 	 	 'The specified directory is of type "' . gettype($directory) . '" but a string is expected.',
2951  	 	 	 	 1303662955
2952  	 	 	 );
2953  	 	 }
2954  	 	 if (!is_string($deepDirectory)) {
2955  	 	 	 throw new \InvalidArgumentException(
2956  	 	 	 	 'The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.',
2957  	 	 	 	 1303662956
2958  	 	 	 );
2959  	 	 }
2960  
2961  	 	 $fullPath = $directory . $deepDirectory;
2962  	 	 if (!is_dir($fullPath) && strlen($fullPath) > 0) {
2963  	 	 	 $firstCreatedPath = self::createDirectoryPath($fullPath);
2964  	 	 	 if ($firstCreatedPath !== '') {
2965  	 	 	 	 self::fixPermissions($firstCreatedPath, TRUE);
2966  	 	 	 }
2967  	 	 }
2968  	 }
2969  
2970  	 /**
2971  	  * Creates directories for the specified paths if they do not exist. This
2972  	  * functions sets proper permission mask but does not set proper user and
2973  	  * group.
2974  	  *
2975  	  * @static
2976  	  * @param string $fullDirectoryPath
2977  	  * @return string Path to the the first created directory in the hierarchy
2978  	  * @see t3lib_div::mkdir_deep
2979  	  * @throws \RuntimeException If directory could not be created
2980  	  */
2981  	protected static function createDirectoryPath($fullDirectoryPath) {
2982  	 	 $currentPath = $fullDirectoryPath;
2983  	 	 $firstCreatedPath = '';
2984  	 	 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']);
2985  	 	 if (!@is_dir($currentPath)) {
2986  	 	 	 do {
2987  	 	 	 	 $firstCreatedPath = $currentPath;
2988  	 	 	 	 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR);
2989  	 	 	 	 $currentPath = substr($currentPath, 0, $separatorPosition);
2990  	 	 	 } while (!is_dir($currentPath) && $separatorPosition !== FALSE);
2991  
2992  	 	 	 $result = @mkdir($fullDirectoryPath, $permissionMask, TRUE);
2993  	 	 	 if (!$result) {
2994  	 	 	 	 throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251400);
2995  	 	 	 }
2996  	 	 }
2997  	 	 return $firstCreatedPath;
2998  	 }
2999  
3000  	 /**
3001  	  * Wrapper function for rmdir, allowing recursive deletion of folders and files
3002  	  *
3003  	  * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
3004  	  * @param boolean $removeNonEmpty Allow deletion of non-empty directories
3005  	  * @return boolean TRUE if @rmdir went well!
3006  	  */
3007  	public static function rmdir($path, $removeNonEmpty = FALSE) {
3008  	 	 $OK = FALSE;
3009  	 	 $path = preg_replace('|/$|', '', $path); // Remove trailing slash
3010  
3011  	 	 if (file_exists($path)) {
3012  	 	 	 $OK = TRUE;
3013  
3014  	 	 	 if (is_dir($path)) {
3015  	 	 	 	 if ($removeNonEmpty == TRUE && $handle = opendir($path)) {
3016  	 	 	 	 	 while ($OK && FALSE !== ($file = readdir($handle))) {
3017  	 	 	 	 	 	 if ($file == '.' || $file == '..') {
3018  	 	 	 	 	 	 	 continue;
3019  	 	 	 	 	 	 }
3020  	 	 	 	 	 	 $OK = self::rmdir($path . '/' . $file, $removeNonEmpty);
3021  	 	 	 	 	 }
3022  	 	 	 	 	 closedir($handle);
3023  	 	 	 	 }
3024  	 	 	 	 if ($OK) {
3025  	 	 	 	 	 $OK = rmdir($path);
3026  	 	 	 	 }
3027  
3028  	 	 	 } else { // If $dirname is a file, simply remove it
3029  	 	 	 	 $OK = unlink($path);
3030  	 	 	 }
3031  
3032  	 	 	 clearstatcache();
3033  	 	 }
3034  
3035  	 	 return $OK;
3036  	 }
3037  
3038  	 /**
3039  	  * Returns an array with the names of folders in a specific path
3040  	  * Will return 'error' (string) if there were an error with reading directory content.
3041  	  *
3042  	  * @param string $path Path to list directories from
3043  	  * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
3044  	  */
3045  	public static function get_dirs($path) {
3046  	 	 if ($path) {
3047  	 	 	 if (is_dir($path)) {
3048  	 	 	 	 $dir = scandir($path);
3049  	 	 	 	 $dirs = array();
3050  	 	 	 	 foreach ($dir as $entry) {
3051  	 	 	 	 	 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
3052  	 	 	 	 	 	 $dirs[] = $entry;
3053  	 	 	 	 	 }
3054  	 	 	 	 }
3055  	 	 	 } else {
3056  	 	 	 	 $dirs = 'error';
3057  	 	 	 }
3058  	 	 }
3059  	 	 return $dirs;
3060  	 }
3061  
3062  	 /**
3063  	  * Returns an array with the names of files in a specific path
3064  	  *
3065  	  * @param string $path Is the path to the file
3066  	  * @param string $extensionList is the comma list of extensions to read only (blank = all)
3067  	  * @param boolean $prependPath If set, then the path is prepended the file names. Otherwise only the file names are returned in the array
3068  	  * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
3069  	  *
3070  	  * @param string $excludePattern A comma separated list of file names to exclude, no wildcards
3071  	  * @return array Array of the files found
3072  	  */
3073  	public static function getFilesInDir($path, $extensionList = '', $prependPath = FALSE, $order = '', $excludePattern = '') {
3074  
3075  	 	 	 // Initialize variables:
3076  	 	 $filearray = array();
3077  	 	 $sortarray = array();
3078  	 	 $path = rtrim($path, '/');
3079  
3080  	 	 	 // Find files+directories:
3081  	 	 if (@is_dir($path)) {
3082  	 	 	 $extensionList = strtolower($extensionList);
3083  	 	 	 $d = dir($path);
3084  	 	 	 if (is_object($d)) {
3085  	 	 	 	 while ($entry = $d->read()) {
3086  	 	 	 	 	 if (@is_file($path . '/' . $entry)) {
3087  	 	 	 	 	 	 $fI = pathinfo($entry);
3088  	 	 	 	 	 	 $key = md5($path . '/' . $entry); // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
3089  	 	 	 	 	 	 if ((!strlen($extensionList) || self::inList($extensionList, strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^' . $excludePattern . '$/', $entry))) {
3090  	 	 	 	 	 	 	 $filearray[$key] = ($prependPath ? $path . '/' : '') . $entry;
3091  	 	 	 	 	 	 	 if ($order == 'mtime') {
3092  	 	 	 	 	 	 	 	 $sortarray[$key] = filemtime($path . '/' . $entry);
3093  	 	 	 	 	 	 	 }
3094  	 	 	 	 	 	 	 elseif ($order) {
3095  	 	 	 	 	 	 	 	 $sortarray[$key] = strtolower($entry);
3096  	 	 	 	 	 	 	 }
3097  	 	 	 	 	 	 }
3098  	 	 	 	 	 }
3099  	 	 	 	 }
3100  	 	 	 	 $d->close();
3101  	 	 	 } else {
3102  	 	 	 	 return 'error opening path: "' . $path . '"';
3103  	 	 	 }
3104  	 	 }
3105  
3106  	 	 	 // Sort them:
3107  	 	 if ($order) {
3108  	 	 	 asort($sortarray);
3109  	 	 	 $newArr = array();
3110  	 	 	 foreach ($sortarray as $k => $v) {
3111  	 	 	 	 $newArr[$k] = $filearray[$k];
3112  	 	 	 }
3113  	 	 	 $filearray = $newArr;
3114  	 	 }
3115  
3116  	 	 	 // Return result
3117  	 	 reset($filearray);
3118  	 	 return $filearray;
3119  	 }
3120  
3121  	 /**
3122  	  * Recursively gather all files and folders of a path.
3123  	  *
3124  	  * @param array $fileArr Empty input array (will have files added to it)
3125  	  * @param string $path The path to read recursively from (absolute) (include trailing slash!)
3126  	  * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
3127  	  * @param boolean $regDirs If set, directories are also included in output.
3128  	  * @param integer $recursivityLevels The number of levels to dig down...
3129  	  * @param string $excludePattern regex pattern of files/directories to exclude
3130  	  * @return array An array with the found files/directories.
3131  	  */
3132  	public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = FALSE, $recursivityLevels = 99, $excludePattern = '') {
3133  	 	 if ($regDirs) {
3134  	 	 	 $fileArr[] = $path;
3135  	 	 }
3136  	 	 $fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
3137  
3138  	 	 $dirs = self::get_dirs($path);
3139  	 	 if (is_array($dirs) && $recursivityLevels > 0) {
3140  	 	 	 foreach ($dirs as $subdirs) {
3141  	 	 	 	 if ((string) $subdirs != '' && (!strlen($excludePattern) || !preg_match('/^' . $excludePattern . '$/', $subdirs))) {
3142  	 	 	 	 	 $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
3143  	 	 	 	 }
3144  	 	 	 }
3145  	 	 }
3146  	 	 return $fileArr;
3147  	 }
3148  
3149  	 /**
3150  	  * Removes the absolute part of all files/folders in fileArr
3151  	  *
3152  	  * @param array $fileArr: The file array to remove the prefix from
3153  	  * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
3154  	  * @return array The input $fileArr processed.
3155  	  */
3156  	public static function removePrefixPathFromList(array $fileArr, $prefixToRemove) {
3157  	 	 foreach ($fileArr as $k => &$absFileRef) {
3158  	 	 	 if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
3159  	 	 	 	 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
3160  	 	 	 } else {
3161  	 	 	 	 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
3162  	 	 	 }
3163  	 	 }
3164  	 	 unset($absFileRef);
3165  	 	 return $fileArr;
3166  	 }
3167  
3168  	 /**
3169  	  * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
3170  	  *
3171  	  * @param string $theFile File path to process
3172  	  * @return string
3173  	  */
3174  	public static function fixWindowsFilePath($theFile) {
3175  	 	 return str_replace('//', '/', str_replace('\\', '/', $theFile));
3176  	 }
3177  
3178  	 /**
3179  	  * Resolves "../" sections in the input path string.
3180  	  * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
3181  	  *
3182  	  * @param string $pathStr File path in which "/../" is resolved
3183  	  * @return string
3184  	  */
3185  	public static function resolveBackPath($pathStr) {
3186  	 	 $parts = explode('/', $pathStr);
3187  	 	 $output = array();
3188  	 	 $c = 0;
3189  	 	 foreach ($parts as $pV) {
3190  	 	 	 if ($pV == '..') {
3191  	 	 	 	 if ($c) {
3192  	 	 	 	 	 array_pop($output);
3193  	 	 	 	 	 $c--;
3194  	 	 	 	 } else {
3195  	 	 	 	 	 $output[] = $pV;
3196  	 	 	 	 }
3197  	 	 	 } else {
3198  	 	 	 	 $c++;
3199  	 	 	 	 $output[] = $pV;
3200  	 	 	 }
3201  	 	 }
3202  	 	 return implode('/', $output);
3203  	 }
3204  
3205  	 /**
3206  	  * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
3207  	  * - If already having a scheme, nothing is prepended
3208  	  * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
3209  	  * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
3210  	  *
3211  	  * @param string $path URL / path to prepend full URL addressing to.
3212  	  * @return string
3213  	  */
3214  	public static function locationHeaderUrl($path) {
3215  	 	 $uI = parse_url($path);
3216  	 	 if (substr($path, 0, 1) == '/') { // relative to HOST
3217  	 	 	 $path = self::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
3218  	 	 } elseif (!$uI['scheme']) { // No scheme either
3219  	 	 	 $path = self::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
3220  	 	 }
3221  	 	 return $path;
3222  	 }
3223  
3224  	 /**
3225  	  * Returns the maximum upload size for a file that is allowed. Measured in KB.
3226  	  * This might be handy to find out the real upload limit that is possible for this
3227  	  * TYPO3 installation. The first parameter can be used to set something that overrides
3228  	  * the maxFileSize, usually for the TCA values.
3229  	  *
3230  	  * @param integer $localLimit: the number of Kilobytes (!) that should be used as
3231  	  *	 	 	 	 	 	 the initial Limit, otherwise $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize'] will be used
3232  	  * @return integer the maximum size of uploads that are allowed (measured in kilobytes)
3233  	  */
3234  	public static function getMaxUploadFileSize($localLimit = 0) {
3235  	 	 	 // don't allow more than the global max file size at all
3236  	 	 $t3Limit = (intval($localLimit > 0 ? $localLimit : $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize']));
3237  	 	 	 // as TYPO3 is handling the file size in KB, multiply by 1024 to get bytes
3238  	 	 $t3Limit = $t3Limit * 1024;
3239  
3240  	 	 	 // check for PHP restrictions of the maximum size of one of the $_FILES
3241  	 	 $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
3242  	 	 	 // check for PHP restrictions of the maximum $_POST size
3243  	 	 $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
3244  	 	 	 // if the total amount of post data is smaller (!) than the upload_max_filesize directive,
3245  	 	 	 // then this is the real limit in PHP
3246  	 	 $phpUploadLimit = ($phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit);
3247  
3248  	 	 	 // is the allowed PHP limit (upload_max_filesize) lower than the TYPO3 limit?, also: revert back to KB
3249  	 	 return floor($phpUploadLimit < $t3Limit ? $phpUploadLimit : $t3Limit) / 1024;
3250  	 }
3251  
3252  	 /**
3253  	  * Gets the bytes value from a measurement string like "100k".
3254  	  *
3255  	  * @param string $measurement: The measurement (e.g. "100k")
3256  	  * @return integer The bytes value (e.g. 102400)
3257  	  */
3258  	public static function getBytesFromSizeMeasurement($measurement) {
3259  	 	 $bytes = doubleval($measurement);
3260  	 	 if (stripos($measurement, 'G')) {
3261  	 	 	 $bytes *= 1024 * 1024 * 1024;
3262  	 	 } elseif (stripos($measurement, 'M')) {
3263  	 	 	 $bytes *= 1024 * 1024;
3264  	 	 } elseif (stripos($measurement, 'K')) {
3265  	 	 	 $bytes *= 1024;
3266  	 	 }
3267  	 	 return $bytes;
3268  	 }
3269  
3270  	 /**
3271  	  * Retrieves the maximum path length that is valid in the current environment.
3272  	  *
3273  	  * @return integer The maximum available path length
3274  	  */
3275  	public static function getMaximumPathLength() {
3276  	 	 return PHP_MAXPATHLEN;
3277  	 }
3278  
3279  
3280  	 /**
3281  	  * Function for static version numbers on files, based on the filemtime
3282  	  *
3283  	  * This will make the filename automatically change when a file is
3284  	  * changed, and by that re-cached by the browser. If the file does not
3285  	  * exist physically the original file passed to the function is
3286  	  * returned without the timestamp.
3287  	  *
3288  	  * Behaviour is influenced by the setting
3289  	  * TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename]
3290  	  * = TRUE (BE) / "embed" (FE) : modify filename
3291  	  * = FALSE (BE) / "querystring" (FE) : add timestamp as parameter
3292  	  *
3293  	  * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
3294  	  * @param boolean $forceQueryString If settings would suggest to embed in filename, this parameter allows us to force the versioning to occur in the query string. This is needed for scriptaculous.js which cannot have a different filename in order to load its modules (?load=...)
3295  	  * @return Relative path with version filename including the timestamp
3296  	  */
3297  	public static function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
3298  	 	 $lookupFile = explode('?', $file);
3299  	 	 $path = self::resolveBackPath(self::dirname(PATH_thisScript) . '/' . $lookupFile[0]);
3300  
3301  	 	 if (TYPO3_MODE == 'FE') {
3302  	 	 	 $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
3303  	 	 	 if ($mode === 'embed') {
3304  	 	 	 	 $mode = TRUE;
3305  	 	 	 } else {
3306  	 	 	 	 if ($mode === 'querystring') {
3307  	 	 	 	 	 $mode = FALSE;
3308  	 	 	 	 } else {
3309  	 	 	 	 	 $doNothing = TRUE;
3310  	 	 	 	 }
3311  	 	 	 }
3312  	 	 } else {
3313  	 	 	 $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
3314  	 	 }
3315  
3316  	 	 if (!file_exists($path) || $doNothing) {
3317  	 	 	 	 // File not found, return filename unaltered
3318  	 	 	 $fullName = $file;
3319  
3320  	 	 } else {
3321  	 	 	 if (!$mode || $forceQueryString) {
3322  	 	 	 	 	 // If use of .htaccess rule is not configured,
3323  	 	 	 	 	 // we use the default query-string method
3324  	 	 	 	 if ($lookupFile[1]) {
3325  	 	 	 	 	 $separator = '&';
3326  	 	 	 	 } else {
3327  	 	 	 	 	 $separator = '?';
3328  	 	 	 	 }
3329  	 	 	 	 $fullName = $file . $separator . filemtime($path);
3330  
3331  	 	 	 } else {
3332  	 	 	 	 	 // Change the filename
3333  	 	 	 	 $name = explode('.', $lookupFile[0]);
3334  	 	 	 	 $extension = array_pop($name);
3335  
3336  	 	 	 	 array_push($name, filemtime($path), $extension);
3337  	 	 	 	 $fullName = implode('.', $name);
3338  	 	 	 	 	 // append potential query string
3339  	 	 	 	 $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
3340  	 	 	 }
3341  	 	 }
3342  
3343  	 	 return $fullName;
3344  	 }
3345  
3346  	 /*************************
3347  	  *
3348  	  * SYSTEM INFORMATION
3349  	  *
3350  	  *************************/
3351  
3352  	 /**
3353  	  * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
3354  	  *
3355  	  * @return string
3356  	  */
3357  	public static function getThisUrl() {
3358  	 	 $p = parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
3359  	 	 $dir = self::dirname($p['path']) . '/'; // Strip file
3360  	 	 $url = str_replace('//', '/', $p['host'] . ($p['port'] ? ':' . $p['port'] : '') . $dir);
3361  	 	 return $url;
3362  	 }
3363  
3364  	 /**
3365  	  * Returns the link-url to the current script.
3366  	  * In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.
3367  	  * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
3368  	  *
3369  	  * @param array $getParams Array of GET parameters to include
3370  	  * @return string
3371  	  */
3372  	public static function linkThisScript(array $getParams = array()) {
3373  	 	 $parts = self::getIndpEnv('SCRIPT_NAME');
3374  	 	 $params = self::_GET();
3375  
3376  	 	 foreach ($getParams as $key => $value) {
3377  	 	 	 if ($value !== '') {
3378  	 	 	 	 $params[$key] = $value;
3379  	 	 	 } else {
3380  	 	 	 	 unset($params[$key]);
3381  	 	 	 }
3382  	 	 }
3383  
3384  	 	 $pString = self::implodeArrayForUrl('', $params);
3385  
3386  	 	 return $pString ? $parts . '?' . preg_replace('/^&/', '', $pString) : $parts;
3387  	 }
3388  
3389  	 /**
3390  	  * Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again.
3391  	  * So basically it adds the parameters in $getParams to an existing URL, $url
3392  	  *
3393  	  * @param string $url URL string
3394  	  * @param array $getParams Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
3395  	  * @return string Output URL with added getParams.
3396  	  */
3397  	public static function linkThisUrl($url, array $getParams = array()) {
3398  	 	 $parts = parse_url($url);
3399  	 	 $getP = array();
3400  	 	 if ($parts['query']) {
3401  	 	 	 parse_str($parts['query'], $getP);
3402  	 	 }
3403  	 	 $getP = self::array_merge_recursive_overrule($getP, $getParams);
3404  	 	 $uP = explode('?', $url);
3405  
3406  	 	 $params = self::implodeArrayForUrl('', $getP);
3407  	 	 $outurl = $uP[0] . ($params ? '?' . substr($params, 1) : '');
3408  
3409  	 	 return $outurl;
3410  	 }
3411  
3412  	 /**
3413  	  * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
3414  	  * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
3415  	  *
3416  	  * @param string $getEnvName Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
3417  	  * @return string Value based on the input key, independent of server/os environment.
3418  	  */
3419  	public static function getIndpEnv($getEnvName) {
3420  	 	 /*
3421  	 	 	 Conventions:
3422  	 	 	 output from parse_url():
3423  	 	 	 URL:	 http://username:password@192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
3424  	 	 	 	 [scheme] => 'http'
3425  	 	 	 	 [user] => 'username'
3426  	 	 	 	 [pass] => 'password'
3427  	 	 	 	 [host] => '192.168.1.4'
3428  	 	 	 	 [port] => '8080'
3429  	 	 	 	 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
3430  	 	 	 	 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
3431  	 	 	 	 [fragment] => 'link1'
3432  
3433  	 	 	 	 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
3434  	 	 	 	 	 	 	 	 	 [path_dir] = '/typo3/32/temp/phpcheck/'
3435  	 	 	 	 	 	 	 	 	 [path_info] = '/arg1/arg2/arg3/'
3436  	 	 	 	 	 	 	 	 	 [path] = [path_script/path_dir][path_info]
3437  
3438  	 	 	 Keys supported:
3439  
3440  	 	 	 URI______:
3441  	 	 	 	 REQUEST_URI	 	 =	 [path]?[query]	 	 = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
3442  	 	 	 	 HTTP_HOST	 	 =	 [host][:[port]]	 	 = 192.168.1.4:8080
3443  	 	 	 	 SCRIPT_NAME	 	 =	 [path_script]++	 	 = /typo3/32/temp/phpcheck/index.php	 	 // NOTICE THAT SCRIPT_NAME will return the php-script name ALSO. [path_script] may not do that (eg. '/somedir/' may result in SCRIPT_NAME '/somedir/index.php')!
3444  	 	 	 	 PATH_INFO	 	 =	 [path_info]	 	 	 = /arg1/arg2/arg3/
3445  	 	 	 	 QUERY_STRING	 =	 [query]	 	 	 	 = arg1,arg2,arg3&p1=parameter1&p2[key]=value
3446  	 	 	 	 HTTP_REFERER	 =	 [scheme]://[host][:[port]][path]	 = http://192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
3447  	 	 	 	 	 	 	 	 	 	 (Notice: NO username/password + NO fragment)
3448  
3449  	 	 	 CLIENT____:
3450  	 	 	 	 REMOTE_ADDR	 	 =	 (client IP)
3451  	 	 	 	 REMOTE_HOST	 	 =	 (client host)
3452  	 	 	 	 HTTP_USER_AGENT	 =	 (client user agent)
3453  	 	 	 	 HTTP_ACCEPT_LANGUAGE	 = (client accept language)
3454  
3455  	 	 	 SERVER____:
3456  	 	 	 	 SCRIPT_FILENAME	 =	 Absolute filename of script	 	 (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
3457  
3458  	 	 	 Special extras:
3459  	 	 	 	 TYPO3_HOST_ONLY =	 	 [host] = 192.168.1.4
3460  	 	 	 	 TYPO3_PORT =	 	 	 [port] = 8080 (blank if 80, taken from host value)
3461  	 	 	 	 TYPO3_REQUEST_HOST = 	 	 [scheme]://[host][:[port]]
3462  	 	 	 	 TYPO3_REQUEST_URL =	 	 [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
3463  	 	 	 	 TYPO3_REQUEST_SCRIPT =  	 [scheme]://[host][:[port]][path_script]
3464  	 	 	 	 TYPO3_REQUEST_DIR =	 	 [scheme]://[host][:[port]][path_dir]
3465  	 	 	 	 TYPO3_SITE_URL = 	 	 [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
3466  	 	 	 	 TYPO3_SITE_PATH = 	 	 [path_dir] of the TYPO3 website frontend
3467  	 	 	 	 TYPO3_SITE_SCRIPT = 	 	 [script / Speaking URL] of the TYPO3 website
3468  	 	 	 	 TYPO3_DOCUMENT_ROOT =	 	 Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
3469  	 	 	 	 TYPO3_SSL = 	 	 	 Returns TRUE if this session uses SSL/TLS (https)
3470  	 	 	 	 TYPO3_PROXY = 	 	 	 Returns TRUE if this session runs over a well known proxy
3471  
3472  	 	 	 Notice: [fragment] is apparently NEVER available to the script!
3473  
3474  	 	 	 Testing suggestions:
3475  	 	 	 - Output all the values.
3476  	 	 	 - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
3477  	 	 	 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
3478  	 	 */
3479  
3480  	 	 $retVal = '';
3481  
3482  	 	 switch ((string) $getEnvName) {
3483  	 	 	 case 'SCRIPT_NAME':
3484  	 	 	 	 $retVal = (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'cgi-fcgi') &&
3485  	 	 	 	 	 	 ($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) ?
3486  	 	 	 	 	 	 ($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) :
3487  	 	 	 	 	 	 ($_SERVER['ORIG_SCRIPT_NAME'] ? $_SERVER['ORIG_SCRIPT_NAME'] : $_SERVER['SCRIPT_NAME']);
3488  	 	 	 	 	 // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
3489  	 	 	 	 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3490  	 	 	 	 	 if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
3491  	 	 	 	 	 	 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
3492  	 	 	 	 	 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
3493  	 	 	 	 	 	 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
3494  	 	 	 	 	 }
3495  	 	 	 	 }
3496  	 	 	 	 break;
3497  	 	 	 case 'SCRIPT_FILENAME':
3498  	 	 	 	 $retVal = str_replace('//', '/', str_replace('\\', '/',
3499  	 	 	 	 	 (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
3500  	 	 	 	 	 	 	 ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
3501  	 	 	 	 	 	 	 ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
3502  	 	 	 	 	 	 	 ($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME'])));
3503  
3504  	 	 	 	 break;
3505  	 	 	 case 'REQUEST_URI':
3506  	 	 	 	 	 // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
3507  	 	 	 	 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']) { // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
3508  	 	 	 	 	 list($v, $n) = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
3509  	 	 	 	 	 $retVal = $GLOBALS[$v][$n];
3510  	 	 	 	 } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
3511  	 	 	 	 	 $retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') .
3512  	 	 	 	 	 	 	 ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
3513  	 	 	 	 } else {
3514  	 	 	 	 	 $retVal = $_SERVER['REQUEST_URI'];
3515  	 	 	 	 }
3516  	 	 	 	 	 // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
3517  	 	 	 	 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3518  	 	 	 	 	 if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
3519  	 	 	 	 	 	 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
3520  	 	 	 	 	 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
3521  	 	 	 	 	 	 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
3522  	 	 	 	 	 }
3523  	 	 	 	 }
3524  	 	 	 	 break;
3525  	 	 	 case 'PATH_INFO':
3526  	 	 	 	 	 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
3527  	 	 	 	 	 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
3528  	 	 	 	 	 // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, then 'PHP_SAPI=='cgi'' might be a better check. Right now strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) will always return FALSE for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO because of PHP_SAPI=='cgi' (see above)
3529  	 	 	 	 	 //	 	 	 	 if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)	 {
3530  	 	 	 	 if (PHP_SAPI != 'cgi' && PHP_SAPI != 'cgi-fcgi' && PHP_SAPI != 'fpm-fcgi') {
3531  	 	 	 	 	 $retVal = $_SERVER['PATH_INFO'];
3532  	 	 	 	 }
3533  	 	 	 	 break;
3534  	 	 	 case 'TYPO3_REV_PROXY':
3535  	 	 	 	 $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
3536  	 	 	 	 break;
3537  	 	 	 case 'REMOTE_ADDR':
3538  	 	 	 	 $retVal = $_SERVER['REMOTE_ADDR'];
3539  	 	 	 	 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3540  	 	 	 	 	 $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
3541  	 	 	 	 	 	 // choose which IP in list to use
3542  	 	 	 	 	 if (count($ip)) {
3543  	 	 	 	 	 	 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
3544  	 	 	 	 	 	 	 case 'last':
3545  	 	 	 	 	 	 	 	 $ip = array_pop($ip);
3546  	 	 	 	 	 	 	 	 break;
3547  	 	 	 	 	 	 	 case 'first':
3548  	 	 	 	 	 	 	 	 $ip = array_shift($ip);
3549  	 	 	 	 	 	 	 	 break;
3550  	 	 	 	 	 	 	 case 'none':
3551  	 	 	 	 	 	 	 default:
3552  	 	 	 	 	 	 	 	 $ip = '';
3553  	 	 	 	 	 	 	 	 break;
3554  	 	 	 	 	 	 }
3555  	 	 	 	 	 }
3556  	 	 	 	 	 if (self::validIP($ip)) {
3557  	 	 	 	 	 	 $retVal = $ip;
3558  	 	 	 	 	 }
3559  	 	 	 	 }
3560  	 	 	 	 break;
3561  	 	 	 case 'HTTP_HOST':
3562  	 	 	 	 $retVal = $_SERVER['HTTP_HOST'];
3563  	 	 	 	 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3564  	 	 	 	 	 $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
3565  	 	 	 	 	 	 // choose which host in list to use
3566  	 	 	 	 	 if (count($host)) {
3567  	 	 	 	 	 	 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
3568  	 	 	 	 	 	 	 case 'last':
3569  	 	 	 	 	 	 	 	 $host = array_pop($host);
3570  	 	 	 	 	 	 	 	 break;
3571  	 	 	 	 	 	 	 case 'first':
3572  	 	 	 	 	 	 	 	 $host = array_shift($host);
3573  	 	 	 	 	 	 	 	 break;
3574  	 	 	 	 	 	 	 case 'none':
3575  	 	 	 	 	 	 	 default:
3576  	 	 	 	 	 	 	 	 $host = '';
3577  	 	 	 	 	 	 	 	 break;
3578  	 	 	 	 	 	 }
3579  	 	 	 	 	 }
3580  	 	 	 	 	 if ($host) {
3581  	 	 	 	 	 	 $retVal = $host;
3582  	 	 	 	 	 }
3583  	 	 	 	 }
3584  	 	 	 	 if (!self::isAllowedHostHeaderValue($retVal)) {
3585  	 	 	 	 	 throw new UnexpectedValueException(
3586  	 	 	 	 	 	 'The current host header value does not match the configured trusted hosts pattern! Check the pattern defined in $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'trustedHostsPattern\'] and adapt it, if you want to allow the current host header \'' . $retVal . '\' for your installation.',
3587  	 	 	 	 	 	 1396795884
3588  	 	 	 	 	 );
3589  	 	 	 	 }
3590  	 	 	 	 break;
3591  	 	 	 	 // These are let through without modification
3592  	 	 	 case 'HTTP_REFERER':
3593  	 	 	 case 'HTTP_USER_AGENT':
3594  	 	 	 case 'HTTP_ACCEPT_ENCODING':
3595  	 	 	 case 'HTTP_ACCEPT_LANGUAGE':
3596  	 	 	 case 'REMOTE_HOST':
3597  	 	 	 case 'QUERY_STRING':
3598  	 	 	 	 $retVal = $_SERVER[$getEnvName];
3599  	 	 	 	 break;
3600  	 	 	 case 'TYPO3_DOCUMENT_ROOT':
3601  	 	 	 	 	 // Get the web root (it is not the root of the TYPO3 installation)
3602  	 	 	 	 	 // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
3603  	 	 	 	 	 // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
3604  	 	 	 	 	 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
3605  	 	 	 	 $SFN = self::getIndpEnv('SCRIPT_FILENAME');
3606  	 	 	 	 $SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME')));
3607  	 	 	 	 $SFN_A = explode('/', strrev($SFN));
3608  	 	 	 	 $acc = array();
3609  	 	 	 	 foreach ($SN_A as $kk => $vv) {
3610  	 	 	 	 	 if (!strcmp($SFN_A[$kk], $vv)) {
3611  	 	 	 	 	 	 $acc[] = $vv;
3612  	 	 	 	 	 } else {
3613  	 	 	 	 	 	 break;
3614  	 	 	 	 	 }
3615  	 	 	 	 }
3616  	 	 	 	 $commonEnd = strrev(implode('/', $acc));
3617  	 	 	 	 if (strcmp($commonEnd, '')) {
3618  	 	 	 	 	 $DR = substr($SFN, 0, -(strlen($commonEnd) + 1));
3619  	 	 	 	 }
3620  	 	 	 	 $retVal = $DR;
3621  	 	 	 	 break;
3622  	 	 	 case 'TYPO3_HOST_ONLY':
3623  	 	 	 	 $httpHost = self::getIndpEnv('HTTP_HOST');
3624  	 	 	 	 $httpHostBracketPosition = strpos($httpHost, ']');
3625  	 	 	 	 $httpHostParts = explode(':', $httpHost);
3626  	 	 	 	 $retVal = ($httpHostBracketPosition !== FALSE) ? substr($httpHost, 0, ($httpHostBracketPosition + 1)) : array_shift($httpHostParts);
3627  	 	 	 	 break;
3628  	 	 	 case 'TYPO3_PORT':
3629  	 	 	 	 $httpHost = self::getIndpEnv('HTTP_HOST');
3630  	 	 	 	 $httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY');
3631  	 	 	 	 $retVal = (strlen($httpHost) > strlen($httpHostOnly)) ? substr($httpHost, strlen($httpHostOnly) + 1) : '';
3632  	 	 	 	 break;
3633  	 	 	 case 'TYPO3_REQUEST_HOST':
3634  	 	 	 	 $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') .
3635  	 	 	 	 	 	 self::getIndpEnv('HTTP_HOST');
3636  	 	 	 	 break;
3637  	 	 	 case 'TYPO3_REQUEST_URL':
3638  	 	 	 	 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI');
3639  	 	 	 	 break;
3640  	 	 	 case 'TYPO3_REQUEST_SCRIPT':
3641  	 	 	 	 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME');
3642  	 	 	 	 break;
3643  	 	 	 case 'TYPO3_REQUEST_DIR':
3644  	 	 	 	 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/';
3645  	 	 	 	 break;
3646  	 	 	 case 'TYPO3_SITE_URL':
3647  	 	 	 	 if (defined('PATH_thisScript') && defined('PATH_site')) {
3648  	 	 	 	 	 $lPath = substr(dirname(PATH_thisScript), strlen(PATH_site)) . '/';
3649  	 	 	 	 	 $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
3650  	 	 	 	 	 $siteUrl = substr($url, 0, -strlen($lPath));
3651  	 	 	 	 	 if (substr($siteUrl, -1) != '/') {
3652  	 	 	 	 	 	 $siteUrl .= '/';
3653  	 	 	 	 	 }
3654  	 	 	 	 	 $retVal = $siteUrl;
3655  	 	 	 	 }
3656  	 	 	 	 break;
3657  	 	 	 case 'TYPO3_SITE_PATH':
3658  	 	 	 	 $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
3659  	 	 	 	 break;
3660  	 	 	 case 'TYPO3_SITE_SCRIPT':
3661  	 	 	 	 $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL')));
3662  	 	 	 	 break;
3663  	 	 	 case 'TYPO3_SSL':
3664  	 	 	 	 $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
3665  	 	 	 	 if ($proxySSL == '*') {
3666  	 	 	 	 	 $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
3667  	 	 	 	 }
3668  	 	 	 	 if (self::cmpIP(self::getIndpEnv('REMOTE_ADDR'), $proxySSL)) {
3669  	 	 	 	 	 $retVal = TRUE;
3670  	 	 	 	 } else {
3671  	 	 	 	 	 $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? TRUE : FALSE; // see http://bugs.typo3.org/view.php?id=3909
3672  	 	 	 	 }
3673  	 	 	 	 break;
3674  	 	 	 case '_ARRAY':
3675  	 	 	 	 $out = array();
3676  	 	 	 	 	 // Here, list ALL possible keys to this function for debug display.
3677  	 	 	 	 $envTestVars = self::trimExplode(',', '
3678  	 	 	 	 	 HTTP_HOST,
3679  	 	 	 	 	 TYPO3_HOST_ONLY,
3680  	 	 	 	 	 TYPO3_PORT,
3681  	 	 	 	 	 PATH_INFO,
3682  	 	 	 	 	 QUERY_STRING,
3683  	 	 	 	 	 REQUEST_URI,
3684  	 	 	 	 	 HTTP_REFERER,
3685  	 	 	 	 	 TYPO3_REQUEST_HOST,
3686  	 	 	 	 	 TYPO3_REQUEST_URL,
3687  	 	 	 	 	 TYPO3_REQUEST_SCRIPT,
3688  	 	 	 	 	 TYPO3_REQUEST_DIR,
3689  	 	 	 	 	 TYPO3_SITE_URL,
3690  	 	 	 	 	 TYPO3_SITE_SCRIPT,
3691  	 	 	 	 	 TYPO3_SSL,
3692  	 	 	 	 	 TYPO3_REV_PROXY,
3693  	 	 	 	 	 SCRIPT_NAME,
3694  	 	 	 	 	 TYPO3_DOCUMENT_ROOT,
3695  	 	 	 	 	 SCRIPT_FILENAME,
3696  	 	 	 	 	 REMOTE_ADDR,
3697  	 	 	 	 	 REMOTE_HOST,
3698  	 	 	 	 	 HTTP_USER_AGENT,
3699  	 	 	 	 	 HTTP_ACCEPT_LANGUAGE', 1);
3700  	 	 	 	 foreach ($envTestVars as $v) {
3701  	 	 	 	 	 $out[$v] = self::getIndpEnv($v);
3702  	 	 	 	 }
3703  	 	 	 	 reset($out);
3704  	 	 	 	 $retVal = $out;
3705  	 	 	 	 break;
3706  	 	 }
3707  	 	 return $retVal;
3708  	 }
3709  
3710  	 /**
3711  	  * Checks if the provided host header value matches the trusted hosts pattern.
3712  	  * If the pattern is not defined (which only can happen early in the bootstrap), deny any value.
3713  	  *
3714  	  * @param string $hostHeaderValue HTTP_HOST header value as sent during the request (may include port)
3715  	  * @return bool
3716  	  */
3717  	static public function isAllowedHostHeaderValue($hostHeaderValue) {
3718  	 	 if (self::$allowHostHeaderValue === TRUE) {
3719  	 	 	 return TRUE;
3720  	 	 }
3721  
3722  	 	 // Allow all install tool requests
3723  	 	 // We accept this risk to have the install tool always available
3724  	 	 // Also CLI needs to be allowed as unfortunately AbstractUserAuthentication::getAuthInfoArray() accesses HTTP_HOST without reason on CLI
3725  	 	 if (defined('TYPO3_REQUESTTYPE') && (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_INSTALL) || (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) {
3726  	 	 	 return self::$allowHostHeaderValue = TRUE;
3727  	 	 }
3728  
3729  	 	 // Deny the value if trusted host patterns is empty, which means we are early in the bootstrap
3730  	 	 if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'])) {
3731  	 	 	 return FALSE;
3732  	 	 }
3733  
3734  	 	 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL) {
3735  	 	 	 self::$allowHostHeaderValue = TRUE;
3736  	 	 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME) {
3737  	 	 	 // Allow values that equal the server name
3738  	 	 	 // Note that this is only secure if name base virtual host are configured correctly in the webserver
3739  	 	 	 $defaultPort = self::getIndpEnv('TYPO3_SSL') ? '443' : '80';
3740  	 	 	 $parsedHostValue = parse_url('http://' . $hostHeaderValue);
3741  	 	 	 if (isset($parsedHostValue['port'])) {
3742  	 	 	 	 self::$allowHostHeaderValue = ($parsedHostValue['host'] === $_SERVER['SERVER_NAME'] && (string)$parsedHostValue['port'] === $_SERVER['SERVER_PORT']);
3743  	 	 	 } else {
3744  	 	 	 	 self::$allowHostHeaderValue = ($hostHeaderValue === $_SERVER['SERVER_NAME'] && $defaultPort === $_SERVER['SERVER_PORT']);
3745  	 	 	 }
3746  	 	 } else {
3747  	 	 	 // In case name based virtual hosts are not possible, we allow setting a trusted host pattern
3748  	 	 	 // See https://typo3.org/teams/security/security-bulletins/typo3-core/typo3-core-sa-2014-001/ for further details
3749  	 	 	 self::$allowHostHeaderValue = (bool)preg_match('/^' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] . '$/', $hostHeaderValue);
3750  	 	 }
3751  
3752  	 	 return self::$allowHostHeaderValue;
3753  	 }
3754  
3755  	 /**
3756  	  * Gets the unixtime as milliseconds.
3757  	  *
3758  	  * @return integer The unixtime as milliseconds
3759  	  */
3760  	public static function milliseconds() {
3761  	 	 return round(microtime(TRUE) * 1000);
3762  	 }
3763  
3764  	 /**
3765  	  * Client Browser Information
3766  	  *
3767  	  * @param string $useragent Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
3768  	  * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
3769  	  */
3770  	public static function clientInfo($useragent = '') {
3771  	 	 if (!$useragent) {
3772  	 	 	 $useragent = self::getIndpEnv('HTTP_USER_AGENT');
3773  	 	 }
3774  
3775  	 	 $bInfo = array();
3776  	 	 	 // Which browser?
3777  	 	 if (strpos($useragent, 'Konqueror') !== FALSE) {
3778  	 	 	 $bInfo['BROWSER'] = 'konqu';
3779  	 	 } elseif (strpos($useragent, 'Opera') !== FALSE) {
3780  	 	 	 $bInfo['BROWSER'] = 'opera';
3781  	 	 } elseif (strpos($useragent, 'MSIE') !== FALSE) {
3782  	 	 	 $bInfo['BROWSER'] = 'msie';
3783  	 	 } elseif (strpos($useragent, 'Mozilla') !== FALSE) {
3784  	 	 	 $bInfo['BROWSER'] = 'net';
3785  	 	 } elseif (strpos($useragent, 'Flash') !== FALSE) {
3786  	 	 	 $bInfo['BROWSER'] = 'flash';
3787  	 	 }
3788  	 	 if ($bInfo['BROWSER']) {
3789  	 	 	 	 // Browser version
3790  	 	 	 switch ($bInfo['BROWSER']) {
3791  	 	 	 	 case 'net':
3792  	 	 	 	 	 $bInfo['VERSION'] = doubleval(substr($useragent, 8));
3793  	 	 	 	 	 if (strpos($useragent, 'Netscape6/') !== FALSE) {
3794  	 	 	 	 	 	 $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape6/'), 10));
3795  	 	 	 	 	 } // Will we ever know if this was a typo or intention...?! :-(
3796  	 	 	 	 	 if (strpos($useragent, 'Netscape/6') !== FALSE) {
3797  	 	 	 	 	 	 $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/6'), 10));
3798  	 	 	 	 	 }
3799  	 	 	 	 	 if (strpos($useragent, 'Netscape/7') !== FALSE) {
3800  	 	 	 	 	 	 $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/7'), 9));
3801  	 	 	 	 	 }
3802  	 	 	 	 	 break;
3803  	 	 	 	 case 'msie':
3804  	 	 	 	 	 $tmp = strstr($useragent, 'MSIE');
3805  	 	 	 	 	 $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 4)));
3806  	 	 	 	 	 break;
3807  	 	 	 	 case 'opera':
3808  	 	 	 	 	 $tmp = strstr($useragent, 'Opera');
3809  	 	 	 	 	 $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 5)));
3810  	 	 	 	 	 break;
3811  	 	 	 	 case 'konqu':
3812  	 	 	 	 	 $tmp = strstr($useragent, 'Konqueror/');
3813  	 	 	 	 	 $bInfo['VERSION'] = doubleval(substr($tmp, 10));
3814  	 	 	 	 	 break;
3815  	 	 	 }
3816  	 	 	 // Client system
3817  	 	 	 if (strpos($useragent, 'Win') !== FALSE) {
3818  	 	 	 	 $bInfo['SYSTEM'] = 'win';
3819  	 	 	 } elseif (strpos($useragent, 'Mac') !== FALSE) {
3820  	 	 	 	 $bInfo['SYSTEM'] = 'mac';
3821  	 	 	 } elseif (strpos($useragent, 'Linux') !== FALSE || strpos($useragent, 'X11') !== FALSE || strpos($useragent, 'SGI') !== FALSE || strpos($useragent, ' SunOS ') !== FALSE || strpos($useragent, ' HP-UX ') !== FALSE) {
3822  	 	 	 	 $bInfo['SYSTEM'] = 'unix';
3823  	 	 	 }
3824  	 	 }
3825  	 	 // Is TRUE if the browser supports css to format forms, especially the width
3826  	 	 $bInfo['FORMSTYLE'] = ($bInfo['BROWSER'] == 'msie' || ($bInfo['BROWSER'] == 'net' && $bInfo['VERSION'] >= 5) || $bInfo['BROWSER'] == 'opera' || $bInfo['BROWSER'] == 'konqu');
3827  
3828  	 	 return $bInfo;
3829  	 }
3830  
3831  	 /**
3832  	  * Get the fully-qualified domain name of the host.
3833  	  *
3834  	  * @param boolean $requestHost Use request host (when not in CLI mode).
3835  	  * @return string The fully-qualified host name.
3836  	  */
3837  	public static function getHostname($requestHost = TRUE) {
3838  	 	 $host = '';
3839  	 	 	 // If not called from the command-line, resolve on getIndpEnv()
3840  	 	 	 // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
3841  	 	 if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
3842  	 	 	 $host = self::getIndpEnv('HTTP_HOST');
3843  	 	 }
3844  	 	 if (!$host) {
3845  	 	 	 	 // will fail for PHP 4.1 and 4.2
3846  	 	 	 $host = @php_uname('n');
3847  	 	 	 	 // 'n' is ignored in broken installations
3848  	 	 	 if (strpos($host, ' ')) {
3849  	 	 	 	 $host = '';
3850  	 	 	 }
3851  	 	 }
3852  	 	 	 // we have not found a FQDN yet
3853  	 	 if ($host && strpos($host, '.') === FALSE) {
3854  	 	 	 $ip = gethostbyname($host);
3855  	 	 	 	 // we got an IP address
3856  	 	 	 if ($ip != $host) {
3857  	 	 	 	 $fqdn = gethostbyaddr($ip);
3858  	 	 	 	 if ($ip != $fqdn) {
3859  	 	 	 	 	 $host = $fqdn;
3860  	 	 	 	 }
3861  	 	 	 }
3862  	 	 }
3863  	 	 if (!$host) {
3864  	 	 	 $host = 'localhost.localdomain';
3865  	 	 }
3866  
3867  	 	 return $host;
3868  	 }
3869  
3870  
3871  	 /*************************
3872  	  *
3873  	  * TYPO3 SPECIFIC FUNCTIONS
3874  	  *
3875  	  *************************/
3876  
3877  	 /**
3878  	  * Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the PATH_site of the TYPO3 installation and implies a check with t3lib_div::validPathStr(). Returns FALSE if checks failed. Does not check if the file exists.
3879  	  *
3880  	  * @param string $filename The input filename/filepath to evaluate
3881  	  * @param boolean $onlyRelative If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
3882  	  * @param boolean $relToTYPO3_mainDir If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
3883  	  * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
3884  	  */
3885  	public static function getFileAbsFileName($filename, $onlyRelative = TRUE, $relToTYPO3_mainDir = FALSE) {
3886  	 	 if (!strcmp($filename, '')) {
3887  	 	 	 return '';
3888  	 	 }
3889  
3890  	 	 if ($relToTYPO3_mainDir) {
3891  	 	 	 if (!defined('PATH_typo3')) {
3892  	 	 	 	 return '';
3893  	 	 	 }
3894  	 	 	 $relPathPrefix = PATH_typo3;
3895  	 	 } else {
3896  	 	 	 $relPathPrefix = PATH_site;
3897  	 	 }
3898  	 	 if (substr($filename, 0, 4) == 'EXT:') { // extension
3899  	 	 	 list($extKey, $local) = explode('/', substr($filename, 4), 2);
3900  	 	 	 $filename = '';
3901  	 	 	 if (strcmp($extKey, '') && t3lib_extMgm::isLoaded($extKey) && strcmp($local, '')) {
3902  	 	 	 	 $filename = t3lib_extMgm::extPath($extKey) . $local;
3903  	 	 	 }
3904  	 	 } elseif (!self::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
3905  	 	 	 $filename = $relPathPrefix . $filename;
3906  	 	 } elseif ($onlyRelative && !self::isFirstPartOfStr($filename, $relPathPrefix)) { // absolute, but set to blank if not allowed
3907  	 	 	 $filename = '';
3908  	 	 }
3909  	 	 if (strcmp($filename, '') && self::validPathStr($filename)) { // checks backpath.
3910  	 	 	 return $filename;
3911  	 	 }
3912  	 }
3913  
3914  	 /**
3915  	  * Checks for malicious file paths.
3916  	  *
3917  	  * Returns TRUE if no '//', '..', '\' or control characters are found in the $theFile.
3918  	  * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
3919  	  * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
3920  	  *
3921  	  * @param string $theFile File path to evaluate
3922  	  * @return boolean TRUE, $theFile is allowed path string, FALSE otherwise
3923  	  * @see http://php.net/manual/en/security.filesystem.nullbytes.php
3924  	  * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded?
3925  	  */
3926  	public static function validPathStr($theFile) {
3927  	 	 if (strpos($theFile, '//') === FALSE && strpos($theFile, '\\') === FALSE && !preg_match('#(?:^\.\.|/\.\./|[[:cntrl:]])#u', $theFile)) {
3928  	 	 	 return TRUE;
3929  	 	 }
3930  
3931  	 	 return FALSE;
3932  	 }
3933  
3934  	 /**
3935  	  * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns TRUE if so.
3936  	  *
3937  	  * @param string $path File path to evaluate
3938  	  * @return boolean
3939  	  */
3940  	public static function isAbsPath($path) {
3941  	 	 	 // on Windows also a path starting with a drive letter is absolute: X:/
3942  	 	 if (TYPO3_OS === 'WIN' && substr($path, 1, 2) === ':/') {
3943  	 	 	 return TRUE;
3944  	 	 }
3945  
3946  	 	 	 // path starting with a / is always absolute, on every system
3947  	 	 return (substr($path, 0, 1) === '/');
3948  	 }
3949  
3950  	 /**
3951  	  * Returns TRUE if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
3952  	  *
3953  	  * @param string $path File path to evaluate
3954  	  * @return boolean
3955  	  */
3956  	public static function isAllowedAbsPath($path) {
3957  	 	 if (self::isAbsPath($path) &&
3958  	 	 	 	 self::validPathStr($path) &&
3959  	 	 	 	 (self::isFirstPartOfStr($path, PATH_site)
3960  	 	 	 	 	 	 ||
3961  	 	 	 	 	 	 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
3962  	 	 	 	 )
3963  	 	 ) {
3964  	 	 	 return TRUE;
3965  	 	 }
3966  	 }
3967  
3968  	 /**
3969  	  * Verifies the input filename against the 'fileDenyPattern'. Returns TRUE if OK.
3970  	  *
3971  	  * @param string $filename File path to evaluate
3972  	  * @return boolean
3973  	  */
3974  	public static function verifyFilenameAgainstDenyPattern($filename) {
3975  	 	 	 // Filenames are not allowed to contain control characters
3976  	 	 if (preg_match('/[[:cntrl:]]/', $filename)) {
3977  	 	 	 return FALSE;
3978  	 	 }
3979  
3980  	 	 if (strcmp($filename, '') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'], '')) {
3981  	 	 	 $result = preg_match('/' . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] . '/i', $filename);
3982  	 	 	 if ($result) {
3983  	 	 	 	 return FALSE;
3984  	 	 	 } // so if a matching filename is found, return FALSE;
3985  	 	 }
3986  	 	 return TRUE;
3987  	 }
3988  
3989  	 /**
3990  	  * Checks if a given string is a valid frame URL to be loaded in the
3991  	  * backend.
3992  	  *
3993  	  * @param string $url potential URL to check
3994  	  * @return string either $url if $url is considered to be harmless, or an
3995  	  *	 	 	 	 empty string otherwise
3996  	  */
3997  	public static function sanitizeLocalUrl($url = '') {
3998  	 	 $sanitizedUrl = '';
3999  	 	 $decodedUrl = rawurldecode($url);
4000  
4001  	 	 if (!empty($url) && self::removeXSS($decodedUrl) === $decodedUrl) {
4002  	 	 	 $testAbsoluteUrl = self::resolveBackPath($decodedUrl);
4003  	 	 	 $testRelativeUrl = self::resolveBackPath(
4004  	 	 	 	 self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
4005  	 	 	 );
4006  
4007  	 	 	 	 // Pass if URL is on the current host:
4008  	 	 	 if (self::isValidUrl($decodedUrl)) {
4009  	 	 	 	 if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) {
4010  	 	 	 	 	 $sanitizedUrl = $url;
4011  	 	 	 	 }
4012  	 	 	 	 // Pass if URL is an absolute file path:
4013  	 	 	 } elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) {
4014  	 	 	 	 $sanitizedUrl = $url;
4015  	 	 	 	 // Pass if URL is absolute and below TYPO3 base directory:
4016  	 	 	 } elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) === '/') {
4017  	 	 	 	 $sanitizedUrl = $url;
4018  	 	 	 	 // Pass if URL is relative and below TYPO3 base directory:
4019  	 	 	 } elseif (strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) !== '/') {
4020  	 	 	 	 $sanitizedUrl = $url;
4021  	 	 	 }
4022  	 	 }
4023  
4024  	 	 if (!empty($url) && empty($sanitizedUrl)) {
4025  	 	 	 self::sysLog('The URL "' . $url . '" is not considered to be local and was denied.', 'Core', self::SYSLOG_SEVERITY_NOTICE);
4026  	 	 }
4027  
4028  	 	 return $sanitizedUrl;
4029  	 }
4030  
4031  	 /**
4032  	  * Moves $source file to $destination if uploaded, otherwise try to make a copy
4033  	  *
4034  	  * @param string $source Source file, absolute path
4035  	  * @param string $destination Destination file, absolute path
4036  	  * @return boolean Returns TRUE if the file was moved.
4037  	  * @coauthor Dennis Petersen <fessor@software.dk>
4038  	  * @see upload_to_tempfile()
4039  	  */
4040  	public static function upload_copy_move($source, $destination) {
4041  	 	 if (is_uploaded_file($source)) {
4042  	 	 	 $uploaded = TRUE;
4043  	 	 	 	 // Return the value of move_uploaded_file, and if FALSE the temporary $source is still around so the user can use unlink to delete it:
4044  	 	 	 $uploadedResult = move_uploaded_file($source, $destination);
4045  	 	 } else {
4046  	 	 	 $uploaded = FALSE;
4047  	 	 	 @copy($source, $destination);
4048  	 	 }
4049  
4050  	 	 self::fixPermissions($destination); // Change the permissions of the file
4051  
4052  	 	 	 // If here the file is copied and the temporary $source is still around, so when returning FALSE the user can try unlink to delete the $source
4053  	 	 return $uploaded ? $uploadedResult : FALSE;
4054  	 }
4055  
4056  	 /**
4057  	  * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it.
4058  	  * Use this function to move uploaded files to where you can work on them.
4059  	  * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
4060  	  *
4061  	  * @param string $uploadedFileName The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
4062  	  * @return string If a new file was successfully created, return its filename, otherwise blank string.
4063  	  * @see unlink_tempfile(), upload_copy_move()
4064  	  */
4065  	public static function upload_to_tempfile($uploadedFileName) {
4066  	 	 if (is_uploaded_file($uploadedFileName)) {
4067  	 	 	 $tempFile = self::tempnam('upload_temp_');
4068  	 	 	 move_uploaded_file($uploadedFileName, $tempFile);
4069  	 	 	 return @is_file($tempFile) ? $tempFile : '';
4070  	 	 }
4071  	 }
4072  
4073  	 /**
4074  	  * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
4075  	  * The function will check that the file exists, is in PATH_site."typo3temp/" and does not contain back-spaces ("../") so it should be pretty safe.
4076  	  * Use this after upload_to_tempfile() or tempnam() from this class!
4077  	  *
4078  	  * @param string $uploadedTempFileName Filepath for a file in PATH_site."typo3temp/". Must be absolute.
4079  	  * @return boolean Returns TRUE if the file was unlink()'ed
4080  	  * @see upload_to_tempfile(), tempnam()
4081  	  */
4082  	public static function unlink_tempfile($uploadedTempFileName) {
4083  	 	 if ($uploadedTempFileName) {
4084  	 	 	 $uploadedTempFileName = self::fixWindowsFilePath($uploadedTempFileName);
4085  	 	 	 if (self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName, PATH_site . 'typo3temp/') && @is_file($uploadedTempFileName)) {
4086  	 	 	 	 if (unlink($uploadedTempFileName)) {
4087  	 	 	 	 	 return TRUE;
4088  	 	 	 	 }
4089  	 	 	 }
4090  	 	 }
4091  	 }
4092  
4093  	 /**
4094  	  * Create temporary filename (Create file with unique file name)
4095  	  * This function should be used for getting temporary file names - will make your applications safe for open_basedir = on
4096  	  * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
4097  	  *
4098  	  * @param string $filePrefix Prefix to temp file (which will have no extension btw)
4099  	  * @return string result from PHP function tempnam() with PATH_site . 'typo3temp/' set for temp path.
4100  	  * @see unlink_tempfile(), upload_to_tempfile()
4101  	  */
4102  	public static function tempnam($filePrefix) {
4103  	 	 return tempnam(PATH_site . 'typo3temp/', $filePrefix);
4104  	 }
4105  
4106  	 /**
4107  	  * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
4108  	  *
4109  	  * @param mixed $uid_or_record Uid (integer) or record (array)
4110  	  * @param string $fields List of fields from the record if that is given.
4111  	  * @param integer $codeLength Length of returned authentication code.
4112  	  * @return string MD5 hash of 8 chars.
4113  	  */
4114  	public static function stdAuthCode($uid_or_record, $fields = '', $codeLength = 8) {
4115  
4116  	 	 if (is_array($uid_or_record)) {
4117  	 	 	 $recCopy_temp = array();
4118  	 	 	 if ($fields) {
4119  	 	 	 	 $fieldArr = self::trimExplode(',', $fields, 1);
4120  	 	 	 	 foreach ($fieldArr as $k => $v) {
4121  	 	 	 	 	 $recCopy_temp[$k] = $uid_or_record[$v];
4122  	 	 	 	 }
4123  	 	 	 } else {
4124  	 	 	 	 $recCopy_temp = $uid_or_record;
4125  	 	 	 }
4126  	 	 	 $preKey = implode('|', $recCopy_temp);
4127  	 	 } else {
4128  	 	 	 $preKey = $uid_or_record;
4129  	 	 }
4130  
4131  	 	 $authCode = $preKey . '||' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
4132  	 	 $authCode = substr(md5($authCode), 0, $codeLength);
4133  	 	 return $authCode;
4134  	 }
4135  
4136  	 /**
4137  	  * Splits the input query-parameters into an array with certain parameters filtered out.
4138  	  * Used to create the cHash value
4139  	  *
4140  	  * @param string $addQueryParams Query-parameters: "&xxx=yyy&zzz=uuu"
4141  	  * @return array Array with key/value pairs of query-parameters WITHOUT a certain list of variable names (like id, type, no_cache etc.) and WITH a variable, encryptionKey, specific for this server/installation
4142  	  * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink(), t3lib_div::calculateCHash()
4143  	  * @deprecated since TYPO3 4.7 - will be removed in TYPO3 6.1 - use t3lib_cacheHash instead
4144  	  */
4145  	public static function cHashParams($addQueryParams) {
4146  	 	 t3lib_div::logDeprecatedFunction();
4147  	 	 $params = explode('&', substr($addQueryParams, 1)); // Splitting parameters up
4148  	 	 /* @var $cacheHash t3lib_cacheHash */
4149  	 	 $cacheHash = t3lib_div::makeInstance('t3lib_cacheHash');
4150  	 	 $pA = $cacheHash->getRelevantParameters($addQueryParams);
4151  
4152  	 	 	 // Hook: Allows to manipulate the parameters which are taken to build the chash:
4153  	 	 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
4154  	 	 	 $cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
4155  	 	 	 if (is_array($cHashParamsHook)) {
4156  	 	 	 	 $hookParameters = array(
4157  	 	 	 	 	 'addQueryParams' => &$addQueryParams,
4158  	 	 	 	 	 'params' => &$params,
4159  	 	 	 	 	 'pA' => &$pA,
4160  	 	 	 	 );
4161  	 	 	 	 $hookReference = NULL;
4162  	 	 	 	 foreach ($cHashParamsHook as $hookFunction) {
4163  	 	 	 	 	 self::callUserFunction($hookFunction, $hookParameters, $hookReference);
4164  	 	 	 	 }
4165  	 	 	 }
4166  	 	 }
4167  
4168  	 	 return $pA;
4169  	 }
4170  
4171  	 /**
4172  	  * Returns the cHash based on provided query parameters and added values from internal call
4173  	  *
4174  	  * @param string $addQueryParams Query-parameters: "&xxx=yyy&zzz=uuu"
4175  	  * @return string Hash of all the values
4176  	  * @see t3lib_div::cHashParams(), t3lib_div::calculateCHash()
4177  	  * @deprecated since TYPO3 4.7 - will be removed in TYPO3 6.1 - use t3lib_cacheHash instead
4178  	  */
4179  	public static function generateCHash($addQueryParams) {
4180  	 	 t3lib_div::logDeprecatedFunction();
4181  	 	 /* @var $cacheHash t3lib_cacheHash */
4182  	 	 $cacheHash = t3lib_div::makeInstance('t3lib_cacheHash');
4183  	 	 return $cacheHash->generateForParameters($addQueryParams);
4184  	 }
4185  
4186  	 /**
4187  	  * Calculates the cHash based on the provided parameters
4188  	  *
4189  	  * @param array $params Array of key-value pairs
4190  	  * @return string Hash of all the values
4191  	  * @deprecated since TYPO3 4.7 - will be removed in TYPO3 6.1 - use t3lib_cacheHash instead
4192  	  */
4193  	public static function calculateCHash($params) {
4194  	 	 t3lib_div::logDeprecatedFunction();
4195  	 	 /* @var $cacheHash t3lib_cacheHash */
4196  	 	 $cacheHash = t3lib_div::makeInstance('t3lib_cacheHash');
4197  	 	 return $cacheHash->calculateCacheHash($params);
4198  	 }
4199  
4200  	 /**
4201  	  * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
4202  	  *
4203  	  * @param integer $l18n_cfg_fieldValue Value from "l18n_cfg" field of a page record
4204  	  * @return boolean TRUE if the page should be hidden
4205  	  */
4206  	public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
4207  	 	 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
4208  	 	 	 return $l18n_cfg_fieldValue & 2 ? FALSE : TRUE;
4209  	 	 } else {
4210  	 	 	 return $l18n_cfg_fieldValue & 2 ? TRUE : FALSE;
4211  	 	 }
4212  	 }
4213  
4214  	 /**
4215  	  * Returns true if the "l18n_cfg" field value is not set to hide
4216  	  * pages in the default language
4217  	  *
4218  	  * @param int $localizationConfiguration
4219  	  * @return boolean
4220  	  */
4221  	public static function hideIfDefaultLanguage($localizationConfiguration) {
4222  	 	 return ($localizationConfiguration & 1);
4223  	 }
4224  
4225  	 /**
4226  	  * Includes a locallang file and returns the $LOCAL_LANG array found inside.
4227  	  *
4228  	  * @param string $fileRef Input is a file-reference (see t3lib_div::getFileAbsFileName). That file is expected to be a 'locallang.php' file containing a $LOCAL_LANG array (will be included!) or a 'locallang.xml' file conataining a valid XML TYPO3 language structure.
4229  	  * @param string $langKey Language key
4230  	  * @param string $charset Character set (option); if not set, determined by the language key
4231  	  * @param integer $errorMode Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
4232  	  * @return array Value of $LOCAL_LANG found in the included file. If that array is found it will returned.
4233  	  *	 	 	 	 	 	  Otherwise an empty array and it is FALSE in error case.
4234  	  */
4235  	public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
4236  	 	 /** @var $languageFactory t3lib_l10n_Factory */
4237  	 	 $languageFactory = t3lib_div::makeInstance('t3lib_l10n_Factory');
4238  	 	 return $languageFactory->getParsedData($fileRef, $langKey, $charset, $errorMode);
4239  	 }
4240  
4241  	 /**
4242  	  * Includes a locallang-php file and returns the $LOCAL_LANG array
4243  	  * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
4244  	  *
4245  	  * @param string $fileRef Absolute reference to locallang-PHP file
4246  	  * @param string $langKey TYPO3 language key, eg. "dk" or "de" or "default"
4247  	  * @param string $charset Character set (optional)
4248  	  * @return array LOCAL_LANG array in return.
4249  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - use t3lib_l10n_parser_Llphp::getParsedData() from now on
4250  	  */
4251  	public static function readLLPHPfile($fileRef, $langKey, $charset = '') {
4252  	 	 t3lib_div::logDeprecatedFunction();
4253  
4254  	 	 if (is_object($GLOBALS['LANG'])) {
4255  	 	 	 $csConvObj = $GLOBALS['LANG']->csConvObj;
4256  	 	 } elseif (is_object($GLOBALS['TSFE'])) {
4257  	 	 	 $csConvObj = $GLOBALS['TSFE']->csConvObj;
4258  	 	 } else {
4259  	 	 	 $csConvObj = self::makeInstance('t3lib_cs');
4260  	 	 }
4261  
4262  	 	 if (@is_file($fileRef) && $langKey) {
4263  
4264  	 	 	 	 // Set charsets:
4265  	 	 	 $sourceCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'utf-8');
4266  	 	 	 if ($charset) {
4267  	 	 	 	 $targetCharset = $csConvObj->parse_charset($charset);
4268  	 	 	 } else {
4269  	 	 	 	 $targetCharset = 'utf-8';
4270  	 	 	 }
4271  
4272  	 	 	 	 // Cache file name:
4273  	 	 	 $hashSource = substr($fileRef, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
4274  	 	 	 $cacheFileName = PATH_site . 'typo3temp/llxml/' .
4275  	 	 	 	 	 substr(basename($fileRef), 10, 15) .
4276  	 	 	 	 	 '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
4277  	 	 	 	 // Check if cache file exists...
4278  	 	 	 if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
4279  	 	 	 	 $LOCAL_LANG = NULL;
4280  	 	 	 	 	 // Get PHP data
4281  	 	 	 	 include($fileRef);
4282  	 	 	 	 if (!is_array($LOCAL_LANG)) {
4283  	 	 	 	 	 $fileName = substr($fileRef, strlen(PATH_site));
4284  	 	 	 	 	 throw new RuntimeException(
4285  	 	 	 	 	 	 'TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!',
4286  	 	 	 	 	 	 1270853900
4287  	 	 	 	 	 );
4288  	 	 	 	 }
4289  
4290  	 	 	 	 	 // converting the default language (English)
4291  	 	 	 	 	 // this needs to be done for a few accented loan words and extension names
4292  	 	 	 	 if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
4293  	 	 	 	 	 foreach ($LOCAL_LANG['default'] as &$labelValue) {
4294  	 	 	 	 	 	 $labelValue = $csConvObj->conv($labelValue, 'utf-8', $targetCharset);
4295  	 	 	 	 	 }
4296  	 	 	 	 	 unset($labelValue);
4297  	 	 	 	 }
4298  
4299  	 	 	 	 if ($langKey != 'default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset != $targetCharset) {
4300  	 	 	 	 	 foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
4301  	 	 	 	 	 	 $labelValue = $csConvObj->conv($labelValue, $sourceCharset, $targetCharset);
4302  	 	 	 	 	 }
4303  	 	 	 	 	 unset($labelValue);
4304  	 	 	 	 }
4305  
4306  	 	 	 	 	 // Cache the content now:
4307  	 	 	 	 $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
4308  	 	 	 	 $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
4309  	 	 	 	 if ($res) {
4310  	 	 	 	 	 throw new RuntimeException(
4311  	 	 	 	 	 	 'TYPO3 Fatal Error: "' . $res,
4312  	 	 	 	 	 	 1270853901
4313  	 	 	 	 	 );
4314  	 	 	 	 }
4315  	 	 	 } else {
4316  	 	 	 	 	 // Get content from cache:
4317  	 	 	 	 $serContent = unserialize(self::getUrl($cacheFileName));
4318  	 	 	 	 $LOCAL_LANG = $serContent['LOCAL_LANG'];
4319  	 	 	 }
4320  
4321  	 	 	 return $LOCAL_LANG;
4322  	 	 }
4323  	 }
4324  
4325  	 /**
4326  	  * Includes a locallang-xml file and returns the $LOCAL_LANG array
4327  	  * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
4328  	  *
4329  	  * @param string $fileRef Absolute reference to locallang-XML file
4330  	  * @param string $langKey TYPO3 language key, eg. "dk" or "de" or "default"
4331  	  * @param string $charset Character set (optional)
4332  	  * @return array LOCAL_LANG array in return.
4333  	  * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - use t3lib_l10n_parser_Llxml::getParsedData() from now on
4334  	  */
4335  	public static function readLLXMLfile($fileRef, $langKey, $charset = '') {
4336  	 	 t3lib_div::logDeprecatedFunction();
4337  
4338  	 	 if (is_object($GLOBALS['LANG'])) {
4339  	 	 	 $csConvObj = $GLOBALS['LANG']->csConvObj;
4340  	 	 } elseif (is_object($GLOBALS['TSFE'])) {
4341  	 	 	 $csConvObj = $GLOBALS['TSFE']->csConvObj;
4342  	 	 } else {
4343  	 	 	 $csConvObj = self::makeInstance('t3lib_cs');
4344  	 	 }
4345  
4346  	 	 $LOCAL_LANG = NULL;
4347  	 	 if (@is_file($fileRef) && $langKey) {
4348  
4349  	 	 	 	 // Set charset:
4350  	 	 	 if ($charset) {
4351  	 	 	 	 $targetCharset = $csConvObj->parse_charset($charset);
4352  	 	 	 } else {
4353  	 	 	 	 $targetCharset = 'utf-8';
4354  	 	 	 }
4355  
4356  	 	 	 	 // Cache file name:
4357  	 	 	 $hashSource = substr($fileRef, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
4358  	 	 	 $cacheFileName = PATH_site . 'typo3temp/llxml/' .
4359  	 	 	 	 	 substr(basename($fileRef), 10, 15) .
4360  	 	 	 	 	 '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
4361  
4362  	 	 	 	 // Check if cache file exists...
4363  	 	 	 if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
4364  
4365  	 	 	 	 	 // Read XML, parse it.
4366  	 	 	 	 $xmlString = self::getUrl($fileRef);
4367  	 	 	 	 $xmlContent = self::xml2array($xmlString);
4368  	 	 	 	 if (!is_array($xmlContent)) {
4369  	 	 	 	 	 $fileName = substr($fileRef, strlen(PATH_site));
4370  	 	 	 	 	 throw new RuntimeException(
4371  	 	 	 	 	 	 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
4372  	 	 	 	 	 	 1270853902
4373  	 	 	 	 	 );
4374  	 	 	 	 }
4375  
4376  	 	 	 	 	 // Set default LOCAL_LANG array content:
4377  	 	 	 	 $LOCAL_LANG = array();
4378  	 	 	 	 $LOCAL_LANG['default'] = $xmlContent['data']['default'];
4379  
4380  	 	 	 	 	 // converting the default language (English)
4381  	 	 	 	 	 // this needs to be done for a few accented loan words and extension names
4382  	 	 	 	 	 // NOTE: no conversion is done when in UTF-8 mode!
4383  	 	 	 	 if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
4384  	 	 	 	 	 foreach ($LOCAL_LANG['default'] as &$labelValue) {
4385  	 	 	 	 	 	 $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
4386  	 	 	 	 	 }
4387  	 	 	 	 	 unset($labelValue);
4388  	 	 	 	 }
4389  
4390  	 	 	 	 	 // converting other languages to their "native" charsets
4391  	 	 	 	 	 // NOTE: no conversion is done when in UTF-8 mode!
4392  	 	 	 	 if ($langKey != 'default') {
4393  
4394  	 	 	 	 	 	 // If no entry is found for the language key, then force a value depending on meta-data setting. By default an automated filename will be used:
4395  	 	 	 	 	 $LOCAL_LANG[$langKey] = self::llXmlAutoFileName($fileRef, $langKey);
4396  	 	 	 	 	 $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
4397  	 	 	 	 	 if (!@is_file($localized_file) && isset($xmlContent['data'][$langKey])) {
4398  	 	 	 	 	 	 $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
4399  	 	 	 	 	 }
4400  
4401  	 	 	 	 	 	 // Checking if charset should be converted.
4402  	 	 	 	 	 if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
4403  	 	 	 	 	 	 foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
4404  	 	 	 	 	 	 	 $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
4405  	 	 	 	 	 	 }
4406  	 	 	 	 	 	 unset($labelValue);
4407  	 	 	 	 	 }
4408  	 	 	 	 }
4409  
4410  	 	 	 	 	 // Cache the content now:
4411  	 	 	 	 $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
4412  	 	 	 	 $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
4413  	 	 	 	 if ($res) {
4414  	 	 	 	 	 throw new RuntimeException(
4415  	 	 	 	 	 	 'TYPO3 Fatal Error: ' . $res,
4416  	 	 	 	 	 	 1270853903
4417  	 	 	 	 	 );
4418  	 	 	 	 }
4419  	 	 	 } else {
4420  	 	 	 	 	 // Get content from cache:
4421  	 	 	 	 $serContent = unserialize(self::getUrl($cacheFileName));
4422  	 	 	 	 $LOCAL_LANG = $serContent['LOCAL_LANG'];
4423  	 	 	 }
4424  
4425  	 	 	 	 // Checking for EXTERNAL file for non-default language:
4426  	 	 	 if ($langKey != 'default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
4427  
4428  	 	 	 	 	 // Look for localized file:
4429  	 	 	 	 $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
4430  	 	 	 	 if ($localized_file && @is_file($localized_file)) {
4431  
4432  	 	 	 	 	 	 // Cache file name:
4433  	 	 	 	 	 $hashSource = substr($localized_file, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($localized_file)) . '|version=2.3';
4434  	 	 	 	 	 $cacheFileName = PATH_site . 'typo3temp/llxml/EXT_' .
4435  	 	 	 	 	 	 	 substr(basename($localized_file), 10, 15) .
4436  	 	 	 	 	 	 	 '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
4437  
4438  	 	 	 	 	 	 // Check if cache file exists...
4439  	 	 	 	 	 if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
4440  
4441  	 	 	 	 	 	 	 // Read and parse XML content:
4442  	 	 	 	 	 	 $local_xmlString = self::getUrl($localized_file);
4443  	 	 	 	 	 	 $local_xmlContent = self::xml2array($local_xmlString);
4444  	 	 	 	 	 	 if (!is_array($local_xmlContent)) {
4445  	 	 	 	 	 	 	 $fileName = substr($localized_file, strlen(PATH_site));
4446  	 	 	 	 	 	 	 throw new RuntimeException(
4447  	 	 	 	 	 	 	 	 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
4448  	 	 	 	 	 	 	 	 1270853904
4449  	 	 	 	 	 	 	 );
4450  	 	 	 	 	 	 }
4451  	 	 	 	 	 	 $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
4452  
4453  	 	 	 	 	 	 	 // Checking if charset should be converted.
4454  	 	 	 	 	 	 if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
4455  	 	 	 	 	 	 	 foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
4456  	 	 	 	 	 	 	 	 $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
4457  	 	 	 	 	 	 	 }
4458  	 	 	 	 	 	 	 unset($labelValue);
4459  	 	 	 	 	 	 }
4460  
4461  	 	 	 	 	 	 	 // Cache the content now:
4462  	 	 	 	 	 	 $serContent = array('extlang' => $langKey, 'origFile' => $hashSource, 'EXT_DATA' => $LOCAL_LANG[$langKey]);
4463  	 	 	 	 	 	 $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
4464  	 	 	 	 	 	 if ($res) {
4465  	 	 	 	 	 	 	 throw new RuntimeException(
4466  	 	 	 	 	 	 	 	 'TYPO3 Fatal Error: ' . $res,
4467  	 	 	 	 	 	 	 	 1270853905
4468  	 	 	 	 	 	 	 );
4469  	 	 	 	 	 	 }
4470  	 	 	 	 	 } else {
4471  	 	 	 	 	 	 	 // Get content from cache:
4472  	 	 	 	 	 	 $serContent = unserialize(self::getUrl($cacheFileName));
4473  	 	 	 	 	 	 $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
4474  	 	 	 	 	 }
4475  	 	 	 	 } else {
4476  	 	 	 	 	 $LOCAL_LANG[$langKey] = array();
4477  	 	 	 	 }
4478  	 	 	 }
4479  
4480  	 	 	 	 // Convert the $LOCAL_LANG array to XLIFF structure
4481  	 	 	 foreach ($LOCAL_LANG as &$keysLabels) {
4482  	 	 	 	 foreach ($keysLabels as &$label) {
4483  	 	 	 	 	 $label = array(0 => array(
4484  	 	 	 	 	 	 'target' => $label,
4485  	 	 	 	 	 ));
4486  	 	 	 	 }
4487  	 	 	 	 unset($label);
4488  	 	 	 }
4489  	 	 	 unset($keysLabels);
4490  
4491  	 	 	 return $LOCAL_LANG;
4492  	 	 }
4493  	 }
4494  
4495  	 /**
4496  	  * Returns auto-filename for locallang-XML localizations.
4497  	  *
4498  	  * @param string $fileRef Absolute file reference to locallang-XML file. Must be inside system/global/local extension
4499  	  * @param string $language Language key
4500  	  * @param boolean $sameLocation if TRUE, then locallang-XML localization file name will be returned with same directory as $fileRef
4501  	  * @return string Returns the filename reference for the language unless error occurred (or local mode is used) in which case it will be NULL
4502  	  */
4503  	public static function llXmlAutoFileName($fileRef, $language, $sameLocation = FALSE) {
4504  	 	 if ($sameLocation) {
4505  	 	 	 $location = 'EXT:';
4506  	 	 } else {
4507  	 	 	 $location = 'typo3conf/l10n/' . $language . '/'; // Default location of translations
4508  	 	 }
4509  
4510  	 	 	 // Analyse file reference:
4511  	 	 if (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'sysext/')) { // Is system:
4512  	 	 	 $validatedPrefix = PATH_typo3 . 'sysext/';
4513  	 	 	 #$location = 'EXT:csh_'.$language.'/';	 // For system extensions translations are found in "csh_*" extensions (language packs)
4514  	 	 } elseif (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'ext/')) { // Is global:
4515  	 	 	 $validatedPrefix = PATH_typo3 . 'ext/';
4516  	 	 } elseif (self::isFirstPartOfStr($fileRef, PATH_typo3conf . 'ext/')) { // Is local:
4517  	 	 	 $validatedPrefix = PATH_typo3conf . 'ext/';
4518  	 	 } elseif (self::isFirstPartOfStr($fileRef, PATH_site . 'typo3_src/tests/')) { // Is test:
4519  	 	 	 $validatedPrefix = PATH_site . 'typo3_src/tests/';
4520  	 	 	 $location = $validatedPrefix;
4521  	 	 } else {
4522  	 	 	 $validatedPrefix = '';
4523  	 	 }
4524  
4525  	 	 if ($validatedPrefix) {
4526  
4527  	 	 	 	 // Divide file reference into extension key, directory (if any) and base name:
4528  	 	 	 list($file_extKey, $file_extPath) = explode('/', substr($fileRef, strlen($validatedPrefix)), 2);
4529  	 	 	 $temp = self::revExplode('/', $file_extPath, 2);
4530  	 	 	 if (count($temp) == 1) {
4531  	 	 	 	 array_unshift($temp, '');
4532  	 	 	 } // Add empty first-entry if not there.
4533  	 	 	 list($file_extPath, $file_fileName) = $temp;
4534  
4535  	 	 	 	 // If $fileRef is already prefix with "[language key]" then we should return it as this
4536  	 	 	 if (substr($file_fileName, 0, strlen($language) + 1) === $language . '.') {
4537  	 	 	 	 return $fileRef;
4538  	 	 	 }
4539  
4540  	 	 	 	 // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
4541  	 	 	 return $location .
4542  	 	 	 	 	 $file_extKey . '/' .
4543  	 	 	 	 	 ($file_extPath ? $file_extPath . '/' : '') .
4544  	 	 	 	 	 $language . '.' . $file_fileName;
4545  	 	 } else {
4546  	 	 	 return NULL;
4547  	 	 }
4548  	 }
4549  
4550  
4551  	 /**
4552  	  * Loads the $GLOBALS['TCA'] (Table Configuration Array) for the $table
4553  	  *
4554  	  * Requirements:
4555  	  * 1) must be configured table (the ctrl-section configured),
4556  	  * 2) columns must not be an array (which it is always if whole table loaded), and
4557  	  * 3) there is a value for dynamicConfigFile (filename in typo3conf)
4558  	  *
4559  	  * Note: For the frontend this loads only 'ctrl' and 'feInterface' parts.
4560  	  * For complete TCA use $GLOBALS['TSFE']->includeTCA() instead.
4561  	  *
4562  	  * @param string $table Table name for which to load the full TCA array part into $GLOBALS['TCA']
4563  	  * @return void
4564  	  */
4565  	public static function loadTCA($table) {
4566  	 	 	 //needed for inclusion of the dynamic config files.
4567  	 	 global $TCA;
4568  	 	 if (isset($TCA[$table])) {
4569  	 	 	 $tca = &$TCA[$table];
4570  	 	 	 if (!$tca['columns']) {
4571  	 	 	 	 $dcf = $tca['ctrl']['dynamicConfigFile'];
4572  	 	 	 	 if ($dcf) {
4573  	 	 	 	 	 if (!strcmp(substr($dcf, 0, 6), 'T3LIB:')) {
4574  	 	 	 	 	 	 include(PATH_t3lib . 'stddb/' . substr($dcf, 6));
4575  	 	 	 	 	 } elseif (self::isAbsPath($dcf) && @is_file($dcf)) { // Absolute path...
4576  	 	 	 	 	 	 include($dcf);
4577  	 	 	 	 	 } else {
4578  	 	 	 	 	 	 include(PATH_typo3conf . $dcf);
4579  	 	 	 	 	 }
4580  	 	 	 	 }
4581  	 	 	 }
4582  	 	 }
4583  	 }
4584  
4585  	 /**
4586  	  * Looks for a sheet-definition in the input data structure array. If found it will return the data structure for the sheet given as $sheet (if found).
4587  	  * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
4588  	  *
4589  	  * @param array $dataStructArray Input data structure, possibly with a sheet-definition and references to external data source files.
4590  	  * @param string $sheet The sheet to return, preferably.
4591  	  * @return array An array with two num. keys: key0: The data structure is returned in this key (array) UNLESS an error occurred in which case an error string is returned (string). key1: The used sheet key value!
4592  	  */
4593  	public static function resolveSheetDefInDS($dataStructArray, $sheet = 'sDEF') {
4594  	 	 if (!is_array($dataStructArray)) {
4595  	 	 	 return 'Data structure must be an array';
4596  	 	 }
4597  
4598  	 	 if (is_array($dataStructArray['sheets'])) {
4599  	 	 	 $singleSheet = FALSE;
4600  	 	 	 if (!isset($dataStructArray['sheets'][$sheet])) {
4601  	 	 	 	 $sheet = 'sDEF';
4602  	 	 	 }
4603  	 	 	 $dataStruct = $dataStructArray['sheets'][$sheet];
4604  
4605  	 	 	 	 // If not an array, but still set, then regard it as a relative reference to a file:
4606  	 	 	 if ($dataStruct && !is_array($dataStruct)) {
4607  	 	 	 	 $file = self::getFileAbsFileName($dataStruct);
4608  	 	 	 	 if ($file && @is_file($file)) {
4609  	 	 	 	 	 $dataStruct = self::xml2array(self::getUrl($file));
4610  	 	 	 	 }
4611  	 	 	 }
4612  	 	 } else {
4613  	 	 	 $singleSheet = TRUE;
4614  	 	 	 $dataStruct = $dataStructArray;
4615  	 	 	 if (isset($dataStruct['meta'])) {
4616  	 	 	 	 unset($dataStruct['meta']);
4617  	 	 	 } // Meta data should not appear there.
4618  	 	 	 $sheet = 'sDEF'; // Default sheet
4619  	 	 }
4620  	 	 return array($dataStruct, $sheet, $singleSheet);
4621  	 }
4622  
4623  	 /**
4624  	  * Resolves ALL sheet definitions in dataStructArray
4625  	  * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
4626  	  *
4627  	  * @param array $dataStructArray Input data structure, possibly with a sheet-definition and references to external data source files.
4628  	  * @return array Output data structure with all sheets resolved as arrays.
4629  	  */
4630  	public static function resolveAllSheetsInDS(array $dataStructArray) {
4631  	 	 if (is_array($dataStructArray['sheets'])) {
4632  	 	 	 $out = array('sheets' => array());
4633  	 	 	 foreach ($dataStructArray['sheets'] as $sheetId => $sDat) {
4634  	 	 	 	 list($ds, $aS) = self::resolveSheetDefInDS($dataStructArray, $sheetId);
4635  	 	 	 	 if ($sheetId == $aS) {
4636  	 	 	 	 	 $out['sheets'][$aS] = $ds;
4637  	 	 	 	 }
4638  	 	 	 }
4639  	 	 } else {
4640  	 	 	 list($ds) = self::resolveSheetDefInDS($dataStructArray);
4641  	 	 	 $out = array('sheets' => array('sDEF' => $ds));
4642  	 	 }
4643  	 	 return $out;
4644  	 }
4645  
4646  	 /**
4647  	  * Calls a user-defined function/method in class
4648  	  * Such a function/method should look like this: "function proc(&$params, &$ref)	 {...}"
4649  	  *
4650  	  * @param string $funcName Function/Method reference, '[file-reference":"]["&"]class/function["->"method-name]'. You can prefix this reference with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl->encodeSpURL". Finally; you can prefix the class name with "&" if you want to reuse a former instance of the same object call ("singleton").
4651  	  * @param mixed $params Parameters to be pass along (typically an array) (REFERENCE!)
4652  	  * @param mixed $ref Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
4653  	  * @param string $checkPrefix Alternative allowed prefix of class or function name
4654  	  * @param integer $errorMode Error mode (when class/function could not be found): 0 - call debug(), 1 - do nothing, 2 - raise an exception (allows to call a user function that may return FALSE)
4655  	  * @return mixed Content from method/function call or FALSE if the class/method/function was not found
4656  	  * @see getUserObj()
4657  	  */
4658  	public static function callUserFunction($funcName, &$params, &$ref, $checkPrefix = 'user_', $errorMode = 0) {
4659  	 	 $content = FALSE;
4660  
4661  	 	 	 // Check persistent object and if found, call directly and exit.
4662  	 	 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
4663  	 	 	 return call_user_func_array(
4664  	 	 	 	 array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
4665  	 	 	 	 	 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
4666  	 	 	 	 array(&$params, &$ref)
4667  	 	 	 );
4668  	 	 }
4669  
4670  	 	 	 // Check file-reference prefix; if found, require_once() the file (should be library of code)
4671  	 	 if (strpos($funcName, ':') !== FALSE) {
4672  	 	 	 list($file, $funcRef) = self::revExplode(':', $funcName, 2);
4673  	 	 	 $requireFile = self::getFileAbsFileName($file);
4674  	 	 	 if ($requireFile) {
4675  	 	 	 	 self::requireOnce($requireFile);
4676  	 	 	 }
4677  	 	 } else {
4678  	 	 	 $funcRef = $funcName;
4679  	 	 }
4680  
4681  	 	 	 // Check for persistent object token, "&"
4682  	 	 if (substr($funcRef, 0, 1) == '&') {
4683  	 	 	 $funcRef = substr($funcRef, 1);
4684  	 	 	 $storePersistentObject = TRUE;
4685  	 	 } else {
4686  	 	 	 $storePersistentObject = FALSE;
4687  	 	 }
4688  
4689  	 	 	 // Check prefix is valid:
4690  	 	 if ($checkPrefix && !self::hasValidClassPrefix($funcRef, array($checkPrefix))) {
4691  	 	 	 $errorMsg = "Function/class '$funcRef' was not prepended with '$checkPrefix'";
4692  	 	 	 if ($errorMode == 2) {
4693  	 	 	 	 throw new InvalidArgumentException($errorMsg, 1294585864);
4694  	 	 	 } elseif (!$errorMode) {
4695  	 	 	 	 debug($errorMsg, 't3lib_div::callUserFunction');
4696  	 	 	 }
4697  	 	 	 return FALSE;
4698  	 	 }
4699  
4700  	 	 	 // Call function or method:
4701  	 	 $parts = explode('->', $funcRef);
4702  	 	 if (count($parts) == 2) { // Class
4703  
4704  	 	 	 	 // Check if class/method exists:
4705  	 	 	 if (class_exists($parts[0])) {
4706  
4707  	 	 	 	 	 // Get/Create object of class:
4708  	 	 	 	 if ($storePersistentObject) { // Get reference to current instance of class:
4709  	 	 	 	 	 if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
4710  	 	 	 	 	 	 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = self::makeInstance($parts[0]);
4711  	 	 	 	 	 }
4712  	 	 	 	 	 $classObj = $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
4713  	 	 	 	 } else { // Create new object:
4714  	 	 	 	 	 $classObj = self::makeInstance($parts[0]);
4715  	 	 	 	 }
4716  
4717  	 	 	 	 if (method_exists($classObj, $parts[1])) {
4718  
4719  	 	 	 	 	 	 // If persistent object should be created, set reference:
4720  	 	 	 	 	 if ($storePersistentObject) {
4721  	 	 	 	 	 	 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array(
4722  	 	 	 	 	 	 	 'method' => $parts[1],
4723  	 	 	 	 	 	 	 'obj' => &$classObj
4724  	 	 	 	 	 	 );
4725  	 	 	 	 	 }
4726  	 	 	 	 	 	 // Call method:
4727  	 	 	 	 	 $content = call_user_func_array(
4728  	 	 	 	 	 	 array(&$classObj, $parts[1]),
4729  	 	 	 	 	 	 array(&$params, &$ref)
4730  	 	 	 	 	 );
4731  	 	 	 	 } else {
4732  	 	 	 	 	 $errorMsg = "No method name '" . $parts[1] . "' in class " . $parts[0];
4733  	 	 	 	 	 if ($errorMode == 2) {
4734  	 	 	 	 	 	 throw new InvalidArgumentException($errorMsg, 1294585865);
4735  	 	 	 	 	 } elseif (!$errorMode) {
4736  	 	 	 	 	 	 debug($errorMsg, 't3lib_div::callUserFunction');
4737  	 	 	 	 	 }
4738  	 	 	 	 }
4739  	 	 	 } else {
4740  	 	 	 	 $errorMsg = 'No class named ' . $parts[0];
4741  	 	 	 	 if ($errorMode == 2) {
4742  	 	 	 	 	 throw new InvalidArgumentException($errorMsg, 1294585866);
4743  	 	 	 	 } elseif (!$errorMode) {
4744  	 	 	 	 	 debug($errorMsg, 't3lib_div::callUserFunction');
4745  	 	 	 	 }
4746  	 	 	 }
4747  	 	 } else { // Function
4748  	 	 	 if (function_exists($funcRef)) {
4749  	 	 	 	 $content = call_user_func_array($funcRef, array(&$params, &$ref));
4750  	 	 	 } else {
4751  	 	 	 	 $errorMsg = 'No function named: ' . $funcRef;
4752  	 	 	 	 if ($errorMode == 2) {
4753  	 	 	 	 	 throw new InvalidArgumentException($errorMsg, 1294585867);
4754  	 	 	 	 } elseif (!$errorMode) {
4755  	 	 	 	 	 debug($errorMsg, 't3lib_div::callUserFunction');
4756  	 	 	 	 }
4757  	 	 	 }
4758  	 	 }
4759  	 	 return $content;
4760  	 }
4761  
4762  	 /**
4763  	  * Creates and returns reference to a user defined object.
4764  	  * This function can return an object reference if you like. Just prefix the function call with "&": "$objRef = &t3lib_div::getUserObj('EXT:myext/class.tx_myext_myclass.php:&tx_myext_myclass');". This will work ONLY if you prefix the class name with "&" as well. See description of function arguments.
4765  	  *
4766  	  * @param string $classRef Class reference, '[file-reference":"]["&"]class-name'. You can prefix the class name with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl". Finally; for the class name you can prefix it with "&" and you will reuse the previous instance of the object identified by the full reference string (meaning; if you ask for the same $classRef later in another place in the code you will get a reference to the first created one!).
4767  	  * @param string $checkPrefix Required prefix of class name. By default "tx_" and "Tx_" are allowed.
4768  	  * @param boolean $silent If set, no debug() error message is shown if class/function is not present.
4769  	  * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
4770  	  * @see callUserFunction()
4771  	  */
4772  	public static function getUserObj($classRef, $checkPrefix = 'user_', $silent = FALSE) {
4773  	 	 	 // Check persistent object and if found, call directly and exit.
4774  	 	 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
4775  	 	 	 return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
4776  	 	 } else {
4777  
4778  	 	 	 	 // Check file-reference prefix; if found, require_once() the file (should be library of code)
4779  	 	 	 if (strpos($classRef, ':') !== FALSE) {
4780  	 	 	 	 list($file, $class) = self::revExplode(':', $classRef, 2);
4781  	 	 	 	 $requireFile = self::getFileAbsFileName($file);
4782  	 	 	 	 if ($requireFile) {
4783  	 	 	 	 	 self::requireOnce($requireFile);
4784  	 	 	 	 }
4785  	 	 	 } else {
4786  	 	 	 	 $class = $classRef;
4787  	 	 	 }
4788  
4789  	 	 	 	 // Check for persistent object token, "&"
4790  	 	 	 if (substr($class, 0, 1) == '&') {
4791  	 	 	 	 $class = substr($class, 1);
4792  	 	 	 	 $storePersistentObject = TRUE;
4793  	 	 	 } else {
4794  	 	 	 	 $storePersistentObject = FALSE;
4795  	 	 	 }
4796  
4797  	 	 	 	 // Check prefix is valid:
4798  	 	 	 if ($checkPrefix && !self::hasValidClassPrefix($class, array($checkPrefix))) {
4799  	 	 	 	 if (!$silent) {
4800  	 	 	 	 	 debug("Class '" . $class . "' was not prepended with '" . $checkPrefix . "'", 't3lib_div::getUserObj');
4801  	 	 	 	 }
4802  	 	 	 	 return FALSE;
4803  	 	 	 }
4804  
4805  	 	 	 	 // Check if class exists:
4806  	 	 	 if (class_exists($class)) {
4807  	 	 	 	 $classObj = self::makeInstance($class);
4808  
4809  	 	 	 	 	 // If persistent object should be created, set reference:
4810  	 	 	 	 if ($storePersistentObject) {
4811  	 	 	 	 	 $GLOBALS['T3_VAR']['getUserObj'][$classRef] = $classObj;
4812  	 	 	 	 }
4813  
4814  	 	 	 	 return $classObj;
4815  	 	 	 } else {
4816  	 	 	 	 if (!$silent) {
4817  	 	 	 	 	 debug("<strong>ERROR:</strong> No class named: " . $class, 't3lib_div::getUserObj');
4818  	 	 	 	 }
4819  	 	 	 }
4820  	 	 }
4821  	 }
4822  
4823  	 /**
4824  	  * Checks if a class or function has a valid prefix: tx_, Tx_ or custom, e.g. user_
4825  	  *
4826  	  * @param string $classRef The class or function to check
4827  	  * @param array $additionalPrefixes Additional allowed prefixes, mostly this will be user_
4828  	  * @return bool TRUE if name is allowed
4829  	  */
4830  	public static function hasValidClassPrefix($classRef, array $additionalPrefixes = array()) {
4831  	 	 if (empty($classRef)) {
4832  	 	 	 return FALSE;
4833  	 	 }
4834  	 	 if (!is_string($classRef)) {
4835  	 	 	 throw new InvalidArgumentException('$classRef has to be of type string', 1313917992);
4836  	 	 }
4837  	 	 $hasValidPrefix = FALSE;
4838  	 	 $validPrefixes = self::getValidClassPrefixes();
4839  	 	 $classRef = trim($classRef);
4840  
4841  	 	 if (count($additionalPrefixes)) {
4842  	 	 	 $validPrefixes = array_merge($validPrefixes, $additionalPrefixes);
4843  	 	 }
4844  	 	 foreach ($validPrefixes as $prefixToCheck) {
4845  	 	 	 if (self::isFirstPartOfStr($classRef, $prefixToCheck) || $prefixToCheck === '') {
4846  	 	 	 	 $hasValidPrefix = TRUE;
4847  	 	 	 	 break;
4848  	 	 	 }
4849  	 	 }
4850  
4851  	 	 return $hasValidPrefix;
4852  	 }
4853  
4854  	 /**
4855  	  * Returns all valid class prefixes.
4856  	  *
4857  	  * @return array Array of valid prefixed of class names
4858  	  */
4859  	public static function getValidClassPrefixes() {
4860  	 	 $validPrefixes = array('tx_', 'Tx_', 'user_', 'User_');
4861  	 	 if (
4862  	 	 	 isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
4863  	 	 	 && is_string($GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
4864  	 	 ) {
4865  	 	 	 $validPrefixes = array_merge(
4866  	 	 	 	 $validPrefixes,
4867  	 	 	 	 t3lib_div::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
4868  	 	 	 );
4869  	 	 }
4870  	 	 return $validPrefixes;
4871  	 }
4872  
4873  	 /**
4874  	  * Creates an instance of a class taking into account the class-extensions
4875  	  * API of TYPO3. USE THIS method instead of the PHP "new" keyword.
4876  	  * Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
4877  	  *
4878  	  * You can also pass arguments for a constructor:
4879  	  * 	 	 t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
4880  	  *
4881  	  * @throws InvalidArgumentException if classname is an empty string
4882  	  * @param string $className
4883  	  * 	 	 	 name of the class to instantiate, must not be empty
4884  	  * @return object the created instance
4885  	  */
4886  	public static function makeInstance($className) {
4887  	 	 if (!is_string($className) || empty($className)) {
4888  	 	 	 throw new InvalidArgumentException('$className must be a non empty string.', 1288965219);
4889  	 	 }
4890  
4891  	 	 	 // Determine final class name which must be instantiated, this takes XCLASS handling
4892  	 	 	 // into account. Cache in a local array to save some cycles for consecutive calls.
4893  	 	 if (!isset(self::$finalClassNameRegister[$className])) {
4894  	 	 	 self::$finalClassNameRegister[$className] = self::getClassName($className);
4895  	 	 }
4896  	 	 $finalClassName = self::$finalClassNameRegister[$className];
4897  
4898  	 	 	 // Return singleton instance if it is already registered
4899  	 	 if (isset(self::$singletonInstances[$finalClassName])) {
4900  	 	 	 return self::$singletonInstances[$finalClassName];
4901  	 	 }
4902  
4903  	 	 	 // Return instance if it has been injected by addInstance()
4904  	 	 if (isset(self::$nonSingletonInstances[$finalClassName])
4905  	 	 	 && !empty(self::$nonSingletonInstances[$finalClassName])
4906  	 	 ) {
4907  	 	 	 return array_shift(self::$nonSingletonInstances[$finalClassName]);
4908  	 	 }
4909  
4910  	 	 	 // Create new instance and call constructor with parameters
4911  	 	 $instance = static::instantiateClass($finalClassName, func_get_args());
4912  
4913  	 	 	 // Register new singleton instance
4914  	 	 if ($instance instanceof t3lib_Singleton) {
4915  	 	 	 self::$singletonInstances[$finalClassName] = $instance;
4916  	 	 }
4917  
4918  	 	 return $instance;
4919  	 }
4920  
4921  	 /**
4922  	  * Speed optimized alternative to ReflectionClass::newInstanceArgs()
4923  	  *
4924  	  * @param string $className Name of the class to instantiate
4925  	  * @param array $arguments Arguments passed to self::makeInstance() thus the first one with index 0 holds the requested class name
4926  	  * @return mixed
4927  	  */
4928  	protected static function instantiateClass($className, $arguments) {
4929  	 	 switch (count($arguments)) {
4930  	 	 	 case 1:
4931  	 	 	 	 $instance = new $className();
4932  	 	 	 	 break;
4933  	 	 	 case 2:
4934  	 	 	 	 $instance = new $className($arguments[1]);
4935  	 	 	 	 break;
4936  	 	 	 case 3:
4937  	 	 	 	 $instance = new $className($arguments[1], $arguments[2]);
4938  	 	 	 	 break;
4939  	 	 	 case 4:
4940  	 	 	 	 $instance = new $className($arguments[1], $arguments[2], $arguments[3]);
4941  	 	 	 	 break;
4942  	 	 	 case 5:
4943  	 	 	 	 $instance = new $className($arguments[1], $arguments[2], $arguments[3], $arguments[4]);
4944  	 	 	 	 break;
4945  	 	 	 case 6:
4946  	 	 	 	 $instance = new $className($arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
4947  	 	 	 	 break;
4948  	 	 	 case 7:
4949  	 	 	 	 $instance = new $className($arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
4950  	 	 	 	 break;
4951  	 	 	 case 8:
4952  	 	 	 	 $instance = new $className($arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
4953  	 	 	 	 break;
4954  	 	 	 case 9:
4955  	 	 	 	 $instance = new $className($arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
4956  	 	 	 	 break;
4957  	 	 	 default:
4958  	 	 	 	 // The default case for classes with constructors that have more than 8 arguments.
4959  	 	 	 	 // This will fail when one of the arguments shall be passed by reference.
4960  	 	 	 	 // In case we really need to support this edge case, we can implement the solution from here: https://review.typo3.org/26344
4961  	 	 	 	 $class = new ReflectionClass($className);
4962  	 	 	 	 array_shift($arguments);
4963  	 	 	 	 $instance = $class->newInstanceArgs($arguments);
4964  	 	 	 	 return $instance;
4965  	 	 }
4966  	 	 return $instance;
4967  	 }
4968  
4969  	 /**
4970  	  * Returns the class name for a new instance, taking into account the
4971  	  * class-extension API.
4972  	  *
4973  	  * @param string $className Base class name to evaluate
4974  	  * @return string Final class name to instantiate with "new [classname]"
4975  	  */
4976  	protected static function getClassName($className) {
4977  	 	 if (class_exists($className)) {
4978  	 	 	 while (class_exists('ux_' . $className, FALSE)) {
4979  	 	 	 	 $className = 'ux_' . $className;
4980  	 	 	 }
4981  	 	 }
4982  
4983  	 	 return $className;
4984  	 }
4985  
4986  	 /**
4987  	  * Sets the instance of a singleton class to be returned by makeInstance.
4988  	  *
4989  	  * If this function is called multiple times for the same $className,
4990  	  * makeInstance will return the last set instance.
4991  	  *
4992  	  * Warning: This is a helper method for unit tests. Do not call this directly in production code!
4993  	  *
4994  	  * @see makeInstance
4995  	  * @param string $className
4996  	  *        the name of the class to set, must not be empty
4997  	  * @param t3lib_Singleton $instance
4998  	  *        the instance to set, must be an instance of $className
4999  	  * @return void
5000  	  */
5001  	public static function setSingletonInstance($className, t3lib_Singleton $instance) {
5002  	 	 self::checkInstanceClassName($className, $instance);
5003  	 	 self::$singletonInstances[$className] = $instance;
5004  	 }
5005  
5006  	 /**
5007  	  * Sets the instance of a non-singleton class to be returned by makeInstance.
5008  	  *
5009  	  * If this function is called multiple times for the same $className,
5010  	  * makeInstance will return the instances in the order in which they have
5011  	  * been added (FIFO).
5012  	  *
5013  	  * Warning: This is a helper method for unit tests. Do not call this directly in production code!
5014  	  *
5015  	  * @see makeInstance
5016  	  * @throws InvalidArgumentException if class extends t3lib_Singleton
5017  	  * @param string $className
5018  	  *        the name of the class to set, must not be empty
5019  	  * @param object $instance
5020  	  *        the instance to set, must be an instance of $className
5021  	  * @return void
5022  	  */
5023  	public static function addInstance($className, $instance) {
5024  	 	 self::checkInstanceClassName($className, $instance);
5025  
5026  	 	 if ($instance instanceof t3lib_Singleton) {
5027  	 	 	 throw new InvalidArgumentException(
5028  	 	 	 	 '$instance must not be an instance of t3lib_Singleton. ' .
5029  	 	 	 	 	 'For setting singletons, please use setSingletonInstance.',
5030  	 	 	 	 1288969325
5031  	 	 	 );
5032  	 	 }
5033  
5034  	 	 if (!isset(self::$nonSingletonInstances[$className])) {
5035  	 	 	 self::$nonSingletonInstances[$className] = array();
5036  	 	 }
5037  	 	 self::$nonSingletonInstances[$className][] = $instance;
5038  	 }
5039  
5040  	 /**
5041  	  * Checks that $className is non-empty and that $instance is an instance of
5042  	  * $className.
5043  	  *
5044  	  * @throws InvalidArgumentException if $className is empty or if $instance is no instance of $className
5045  	  * @param string $className a class name
5046  	  * @param object $instance an object
5047  	  * @return void
5048  	  */
5049  	protected static function checkInstanceClassName($className, $instance) {
5050  	 	 if ($className === '') {
5051  	 	 	 throw new InvalidArgumentException('$className must not be empty.', 1288967479);
5052  	 	 }
5053  	 	 if (!($instance instanceof $className)) {
5054  	 	 	 throw new InvalidArgumentException(
5055  	 	 	 	 '$instance must be an instance of ' . $className . ', but actually is an instance of ' . get_class($instance) . '.',
5056  	 	 	 	 1288967686
5057  	 	 	 );
5058  	 	 }
5059  	 }
5060  
5061  	 /**
5062  	  * Purge all instances returned by makeInstance.
5063  	  *
5064  	  * This function is most useful when called from tearDown in a test case
5065  	  * to drop any instances that have been created by the tests.
5066  	  *
5067  	  * Warning: This is a helper method for unit tests. Do not call this directly in production code!
5068  	  *
5069  	  * @see makeInstance
5070  	  * @return void
5071  	  */
5072  	public static function purgeInstances() {
5073  	 	 self::$singletonInstances = array();
5074  	 	 self::$nonSingletonInstances = array();
5075  	 }
5076  
5077  	 /**
5078  	  * Find the best service and check if it works.
5079  	  * Returns object of the service class.
5080  	  *
5081  	  * @param string $serviceType Type of service (service key).
5082  	  * @param string $serviceSubType Sub type like file extensions or similar. Defined by the service.
5083  	  * @param mixed $excludeServiceKeys List of service keys which should be excluded in the search for a service. Array or comma list.
5084  	  * @return object The service object or an array with error info's.
5085  	  */
5086  	public static function makeInstanceService($serviceType, $serviceSubType = '', $excludeServiceKeys = array()) {
5087  	 	 $error = FALSE;
5088  
5089  	 	 if (!is_array($excludeServiceKeys)) {
5090  	 	 	 $excludeServiceKeys = self::trimExplode(',', $excludeServiceKeys, 1);
5091  	 	 }
5092  
5093  	 	 $requestInfo = array(
5094  	 	 	 'requestedServiceType' => $serviceType,
5095  	 	 	 'requestedServiceSubType' => $serviceSubType,
5096  	 	 	 'requestedExcludeServiceKeys' => $excludeServiceKeys,
5097  	 	 );
5098  
5099  	 	 while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
5100  
5101  	 	 	 	 // provide information about requested service to service object
5102  	 	 	 $info = array_merge($info, $requestInfo);
5103  
5104  	 	 	 	 // Check persistent object and if found, call directly and exit.
5105  	 	 	 if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
5106  
5107  	 	 	 	 	 // update request info in persistent object
5108  	 	 	 	 $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->info = $info;
5109  
5110  	 	 	 	 	 // reset service and return object
5111  	 	 	 	 $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->reset();
5112  	 	 	 	 return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
5113  
5114  	 	 	 	 // include file and create object
5115  	 	 	 } else {
5116  	 	 	 	 $requireFile = self::getFileAbsFileName($info['classFile']);
5117  	 	 	 	 if (@is_file($requireFile)) {
5118  	 	 	 	 	 self::requireOnce($requireFile);
5119  	 	 	 	 	 $obj = self::makeInstance($info['className']);
5120  	 	 	 	 	 if (is_object($obj)) {
5121  	 	 	 	 	 	 if (!@is_callable(array($obj, 'init'))) {
5122  	 	 	 	 	 	 	 	 // use silent logging??? I don't think so.
5123  	 	 	 	 	 	 	 die ('Broken service:' . t3lib_utility_Debug::viewArray($info));
5124  	 	 	 	 	 	 }
5125  	 	 	 	 	 	 $obj->info = $info;
5126  	 	 	 	 	 	 if ($obj->init()) { // service available?
5127  
5128  	 	 	 	 	 	 	 	 // create persistent object
5129  	 	 	 	 	 	 	 $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']] = $obj;
5130  
5131  	 	 	 	 	 	 	 	 // needed to delete temp files
5132  	 	 	 	 	 	 	 register_shutdown_function(array(&$obj, '__destruct'));
5133  
5134  	 	 	 	 	 	 	 return $obj; // object is passed as reference by function definition
5135  	 	 	 	 	 	 }
5136  	 	 	 	 	 	 $error = $obj->getLastErrorArray();
5137  	 	 	 	 	 	 unset($obj);
5138  	 	 	 	 	 }
5139  	 	 	 	 }
5140  	 	 	 }
5141  	 	 	 	 // deactivate the service
5142  	 	 	 t3lib_extMgm::deactivateService($info['serviceType'], $info['serviceKey']);
5143  	 	 }
5144  	 	 return $error;
5145  	 }
5146  
5147  	 /**
5148  	  * Require a class for TYPO3
5149  	  * Useful to require classes from inside other classes (not global scope). A limited set of global variables are available (see function)
5150  	  *
5151  	  * @param string $requireFile: Path of the file to be included
5152  	  * @return void
5153  	  */
5154  	public static function requireOnce($requireFile) {
5155  	 	 	 // Needed for require_once
5156  	 	 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
5157  
5158  	 	 require_once ($requireFile);
5159  	 }
5160  
5161  	 /**
5162  	  * Requires a class for TYPO3
5163  	  * Useful to require classes from inside other classes (not global scope).
5164  	  * A limited set of global variables are available (see function)
5165  	  *
5166  	  * @param string $requireFile: Path of the file to be included
5167  	  * @return void
5168  	  */
5169  	public static function requireFile($requireFile) {
5170  	 	 	 // Needed for require
5171  	 	 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
5172  	 	 require $requireFile;
5173  	 }
5174  
5175  	 /**
5176  	  * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
5177  	  * The fifth parameter ($encoding) will allow you to specify 'base64' encryption for the output (set $encoding=base64)
5178  	  * Further the output has the charset set to UTF-8 by default.
5179  	  *
5180  	  * @param string $email Email address to send to. (see PHP function mail())
5181  	  * @param string $subject Subject line, non-encoded. (see PHP function mail())
5182  	  * @param string $message Message content, non-encoded. (see PHP function mail())
5183  	  * @param string $headers Headers, separated by LF
5184  	  * @param string $encoding Encoding type: "base64", "quoted-printable", "8bit". Default value is "quoted-printable".
5185  	  * @param string $charset Charset used in encoding-headers (only if $encoding is set to a valid value which produces such a header)
5186  	  * @param boolean $dontEncodeHeader If set, the header content will not be encoded.
5187  	  * @return boolean TRUE if mail was accepted for delivery, FALSE otherwise
5188  	  */
5189  	public static function plainMailEncoded($email, $subject, $message, $headers = '', $encoding = 'quoted-printable', $charset = '', $dontEncodeHeader = FALSE) {
5190  	 	 if (!$charset) {
5191  	 	 	 $charset = 'utf-8';
5192  	 	 }
5193  
5194  	 	 $email = self::normalizeMailAddress($email);
5195  	 	 if (!$dontEncodeHeader) {
5196  	 	 	 	 // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
5197  	 	 	 $newHeaders = array();
5198  	 	 	 foreach (explode(LF, $headers) as $line) { // Split the header in lines and convert each line separately
5199  	 	 	 	 $parts = explode(': ', $line, 2); // Field tags must not be encoded
5200  	 	 	 	 if (count($parts) == 2) {
5201  	 	 	 	 	 if (0 == strcasecmp($parts[0], 'from')) {
5202  	 	 	 	 	 	 $parts[1] = self::normalizeMailAddress($parts[1]);
5203  	 	 	 	 	 }
5204  	 	 	 	 	 $parts[1] = self::encodeHeader($parts[1], $encoding, $charset);
5205  	 	 	 	 	 $newHeaders[] = implode(': ', $parts);
5206  	 	 	 	 } else {
5207  	 	 	 	 	 $newHeaders[] = $line; // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
5208  	 	 	 	 }
5209  	 	 	 }
5210  	 	 	 $headers = implode(LF, $newHeaders);
5211  	 	 	 unset($newHeaders);
5212  
5213  	 	 	 $email = self::encodeHeader($email, $encoding, $charset); // Email address must not be encoded, but it could be appended by a name which should be so (e.g. "Kasper Skårhøj <kasperYYYY@typo3.com>")
5214  	 	 	 $subject = self::encodeHeader($subject, $encoding, $charset);
5215  	 	 }
5216  
5217  	 	 switch ((string) $encoding) {
5218  	 	 	 case 'base64':
5219  	 	 	 	 $headers = trim($headers) . LF .
5220  	 	 	 	 	 	 'Mime-Version: 1.0' . LF .
5221  	 	 	 	 	 	 'Content-Type: text/plain; charset="' . $charset . '"' . LF .
5222  	 	 	 	 	 	 'Content-Transfer-Encoding: base64';
5223  
5224  	 	 	 	 $message = trim(chunk_split(base64_encode($message . LF))) . LF; // Adding LF because I think MS outlook 2002 wants it... may be removed later again.
5225  	 	 	 	 break;
5226  	 	 	 case '8bit':
5227  	 	 	 	 $headers = trim($headers) . LF .
5228  	 	 	 	 	 	 'Mime-Version: 1.0' . LF .
5229  	 	 	 	 	 	 'Content-Type: text/plain; charset=' . $charset . LF .
5230  	 	 	 	 	 	 'Content-Transfer-Encoding: 8bit';
5231  	 	 	 	 break;
5232  	 	 	 case 'quoted-printable':
5233  	 	 	 default:
5234  	 	 	 	 $headers = trim($headers) . LF .
5235  	 	 	 	 	 	 'Mime-Version: 1.0' . LF .
5236  	 	 	 	 	 	 'Content-Type: text/plain; charset=' . $charset . LF .
5237  	 	 	 	 	 	 'Content-Transfer-Encoding: quoted-printable';
5238  
5239  	 	 	 	 $message = self::quoted_printable($message);
5240  	 	 	 	 break;
5241  	 	 }
5242  
5243  	 	 	 // Headers must be separated by CRLF according to RFC 2822, not just LF.
5244  	 	 	 // But many servers (Gmail, for example) behave incorrectly and want only LF.
5245  	 	 	 // So we stick to LF in all cases.
5246  	 	 $headers = trim(implode(LF, self::trimExplode(LF, $headers, TRUE))); // Make sure no empty lines are there.
5247  
5248  	 	 return t3lib_utility_Mail::mail($email, $subject, $message, $headers);
5249  	 }
5250  
5251  	 /**
5252  	  * Implementation of quoted-printable encode.
5253  	  * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
5254  	  *
5255  	  * @param string $string Content to encode
5256  	  * @param integer $maxlen Length of the lines, default is 76
5257  	  * @return string The QP encoded string
5258  	  */
5259  	public static function quoted_printable($string, $maxlen = 76) {
5260  	 	 	 // Make sure the string contains only Unix line breaks
5261  	 	 $string = str_replace(CRLF, LF, $string); // Replace Windows breaks (\r\n)
5262  	 	 $string = str_replace(CR, LF, $string); // Replace Mac breaks (\r)
5263  
5264  	 	 $linebreak = LF; // Default line break for Unix systems.
5265  	 	 if (TYPO3_OS == 'WIN') {
5266  	 	 	 $linebreak = CRLF; // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the line break needs to be \r\n.
5267  	 	 }
5268  
5269  	 	 $newString = '';
5270  	 	 $theLines = explode(LF, $string); // Split lines
5271  	 	 foreach ($theLines as $val) {
5272  	 	 	 $newVal = '';
5273  	 	 	 $theValLen = strlen($val);
5274  	 	 	 $len = 0;
5275  	 	 	 for ($index = 0; $index < $theValLen; $index++) { // Walk through each character of this line
5276  	 	 	 	 $char = substr($val, $index, 1);
5277  	 	 	 	 $ordVal = ord($char);
5278  	 	 	 	 if ($len > ($maxlen - 4) || ($len > ($maxlen - 14) && $ordVal == 32)) {
5279  	 	 	 	 	 $newVal .= '=' . $linebreak; // Add a line break
5280  	 	 	 	 	 $len = 0; // Reset the length counter
5281  	 	 	 	 }
5282  	 	 	 	 if (($ordVal >= 33 && $ordVal <= 60) || ($ordVal >= 62 && $ordVal <= 126) || $ordVal == 9 || $ordVal == 32) {
5283  	 	 	 	 	 $newVal .= $char; // This character is ok, add it to the message
5284  	 	 	 	 	 $len++;
5285  	 	 	 	 } else {
5286  	 	 	 	 	 $newVal .= sprintf('=%02X', $ordVal); // Special character, needs to be encoded
5287  	 	 	 	 	 $len += 3;
5288  	 	 	 	 }
5289  	 	 	 }
5290  	 	 	 $newVal = preg_replace('/' . chr(32) . '$/', '=20', $newVal); // Replaces a possible SPACE-character at the end of a line
5291  	 	 	 $newVal = preg_replace('/' . TAB . '$/', '=09', $newVal); // Replaces a possible TAB-character at the end of a line
5292  	 	 	 $newString .= $newVal . $linebreak;
5293  	 	 }
5294  	 	 return preg_replace('/' . $linebreak . '$/', '', $newString); // Remove last newline
5295  	 }
5296  
5297  	 /**
5298  	  * Encode header lines
5299  	  * Email headers must be ASCII, therefore they will be encoded to quoted_printable (default) or base64.
5300  	  *
5301  	  * @param string $line Content to encode
5302  	  * @param string $enc Encoding type: "base64" or "quoted-printable". Default value is "quoted-printable".
5303  	  * @param string $charset Charset used for encoding
5304  	  * @return string The encoded string
5305  	  */
5306  	public static function encodeHeader($line, $enc = 'quoted-printable', $charset = 'utf-8') {
5307  	 	 	 // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
5308  	 	 if (strpos($line, '###') !== FALSE) {
5309  	 	 	 return $line;
5310  	 	 }
5311  	 	 	 // Check if any non-ASCII characters are found - otherwise encoding is not needed
5312  	 	 if (!preg_match('/[^' . chr(32) . '-' . chr(127) . ']/', $line)) {
5313  	 	 	 return $line;
5314  	 	 }
5315  	 	 	 // Wrap email addresses in a special marker
5316  	 	 $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
5317  
5318  	 	 $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
5319  	 	 foreach ($matches as $part) {
5320  	 	 	 $oldPart = $part;
5321  	 	 	 $partWasQuoted = ($part[0] == '"');
5322  	 	 	 $part = trim($part, '"');
5323  	 	 	 switch ((string) $enc) {
5324  	 	 	 	 case 'base64':
5325  	 	 	 	 	 $part = '=?' . $charset . '?B?' . base64_encode($part) . '?=';
5326  	 	 	 	 	 break;
5327  	 	 	 	 case 'quoted-printable':
5328  	 	 	 	 default:
5329  	 	 	 	 	 $qpValue = self::quoted_printable($part, 1000);
5330  	 	 	 	 	 if ($part != $qpValue) {
5331  	 	 	 	 	 	 	 // Encoded words in the header should not contain non-encoded:
5332  	 	 	 	 	 	 	 // * spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
5333  	 	 	 	 	 	 	 // * question mark. See RFC 1342 (http://tools.ietf.org/html/rfc1342)
5334  	 	 	 	 	 	 $search = array(' ', '?');
5335  	 	 	 	 	 	 $replace = array('_', '=3F');
5336  	 	 	 	 	 	 $qpValue = str_replace($search, $replace, $qpValue);
5337  	 	 	 	 	 	 $part = '=?' . $charset . '?Q?' . $qpValue . '?=';
5338  	 	 	 	 	 }
5339  	 	 	 	 	 break;
5340  	 	 	 }
5341  	 	 	 if ($partWasQuoted) {
5342  	 	 	 	 $part = '"' . $part . '"';
5343  	 	 	 }
5344  	 	 	 $line = str_replace($oldPart, $part, $line);
5345  	 	 }
5346  	 	 $line = preg_replace('/###(.+?)###/', '$1', $line); // Remove the wrappers
5347  
5348  	 	 return $line;
5349  	 }
5350  
5351  	 /**
5352  	  * Takes a clear-text message body for a plain text email, finds all 'http://' links and if they are longer than 76 chars they are converted to a shorter URL with a hash parameter. The real parameter is stored in the database and the hash-parameter/URL will be redirected to the real parameter when the link is clicked.
5353  	  * This function is about preserving long links in messages.
5354  	  *
5355  	  * @param string $message Message content
5356  	  * @param string $urlmode URL mode; "76" or "all"
5357  	  * @param string $index_script_url URL of index script (see makeRedirectUrl())
5358  	  * @return string Processed message content
5359  	  * @see makeRedirectUrl()
5360  	  */
5361  	public static function substUrlsInPlainText($message, $urlmode = '76', $index_script_url = '') {
5362  	 	 $lengthLimit = FALSE;
5363  
5364  	 	 switch ((string) $urlmode) {
5365  	 	 	 case '':
5366  	 	 	 	 $lengthLimit = FALSE;
5367  	 	 	 	 break;
5368  	 	 	 case 'all':
5369  	 	 	 	 $lengthLimit = 0;
5370  	 	 	 	 break;
5371  	 	 	 case '76':
5372  	 	 	 default:
5373  	 	 	 	 $lengthLimit = (int) $urlmode;
5374  	 	 }
5375  
5376  	 	 if ($lengthLimit === FALSE) {
5377  	 	 	 	 // no processing
5378  	 	 	 $messageSubstituted = $message;
5379  	 	 } else {
5380  	 	 	 $messageSubstituted = preg_replace(
5381  	 	 	 	 '/(http|https):\/\/.+(?=[\]\.\?]*([\! \'"()<>]+|$))/eiU',
5382  	 	 	 	 'self::makeRedirectUrl("\\0",' . $lengthLimit . ',"' . $index_script_url . '")',
5383  	 	 	 	 $message
5384  	 	 	 );
5385  	 	 }
5386  
5387  	 	 return $messageSubstituted;
5388  	 }
5389  
5390  	 /**
5391  	  * Sub-function for substUrlsInPlainText() above.
5392  	  *
5393  	  * @param string $inUrl Input URL
5394  	  * @param integer $l URL string length limit
5395  	  * @param string $index_script_url URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplied it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php'
5396  	  * @return string Processed URL
5397  	  */
5398  	public static function makeRedirectUrl($inUrl, $l = 0, $index_script_url = '') {
5399  	 	 if (strlen($inUrl) > $l) {
5400  	 	 	 $md5 = substr(md5($inUrl), 0, 20);
5401  	 	 	 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
5402  	 	 	 	 '*',
5403  	 	 	 	 'cache_md5params',
5404  	 	 	 	 	 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params')
5405  	 	 	 );
5406  	 	 	 if (!$count) {
5407  	 	 	 	 $insertFields = array(
5408  	 	 	 	 	 'md5hash' => $md5,
5409  	 	 	 	 	 'tstamp' => $GLOBALS['EXEC_TIME'],
5410  	 	 	 	 	 'type' => 2,
5411  	 	 	 	 	 'params' => $inUrl
5412  	 	 	 	 );
5413  
5414  	 	 	 	 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
5415  	 	 	 }
5416  	 	 	 $inUrl = ($index_script_url ? $index_script_url : self::getIndpEnv('TYPO3_REQUEST_DIR') . 'index.php') .
5417  	 	 	 	 	 '?RDCT=' . $md5;
5418  	 	 }
5419  
5420  	 	 return $inUrl;
5421  	 }
5422  
5423  	 /**
5424  	  * Function to compensate for FreeType2 96 dpi
5425  	  *
5426  	  * @param integer $font_size Fontsize for freetype function call
5427  	  * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
5428  	  */
5429  	public static function freetypeDpiComp($font_size) {
5430  	 	 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
5431  	 	 if ($dpi != 72) {
5432  	 	 	 $font_size = $font_size / $dpi * 72;
5433  	 	 }
5434  	 	 return $font_size;
5435  	 }
5436  
5437  	 /**
5438  	  * Initialize the system log.
5439  	  *
5440  	  * @return void
5441  	  * @see sysLog()
5442  	  */
5443  	public static function initSysLog() {
5444  	 	 	 // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
5445  	 	 	 // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
5446  	 	 if (defined('TYPO3_cliMode') && TYPO3_cliMode) {
5447  	 	 	 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getHostname($requestHost = FALSE) . ':' . PATH_site;
5448  	 	 }
5449  	 	 	 // for Web logging name is <protocol>://<request-hostame>/<site-path>
5450  	 	 else {
5451  	 	 	 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getIndpEnv('TYPO3_SITE_URL');
5452  	 	 }
5453  
5454  	 	 	 // init custom logging
5455  	 	 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
5456  	 	 	 $params = array('initLog' => TRUE);
5457  	 	 	 $fakeThis = FALSE;
5458  	 	 	 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
5459  	 	 	 	 self::callUserFunction($hookMethod, $params, $fakeThis);
5460  	 	 	 }
5461  	 	 }
5462  
5463  	 	 	 // init TYPO3 logging
5464  	 	 foreach (explode(';', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'], 2) as $log) {
5465  	 	 	 list($type, $destination) = explode(',', $log, 3);
5466  
5467  	 	 	 if ($type == 'syslog') {
5468  	 	 	 	 if (TYPO3_OS == 'WIN') {
5469  	 	 	 	 	 $facility = LOG_USER;
5470  	 	 	 	 } else {
5471  	 	 	 	 	 $facility = constant('LOG_' . strtoupper($destination));
5472  	 	 	 	 }
5473  	 	 	 	 openlog($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
5474  	 	 	 }
5475  	 	 }
5476  
5477  	 	 $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] = t3lib_utility_Math::forceIntegerInRange($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'], 0, 4);
5478  	 	 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
5479  	 }
5480  
5481  	 /**
5482  	  * Logs message to the system log.
5483  	  * This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
5484  	  * If you want to implement the sysLog in your applications, simply add lines like:
5485  	  *	 	  t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
5486  	  *
5487  	  * @param string $msg Message (in English).
5488  	  * @param string $extKey Extension key (from which extension you are calling the log) or "Core"
5489  	  * @param integer $severity Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
5490  	  * @return void
5491  	  */
5492  	public static function sysLog($msg, $extKey, $severity = 0) {
5493  	 	 $severity = t3lib_utility_Math::forceIntegerInRange($severity, 0, 4);
5494  
5495  	 	 	 // is message worth logging?
5496  	 	 if (intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel']) > $severity) {
5497  	 	 	 return;
5498  	 	 }
5499  
5500  	 	 	 // initialize logging
5501  	 	 if (!$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
5502  	 	 	 self::initSysLog();
5503  	 	 }
5504  
5505  	 	 	 // do custom logging
5506  	 	 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) &&
5507  	 	 	 	 is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
5508  	 	 	 $params = array('msg' => $msg, 'extKey' => $extKey, 'backTrace' => debug_backtrace(), 'severity' => $severity);
5509  	 	 	 $fakeThis = FALSE;
5510  	 	 	 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
5511  	 	 	 	 self::callUserFunction($hookMethod, $params, $fakeThis);
5512  	 	 	 }
5513  	 	 }
5514  
5515  	 	 	 // TYPO3 logging enabled?
5516  	 	 if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog']) {
5517  	 	 	 return;
5518  	 	 }
5519  
5520  	 	 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
5521  	 	 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
5522  
5523  	 	 	 // use all configured logging options
5524  	 	 foreach (explode(';', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'], 2) as $log) {
5525  	 	 	 list($type, $destination, $level) = explode(',', $log, 4);
5526  
5527  	 	 	 	 // is message worth logging for this log type?
5528  	 	 	 if (intval($level) > $severity) {
5529  	 	 	 	 continue;
5530  	 	 	 }
5531  
5532  	 	 	 $msgLine = ' - ' . $extKey . ': ' . $msg;
5533  
5534  	 	 	 	 // write message to a file
5535  	 	 	 if ($type == 'file') {
5536  	 	 	 	 $lockObject = t3lib_div::makeInstance('t3lib_lock', $destination, $GLOBALS['TYPO3_CONF_VARS']['SYS']['lockingMode']);
5537  	 	 	 	 /** @var t3lib_lock $lockObject */
5538  	 	 	 	 $lockObject->setEnableLogging(FALSE);
5539  	 	 	 	 $lockObject->acquire();
5540  	 	 	 	 $file = fopen($destination, 'a');
5541  	 	 	 	 if ($file) {
5542  	 	 	 	 	 fwrite($file, date($dateFormat . ' ' . $timeFormat) . $msgLine . LF);
5543  	 	 	 	 	 fclose($file);
5544  	 	 	 	 	 self::fixPermissions($destination);
5545  	 	 	 	 }
5546  	 	 	 	 $lockObject->release();
5547  	 	 	 }
5548  	 	 	 	 // send message per mail
5549  	 	 	 elseif ($type == 'mail') {
5550  	 	 	 	 list($to, $from) = explode('/', $destination);
5551  	 	 	 	 if (!t3lib_div::validEmail($from)) {
5552  	 	 	 	 	 $from = t3lib_utility_Mail::getSystemFrom();
5553  	 	 	 	 }
5554  	 	 	 	 /** @var $mail t3lib_mail_Message */
5555  	 	 	 	 $mail = t3lib_div::makeInstance('t3lib_mail_Message');
5556  	 	 	 	 $mail->setTo($to)
5557  	 	 	 	 	 	 ->setFrom($from)
5558  	 	 	 	 	 	 ->setSubject('Warning - error in TYPO3 installation')
5559  	 	 	 	 	 	 ->setBody('Host: ' . $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . LF .
5560  	 	 	 	 	 	 	 	 'Extension: ' . $extKey . LF .
5561  	 	 	 	 	 	 	 	 'Severity: ' . $severity . LF .
5562  	 	 	 	 	 	 	 	 LF . $msg
5563  	 	 	 	 );
5564  	 	 	 	 $mail->send();
5565  	 	 	 }
5566  	 	 	 	 // use the PHP error log
5567  	 	 	 elseif ($type == 'error_log') {
5568  	 	 	 	 error_log($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . $msgLine, 0);
5569  	 	 	 }
5570  	 	 	 	 // use the system log
5571  	 	 	 elseif ($type == 'syslog') {
5572  	 	 	 	 $priority = array(LOG_INFO, LOG_NOTICE, LOG_WARNING, LOG_ERR, LOG_CRIT);
5573  	 	 	 	 syslog($priority[(int) $severity], $msgLine);
5574  	 	 	 }
5575  	 	 }
5576  	 }
5577  
5578  	 /**
5579  	  * Logs message to the development log.
5580  	  * This should be implemented around the source code, both frontend and backend, logging everything from the flow through an application, messages, results from comparisons to fatal errors.
5581  	  * The result is meant to make sense to developers during development or debugging of a site.
5582  	  * The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like.
5583  	  * If you want to implement the devLog in your applications, simply add lines like:
5584  	  *	 	  if (TYPO3_DLOG)	 t3lib_div::devLog('[write message in english here]', 'extension key');
5585  	  *
5586  	  * @param string $msg Message (in english).
5587  	  * @param string $extKey Extension key (from which extension you are calling the log)
5588  	  * @param integer $severity Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
5589  	  * @param mixed $dataVar Additional data you want to pass to the logger.
5590  	  * @return void
5591  	  */
5592  	public static function devLog($msg, $extKey, $severity = 0, $dataVar = FALSE) {
5593  	 	 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
5594  	 	 	 $params = array('msg' => $msg, 'extKey' => $extKey, 'severity' => $severity, 'dataVar' => $dataVar);
5595  	 	 	 $fakeThis = FALSE;
5596  	 	 	 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
5597  	 	 	 	 self::callUserFunction($hookMethod, $params, $fakeThis);
5598  	 	 	 }
5599  	 	 }
5600  	 }
5601  
5602  	 /**
5603  	  * Writes a message to the deprecation log.
5604  	  *
5605  	  * @param string $msg Message (in English).
5606  	  * @return void
5607  	  */
5608  	public static function deprecationLog($msg) {
5609  	 	 if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
5610  	 	 	 return;
5611  	 	 }
5612  
5613  	 	 $log = $GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog'];
5614  	 	 $date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': ');
5615  
5616  	 	 	 // legacy values (no strict comparison, $log can be boolean, string or int)
5617  	 	 if ($log === TRUE || $log == '1') {
5618  	 	 	 $log = 'file';
5619  	 	 }
5620  
5621  	 	 if (stripos($log, 'file') !== FALSE) {
5622  	 	 	 	 // In case lock is acquired before autoloader was defined:
5623  	 	 	 if (class_exists('t3lib_lock') === FALSE) {
5624  	 	 	 	 require_once PATH_t3lib . 'class.t3lib_lock.php';
5625  	 	 	 }
5626  	 	 	 	 // write a longer message to the deprecation log
5627  	 	 	 $destination = self::getDeprecationLogFileName();
5628  	 	 	 $lockObject = t3lib_div::makeInstance('t3lib_lock', $destination, $GLOBALS['TYPO3_CONF_VARS']['SYS']['lockingMode']);
5629  	 	 	 /** @var t3lib_lock $lockObject */
5630  	 	 	 $lockObject->setEnableLogging(FALSE);
5631  	 	 	 $lockObject->acquire();
5632  	 	 	 $file = @fopen($destination, 'a');
5633  	 	 	 if ($file) {
5634  	 	 	 	 @fwrite($file, $date . $msg . LF);
5635  	 	 	 	 @fclose($file);
5636  	 	 	 	 self::fixPermissions($destination);
5637  	 	 	 }
5638  	 	 	 $lockObject->release();
5639  	 	 }
5640  
5641  	 	 if (stripos($log, 'devlog') !== FALSE) {
5642  	 	 	 	 // copy message also to the developer log
5643  	 	 	 self::devLog($msg, 'Core', self::SYSLOG_SEVERITY_WARNING);
5644  	 	 }
5645  
5646  	 	 	 // do not use console in login screen
5647  	 	 if (stripos($log, 'console') !== FALSE && isset($GLOBALS['BE_USER']->user['uid'])) {
5648  	 	 	 t3lib_utility_Debug::debug($msg, $date, 'Deprecation Log');
5649  	 	 }
5650  	 }
5651  
5652  	 /**
5653  	  * Gets the absolute path to the deprecation log file.
5654  	  *
5655  	  * @return string absolute path to the deprecation log file
5656  	  */
5657  	public static function getDeprecationLogFileName() {
5658  	 	 return PATH_typo3conf .
5659  	 	 	 	 'deprecation_' .
5660  	 	 	 	 self::shortMD5(
5661  	 	 	 	 	 PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
5662  	 	 	 	 ) .
5663  	 	 	 	 '.log';
5664  	 }
5665  
5666  	 /**
5667  	  * Logs a call to a deprecated function.
5668  	  * The log message will be taken from the annotation.
5669  	  * @return void
5670  	  */
5671  	public static function logDeprecatedFunction() {
5672  	 	 if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
5673  	 	 	 return;
5674  	 	 }
5675  
5676  	 	 	 // This require_once is needed for deprecation calls
5677  	 	 	 // thrown early during bootstrap, if the autoloader is
5678  	 	 	 // not instantiated yet. This can happen for example if
5679  	 	 	 // ext_localconf triggers a deprecation.
5680  	 	 require_once  __DIR__.'/class.t3lib_utility_debug.php';
5681  
5682  	 	 $trail = debug_backtrace();
5683  
5684  	 	 if ($trail[1]['type']) {
5685  	 	 	 $function = new ReflectionMethod($trail[1]['class'], $trail[1]['function']);
5686  	 	 } else {
5687  	 	 	 $function = new ReflectionFunction($trail[1]['function']);
5688  	 	 }
5689  
5690  	 	 $msg = '';
5691  	 	 if (preg_match('/@deprecated\s+(.*)/', $function->getDocComment(), $match)) {
5692  	 	 	 $msg = $match[1];
5693  	 	 }
5694  
5695  	 	 	 // trigger PHP error with a short message: <function> is deprecated (called from <source>, defined in <source>)
5696  	 	 $errorMsg = 'Function ' . $trail[1]['function'];
5697  	 	 if ($trail[1]['class']) {
5698  	 	 	 $errorMsg .= ' of class ' . $trail[1]['class'];
5699  	 	 }
5700  	 	 $errorMsg .= ' is deprecated (called from ' . $trail[1]['file'] . '#' . $trail[1]['line'] . ', defined in ' . $function->getFileName() . '#' . $function->getStartLine() . ')';
5701  
5702  	 	 	 // write a longer message to the deprecation log: <function> <annotion> - <trace> (<source>)
5703  	 	 $logMsg = $trail[1]['class'] . $trail[1]['type'] . $trail[1]['function'];
5704  	 	 $logMsg .= '() - ' . $msg.' - ' . t3lib_utility_Debug::debugTrail();
5705  	 	 $logMsg .= ' (' . substr($function->getFileName(), strlen(PATH_site)) . '#' . $function->getStartLine() . ')';
5706  	 	 self::deprecationLog($logMsg);
5707  	 }
5708  
5709  	 /**
5710  	  * Converts a one dimensional array to a one line string which can be used for logging or debugging output
5711  	  * Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;"
5712  	  *
5713  	  * @param array $arr Data array which should be outputted
5714  	  * @param mixed $valueList List of keys which should be listed in the output string. Pass a comma list or an array. An empty list outputs the whole array.
5715  	  * @param integer $valueLength Long string values are shortened to this length. Default: 20
5716  	  * @return string Output string with key names and their value as string
5717  	  */
5718  	public static function arrayToLogString(array $arr, $valueList = array(), $valueLength = 20) {
5719  	 	 $str = '';
5720  	 	 if (!is_array($valueList)) {
5721  	 	 	 $valueList = self::trimExplode(',', $valueList, 1);
5722  	 	 }
5723  	 	 $valListCnt = count($valueList);
5724  	 	 foreach ($arr as $key => $value) {
5725  	 	 	 if (!$valListCnt || in_array($key, $valueList)) {
5726  	 	 	 	 $str .= (string) $key . trim(': ' . self::fixed_lgd_cs(str_replace(LF, '|', (string) $value), $valueLength)) . '; ';
5727  	 	 	 }
5728  	 	 }
5729  	 	 return $str;
5730  	 }
5731  
5732  	 /**
5733  	  * Compile the command for running ImageMagick/GraphicsMagick.
5734  	  *
5735  	  * @param string $command Command to be run: identify, convert or combine/composite
5736  	  * @param string $parameters The parameters string
5737  	  * @param string $path Override the default path (e.g. used by the install tool)
5738  	  * @return string Compiled command that deals with IM6 & GraphicsMagick
5739  	  */
5740  	public static function imageMagickCommand($command, $parameters, $path = '') {
5741  	 	 return t3lib_utility_Command::imageMagickCommand($command, $parameters, $path);
5742  	 }
5743  
5744  	 /**
5745  	  * Explode a string (normally a list of filenames) with whitespaces by considering quotes in that string. This is mostly needed by the imageMagickCommand function above.
5746  	  *
5747  	  * @param string $parameters The whole parameters string
5748  	  * @param boolean $unQuote If set, the elements of the resulting array are unquoted.
5749  	  * @return array Exploded parameters
5750  	  */
5751  	public static function unQuoteFilenames($parameters, $unQuote = FALSE) {
5752  	 	 $paramsArr = explode(' ', trim($parameters));
5753  
5754  	 	 $quoteActive = -1; // Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position.
5755  	 	 foreach ($paramsArr as $k => $v) {
5756  	 	 	 if ($quoteActive > -1) {
5757  	 	 	 	 $paramsArr[$quoteActive] .= ' ' . $v;
5758  	 	 	 	 unset($paramsArr[$k]);
5759  	 	 	 	 if (substr($v, -1) === $paramsArr[$quoteActive][0]) {
5760  	 	 	 	 	 $quoteActive = -1;
5761  	 	 	 	 }
5762  	 	 	 } elseif (!trim($v)) {
5763  	 	 	 	 unset($paramsArr[$k]); // Remove empty elements
5764  
5765  	 	 	 } elseif (preg_match('/^(["\'])/', $v) && substr($v, -1) !== $v[0]) {
5766  	 	 	 	 $quoteActive = $k;
5767  	 	 	 }
5768  	 	 }
5769  
5770  	 	 if ($unQuote) {
5771  	 	 	 foreach ($paramsArr as $key => &$val) {
5772  	 	 	 	 $val = preg_replace('/(^"|"$)/', '', $val);
5773  	 	 	 	 $val = preg_replace('/(^\'|\'$)/', '', $val);
5774  
5775  	 	 	 }
5776  	 	 	 unset($val);
5777  	 	 }
5778  	 	 	 // return reindexed array
5779  	 	 return array_values($paramsArr);
5780  	 }
5781  
5782  
5783  	 /**
5784  	  * Quotes a string for usage as JS parameter.
5785  	  *
5786  	  * @param string $value the string to encode, may be empty
5787  	  *
5788  	  * @return string the encoded value already quoted (with single quotes),
5789  	  *	 	 	 	 will not be empty
5790  	  */
5791  	public static function quoteJSvalue($value) {
5792  	 	 $escapedValue = t3lib_div::makeInstance('t3lib_codec_JavaScriptEncoder')->encode($value);
5793  	 	 return '\'' . $escapedValue . '\'';
5794  	 }
5795  
5796  
5797  	 /**
5798  	  * Ends and cleans all output buffers
5799  	  *
5800  	  * @return void
5801  	  */
5802  	public static function cleanOutputBuffers() {
5803  	 	 while (ob_end_clean()) {
5804  	 	 	 ;
5805  	 	 }
5806  	 	 header('Content-Encoding: None', TRUE);
5807  	 }
5808  
5809  
5810  	 /**
5811  	  * Ends and flushes all output buffers
5812  	  *
5813  	  * @return void
5814  	  */
5815  	public static function flushOutputBuffers() {
5816  	 	 $obContent = '';
5817  
5818  	 	 while ($content = ob_get_clean()) {
5819  	 	 	 $obContent .= $content;
5820  	 	 }
5821  
5822  	 	 	 // if previously a "Content-Encoding: whatever" has been set, we have to unset it
5823  	 	 if (!headers_sent()) {
5824  	 	 	 $headersList = headers_list();
5825  	 	 	 foreach ($headersList as $header) {
5826  	 	 	 	 	 // split it up at the :
5827  	 	 	 	 list($key, $value) = self::trimExplode(':', $header, TRUE);
5828  	 	 	 	 	 // check if we have a Content-Encoding other than 'None'
5829  	 	 	 	 if (strtolower($key) === 'content-encoding' && strtolower($value) !== 'none') {
5830  	 	 	 	 	 header('Content-Encoding: None');
5831  	 	 	 	 	 break;
5832  	 	 	 	 }
5833  	 	 	 }
5834  	 	 }
5835  	 	 echo $obContent;
5836  	 }
5837  }
5838  
5839  ?>