PageRenderTime 85ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/typo3/class.t3lib_div.php

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