PageRenderTime 93ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 2ms

/lib/typo3/class.t3lib_div.php

https://bitbucket.org/ngmares/moodle
PHP | 5843 lines | 3472 code | 473 blank | 1898 comment | 791 complexity | 3f2669a1f22e07ab859a6341fccd16e5 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-3.0, Apache-2.0, BSD-3-Clause
  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. /**
  59. * Singleton instances returned by makeInstance, using the class names as
  60. * array keys
  61. *
  62. * @var array<t3lib_Singleton>
  63. */
  64. protected static $singletonInstances = array();
  65. /**
  66. * Instances returned by makeInstance, using the class names as array keys
  67. *
  68. * @var array<array><object>
  69. */
  70. protected static $nonSingletonInstances = array();
  71. /**
  72. * Register for makeInstance with given class name and final class names to reduce number of class_exists() calls
  73. *
  74. * @var array Given class name => final class name
  75. */
  76. protected static $finalClassNameRegister = array();
  77. /*************************
  78. *
  79. * GET/POST Variables
  80. *
  81. * Background:
  82. * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
  83. * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
  84. * But the clean solution is that quotes are never escaped and that is what the functions below offers.
  85. * Eventually TYPO3 should provide this in the global space as well.
  86. * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
  87. *
  88. *************************/
  89. /**
  90. * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
  91. * Strips slashes from all output, both strings and arrays.
  92. * To enhancement security in your scripts, please consider using t3lib_div::_GET or t3lib_div::_POST if you already
  93. * know by which method your data is arriving to the scripts!
  94. *
  95. * @param string $var GET/POST var to return
  96. * @return mixed POST var named $var and if not set, the GET var of the same name.
  97. */
  98. public static function _GP($var) {
  99. if (empty($var)) {
  100. return;
  101. }
  102. $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
  103. if (isset($value)) {
  104. if (is_array($value)) {
  105. self::stripSlashesOnArray($value);
  106. } else {
  107. $value = stripslashes($value);
  108. }
  109. }
  110. return $value;
  111. }
  112. /**
  113. * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
  114. *
  115. * @param string $parameter Key (variable name) from GET or POST vars
  116. * @return array Returns the GET vars merged recursively onto the POST vars.
  117. */
  118. public static function _GPmerged($parameter) {
  119. $postParameter = (isset($_POST[$parameter]) && is_array($_POST[$parameter])) ? $_POST[$parameter] : array();
  120. $getParameter = (isset($_GET[$parameter]) && is_array($_GET[$parameter])) ? $_GET[$parameter] : array();
  121. $mergedParameters = self::array_merge_recursive_overrule($getParameter, $postParameter);
  122. self::stripSlashesOnArray($mergedParameters);
  123. return $mergedParameters;
  124. }
  125. /**
  126. * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
  127. * ALWAYS use this API function to acquire the GET variables!
  128. *
  129. * @param string $var Optional pointer to value in GET array (basically name of GET var)
  130. * @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!*
  131. * @see _POST(), _GP(), _GETset()
  132. */
  133. public static function _GET($var = NULL) {
  134. $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
  135. if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
  136. if (is_array($value)) {
  137. self::stripSlashesOnArray($value);
  138. } else {
  139. $value = stripslashes($value);
  140. }
  141. }
  142. return $value;
  143. }
  144. /**
  145. * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
  146. * ALWAYS use this API function to acquire the $_POST variables!
  147. *
  148. * @param string $var Optional pointer to value in POST array (basically name of POST var)
  149. * @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself. In any case *slashes are stipped from the output!*
  150. * @see _GET(), _GP()
  151. */
  152. public static function _POST($var = NULL) {
  153. $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
  154. if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
  155. if (is_array($value)) {
  156. self::stripSlashesOnArray($value);
  157. } else {
  158. $value = stripslashes($value);
  159. }
  160. }
  161. return $value;
  162. }
  163. /**
  164. * Writes input value to $_GET.
  165. *
  166. * @param mixed $inputGet
  167. * array or single value to write to $_GET. Values should NOT be
  168. * escaped at input time (but will be escaped before writing
  169. * according to TYPO3 standards).
  170. * @param string $key
  171. * alternative key; If set, this will not set the WHOLE GET array,
  172. * but only the key in it specified by this value!
  173. * You can specify to replace keys on deeper array levels by
  174. * separating the keys with a pipe.
  175. * Example: 'parentKey|childKey' will result in
  176. * array('parentKey' => array('childKey' => $inputGet))
  177. *
  178. * @return void
  179. */
  180. public static function _GETset($inputGet, $key = '') {
  181. // adds slashes since TYPO3 standard currently is that slashes
  182. // must be applied (regardless of magic_quotes setting)
  183. if (is_array($inputGet)) {
  184. self::addSlashesOnArray($inputGet);
  185. } else {
  186. $inputGet = addslashes($inputGet);
  187. }
  188. if ($key != '') {
  189. if (strpos($key, '|') !== FALSE) {
  190. $pieces = explode('|', $key);
  191. $newGet = array();
  192. $pointer =& $newGet;
  193. foreach ($pieces as $piece) {
  194. $pointer =& $pointer[$piece];
  195. }
  196. $pointer = $inputGet;
  197. $mergedGet = self::array_merge_recursive_overrule(
  198. $_GET, $newGet
  199. );
  200. $_GET = $mergedGet;
  201. $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
  202. } else {
  203. $_GET[$key] = $inputGet;
  204. $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
  205. }
  206. } elseif (is_array($inputGet)) {
  207. $_GET = $inputGet;
  208. $GLOBALS['HTTP_GET_VARS'] = $inputGet;
  209. }
  210. }
  211. /**
  212. * Wrapper for the RemoveXSS function.
  213. * Removes potential XSS code from an input string.
  214. *
  215. * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
  216. *
  217. * @param string $string Input string
  218. * @return string Input string with potential XSS code removed
  219. */
  220. public static function removeXSS($string) {
  221. require_once(PATH_typo3 . 'contrib/RemoveXSS/RemoveXSS.php');
  222. $string = RemoveXSS::process($string);
  223. return $string;
  224. }
  225. /*************************
  226. *
  227. * IMAGE FUNCTIONS
  228. *
  229. *************************/
  230. /**
  231. * Compressing a GIF file if not already LZW compressed.
  232. * 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)
  233. *
  234. * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
  235. * GIF:
  236. * 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!)
  237. * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
  238. * PNG:
  239. * No changes.
  240. *
  241. * $theFile is expected to be a valid GIF-file!
  242. * The function returns a code for the operation.
  243. *
  244. * @param string $theFile Filepath
  245. * @param string $type See description of function
  246. * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
  247. */
  248. public static function gif_compress($theFile, $type) {
  249. $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
  250. $returnCode = '';
  251. if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') { // GIF...
  252. if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
  253. // use temporary file to prevent problems with read and write lock on same file on network file systems
  254. $temporaryName = dirname($theFile) . '/' . md5(uniqid()) . '.gif';
  255. // rename could fail, if a simultaneous thread is currently working on the same thing
  256. if (@rename($theFile, $temporaryName)) {
  257. $cmd = self::imageMagickCommand('convert', '"' . $temporaryName . '" "' . $theFile . '"', $gfxConf['im_path_lzw']);
  258. t3lib_utility_Command::exec($cmd);
  259. unlink($temporaryName);
  260. }
  261. $returnCode = 'IM';
  262. if (@is_file($theFile)) {
  263. self::fixPermissions($theFile);
  264. }
  265. } elseif (($type == 'GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
  266. $tempImage = imageCreateFromGif($theFile);
  267. imageGif($tempImage, $theFile);
  268. imageDestroy($tempImage);
  269. $returnCode = 'GD';
  270. if (@is_file($theFile)) {
  271. self::fixPermissions($theFile);
  272. }
  273. }
  274. }
  275. return $returnCode;
  276. }
  277. /**
  278. * Converts a png file to gif.
  279. * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set TRUE.
  280. *
  281. * @param string $theFile the filename with path
  282. * @return string new filename
  283. */
  284. public static function png_to_gif_by_imagemagick($theFile) {
  285. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
  286. && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
  287. && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
  288. && strtolower(substr($theFile, -4, 4)) == '.png'
  289. && @is_file($theFile)) { // IM
  290. $newFile = substr($theFile, 0, -4) . '.gif';
  291. $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
  292. t3lib_utility_Command::exec($cmd);
  293. $theFile = $newFile;
  294. if (@is_file($newFile)) {
  295. self::fixPermissions($newFile);
  296. }
  297. // unlink old file?? May be bad idea because TYPO3 would then recreate the file every time as
  298. // TYPO3 thinks the file is not generated because it's missing!! So do not unlink $theFile here!!
  299. }
  300. return $theFile;
  301. }
  302. /**
  303. * Returns filename of the png/gif version of the input file (which can be png or gif).
  304. * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
  305. *
  306. * @param string $theFile Filepath of image file
  307. * @param boolean $output_png If set, then input file is converted to PNG, otherwise to GIF
  308. * @return string If the new image file exists, its filepath is returned
  309. */
  310. public static function read_png_gif($theFile, $output_png = FALSE) {
  311. if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) {
  312. $ext = strtolower(substr($theFile, -4, 4));
  313. if (
  314. ((string) $ext == '.png' && $output_png) ||
  315. ((string) $ext == '.gif' && !$output_png)
  316. ) {
  317. return $theFile;
  318. } else {
  319. $newFile = PATH_site . 'typo3temp/readPG_' . md5($theFile . '|' . filemtime($theFile)) . ($output_png ? '.png' : '.gif');
  320. $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
  321. t3lib_utility_Command::exec($cmd);
  322. if (@is_file($newFile)) {
  323. self::fixPermissions($newFile);
  324. return $newFile;
  325. }
  326. }
  327. }
  328. }
  329. /*************************
  330. *
  331. * STRING FUNCTIONS
  332. *
  333. *************************/
  334. /**
  335. * Truncates a string with appended/prepended "..." and takes current character set into consideration.
  336. *
  337. * @param string $string string to truncate
  338. * @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.
  339. * @param string $appendString appendix to the truncated string
  340. * @return string cropped string
  341. */
  342. public static function fixed_lgd_cs($string, $chars, $appendString = '...') {
  343. if (is_object($GLOBALS['LANG'])) {
  344. return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
  345. } elseif (is_object($GLOBALS['TSFE'])) {
  346. $charSet = ($GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet);
  347. return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString);
  348. } else {
  349. // this case should not happen
  350. $csConvObj = self::makeInstance('t3lib_cs');
  351. return $csConvObj->crop('iso-8859-1', $string, $chars, $appendString);
  352. }
  353. }
  354. /**
  355. * Breaks up a single line of text for emails
  356. *
  357. * @param string $str The string to break up
  358. * @param string $newlineChar The string to implode the broken lines with (default/typically \n)
  359. * @param integer $lineWidth The line width
  360. * @return string reformatted text
  361. * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Mail::breakLinesForEmail()
  362. */
  363. public static function breakLinesForEmail($str, $newlineChar = LF, $lineWidth = 76) {
  364. self::logDeprecatedFunction();
  365. return t3lib_utility_Mail::breakLinesForEmail($str, $newlineChar, $lineWidth);
  366. }
  367. /**
  368. * Match IP number with list of numbers with wildcard
  369. * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
  370. *
  371. * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
  372. * @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.
  373. * @return boolean TRUE if an IP-mask from $list matches $baseIP
  374. */
  375. public static function cmpIP($baseIP, $list) {
  376. $list = trim($list);
  377. if ($list === '') {
  378. return FALSE;
  379. } elseif ($list === '*') {
  380. return TRUE;
  381. }
  382. if (strpos($baseIP, ':') !== FALSE && self::validIPv6($baseIP)) {
  383. return self::cmpIPv6($baseIP, $list);
  384. } else {
  385. return self::cmpIPv4($baseIP, $list);
  386. }
  387. }
  388. /**
  389. * Match IPv4 number with list of numbers with wildcard
  390. *
  391. * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
  392. * @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
  393. * @return boolean TRUE if an IP-mask from $list matches $baseIP
  394. */
  395. public static function cmpIPv4($baseIP, $list) {
  396. $IPpartsReq = explode('.', $baseIP);
  397. if (count($IPpartsReq) == 4) {
  398. $values = self::trimExplode(',', $list, 1);
  399. foreach ($values as $test) {
  400. $testList = explode('/', $test);
  401. if (count($testList) == 2) {
  402. list($test, $mask) = $testList;
  403. } else {
  404. $mask = FALSE;
  405. }
  406. if (intval($mask)) {
  407. // "192.168.3.0/24"
  408. $lnet = ip2long($test);
  409. $lip = ip2long($baseIP);
  410. $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
  411. $firstpart = substr($binnet, 0, $mask);
  412. $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
  413. $firstip = substr($binip, 0, $mask);
  414. $yes = (strcmp($firstpart, $firstip) == 0);
  415. } else {
  416. // "192.168.*.*"
  417. $IPparts = explode('.', $test);
  418. $yes = 1;
  419. foreach ($IPparts as $index => $val) {
  420. $val = trim($val);
  421. if (($val !== '*') && ($IPpartsReq[$index] !== $val)) {
  422. $yes = 0;
  423. }
  424. }
  425. }
  426. if ($yes) {
  427. return TRUE;
  428. }
  429. }
  430. }
  431. return FALSE;
  432. }
  433. /**
  434. * Match IPv6 address with a list of IPv6 prefixes
  435. *
  436. * @param string $baseIP is the current remote IP address for instance
  437. * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
  438. * @return boolean TRUE if an baseIP matches any prefix
  439. */
  440. public static function cmpIPv6($baseIP, $list) {
  441. $success = FALSE; // Policy default: Deny connection
  442. $baseIP = self::normalizeIPv6($baseIP);
  443. $values = self::trimExplode(',', $list, 1);
  444. foreach ($values as $test) {
  445. $testList = explode('/', $test);
  446. if (count($testList) == 2) {
  447. list($test, $mask) = $testList;
  448. } else {
  449. $mask = FALSE;
  450. }
  451. if (self::validIPv6($test)) {
  452. $test = self::normalizeIPv6($test);
  453. $maskInt = intval($mask) ? intval($mask) : 128;
  454. if ($mask === '0') { // special case; /0 is an allowed mask - equals a wildcard
  455. $success = TRUE;
  456. } elseif ($maskInt == 128) {
  457. $success = ($test === $baseIP);
  458. } else {
  459. $testBin = self::IPv6Hex2Bin($test);
  460. $baseIPBin = self::IPv6Hex2Bin($baseIP);
  461. $success = TRUE;
  462. // modulo is 0 if this is a 8-bit-boundary
  463. $maskIntModulo = $maskInt % 8;
  464. $numFullCharactersUntilBoundary = intval($maskInt / 8);
  465. if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) {
  466. $success = FALSE;
  467. } elseif ($maskIntModulo > 0) {
  468. // if not an 8-bit-boundary, check bits of last character
  469. $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
  470. $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
  471. if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
  472. $success = FALSE;
  473. }
  474. }
  475. }
  476. }
  477. if ($success) {
  478. return TRUE;
  479. }
  480. }
  481. return FALSE;
  482. }
  483. /**
  484. * Transform a regular IPv6 address from hex-representation into binary
  485. *
  486. * @param string $hex IPv6 address in hex-presentation
  487. * @return string Binary representation (16 characters, 128 characters)
  488. * @see IPv6Bin2Hex()
  489. */
  490. public static function IPv6Hex2Bin($hex) {
  491. // use PHP-function if PHP was compiled with IPv6-support
  492. if (defined('AF_INET6')) {
  493. $bin = inet_pton($hex);
  494. } else {
  495. $hex = self::normalizeIPv6($hex);
  496. $hex = str_replace(':', '', $hex); // Replace colon to nothing
  497. $bin = pack("H*" , $hex);
  498. }
  499. return $bin;
  500. }
  501. /**
  502. * Transform an IPv6 address from binary to hex-representation
  503. *
  504. * @param string $bin IPv6 address in hex-presentation
  505. * @return string Binary representation (16 characters, 128 characters)
  506. * @see IPv6Hex2Bin()
  507. */
  508. public static function IPv6Bin2Hex($bin) {
  509. // use PHP-function if PHP was compiled with IPv6-support
  510. if (defined('AF_INET6')) {
  511. $hex = inet_ntop($bin);
  512. } else {
  513. $hex = unpack("H*" , $bin);
  514. $hex = chunk_split($hex[1], 4, ':');
  515. // strip last colon (from chunk_split)
  516. $hex = substr($hex, 0, -1);
  517. // IPv6 is now in normalized form
  518. // compress it for easier handling and to match result from inet_ntop()
  519. $hex = self::compressIPv6($hex);
  520. }
  521. return $hex;
  522. }
  523. /**
  524. * Normalize an IPv6 address to full length
  525. *
  526. * @param string $address Given IPv6 address
  527. * @return string Normalized address
  528. * @see compressIPv6()
  529. */
  530. public static function normalizeIPv6($address) {
  531. $normalizedAddress = '';
  532. $stageOneAddress = '';
  533. // according to RFC lowercase-representation is recommended
  534. $address = strtolower($address);
  535. // normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
  536. if (strlen($address) == 39) {
  537. // already in full expanded form
  538. return $address;
  539. }
  540. $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks
  541. if (count($chunks) == 2) {
  542. $chunksLeft = explode(':', $chunks[0]);
  543. $chunksRight = explode(':', $chunks[1]);
  544. $left = count($chunksLeft);
  545. $right = count($chunksRight);
  546. // Special case: leading zero-only blocks count to 1, should be 0
  547. if ($left == 1 && strlen($chunksLeft[0]) == 0) {
  548. $left = 0;
  549. }
  550. $hiddenBlocks = 8 - ($left + $right);
  551. $hiddenPart = '';
  552. $h = 0;
  553. while ($h < $hiddenBlocks) {
  554. $hiddenPart .= '0000:';
  555. $h++;
  556. }
  557. if ($left == 0) {
  558. $stageOneAddress = $hiddenPart . $chunks[1];
  559. } else {
  560. $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
  561. }
  562. } else {
  563. $stageOneAddress = $address;
  564. }
  565. // normalize the blocks:
  566. $blocks = explode(':', $stageOneAddress);
  567. $divCounter = 0;
  568. foreach ($blocks as $block) {
  569. $tmpBlock = '';
  570. $i = 0;
  571. $hiddenZeros = 4 - strlen($block);
  572. while ($i < $hiddenZeros) {
  573. $tmpBlock .= '0';
  574. $i++;
  575. }
  576. $normalizedAddress .= $tmpBlock . $block;
  577. if ($divCounter < 7) {
  578. $normalizedAddress .= ':';
  579. $divCounter++;
  580. }
  581. }
  582. return $normalizedAddress;
  583. }
  584. /**
  585. * Compress an IPv6 address to the shortest notation
  586. *
  587. * @param string $address Given IPv6 address
  588. * @return string Compressed address
  589. * @see normalizeIPv6()
  590. */
  591. public static function compressIPv6($address) {
  592. // use PHP-function if PHP was compiled with IPv6-support
  593. if (defined('AF_INET6')) {
  594. $bin = inet_pton($address);
  595. $address = inet_ntop($bin);
  596. } else {
  597. $address = self::normalizeIPv6($address);
  598. // append one colon for easier handling
  599. // will be removed later
  600. $address .= ':';
  601. // according to IPv6-notation the longest match
  602. // of a package of '0000:' may be replaced with ':'
  603. // (resulting in something like '1234::abcd')
  604. for ($counter = 8; $counter > 1; $counter--) {
  605. $search = str_repeat('0000:', $counter);
  606. if (($pos = strpos($address, $search)) !== FALSE) {
  607. $address = substr($address, 0, $pos) . ':' . substr($address, $pos + ($counter*5));
  608. break;
  609. }
  610. }
  611. // up to 3 zeros in the first part may be removed
  612. $address = preg_replace('/^0{1,3}/', '', $address);
  613. // up to 3 zeros at the beginning of other parts may be removed
  614. $address = preg_replace('/:0{1,3}/', ':', $address);
  615. // strip last colon (from chunk_split)
  616. $address = substr($address, 0, -1);
  617. }
  618. return $address;
  619. }
  620. /**
  621. * Validate a given IP address.
  622. *
  623. * Possible format are IPv4 and IPv6.
  624. *
  625. * @param string $ip IP address to be tested
  626. * @return boolean TRUE if $ip is either of IPv4 or IPv6 format.
  627. */
  628. public static function validIP($ip) {
  629. return (filter_var($ip, FILTER_VALIDATE_IP) !== FALSE);
  630. }
  631. /**
  632. * Validate a given IP address to the IPv4 address format.
  633. *
  634. * Example for possible format: 10.0.45.99
  635. *
  636. * @param string $ip IP address to be tested
  637. * @return boolean TRUE if $ip is of IPv4 format.
  638. */
  639. public static function validIPv4($ip) {
  640. return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE);
  641. }
  642. /**
  643. * Validate a given IP address to the IPv6 address format.
  644. *
  645. * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
  646. *
  647. * @param string $ip IP address to be tested
  648. * @return boolean TRUE if $ip is of IPv6 format.
  649. */
  650. public static function validIPv6($ip) {
  651. return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE);
  652. }
  653. /**
  654. * Match fully qualified domain name with list of strings with wildcard
  655. *
  656. * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
  657. * @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)
  658. * @return boolean TRUE if a domain name mask from $list matches $baseIP
  659. */
  660. public static function cmpFQDN($baseHost, $list) {
  661. $baseHost = trim($baseHost);
  662. if (empty($baseHost)) {
  663. return FALSE;
  664. }
  665. if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
  666. // resolve hostname
  667. // note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
  668. // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
  669. $baseHostName = gethostbyaddr($baseHost);
  670. if ($baseHostName === $baseHost) {
  671. // unable to resolve hostname
  672. return FALSE;
  673. }
  674. } else {
  675. $baseHostName = $baseHost;
  676. }
  677. $baseHostNameParts = explode('.', $baseHostName);
  678. $values = self::trimExplode(',', $list, 1);
  679. foreach ($values as $test) {
  680. $hostNameParts = explode('.', $test);
  681. // to match hostNameParts can only be shorter (in case of wildcards) or equal
  682. if (count($hostNameParts) > count($baseHostNameParts)) {
  683. continue;
  684. }
  685. $yes = TRUE;
  686. foreach ($hostNameParts as $index => $val) {
  687. $val = trim($val);
  688. if ($val === '*') {
  689. // wildcard valid for one or more hostname-parts
  690. $wildcardStart = $index + 1;
  691. // wildcard as last/only part always matches, otherwise perform recursive checks
  692. if ($wildcardStart < count($hostNameParts)) {
  693. $wildcardMatched = FALSE;
  694. $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
  695. while (($wildcardStart < count($baseHostNameParts)) && (!$wildcardMatched)) {
  696. $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
  697. $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
  698. $wildcardStart++;
  699. }
  700. if ($wildcardMatched) {
  701. // match found by recursive compare
  702. return TRUE;
  703. } else {
  704. $yes = FALSE;
  705. }
  706. }
  707. } elseif ($baseHostNameParts[$index] !== $val) {
  708. // in case of no match
  709. $yes = FALSE;
  710. }
  711. }
  712. if ($yes) {
  713. return TRUE;
  714. }
  715. }
  716. return FALSE;
  717. }
  718. /**
  719. * Checks if a given URL matches the host that currently handles this HTTP request.
  720. * Scheme, hostname and (optional) port of the given URL are compared.
  721. *
  722. * @param string $url: URL to compare with the TYPO3 request host
  723. * @return boolean Whether the URL matches the TYPO3 request host
  724. */
  725. public static function isOnCurrentHost($url) {
  726. return (stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0);
  727. }
  728. /**
  729. * Check for item in list
  730. * Check if an item exists in a comma-separated list of items.
  731. *
  732. * @param string $list comma-separated list of items (string)
  733. * @param string $item item to check for
  734. * @return boolean TRUE if $item is in $list
  735. */
  736. public static function inList($list, $item) {
  737. return (strpos(',' . $list . ',', ',' . $item . ',') !== FALSE ? TRUE : FALSE);
  738. }
  739. /**
  740. * Removes an item from a comma-separated list of items.
  741. *
  742. * @param string $element element to remove
  743. * @param string $list comma-separated list of items (string)
  744. * @return string new comma-separated list of items
  745. */
  746. public static function rmFromList($element, $list) {
  747. $items = explode(',', $list);
  748. foreach ($items as $k => $v) {
  749. if ($v == $element) {
  750. unset($items[$k]);
  751. }
  752. }
  753. return implode(',', $items);
  754. }
  755. /**
  756. * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
  757. * Ranges are limited to 1000 values per range.
  758. *
  759. * @param string $list comma-separated list of integers with ranges (string)
  760. * @return string new comma-separated list of items
  761. */
  762. public static function expandList($list) {
  763. $items = explode(',', $list);
  764. $list = array();
  765. foreach ($items as $item) {
  766. $range = explode('-', $item);
  767. if (isset($range[1])) {
  768. $runAwayBrake = 1000;
  769. for ($n = $range[0]; $n <= $range[1]; $n++) {
  770. $list[] = $n;
  771. $runAwayBrake--;
  772. if ($runAwayBrake <= 0) {
  773. break;
  774. }
  775. }
  776. } else {
  777. $list[] = $item;
  778. }
  779. }
  780. return implode(',', $list);
  781. }
  782. /**
  783. * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'FALSE' then the $zeroValue is applied.
  784. *
  785. * @param integer $theInt Input value
  786. * @param integer $min Lower limit
  787. * @param integer $max Higher limit
  788. * @param integer $zeroValue Default value if input is FALSE.
  789. * @return integer The input value forced into the boundaries of $min and $max
  790. * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::forceIntegerInRange() instead
  791. */
  792. public static function intInRange($theInt, $min, $max = 2000000000, $zeroValue = 0) {
  793. self::logDeprecatedFunction();
  794. return t3lib_utility_Math::forceIntegerInRange($theInt, $min, $max, $zeroValue);
  795. }
  796. /**
  797. * Returns the $integer if greater than zero, otherwise returns zero.
  798. *
  799. * @param integer $theInt Integer string to process
  800. * @return integer
  801. * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::convertToPositiveInteger() instead
  802. */
  803. public static function intval_positive($theInt) {
  804. self::logDeprecatedFunction();
  805. return t3lib_utility_Math::convertToPositiveInteger($theInt);
  806. }
  807. /**
  808. * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
  809. *
  810. * @param string $verNumberStr Version number on format x.x.x
  811. * @return integer Integer version of version number (where each part can count to 999)
  812. * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.9 - Use t3lib_utility_VersionNumber::convertVersionNumberToInteger() instead
  813. */
  814. public static function int_from_ver($verNumberStr) {
  815. // Deprecation log is activated only for TYPO3 4.7 and above
  816. if (t3lib_utility_VersionNumber::convertVersionNumberToInteger(TYPO3_version) >= 4007000) {
  817. self::logDeprecatedFunction();
  818. }
  819. return t3lib_utility_VersionNumber::convertVersionNumberToInteger($verNumberStr);
  820. }
  821. /**
  822. * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
  823. * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
  824. *
  825. * @param string $verNumberStr Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
  826. * @return boolean Returns TRUE if this setup is compatible with the provided version number
  827. * @todo Still needs a function to convert versions to branches
  828. */
  829. public static function compat_version($verNumberStr) {
  830. $currVersionStr = $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] : TYPO3_branch;
  831. if (t3lib_utility_VersionNumber::convertVersionNumberToInteger($currVersionStr) < t3lib_utility_VersionNumber::convertVersionNumberToInteger($verNumberStr)) {
  832. return FALSE;
  833. } else {
  834. return TRUE;
  835. }
  836. }
  837. /**
  838. * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
  839. *
  840. * @param string $str String to md5-hash
  841. * @return integer Returns 28bit integer-hash
  842. */
  843. public static function md5int($str) {
  844. return hexdec(substr(md5($str), 0, 7));
  845. }
  846. /**
  847. * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
  848. *
  849. * @param string $input Input string to be md5-hashed
  850. * @param integer $len The string-length of the output
  851. * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
  852. */
  853. public static function shortMD5($input, $len = 10) {
  854. return substr(md5($input), 0, $len);
  855. }
  856. /**
  857. * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
  858. *
  859. * @param string $input Input string to create HMAC from
  860. * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
  861. */
  862. public static function hmac($input) {
  863. $hashAlgorithm = 'sha1';
  864. $hashBlocksize = 64;
  865. $hmac = '';
  866. if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
  867. $hmac = hash_hmac($hashAlgorithm, $input, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
  868. } else {
  869. // outer padding
  870. $opad = str_repeat(chr(0x5C), $hashBlocksize);
  871. // inner padding
  872. $ipad = str_repeat(chr(0x36), $hashBlocksize);
  873. if (strlen($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) > $hashBlocksize) {
  874. // keys longer than block size are shorten
  875. $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])), $hashBlocksize, chr(0x00));
  876. } else {
  877. // keys shorter than block size are zero-padded
  878. $key = str_pad($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], $hashBlocksize, chr(0x00));
  879. }
  880. $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, ($key ^ $ipad) . $input)));
  881. }
  882. return $hmac;
  883. }
  884. /**
  885. * Takes comma-separated lists and arrays and removes all duplicates
  886. * If a value in the list is trim(empty), the value is ignored.
  887. *
  888. * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
  889. * @param mixed $secondParameter: Dummy field, which if set will show a warning!
  890. * @return string Returns the list without any duplicates of values, space around values are trimmed
  891. */
  892. public static function uniqueList($in_list, $secondParameter = NULL) {
  893. if (is_array($in_list)) {
  894. throw new InvalidArgumentException(
  895. 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
  896. 1270853885
  897. );
  898. }
  899. if (isset($secondParameter)) {
  900. throw new InvalidArgumentException(
  901. 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!',
  902. 1270853886
  903. );
  904. }
  905. return implode(',', array_unique(self::trimExplode(',', $in_list, 1)));
  906. }
  907. /**
  908. * Splits a reference to a file in 5 parts
  909. *
  910. * @param string $fileref Filename/filepath to be analysed
  911. * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
  912. */
  913. public static function split_fileref($fileref) {
  914. $reg = array();
  915. if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
  916. $info['path'] = $reg[1];
  917. $info['file'] = $reg[2];
  918. } else {
  919. $info['path'] = '';
  920. $info['file'] = $fileref;
  921. }
  922. $reg = '';
  923. if (!is_dir($fileref) && preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
  924. $info['filebody'] = $reg[1];
  925. $info['fileext'] = strtolower($reg[2]);
  926. $info['realFileext'] = $reg[2];
  927. } else {
  928. $info['filebody'] = $info['file'];
  929. $info['fileext'] = '';
  930. }
  931. reset($info);
  932. return $info;
  933. }
  934. /**
  935. * Returns the directory part of a path without trailing slash
  936. * If there is no dir-part, then an empty string is returned.
  937. * Behaviour:
  938. *
  939. * '/dir1/dir2/script.php' => '/dir1/dir2'
  940. * '/dir1/' => '/dir1'
  941. * 'dir1/script.php' => 'dir1'
  942. * 'd/script.php' => 'd'
  943. * '/script.php' => ''
  944. * '' => ''
  945. *
  946. * @param string $path Directory name / path
  947. * @return string Processed input value. See function description.
  948. */
  949. public static function dirname($path) {
  950. $p = self::revExplode('/', $path, 2);
  951. return count($p) == 2 ? $p[0] : '';
  952. }
  953. /**
  954. * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
  955. *
  956. * @param string $color A hexadecimal color code, #xxxxxx
  957. * @param integer $R Offset value 0-255
  958. * @param integer $G Offset value 0-255
  959. * @param integer $B Offset value 0-255
  960. * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
  961. * @see modifyHTMLColorAll()
  962. */
  963. public static function modifyHTMLColor($color, $R, $G, $B) {
  964. // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
  965. $nR = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
  966. $nG = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
  967. $nB = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
  968. return '#' .
  969. substr('0' . dechex($nR), -2) .
  970. substr('0' . dechex($nG), -2) .
  971. substr('0' . dechex($nB), -2);
  972. }
  973. /**
  974. * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
  975. *
  976. * @param string $color A hexadecimal color code, #xxxxxx
  977. * @param integer $all Offset value 0-255 for all three channels.
  978. * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
  979. * @see modifyHTMLColor()
  980. */
  981. public static function modifyHTMLColorAll($color, $all) {
  982. return self::modifyHTMLColor($color, $all, $all, $all);
  983. }
  984. /**
  985. * Removes comma (if present) in the end of string
  986. *
  987. * @param string $string String from which the comma in the end (if any) will be removed.
  988. * @return string
  989. * @deprecated since TYPO3 4.5, will be removed in TYPO3 4.7 - Use rtrim() directly
  990. */
  991. public static function rm_endcomma($string) {
  992. self::logDeprecatedFunction();
  993. return rtrim($string, ',');
  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 4.8 - 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 4.8 - 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 4.8 - 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. return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);
  1172. }
  1173. /**
  1174. * Checks if current e-mail sending method does not accept recipient/sender name
  1175. * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
  1176. * program are known not to process such input correctly and they cause SMTP
  1177. * errors. This function will return TRUE if current mail sending method has
  1178. * problem with recipient name in recipient/sender argument for mail().
  1179. *
  1180. * TODO: 4.3 should have additional configuration variable, which is combined
  1181. * by || with the rest in this function.
  1182. *
  1183. * @return boolean TRUE if mail() does not accept recipient name
  1184. */
  1185. public static function isBrokenEmailEnvironment() {
  1186. return TYPO3_OS == 'WIN' || (FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
  1187. }
  1188. /**
  1189. * Changes from/to arguments for mail() function to work in any environment.
  1190. *
  1191. * @param string $address Address to adjust
  1192. * @return string Adjusted address
  1193. * @see t3lib_::isBrokenEmailEnvironment()
  1194. */
  1195. public static function normalizeMailAddress($address) {
  1196. if (self::isBrokenEmailEnvironment() && FALSE !== ($pos1 = strrpos($address, '<'))) {
  1197. $pos2 = strpos($address, '>', $pos1);
  1198. $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
  1199. }
  1200. return $address;
  1201. }
  1202. /**
  1203. * Formats a string for output between <textarea>-tags
  1204. * All content outputted in a textarea form should be passed through this function
  1205. * 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!
  1206. *
  1207. * @param string $content Input string to be formatted.
  1208. * @return string Formatted for <textarea>-tags
  1209. */
  1210. public static function formatForTextarea($content) {
  1211. return LF . htmlspecialchars($content);
  1212. }
  1213. /**
  1214. * Converts string to uppercase
  1215. * The function converts all Latin characters (a-z, but no accents, etc) to
  1216. * uppercase. It is safe for all supported character sets (incl. utf-8).
  1217. * Unlike strtoupper() it does not honour the locale.
  1218. *
  1219. * @param string $str Input string
  1220. * @return string Uppercase String
  1221. */
  1222. public static function strtoupper($str) {
  1223. return strtr((string) $str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  1224. }
  1225. /**
  1226. * Converts string to lowercase
  1227. * The function converts all Latin characters (A-Z, but no accents, etc) to
  1228. * lowercase. It is safe for all supported character sets (incl. utf-8).
  1229. * Unlike strtolower() it does not honour the locale.
  1230. *
  1231. * @param string $str Input string
  1232. * @return string Lowercase String
  1233. */
  1234. public static function strtolower($str) {
  1235. return strtr((string) $str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
  1236. }
  1237. /**
  1238. * Returns a string of highly randomized bytes (over the full 8-bit range).
  1239. *
  1240. * Note: Returned values are not guaranteed to be crypto-safe,
  1241. * most likely they are not, depending on the used retrieval method.
  1242. *
  1243. * @param integer $bytesToReturn Number of characters (bytes) to return
  1244. * @return string Random Bytes
  1245. * @see http://bugs.php.net/bug.php?id=52523
  1246. * @see http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/index.html
  1247. */
  1248. public static function generateRandomBytes($bytesToReturn) {
  1249. // Cache 4k of the generated bytestream.
  1250. static $bytes = '';
  1251. $bytesToGenerate = max(4096, $bytesToReturn);
  1252. // if we have not enough random bytes cached, we generate new ones
  1253. if (!isset($bytes{$bytesToReturn - 1})) {
  1254. if (TYPO3_OS === 'WIN') {
  1255. // Openssl seems to be deadly slow on Windows, so try to use mcrypt
  1256. // Windows PHP versions have a bug when using urandom source (see #24410)
  1257. $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_RAND);
  1258. } else {
  1259. // Try to use native PHP functions first, precedence has openssl
  1260. $bytes .= self::generateRandomBytesOpenSsl($bytesToGenerate);
  1261. if (!isset($bytes{$bytesToReturn - 1})) {
  1262. $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_DEV_URANDOM);
  1263. }
  1264. // If openssl and mcrypt failed, try /dev/urandom
  1265. if (!isset($bytes{$bytesToReturn - 1})) {
  1266. $bytes .= self::generateRandomBytesUrandom($bytesToGenerate);
  1267. }
  1268. }
  1269. // Fall back if other random byte generation failed until now
  1270. if (!isset($bytes{$bytesToReturn - 1})) {
  1271. $bytes .= self::generateRandomBytesFallback($bytesToReturn);
  1272. }
  1273. }
  1274. // get first $bytesToReturn and remove it from the byte cache
  1275. $output = substr($bytes, 0, $bytesToReturn);
  1276. $bytes = substr($bytes, $bytesToReturn);
  1277. return $output;
  1278. }
  1279. /**
  1280. * Generate random bytes using openssl if available
  1281. *
  1282. * @param string $bytesToGenerate
  1283. * @return string
  1284. */
  1285. protected static function generateRandomBytesOpenSsl($bytesToGenerate) {
  1286. if (!function_exists('openssl_random_pseudo_bytes')) {
  1287. return '';
  1288. }
  1289. $isStrong = NULL;
  1290. return (string) openssl_random_pseudo_bytes($bytesToGenerate, $isStrong);
  1291. }
  1292. /**
  1293. * Generate random bytes using mcrypt if available
  1294. *
  1295. * @param $bytesToGenerate
  1296. * @param $randomSource
  1297. * @return string
  1298. */
  1299. protected static function generateRandomBytesMcrypt($bytesToGenerate, $randomSource) {
  1300. if (!function_exists('mcrypt_create_iv')) {
  1301. return '';
  1302. }
  1303. return (string) @mcrypt_create_iv($bytesToGenerate, $randomSource);
  1304. }
  1305. /**
  1306. * Read random bytes from /dev/urandom if it is accessible
  1307. *
  1308. * @param $bytesToGenerate
  1309. * @return string
  1310. */
  1311. protected static function generateRandomBytesUrandom($bytesToGenerate) {
  1312. $bytes = '';
  1313. $fh = @fopen('/dev/urandom', 'rb');
  1314. if ($fh) {
  1315. // PHP only performs buffered reads, so in reality it will always read
  1316. // at least 4096 bytes. Thus, it costs nothing extra to read and store
  1317. // that much so as to speed any additional invocations.
  1318. $bytes = fread($fh, $bytesToGenerate);
  1319. fclose($fh);
  1320. }
  1321. return $bytes;
  1322. }
  1323. /**
  1324. * Generate pseudo random bytes as last resort
  1325. *
  1326. * @param $bytesToReturn
  1327. * @return string
  1328. */
  1329. protected static function generateRandomBytesFallback($bytesToReturn) {
  1330. $bytes = '';
  1331. // We initialize with somewhat random.
  1332. $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() % pow(10, 6), 10, 2) . microtime() . uniqid('') . getmypid();
  1333. while (!isset($bytes{$bytesToReturn - 1})) {
  1334. $randomState = sha1(microtime() . mt_rand() . $randomState);
  1335. $bytes .= sha1(mt_rand() . $randomState, TRUE);
  1336. }
  1337. return $bytes;
  1338. }
  1339. /**
  1340. * Returns a hex representation of a random byte string.
  1341. *
  1342. * @param integer $count Number of hex characters to return
  1343. * @return string Random Bytes
  1344. */
  1345. public static function getRandomHexString($count) {
  1346. return substr(bin2hex(self::generateRandomBytes(intval(($count + 1) / 2))), 0, $count);
  1347. }
  1348. /**
  1349. * Returns a given string with underscores as UpperCamelCase.
  1350. * Example: Converts blog_example to BlogExample
  1351. *
  1352. * @param string $string: String to be converted to camel case
  1353. * @return string UpperCamelCasedWord
  1354. */
  1355. public static function underscoredToUpperCamelCase($string) {
  1356. $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
  1357. return $upperCamelCase;
  1358. }
  1359. /**
  1360. * Returns a given string with underscores as lowerCamelCase.
  1361. * Example: Converts minimal_value to minimalValue
  1362. *
  1363. * @param string $string: String to be converted to camel case
  1364. * @return string lowerCamelCasedWord
  1365. */
  1366. public static function underscoredToLowerCamelCase($string) {
  1367. $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
  1368. $lowerCamelCase = self::lcfirst($upperCamelCase);
  1369. return $lowerCamelCase;
  1370. }
  1371. /**
  1372. * Returns a given CamelCasedString as an lowercase string with underscores.
  1373. * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
  1374. *
  1375. * @param string $string String to be converted to lowercase underscore
  1376. * @return string lowercase_and_underscored_string
  1377. */
  1378. public static function camelCaseToLowerCaseUnderscored($string) {
  1379. return self::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
  1380. }
  1381. /**
  1382. * Converts the first char of a string to lowercase if it is a latin character (A-Z).
  1383. * Example: Converts "Hello World" to "hello World"
  1384. *
  1385. * @param string $string The string to be used to lowercase the first character
  1386. * @return string The string with the first character as lowercase
  1387. */
  1388. public static function lcfirst($string) {
  1389. return self::strtolower(substr($string, 0, 1)) . substr($string, 1);
  1390. }
  1391. /**
  1392. * Checks if a given string is a Uniform Resource Locator (URL).
  1393. *
  1394. * @param string $url The URL to be validated
  1395. * @return boolean Whether the given URL is valid
  1396. */
  1397. public static function isValidUrl($url) {
  1398. return (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== FALSE);
  1399. }
  1400. /*************************
  1401. *
  1402. * ARRAY FUNCTIONS
  1403. *
  1404. *************************/
  1405. /**
  1406. * Check if an string item exists in an array.
  1407. * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
  1408. *
  1409. * Comparison to PHP in_array():
  1410. * -> $array = array(0, 1, 2, 3);
  1411. * -> variant_a := t3lib_div::inArray($array, $needle)
  1412. * -> variant_b := in_array($needle, $array)
  1413. * -> variant_c := in_array($needle, $array, TRUE)
  1414. * +---------+-----------+-----------+-----------+
  1415. * | $needle | variant_a | variant_b | variant_c |
  1416. * +---------+-----------+-----------+-----------+
  1417. * | '1a' | FALSE | TRUE | FALSE |
  1418. * | '' | FALSE | TRUE | FALSE |
  1419. * | '0' | TRUE | TRUE | FALSE |
  1420. * | 0 | TRUE | TRUE | TRUE |
  1421. * +---------+-----------+-----------+-----------+
  1422. *
  1423. * @param array $in_array one-dimensional array of items
  1424. * @param string $item item to check for
  1425. * @return boolean TRUE if $item is in the one-dimensional array $in_array
  1426. */
  1427. public static function inArray(array $in_array, $item) {
  1428. foreach ($in_array as $val) {
  1429. if (!is_array($val) && !strcmp($val, $item)) {
  1430. return TRUE;
  1431. }
  1432. }
  1433. return FALSE;
  1434. }
  1435. /**
  1436. * Explodes a $string delimited by $delim and passes each item in the array through intval().
  1437. * Corresponds to t3lib_div::trimExplode(), but with conversion to integers for all values.
  1438. *
  1439. * @param string $delimiter Delimiter string to explode with
  1440. * @param string $string The string to explode
  1441. * @param boolean $onlyNonEmptyValues If set, all empty values (='') will NOT be set in output
  1442. * @param integer $limit If positive, the result will contain a maximum of limit elements,
  1443. * if negative, all components except the last -limit are returned,
  1444. * if zero (default), the result is not limited at all
  1445. * @return array Exploded values, all converted to integers
  1446. */
  1447. public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
  1448. $explodedValues = self::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
  1449. return array_map('intval', $explodedValues);
  1450. }
  1451. /**
  1452. * Reverse explode which explodes the string counting from behind.
  1453. * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
  1454. *
  1455. * @param string $delimiter Delimiter string to explode with
  1456. * @param string $string The string to explode
  1457. * @param integer $count Number of array entries
  1458. * @return array Exploded values
  1459. */
  1460. public static function revExplode($delimiter, $string, $count = 0) {
  1461. $explodedValues = explode($delimiter, strrev($string), $count);
  1462. $explodedValues = array_map('strrev', $explodedValues);
  1463. return array_reverse($explodedValues);
  1464. }
  1465. /**
  1466. * Explodes a string and trims all values for whitespace in the ends.
  1467. * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
  1468. *
  1469. * @param string $delim Delimiter string to explode with
  1470. * @param string $string The string to explode
  1471. * @param boolean $removeEmptyValues If set, all empty values will be removed in output
  1472. * @param integer $limit If positive, the result will contain a maximum of
  1473. * $limit elements, if negative, all components except
  1474. * the last -$limit are returned, if zero (default),
  1475. * the result is not limited at all. Attention though
  1476. * that the use of this parameter can slow down this
  1477. * function.
  1478. * @return array Exploded values
  1479. */
  1480. public static function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
  1481. $explodedValues = explode($delim, $string);
  1482. $result = array_map('trim', $explodedValues);
  1483. if ($removeEmptyValues) {
  1484. $temp = array();
  1485. foreach ($result as $value) {
  1486. if ($value !== '') {
  1487. $temp[] = $value;
  1488. }
  1489. }
  1490. $result = $temp;
  1491. }
  1492. if ($limit != 0) {
  1493. if ($limit < 0) {
  1494. $result = array_slice($result, 0, $limit);
  1495. } elseif (count($result) > $limit) {
  1496. $lastElements = array_slice($result, $limit - 1);
  1497. $result = array_slice($result, 0, $limit - 1);
  1498. $result[] = implode($delim, $lastElements);
  1499. }
  1500. }
  1501. return $result;
  1502. }
  1503. /**
  1504. * Removes the value $cmpValue from the $array if found there. Returns the modified array
  1505. *
  1506. * @param array $array Array containing the values
  1507. * @param string $cmpValue Value to search for and if found remove array entry where found.
  1508. * @return array Output array with entries removed if search string is found
  1509. */
  1510. public static function removeArrayEntryByValue(array $array, $cmpValue) {
  1511. foreach ($array as $k => $v) {
  1512. if (is_array($v)) {
  1513. $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
  1514. } elseif (!strcmp($v, $cmpValue)) {
  1515. unset($array[$k]);
  1516. }
  1517. }
  1518. return $array;
  1519. }
  1520. /**
  1521. * Filters an array to reduce its elements to match the condition.
  1522. * The values in $keepItems can be optionally evaluated by a custom callback function.
  1523. *
  1524. * Example (arguments used to call this function):
  1525. * $array = array(
  1526. * array('aa' => array('first', 'second'),
  1527. * array('bb' => array('third', 'fourth'),
  1528. * array('cc' => array('fifth', 'sixth'),
  1529. * );
  1530. * $keepItems = array('third');
  1531. * $getValueFunc = create_function('$value', 'return $value[0];');
  1532. *
  1533. * Returns:
  1534. * array(
  1535. * array('bb' => array('third', 'fourth'),
  1536. * )
  1537. *
  1538. * @param array $array: The initial array to be filtered/reduced
  1539. * @param mixed $keepItems: The items which are allowed/kept in the array - accepts array or csv string
  1540. * @param string $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
  1541. * @return array The filtered/reduced array with the kept items
  1542. */
  1543. public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
  1544. if ($array) {
  1545. // Convert strings to arrays:
  1546. if (is_string($keepItems)) {
  1547. $keepItems = self::trimExplode(',', $keepItems);
  1548. }
  1549. // create_function() returns a string:
  1550. if (!is_string($getValueFunc)) {
  1551. $getValueFunc = NULL;
  1552. }
  1553. // Do the filtering:
  1554. if (is_array($keepItems) && count($keepItems)) {
  1555. foreach ($array as $key => $value) {
  1556. // Get the value to compare by using the callback function:
  1557. $keepValue = (isset($getValueFunc) ? $getValueFunc($value) : $value);
  1558. if (!in_array($keepValue, $keepItems)) {
  1559. unset($array[$key]);
  1560. }
  1561. }
  1562. }
  1563. }
  1564. return $array;
  1565. }
  1566. /**
  1567. * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
  1568. *
  1569. * @param string $name Name prefix for entries. Set to blank if you wish none.
  1570. * @param array $theArray The (multidimensional) array to implode
  1571. * @param string $str (keep blank)
  1572. * @param boolean $skipBlank If set, parameters which were blank strings would be removed.
  1573. * @param boolean $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
  1574. * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
  1575. * @see explodeUrl2Array()
  1576. */
  1577. public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
  1578. foreach ($theArray as $Akey => $AVal) {
  1579. $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
  1580. if (is_array($AVal)) {
  1581. $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
  1582. } else {
  1583. if (!$skipBlank || strcmp($AVal, '')) {
  1584. $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) .
  1585. '=' . rawurlencode($AVal);
  1586. }
  1587. }
  1588. }
  1589. return $str;
  1590. }
  1591. /**
  1592. * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
  1593. *
  1594. * @param string $string GETvars string
  1595. * @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())
  1596. * @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!
  1597. * @see implodeArrayForUrl()
  1598. */
  1599. public static function explodeUrl2Array($string, $multidim = FALSE) {
  1600. $output = array();
  1601. if ($multidim) {
  1602. parse_str($string, $output);
  1603. } else {
  1604. $p = explode('&', $string);
  1605. foreach ($p as $v) {
  1606. if (strlen($v)) {
  1607. list($pK, $pV) = explode('=', $v, 2);
  1608. $output[rawurldecode($pK)] = rawurldecode($pV);
  1609. }
  1610. }
  1611. }
  1612. return $output;
  1613. }
  1614. /**
  1615. * Returns an array with selected keys from incoming data.
  1616. * (Better read source code if you want to find out...)
  1617. *
  1618. * @param string $varList List of variable/key names
  1619. * @param array $getArray Array from where to get values based on the keys in $varList
  1620. * @param boolean $GPvarAlt If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
  1621. * @return array Output array with selected variables.
  1622. */
  1623. public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = TRUE) {
  1624. $keys = self::trimExplode(',', $varList, 1);
  1625. $outArr = array();
  1626. foreach ($keys as $v) {
  1627. if (isset($getArray[$v])) {
  1628. $outArr[$v] = $getArray[$v];
  1629. } elseif ($GPvarAlt) {
  1630. $outArr[$v] = self::_GP($v);
  1631. }
  1632. }
  1633. return $outArr;
  1634. }
  1635. /**
  1636. * AddSlash array
  1637. * This function traverses a multidimensional array and adds slashes to the values.
  1638. * NOTE that the input array is and argument by reference.!!
  1639. * Twin-function to stripSlashesOnArray
  1640. *
  1641. * @param array $theArray Multidimensional input array, (REFERENCE!)
  1642. * @return array
  1643. */
  1644. public static function addSlashesOnArray(array &$theArray) {
  1645. foreach ($theArray as &$value) {
  1646. if (is_array($value)) {
  1647. self::addSlashesOnArray($value);
  1648. } else {
  1649. $value = addslashes($value);
  1650. }
  1651. }
  1652. unset($value);
  1653. reset($theArray);
  1654. }
  1655. /**
  1656. * StripSlash array
  1657. * This function traverses a multidimensional array and strips slashes to the values.
  1658. * NOTE that the input array is and argument by reference.!!
  1659. * Twin-function to addSlashesOnArray
  1660. *
  1661. * @param array $theArray Multidimensional input array, (REFERENCE!)
  1662. * @return array
  1663. */
  1664. public static function stripSlashesOnArray(array &$theArray) {
  1665. foreach ($theArray as &$value) {
  1666. if (is_array($value)) {
  1667. self::stripSlashesOnArray($value);
  1668. } else {
  1669. $value = stripslashes($value);
  1670. }
  1671. }
  1672. unset($value);
  1673. reset($theArray);
  1674. }
  1675. /**
  1676. * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
  1677. *
  1678. * @param array $arr Multidimensional input array
  1679. * @param string $cmd "add" or "strip", depending on usage you wish.
  1680. * @return array
  1681. */
  1682. public static function slashArray(array $arr, $cmd) {
  1683. if ($cmd == 'strip') {
  1684. self::stripSlashesOnArray($arr);
  1685. }
  1686. if ($cmd == 'add') {
  1687. self::addSlashesOnArray($arr);
  1688. }
  1689. return $arr;
  1690. }
  1691. /**
  1692. * Rename Array keys with a given mapping table
  1693. *
  1694. * @param array $array Array by reference which should be remapped
  1695. * @param array $mappingTable Array with remap information, array/$oldKey => $newKey)
  1696. */
  1697. public static function remapArrayKeys(&$array, $mappingTable) {
  1698. if (is_array($mappingTable)) {
  1699. foreach ($mappingTable as $old => $new) {
  1700. if ($new && isset($array[$old])) {
  1701. $array[$new] = $array[$old];
  1702. unset ($array[$old]);
  1703. }
  1704. }
  1705. }
  1706. }
  1707. /**
  1708. * Merges two arrays recursively and "binary safe" (integer keys are
  1709. * overridden as well), overruling similar values in the first array
  1710. * ($arr0) with the values of the second array ($arr1)
  1711. * In case of identical keys, ie. keeping the values of the second.
  1712. *
  1713. * @param array $arr0 First array
  1714. * @param array $arr1 Second array, overruling the first array
  1715. * @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.
  1716. * @param boolean $includeEmptyValues If set, values from $arr1 will overrule if they are empty or zero. Default: TRUE
  1717. * @return array Resulting array where $arr1 values has overruled $arr0 values
  1718. */
  1719. public static function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = FALSE, $includeEmptyValues = TRUE) {
  1720. foreach ($arr1 as $key => $val) {
  1721. if (is_array($arr0[$key])) {
  1722. if (is_array($arr1[$key])) {
  1723. $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key], $arr1[$key], $notAddKeys, $includeEmptyValues);
  1724. }
  1725. } else {
  1726. if ($notAddKeys) {
  1727. if (isset($arr0[$key])) {
  1728. if ($includeEmptyValues || $val) {
  1729. $arr0[$key] = $val;
  1730. }
  1731. }
  1732. } else {
  1733. if ($includeEmptyValues || $val) {
  1734. $arr0[$key] = $val;
  1735. }
  1736. }
  1737. }
  1738. }
  1739. reset($arr0);
  1740. return $arr0;
  1741. }
  1742. /**
  1743. * 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.
  1744. *
  1745. * @param array $arr1 First array
  1746. * @param array $arr2 Second array
  1747. * @return array Merged result.
  1748. */
  1749. public static function array_merge(array $arr1, array $arr2) {
  1750. return $arr2 + $arr1;
  1751. }
  1752. /**
  1753. * Filters keys off from first array that also exist in second array. Comparison is done by keys.
  1754. * This method is a recursive version of php array_diff_assoc()
  1755. *
  1756. * @param array $array1 Source array
  1757. * @param array $array2 Reduce source array by this array
  1758. * @return array Source array reduced by keys also present in second array
  1759. */
  1760. public static function arrayDiffAssocRecursive(array $array1, array $array2) {
  1761. $differenceArray = array();
  1762. foreach ($array1 as $key => $value) {
  1763. if (!array_key_exists($key, $array2)) {
  1764. $differenceArray[$key] = $value;
  1765. } elseif (is_array($value)) {
  1766. if (is_array($array2[$key])) {
  1767. $differenceArray[$key] = self::arrayDiffAssocRecursive($value, $array2[$key]);
  1768. }
  1769. }
  1770. }
  1771. return $differenceArray;
  1772. }
  1773. /**
  1774. * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
  1775. *
  1776. * @param array $row Input array of values
  1777. * @param string $delim Delimited, default is comma
  1778. * @param string $quote Quote-character to wrap around the values.
  1779. * @return string A single line of CSV
  1780. */
  1781. public static function csvValues(array $row, $delim = ',', $quote = '"') {
  1782. $out = array();
  1783. foreach ($row as $value) {
  1784. $out[] = str_replace($quote, $quote . $quote, $value);
  1785. }
  1786. $str = $quote . implode($quote . $delim . $quote, $out) . $quote;
  1787. return $str;
  1788. }
  1789. /**
  1790. * Removes dots "." from end of a key identifier of TypoScript styled array.
  1791. * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
  1792. *
  1793. * @param array $ts: TypoScript configuration array
  1794. * @return array TypoScript configuration array without dots at the end of all keys
  1795. */
  1796. public static function removeDotsFromTS(array $ts) {
  1797. $out = array();
  1798. foreach ($ts as $key => $value) {
  1799. if (is_array($value)) {
  1800. $key = rtrim($key, '.');
  1801. $out[$key] = self::removeDotsFromTS($value);
  1802. } else {
  1803. $out[$key] = $value;
  1804. }
  1805. }
  1806. return $out;
  1807. }
  1808. /**
  1809. * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
  1810. *
  1811. * @param array $array array to be sorted recursively, passed by reference
  1812. * @return boolean TRUE if param is an array
  1813. */
  1814. public static function naturalKeySortRecursive(&$array) {
  1815. if (!is_array($array)) {
  1816. return FALSE;
  1817. }
  1818. uksort($array, 'strnatcasecmp');
  1819. foreach ($array as $key => $value) {
  1820. self::naturalKeySortRecursive($array[$key]);
  1821. }
  1822. return TRUE;
  1823. }
  1824. /*************************
  1825. *
  1826. * HTML/XML PROCESSING
  1827. *
  1828. *************************/
  1829. /**
  1830. * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
  1831. * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
  1832. * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
  1833. *
  1834. * @param string $tag HTML-tag string (or attributes only)
  1835. * @return array Array with the attribute values.
  1836. */
  1837. public static function get_tag_attributes($tag) {
  1838. $components = self::split_tag_attributes($tag);
  1839. $name = ''; // attribute name is stored here
  1840. $valuemode = FALSE;
  1841. $attributes = array();
  1842. foreach ($components as $key => $val) {
  1843. 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
  1844. if ($valuemode) {
  1845. if ($name) {
  1846. $attributes[$name] = $val;
  1847. $name = '';
  1848. }
  1849. } else {
  1850. if ($key = strtolower(preg_replace('/[^[:alnum:]_\:\-]/', '', $val))) {
  1851. $attributes[$key] = '';
  1852. $name = $key;
  1853. }
  1854. }
  1855. $valuemode = FALSE;
  1856. } else {
  1857. $valuemode = TRUE;
  1858. }
  1859. }
  1860. return $attributes;
  1861. }
  1862. /**
  1863. * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
  1864. * Removes tag-name if found
  1865. *
  1866. * @param string $tag HTML-tag string (or attributes only)
  1867. * @return array Array with the attribute values.
  1868. */
  1869. public static function split_tag_attributes($tag) {
  1870. $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
  1871. // Removes any > in the end of the string
  1872. $tag_tmp = trim(rtrim($tag_tmp, '>'));
  1873. $value = array();
  1874. while (strcmp($tag_tmp, '')) { // Compared with empty string instead , 030102
  1875. $firstChar = substr($tag_tmp, 0, 1);
  1876. if (!strcmp($firstChar, '"') || !strcmp($firstChar, "'")) {
  1877. $reg = explode($firstChar, $tag_tmp, 3);
  1878. $value[] = $reg[1];
  1879. $tag_tmp = trim($reg[2]);
  1880. } elseif (!strcmp($firstChar, '=')) {
  1881. $value[] = '=';
  1882. $tag_tmp = trim(substr($tag_tmp, 1)); // Removes = chars.
  1883. } else {
  1884. // There are '' around the value. We look for the next ' ' or '>'
  1885. $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
  1886. $value[] = trim($reg[0]);
  1887. $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
  1888. }
  1889. }
  1890. reset($value);
  1891. return $value;
  1892. }
  1893. /**
  1894. * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
  1895. *
  1896. * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
  1897. * @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!
  1898. * @param boolean $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
  1899. * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
  1900. */
  1901. public static function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
  1902. if ($xhtmlSafe) {
  1903. $newArr = array();
  1904. foreach ($arr as $p => $v) {
  1905. if (!isset($newArr[strtolower($p)])) {
  1906. $newArr[strtolower($p)] = htmlspecialchars($v);
  1907. }
  1908. }
  1909. $arr = $newArr;
  1910. }
  1911. $list = array();
  1912. foreach ($arr as $p => $v) {
  1913. if (strcmp($v, '') || $dontOmitBlankAttribs) {
  1914. $list[] = $p . '="' . $v . '"';
  1915. }
  1916. }
  1917. return implode(' ', $list);
  1918. }
  1919. /**
  1920. * Wraps JavaScript code XHTML ready with <script>-tags
  1921. * Automatic re-indenting of the JS code is done by using the first line as indent reference.
  1922. * This is nice for indenting JS code with PHP code on the same level.
  1923. *
  1924. * @param string $string JavaScript code
  1925. * @param boolean $linebreak Wrap script element in line breaks? Default is TRUE.
  1926. * @return string The wrapped JS code, ready to put into a XHTML page
  1927. */
  1928. public static function wrapJS($string, $linebreak = TRUE) {
  1929. if (trim($string)) {
  1930. // <script wrapped in nl?
  1931. $cr = $linebreak ? LF : '';
  1932. // remove nl from the beginning
  1933. $string = preg_replace('/^\n+/', '', $string);
  1934. // re-ident to one tab using the first line as reference
  1935. $match = array();
  1936. if (preg_match('/^(\t+)/', $string, $match)) {
  1937. $string = str_replace($match[1], TAB, $string);
  1938. }
  1939. $string = $cr . '<script type="text/javascript">
  1940. /*<![CDATA[*/
  1941. ' . $string . '
  1942. /*]]>*/
  1943. </script>' . $cr;
  1944. }
  1945. return trim($string);
  1946. }
  1947. /**
  1948. * Parses XML input into a PHP array with associative keys
  1949. *
  1950. * @param string $string XML data input
  1951. * @param integer $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
  1952. * @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.
  1953. * @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
  1954. */
  1955. public static function xml2tree($string, $depth = 999) {
  1956. $parser = xml_parser_create();
  1957. $vals = array();
  1958. $index = array();
  1959. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  1960. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  1961. xml_parse_into_struct($parser, $string, $vals, $index);
  1962. if (xml_get_error_code($parser)) {
  1963. return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
  1964. }
  1965. xml_parser_free($parser);
  1966. $stack = array(array());
  1967. $stacktop = 0;
  1968. $startPoint = 0;
  1969. $tagi = array();
  1970. foreach ($vals as $key => $val) {
  1971. $type = $val['type'];
  1972. // open tag:
  1973. if ($type == 'open' || $type == 'complete') {
  1974. $stack[$stacktop++] = $tagi;
  1975. if ($depth == $stacktop) {
  1976. $startPoint = $key;
  1977. }
  1978. $tagi = array('tag' => $val['tag']);
  1979. if (isset($val['attributes'])) {
  1980. $tagi['attrs'] = $val['attributes'];
  1981. }
  1982. if (isset($val['value'])) {
  1983. $tagi['values'][] = $val['value'];
  1984. }
  1985. }
  1986. // finish tag:
  1987. if ($type == 'complete' || $type == 'close') {
  1988. $oldtagi = $tagi;
  1989. $tagi = $stack[--$stacktop];
  1990. $oldtag = $oldtagi['tag'];
  1991. unset($oldtagi['tag']);
  1992. if ($depth == ($stacktop + 1)) {
  1993. if ($key - $startPoint > 0) {
  1994. $partArray = array_slice(
  1995. $vals,
  1996. $startPoint + 1,
  1997. $key - $startPoint - 1
  1998. );
  1999. $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
  2000. } else {
  2001. $oldtagi['XMLvalue'] = $oldtagi['values'][0];
  2002. }
  2003. }
  2004. $tagi['ch'][$oldtag][] = $oldtagi;
  2005. unset($oldtagi);
  2006. }
  2007. // cdata
  2008. if ($type == 'cdata') {
  2009. $tagi['values'][] = $val['value'];
  2010. }
  2011. }
  2012. return $tagi['ch'];
  2013. }
  2014. /**
  2015. * Turns PHP array into XML. See array2xml()
  2016. *
  2017. * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
  2018. * @param string $docTag Alternative document tag. Default is "phparray".
  2019. * @param array $options Options for the compilation. See array2xml() for description.
  2020. * @param string $charset Forced charset to prologue
  2021. * @return string An XML string made from the input content in the array.
  2022. * @see xml2array(),array2xml()
  2023. */
  2024. public static function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
  2025. // Figure out charset if not given explicitly:
  2026. if (!$charset) {
  2027. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
  2028. $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
  2029. } elseif (is_object($GLOBALS['LANG'])) {
  2030. $charset = $GLOBALS['LANG']->charSet; // If "LANG" is around, that will hold the current charset
  2031. } else {
  2032. $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
  2033. }
  2034. }
  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] : ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'iso-8859-1');
  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!', 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] = $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. * DEBUG helper FUNCTIONS
  3061. *
  3062. *************************/
  3063. /* Deprecated since 4.5, use t3lib_utility_Debug */
  3064. /**
  3065. * Returns a string with a list of ascii-values for the first $characters characters in $string
  3066. *
  3067. * @param string $string String to show ASCII value for
  3068. * @param integer $characters Number of characters to show
  3069. * @return string The string with ASCII values in separated by a space char.
  3070. * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::ordinalValue instead
  3071. */
  3072. public static function debug_ordvalue($string, $characters = 100) {
  3073. self::logDeprecatedFunction();
  3074. return t3lib_utility_Debug::ordinalValue($string, $characters);
  3075. }
  3076. /**
  3077. * Returns HTML-code, which is a visual representation of a multidimensional array
  3078. * use t3lib_div::print_array() in order to print an array
  3079. * Returns FALSE if $array_in is not an array
  3080. *
  3081. * @param mixed $array_in Array to view
  3082. * @return string HTML output
  3083. * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::viewArray instead
  3084. */
  3085. public static function view_array($array_in) {
  3086. self::logDeprecatedFunction();
  3087. return t3lib_utility_Debug::viewArray($array_in);
  3088. }
  3089. /**
  3090. * Prints an array
  3091. *
  3092. * @param mixed $array_in Array to print visually (in a table).
  3093. * @return void
  3094. * @see view_array()
  3095. * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::printArray instead
  3096. */
  3097. public static function print_array($array_in) {
  3098. self::logDeprecatedFunction();
  3099. t3lib_utility_Debug::printArray($array_in);
  3100. }
  3101. /**
  3102. * Makes debug output
  3103. * Prints $var in bold between two vertical lines
  3104. * If not $var the word 'debug' is printed
  3105. * If $var is an array, the array is printed by t3lib_div::print_array()
  3106. *
  3107. * @param mixed $var Variable to print
  3108. * @param string $header The header.
  3109. * @param string $group Group for the debug console
  3110. * @return void
  3111. * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debug instead
  3112. */
  3113. public static function debug($var = '', $header = '', $group = 'Debug') {
  3114. self::logDeprecatedFunction();
  3115. t3lib_utility_Debug::debug($var, $header, $group);
  3116. }
  3117. /**
  3118. * Displays the "path" of the function call stack in a string, using debug_backtrace
  3119. *
  3120. * @return string
  3121. * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debugTrail instead
  3122. */
  3123. public static function debug_trail() {
  3124. self::logDeprecatedFunction();
  3125. return t3lib_utility_Debug::debugTrail();
  3126. }
  3127. /**
  3128. * Displays an array as rows in a table. Useful to debug output like an array of database records.
  3129. *
  3130. * @param mixed $rows Array of arrays with similar keys
  3131. * @param string $header Table header
  3132. * @param boolean $returnHTML If TRUE, will return content instead of echo'ing out.
  3133. * @return mixed Outputs to browser or returns an HTML string if $returnHTML is TRUE
  3134. * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debugRows instead
  3135. */
  3136. public static function debugRows($rows, $header = '', $returnHTML = FALSE) {
  3137. self::logDeprecatedFunction();
  3138. return t3lib_utility_Debug::debugRows($rows, $header, $returnHTML);
  3139. }
  3140. /*************************
  3141. *
  3142. * SYSTEM INFORMATION
  3143. *
  3144. *************************/
  3145. /**
  3146. * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
  3147. *
  3148. * @return string
  3149. */
  3150. public static function getThisUrl() {
  3151. $p = parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
  3152. $dir = self::dirname($p['path']) . '/'; // Strip file
  3153. $url = str_replace('//', '/', $p['host'] . ($p['port'] ? ':' . $p['port'] : '') . $dir);
  3154. return $url;
  3155. }
  3156. /**
  3157. * Returns the link-url to the current script.
  3158. * 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.
  3159. * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
  3160. *
  3161. * @param array $getParams Array of GET parameters to include
  3162. * @return string
  3163. */
  3164. public static function linkThisScript(array $getParams = array()) {
  3165. $parts = self::getIndpEnv('SCRIPT_NAME');
  3166. $params = self::_GET();
  3167. foreach ($getParams as $key => $value) {
  3168. if ($value !== '') {
  3169. $params[$key] = $value;
  3170. } else {
  3171. unset($params[$key]);
  3172. }
  3173. }
  3174. $pString = self::implodeArrayForUrl('', $params);
  3175. return $pString ? $parts . '?' . preg_replace('/^&/', '', $pString) : $parts;
  3176. }
  3177. /**
  3178. * 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.
  3179. * So basically it adds the parameters in $getParams to an existing URL, $url
  3180. *
  3181. * @param string $url URL string
  3182. * @param array $getParams Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
  3183. * @return string Output URL with added getParams.
  3184. */
  3185. public static function linkThisUrl($url, array $getParams = array()) {
  3186. $parts = parse_url($url);
  3187. $getP = array();
  3188. if ($parts['query']) {
  3189. parse_str($parts['query'], $getP);
  3190. }
  3191. $getP = self::array_merge_recursive_overrule($getP, $getParams);
  3192. $uP = explode('?', $url);
  3193. $params = self::implodeArrayForUrl('', $getP);
  3194. $outurl = $uP[0] . ($params ? '?' . substr($params, 1) : '');
  3195. return $outurl;
  3196. }
  3197. /**
  3198. * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
  3199. * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
  3200. *
  3201. * @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
  3202. * @return string Value based on the input key, independent of server/os environment.
  3203. */
  3204. public static function getIndpEnv($getEnvName) {
  3205. /*
  3206. Conventions:
  3207. output from parse_url():
  3208. 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
  3209. [scheme] => 'http'
  3210. [user] => 'username'
  3211. [pass] => 'password'
  3212. [host] => '192.168.1.4'
  3213. [port] => '8080'
  3214. [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
  3215. [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
  3216. [fragment] => 'link1'
  3217. Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
  3218. [path_dir] = '/typo3/32/temp/phpcheck/'
  3219. [path_info] = '/arg1/arg2/arg3/'
  3220. [path] = [path_script/path_dir][path_info]
  3221. Keys supported:
  3222. URI______:
  3223. REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
  3224. HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
  3225. 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')!
  3226. PATH_INFO = [path_info] = /arg1/arg2/arg3/
  3227. QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
  3228. 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
  3229. (Notice: NO username/password + NO fragment)
  3230. CLIENT____:
  3231. REMOTE_ADDR = (client IP)
  3232. REMOTE_HOST = (client host)
  3233. HTTP_USER_AGENT = (client user agent)
  3234. HTTP_ACCEPT_LANGUAGE = (client accept language)
  3235. SERVER____:
  3236. SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
  3237. Special extras:
  3238. TYPO3_HOST_ONLY = [host] = 192.168.1.4
  3239. TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
  3240. TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
  3241. TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
  3242. TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
  3243. TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
  3244. TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
  3245. TYPO3_SITE_PATH = [path_dir] of the TYPO3 website frontend
  3246. TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
  3247. TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
  3248. TYPO3_SSL = Returns TRUE if this session uses SSL/TLS (https)
  3249. TYPO3_PROXY = Returns TRUE if this session runs over a well known proxy
  3250. Notice: [fragment] is apparently NEVER available to the script!
  3251. Testing suggestions:
  3252. - Output all the values.
  3253. - 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
  3254. - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
  3255. */
  3256. $retVal = '';
  3257. switch ((string) $getEnvName) {
  3258. case 'SCRIPT_NAME':
  3259. $retVal = (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'cgi-fcgi') &&
  3260. ($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) ?
  3261. ($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) :
  3262. ($_SERVER['ORIG_SCRIPT_NAME'] ? $_SERVER['ORIG_SCRIPT_NAME'] : $_SERVER['SCRIPT_NAME']);
  3263. // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
  3264. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3265. if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
  3266. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
  3267. } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
  3268. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
  3269. }
  3270. }
  3271. break;
  3272. case 'SCRIPT_FILENAME':
  3273. $retVal = str_replace('//', '/', str_replace('\\', '/',
  3274. (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
  3275. ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
  3276. ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
  3277. ($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME'])));
  3278. break;
  3279. case 'REQUEST_URI':
  3280. // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
  3281. 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)
  3282. list($v, $n) = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
  3283. $retVal = $GLOBALS[$v][$n];
  3284. } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
  3285. $retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') .
  3286. ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
  3287. } else {
  3288. $retVal = $_SERVER['REQUEST_URI'];
  3289. }
  3290. // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
  3291. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3292. if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
  3293. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
  3294. } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
  3295. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
  3296. }
  3297. }
  3298. break;
  3299. case 'PATH_INFO':
  3300. // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
  3301. // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
  3302. // 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)
  3303. // if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
  3304. if (PHP_SAPI != 'cgi' && PHP_SAPI != 'cgi-fcgi' && PHP_SAPI != 'fpm-fcgi') {
  3305. $retVal = $_SERVER['PATH_INFO'];
  3306. }
  3307. break;
  3308. case 'TYPO3_REV_PROXY':
  3309. $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
  3310. break;
  3311. case 'REMOTE_ADDR':
  3312. $retVal = $_SERVER['REMOTE_ADDR'];
  3313. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3314. $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  3315. // choose which IP in list to use
  3316. if (count($ip)) {
  3317. switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
  3318. case 'last':
  3319. $ip = array_pop($ip);
  3320. break;
  3321. case 'first':
  3322. $ip = array_shift($ip);
  3323. break;
  3324. case 'none':
  3325. default:
  3326. $ip = '';
  3327. break;
  3328. }
  3329. }
  3330. if (self::validIP($ip)) {
  3331. $retVal = $ip;
  3332. }
  3333. }
  3334. break;
  3335. case 'HTTP_HOST':
  3336. $retVal = $_SERVER['HTTP_HOST'];
  3337. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3338. $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
  3339. // choose which host in list to use
  3340. if (count($host)) {
  3341. switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
  3342. case 'last':
  3343. $host = array_pop($host);
  3344. break;
  3345. case 'first':
  3346. $host = array_shift($host);
  3347. break;
  3348. case 'none':
  3349. default:
  3350. $host = '';
  3351. break;
  3352. }
  3353. }
  3354. if ($host) {
  3355. $retVal = $host;
  3356. }
  3357. }
  3358. break;
  3359. // These are let through without modification
  3360. case 'HTTP_REFERER':
  3361. case 'HTTP_USER_AGENT':
  3362. case 'HTTP_ACCEPT_ENCODING':
  3363. case 'HTTP_ACCEPT_LANGUAGE':
  3364. case 'REMOTE_HOST':
  3365. case 'QUERY_STRING':
  3366. $retVal = $_SERVER[$getEnvName];
  3367. break;
  3368. case 'TYPO3_DOCUMENT_ROOT':
  3369. // Get the web root (it is not the root of the TYPO3 installation)
  3370. // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
  3371. // 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.
  3372. // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
  3373. $SFN = self::getIndpEnv('SCRIPT_FILENAME');
  3374. $SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME')));
  3375. $SFN_A = explode('/', strrev($SFN));
  3376. $acc = array();
  3377. foreach ($SN_A as $kk => $vv) {
  3378. if (!strcmp($SFN_A[$kk], $vv)) {
  3379. $acc[] = $vv;
  3380. } else {
  3381. break;
  3382. }
  3383. }
  3384. $commonEnd = strrev(implode('/', $acc));
  3385. if (strcmp($commonEnd, '')) {
  3386. $DR = substr($SFN, 0, -(strlen($commonEnd) + 1));
  3387. }
  3388. $retVal = $DR;
  3389. break;
  3390. case 'TYPO3_HOST_ONLY':
  3391. $httpHost = self::getIndpEnv('HTTP_HOST');
  3392. $httpHostBracketPosition = strpos($httpHost, ']');
  3393. $httpHostParts = explode(':', $httpHost);
  3394. $retVal = ($httpHostBracketPosition !== FALSE) ? substr($httpHost, 0, ($httpHostBracketPosition + 1)) : array_shift($httpHostParts);
  3395. break;
  3396. case 'TYPO3_PORT':
  3397. $httpHost = self::getIndpEnv('HTTP_HOST');
  3398. $httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY');
  3399. $retVal = (strlen($httpHost) > strlen($httpHostOnly)) ? substr($httpHost, strlen($httpHostOnly) + 1) : '';
  3400. break;
  3401. case 'TYPO3_REQUEST_HOST':
  3402. $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') .
  3403. self::getIndpEnv('HTTP_HOST');
  3404. break;
  3405. case 'TYPO3_REQUEST_URL':
  3406. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI');
  3407. break;
  3408. case 'TYPO3_REQUEST_SCRIPT':
  3409. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME');
  3410. break;
  3411. case 'TYPO3_REQUEST_DIR':
  3412. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/';
  3413. break;
  3414. case 'TYPO3_SITE_URL':
  3415. if (defined('PATH_thisScript') && defined('PATH_site')) {
  3416. $lPath = substr(dirname(PATH_thisScript), strlen(PATH_site)) . '/';
  3417. $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
  3418. $siteUrl = substr($url, 0, -strlen($lPath));
  3419. if (substr($siteUrl, -1) != '/') {
  3420. $siteUrl .= '/';
  3421. }
  3422. $retVal = $siteUrl;
  3423. }
  3424. break;
  3425. case 'TYPO3_SITE_PATH':
  3426. $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
  3427. break;
  3428. case 'TYPO3_SITE_SCRIPT':
  3429. $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL')));
  3430. break;
  3431. case 'TYPO3_SSL':
  3432. $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
  3433. if ($proxySSL == '*') {
  3434. $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
  3435. }
  3436. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {
  3437. $retVal = TRUE;
  3438. } else {
  3439. $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? TRUE : FALSE; // see http://bugs.typo3.org/view.php?id=3909
  3440. }
  3441. break;
  3442. case '_ARRAY':
  3443. $out = array();
  3444. // Here, list ALL possible keys to this function for debug display.
  3445. $envTestVars = self::trimExplode(',', '
  3446. HTTP_HOST,
  3447. TYPO3_HOST_ONLY,
  3448. TYPO3_PORT,
  3449. PATH_INFO,
  3450. QUERY_STRING,
  3451. REQUEST_URI,
  3452. HTTP_REFERER,
  3453. TYPO3_REQUEST_HOST,
  3454. TYPO3_REQUEST_URL,
  3455. TYPO3_REQUEST_SCRIPT,
  3456. TYPO3_REQUEST_DIR,
  3457. TYPO3_SITE_URL,
  3458. TYPO3_SITE_SCRIPT,
  3459. TYPO3_SSL,
  3460. TYPO3_REV_PROXY,
  3461. SCRIPT_NAME,
  3462. TYPO3_DOCUMENT_ROOT,
  3463. SCRIPT_FILENAME,
  3464. REMOTE_ADDR,
  3465. REMOTE_HOST,
  3466. HTTP_USER_AGENT,
  3467. HTTP_ACCEPT_LANGUAGE', 1);
  3468. foreach ($envTestVars as $v) {
  3469. $out[$v] = self::getIndpEnv($v);
  3470. }
  3471. reset($out);
  3472. $retVal = $out;
  3473. break;
  3474. }
  3475. return $retVal;
  3476. }
  3477. /**
  3478. * Gets the unixtime as milliseconds.
  3479. *
  3480. * @return integer The unixtime as milliseconds
  3481. */
  3482. public static function milliseconds() {
  3483. return round(microtime(TRUE) * 1000);
  3484. }
  3485. /**
  3486. * Client Browser Information
  3487. *
  3488. * @param string $useragent Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
  3489. * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
  3490. */
  3491. public static function clientInfo($useragent = '') {
  3492. if (!$useragent) {
  3493. $useragent = self::getIndpEnv('HTTP_USER_AGENT');
  3494. }
  3495. $bInfo = array();
  3496. // Which browser?
  3497. if (strpos($useragent, 'Konqueror') !== FALSE) {
  3498. $bInfo['BROWSER'] = 'konqu';
  3499. } elseif (strpos($useragent, 'Opera') !== FALSE) {
  3500. $bInfo['BROWSER'] = 'opera';
  3501. } elseif (strpos($useragent, 'MSIE') !== FALSE) {
  3502. $bInfo['BROWSER'] = 'msie';
  3503. } elseif (strpos($useragent, 'Mozilla') !== FALSE) {
  3504. $bInfo['BROWSER'] = 'net';
  3505. } elseif (strpos($useragent, 'Flash') !== FALSE) {
  3506. $bInfo['BROWSER'] = 'flash';
  3507. }
  3508. if ($bInfo['BROWSER']) {
  3509. // Browser version
  3510. switch ($bInfo['BROWSER']) {
  3511. case 'net':
  3512. $bInfo['VERSION'] = doubleval(substr($useragent, 8));
  3513. if (strpos($useragent, 'Netscape6/') !== FALSE) {
  3514. $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape6/'), 10));
  3515. } // Will we ever know if this was a typo or intention...?! :-(
  3516. if (strpos($useragent, 'Netscape/6') !== FALSE) {
  3517. $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/6'), 10));
  3518. }
  3519. if (strpos($useragent, 'Netscape/7') !== FALSE) {
  3520. $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/7'), 9));
  3521. }
  3522. break;
  3523. case 'msie':
  3524. $tmp = strstr($useragent, 'MSIE');
  3525. $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 4)));
  3526. break;
  3527. case 'opera':
  3528. $tmp = strstr($useragent, 'Opera');
  3529. $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 5)));
  3530. break;
  3531. case 'konqu':
  3532. $tmp = strstr($useragent, 'Konqueror/');
  3533. $bInfo['VERSION'] = doubleval(substr($tmp, 10));
  3534. break;
  3535. }
  3536. // Client system
  3537. if (strpos($useragent, 'Win') !== FALSE) {
  3538. $bInfo['SYSTEM'] = 'win';
  3539. } elseif (strpos($useragent, 'Mac') !== FALSE) {
  3540. $bInfo['SYSTEM'] = 'mac';
  3541. } elseif (strpos($useragent, 'Linux') !== FALSE || strpos($useragent, 'X11') !== FALSE || strpos($useragent, 'SGI') !== FALSE || strpos($useragent, ' SunOS ') !== FALSE || strpos($useragent, ' HP-UX ') !== FALSE) {
  3542. $bInfo['SYSTEM'] = 'unix';
  3543. }
  3544. }
  3545. // Is TRUE if the browser supports css to format forms, especially the width
  3546. $bInfo['FORMSTYLE'] = ($bInfo['BROWSER'] == 'msie' || ($bInfo['BROWSER'] == 'net' && $bInfo['VERSION'] >= 5) || $bInfo['BROWSER'] == 'opera' || $bInfo['BROWSER'] == 'konqu');
  3547. return $bInfo;
  3548. }
  3549. /**
  3550. * Get the fully-qualified domain name of the host.
  3551. *
  3552. * @param boolean $requestHost Use request host (when not in CLI mode).
  3553. * @return string The fully-qualified host name.
  3554. */
  3555. public static function getHostname($requestHost = TRUE) {
  3556. $host = '';
  3557. // If not called from the command-line, resolve on getIndpEnv()
  3558. // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
  3559. if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
  3560. $host = self::getIndpEnv('HTTP_HOST');
  3561. }
  3562. if (!$host) {
  3563. // will fail for PHP 4.1 and 4.2
  3564. $host = @php_uname('n');
  3565. // 'n' is ignored in broken installations
  3566. if (strpos($host, ' ')) {
  3567. $host = '';
  3568. }
  3569. }
  3570. // we have not found a FQDN yet
  3571. if ($host && strpos($host, '.') === FALSE) {
  3572. $ip = gethostbyname($host);
  3573. // we got an IP address
  3574. if ($ip != $host) {
  3575. $fqdn = gethostbyaddr($ip);
  3576. if ($ip != $fqdn) {
  3577. $host = $fqdn;
  3578. }
  3579. }
  3580. }
  3581. if (!$host) {
  3582. $host = 'localhost.localdomain';
  3583. }
  3584. return $host;
  3585. }
  3586. /*************************
  3587. *
  3588. * TYPO3 SPECIFIC FUNCTIONS
  3589. *
  3590. *************************/
  3591. /**
  3592. * 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.
  3593. *
  3594. * @param string $filename The input filename/filepath to evaluate
  3595. * @param boolean $onlyRelative If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
  3596. * @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
  3597. * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
  3598. */
  3599. public static function getFileAbsFileName($filename, $onlyRelative = TRUE, $relToTYPO3_mainDir = FALSE) {
  3600. if (!strcmp($filename, '')) {
  3601. return '';
  3602. }
  3603. if ($relToTYPO3_mainDir) {
  3604. if (!defined('PATH_typo3')) {
  3605. return '';
  3606. }
  3607. $relPathPrefix = PATH_typo3;
  3608. } else {
  3609. $relPathPrefix = PATH_site;
  3610. }
  3611. if (substr($filename, 0, 4) == 'EXT:') { // extension
  3612. list($extKey, $local) = explode('/', substr($filename, 4), 2);
  3613. $filename = '';
  3614. if (strcmp($extKey, '') && t3lib_extMgm::isLoaded($extKey) && strcmp($local, '')) {
  3615. $filename = t3lib_extMgm::extPath($extKey) . $local;
  3616. }
  3617. } elseif (!self::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
  3618. $filename = $relPathPrefix . $filename;
  3619. } elseif ($onlyRelative && !self::isFirstPartOfStr($filename, $relPathPrefix)) { // absolute, but set to blank if not allowed
  3620. $filename = '';
  3621. }
  3622. if (strcmp($filename, '') && self::validPathStr($filename)) { // checks backpath.
  3623. return $filename;
  3624. }
  3625. }
  3626. /**
  3627. * Checks for malicious file paths.
  3628. *
  3629. * Returns TRUE if no '//', '..', '\' or control characters are found in the $theFile.
  3630. * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
  3631. * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
  3632. *
  3633. * @param string $theFile File path to evaluate
  3634. * @return boolean TRUE, $theFile is allowed path string
  3635. * @see http://php.net/manual/en/security.filesystem.nullbytes.php
  3636. * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded?
  3637. */
  3638. public static function validPathStr($theFile) {
  3639. if (strpos($theFile, '//') === FALSE && strpos($theFile, '\\') === FALSE && !preg_match('#(?:^\.\.|/\.\./|[[:cntrl:]])#u', $theFile)) {
  3640. return TRUE;
  3641. }
  3642. }
  3643. /**
  3644. * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns TRUE if so.
  3645. *
  3646. * @param string $path File path to evaluate
  3647. * @return boolean
  3648. */
  3649. public static function isAbsPath($path) {
  3650. // on Windows also a path starting with a drive letter is absolute: X:/
  3651. if (TYPO3_OS === 'WIN' && substr($path, 1, 2) === ':/') {
  3652. return TRUE;
  3653. }
  3654. // path starting with a / is always absolute, on every system
  3655. return (substr($path, 0, 1) === '/');
  3656. }
  3657. /**
  3658. * Returns TRUE if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
  3659. *
  3660. * @param string $path File path to evaluate
  3661. * @return boolean
  3662. */
  3663. public static function isAllowedAbsPath($path) {
  3664. if (self::isAbsPath($path) &&
  3665. self::validPathStr($path) &&
  3666. (self::isFirstPartOfStr($path, PATH_site)
  3667. ||
  3668. ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
  3669. )
  3670. ) {
  3671. return TRUE;
  3672. }
  3673. }
  3674. /**
  3675. * Verifies the input filename against the 'fileDenyPattern'. Returns TRUE if OK.
  3676. *
  3677. * @param string $filename File path to evaluate
  3678. * @return boolean
  3679. */
  3680. public static function verifyFilenameAgainstDenyPattern($filename) {
  3681. // Filenames are not allowed to contain control characters
  3682. if (preg_match('/[[:cntrl:]]/', $filename)) {
  3683. return FALSE;
  3684. }
  3685. if (strcmp($filename, '') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'], '')) {
  3686. $result = preg_match('/' . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] . '/i', $filename);
  3687. if ($result) {
  3688. return FALSE;
  3689. } // so if a matching filename is found, return FALSE;
  3690. }
  3691. return TRUE;
  3692. }
  3693. /**
  3694. * Checks if a given string is a valid frame URL to be loaded in the
  3695. * backend.
  3696. *
  3697. * @param string $url potential URL to check
  3698. * @return string either $url if $url is considered to be harmless, or an
  3699. * empty string otherwise
  3700. */
  3701. public static function sanitizeLocalUrl($url = '') {
  3702. $sanitizedUrl = '';
  3703. $decodedUrl = rawurldecode($url);
  3704. if (!empty($url) && self::removeXSS($decodedUrl) === $decodedUrl) {
  3705. $testAbsoluteUrl = self::resolveBackPath($decodedUrl);
  3706. $testRelativeUrl = self::resolveBackPath(
  3707. self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
  3708. );
  3709. // Pass if URL is on the current host:
  3710. if (self::isValidUrl($decodedUrl)) {
  3711. if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) {
  3712. $sanitizedUrl = $url;
  3713. }
  3714. // Pass if URL is an absolute file path:
  3715. } elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) {
  3716. $sanitizedUrl = $url;
  3717. // Pass if URL is absolute and below TYPO3 base directory:
  3718. } elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) === '/') {
  3719. $sanitizedUrl = $url;
  3720. // Pass if URL is relative and below TYPO3 base directory:
  3721. } elseif (strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) !== '/') {
  3722. $sanitizedUrl = $url;
  3723. }
  3724. }
  3725. if (!empty($url) && empty($sanitizedUrl)) {
  3726. self::sysLog('The URL "' . $url . '" is not considered to be local and was denied.', 'Core', self::SYSLOG_SEVERITY_NOTICE);
  3727. }
  3728. return $sanitizedUrl;
  3729. }
  3730. /**
  3731. * Moves $source file to $destination if uploaded, otherwise try to make a copy
  3732. *
  3733. * @param string $source Source file, absolute path
  3734. * @param string $destination Destination file, absolute path
  3735. * @return boolean Returns TRUE if the file was moved.
  3736. * @coauthor Dennis Petersen <fessor@software.dk>
  3737. * @see upload_to_tempfile()
  3738. */
  3739. public static function upload_copy_move($source, $destination) {
  3740. if (is_uploaded_file($source)) {
  3741. $uploaded = TRUE;
  3742. // 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:
  3743. $uploadedResult = move_uploaded_file($source, $destination);
  3744. } else {
  3745. $uploaded = FALSE;
  3746. @copy($source, $destination);
  3747. }
  3748. self::fixPermissions($destination); // Change the permissions of the file
  3749. // 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
  3750. return $uploaded ? $uploadedResult : FALSE;
  3751. }
  3752. /**
  3753. * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it.
  3754. * Use this function to move uploaded files to where you can work on them.
  3755. * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
  3756. *
  3757. * @param string $uploadedFileName The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
  3758. * @return string If a new file was successfully created, return its filename, otherwise blank string.
  3759. * @see unlink_tempfile(), upload_copy_move()
  3760. */
  3761. public static function upload_to_tempfile($uploadedFileName) {
  3762. if (is_uploaded_file($uploadedFileName)) {
  3763. $tempFile = self::tempnam('upload_temp_');
  3764. move_uploaded_file($uploadedFileName, $tempFile);
  3765. return @is_file($tempFile) ? $tempFile : '';
  3766. }
  3767. }
  3768. /**
  3769. * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
  3770. * 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.
  3771. * Use this after upload_to_tempfile() or tempnam() from this class!
  3772. *
  3773. * @param string $uploadedTempFileName Filepath for a file in PATH_site."typo3temp/". Must be absolute.
  3774. * @return boolean Returns TRUE if the file was unlink()'ed
  3775. * @see upload_to_tempfile(), tempnam()
  3776. */
  3777. public static function unlink_tempfile($uploadedTempFileName) {
  3778. if ($uploadedTempFileName && self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName, PATH_site . 'typo3temp/') && @is_file($uploadedTempFileName)) {
  3779. if (unlink($uploadedTempFileName)) {
  3780. return TRUE;
  3781. }
  3782. }
  3783. }
  3784. /**
  3785. * Create temporary filename (Create file with unique file name)
  3786. * This function should be used for getting temporary file names - will make your applications safe for open_basedir = on
  3787. * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
  3788. *
  3789. * @param string $filePrefix Prefix to temp file (which will have no extension btw)
  3790. * @return string result from PHP function tempnam() with PATH_site . 'typo3temp/' set for temp path.
  3791. * @see unlink_tempfile(), upload_to_tempfile()
  3792. */
  3793. public static function tempnam($filePrefix) {
  3794. return tempnam(PATH_site . 'typo3temp/', $filePrefix);
  3795. }
  3796. /**
  3797. * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
  3798. *
  3799. * @param mixed $uid_or_record Uid (integer) or record (array)
  3800. * @param string $fields List of fields from the record if that is given.
  3801. * @param integer $codeLength Length of returned authentication code.
  3802. * @return string MD5 hash of 8 chars.
  3803. */
  3804. public static function stdAuthCode($uid_or_record, $fields = '', $codeLength = 8) {
  3805. if (is_array($uid_or_record)) {
  3806. $recCopy_temp = array();
  3807. if ($fields) {
  3808. $fieldArr = self::trimExplode(',', $fields, 1);
  3809. foreach ($fieldArr as $k => $v) {
  3810. $recCopy_temp[$k] = $uid_or_record[$v];
  3811. }
  3812. } else {
  3813. $recCopy_temp = $uid_or_record;
  3814. }
  3815. $preKey = implode('|', $recCopy_temp);
  3816. } else {
  3817. $preKey = $uid_or_record;
  3818. }
  3819. $authCode = $preKey . '||' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  3820. $authCode = substr(md5($authCode), 0, $codeLength);
  3821. return $authCode;
  3822. }
  3823. /**
  3824. * Splits the input query-parameters into an array with certain parameters filtered out.
  3825. * Used to create the cHash value
  3826. *
  3827. * @param string $addQueryParams Query-parameters: "&xxx=yyy&zzz=uuu"
  3828. * @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
  3829. * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink(), t3lib_div::calculateCHash()
  3830. */
  3831. public static function cHashParams($addQueryParams) {
  3832. $params = explode('&', substr($addQueryParams, 1)); // Splitting parameters up
  3833. // Make array:
  3834. $pA = array();
  3835. foreach ($params as $theP) {
  3836. $pKV = explode('=', $theP); // Splitting single param by '=' sign
  3837. if (!self::inList('id,type,no_cache,cHash,MP,ftu', $pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/', $pKV[0])) {
  3838. $pA[rawurldecode($pKV[0])] = (string) rawurldecode($pKV[1]);
  3839. }
  3840. }
  3841. // Hook: Allows to manipulate the parameters which are taken to build the chash:
  3842. if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
  3843. $cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
  3844. if (is_array($cHashParamsHook)) {
  3845. $hookParameters = array(
  3846. 'addQueryParams' => &$addQueryParams,
  3847. 'params' => &$params,
  3848. 'pA' => &$pA,
  3849. );
  3850. $hookReference = NULL;
  3851. foreach ($cHashParamsHook as $hookFunction) {
  3852. self::callUserFunction($hookFunction, $hookParameters, $hookReference);
  3853. }
  3854. }
  3855. }
  3856. // Finish and sort parameters array by keys:
  3857. $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  3858. ksort($pA);
  3859. return $pA;
  3860. }
  3861. /**
  3862. * Returns the cHash based on provided query parameters and added values from internal call
  3863. *
  3864. * @param string $addQueryParams Query-parameters: "&xxx=yyy&zzz=uuu"
  3865. * @return string Hash of all the values
  3866. * @see t3lib_div::cHashParams(), t3lib_div::calculateCHash()
  3867. */
  3868. public static function generateCHash($addQueryParams) {
  3869. $cHashParams = self::cHashParams($addQueryParams);
  3870. $cHash = self::calculateCHash($cHashParams);
  3871. return $cHash;
  3872. }
  3873. /**
  3874. * Calculates the cHash based on the provided parameters
  3875. *
  3876. * @param array $params Array of key-value pairs
  3877. * @return string Hash of all the values
  3878. */
  3879. public static function calculateCHash($params) {
  3880. $cHash = md5(serialize($params));
  3881. return $cHash;
  3882. }
  3883. /**
  3884. * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
  3885. *
  3886. * @param integer $l18n_cfg_fieldValue Value from "l18n_cfg" field of a page record
  3887. * @return boolean TRUE if the page should be hidden
  3888. */
  3889. public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
  3890. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
  3891. return $l18n_cfg_fieldValue & 2 ? FALSE : TRUE;
  3892. } else {
  3893. return $l18n_cfg_fieldValue & 2 ? TRUE : FALSE;
  3894. }
  3895. }
  3896. /**
  3897. * Returns true if the "l18n_cfg" field value is not set to hide
  3898. * pages in the default language
  3899. *
  3900. * @param int $localizationConfiguration
  3901. * @return boolean
  3902. */
  3903. public static function hideIfDefaultLanguage($localizationConfiguration) {
  3904. return ($localizationConfiguration & 1);
  3905. }
  3906. /**
  3907. * Includes a locallang file and returns the $LOCAL_LANG array found inside.
  3908. *
  3909. * @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.
  3910. * @param string $langKey Language key
  3911. * @param string $charset Character set (option); if not set, determined by the language key
  3912. * @param integer $errorMode Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
  3913. * @return array Value of $LOCAL_LANG found in the included file. If that array is found it will returned.
  3914. * Otherwise an empty array and it is FALSE in error case.
  3915. */
  3916. public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
  3917. /** @var $languageFactory t3lib_l10n_Factory */
  3918. $languageFactory = t3lib_div::makeInstance('t3lib_l10n_Factory');
  3919. return $languageFactory->getParsedData($fileRef, $langKey, $charset, $errorMode);
  3920. }
  3921. /**
  3922. * Includes a locallang-php file and returns the $LOCAL_LANG array
  3923. * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
  3924. *
  3925. * @param string $fileRef Absolute reference to locallang-PHP file
  3926. * @param string $langKey TYPO3 language key, eg. "dk" or "de" or "default"
  3927. * @param string $charset Character set (optional)
  3928. * @return array LOCAL_LANG array in return.
  3929. * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - use t3lib_l10n_parser_Llphp::getParsedData() from now on
  3930. */
  3931. public static function readLLPHPfile($fileRef, $langKey, $charset = '') {
  3932. t3lib_div::logDeprecatedFunction();
  3933. if (is_object($GLOBALS['LANG'])) {
  3934. $csConvObj = $GLOBALS['LANG']->csConvObj;
  3935. } elseif (is_object($GLOBALS['TSFE'])) {
  3936. $csConvObj = $GLOBALS['TSFE']->csConvObj;
  3937. } else {
  3938. $csConvObj = self::makeInstance('t3lib_cs');
  3939. }
  3940. if (@is_file($fileRef) && $langKey) {
  3941. // Set charsets:
  3942. $sourceCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  3943. if ($charset) {
  3944. $targetCharset = $csConvObj->parse_charset($charset);
  3945. } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
  3946. // when forceCharset is set, we store ALL labels in this charset!!!
  3947. $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
  3948. } else {
  3949. $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  3950. }
  3951. // Cache file name:
  3952. $hashSource = substr($fileRef, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
  3953. $cacheFileName = PATH_site . 'typo3temp/llxml/' .
  3954. substr(basename($fileRef), 10, 15) .
  3955. '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
  3956. // Check if cache file exists...
  3957. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  3958. $LOCAL_LANG = NULL;
  3959. // Get PHP data
  3960. include($fileRef);
  3961. if (!is_array($LOCAL_LANG)) {
  3962. $fileName = substr($fileRef, strlen(PATH_site));
  3963. throw new RuntimeException(
  3964. 'TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!',
  3965. 1270853900
  3966. );
  3967. }
  3968. // converting the default language (English)
  3969. // this needs to be done for a few accented loan words and extension names
  3970. if (is_array($LOCAL_LANG['default']) && $targetCharset != 'iso-8859-1') {
  3971. foreach ($LOCAL_LANG['default'] as &$labelValue) {
  3972. $labelValue = $csConvObj->conv($labelValue, 'iso-8859-1', $targetCharset);
  3973. }
  3974. unset($labelValue);
  3975. }
  3976. if ($langKey != 'default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset != $targetCharset) {
  3977. foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
  3978. $labelValue = $csConvObj->conv($labelValue, $sourceCharset, $targetCharset);
  3979. }
  3980. unset($labelValue);
  3981. }
  3982. // Cache the content now:
  3983. $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
  3984. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  3985. if ($res) {
  3986. throw new RuntimeException(
  3987. 'TYPO3 Fatal Error: "' . $res,
  3988. 1270853901
  3989. );
  3990. }
  3991. } else {
  3992. // Get content from cache:
  3993. $serContent = unserialize(self::getUrl($cacheFileName));
  3994. $LOCAL_LANG = $serContent['LOCAL_LANG'];
  3995. }
  3996. return $LOCAL_LANG;
  3997. }
  3998. }
  3999. /**
  4000. * Includes a locallang-xml file and returns the $LOCAL_LANG array
  4001. * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
  4002. *
  4003. * @param string $fileRef Absolute reference to locallang-XML file
  4004. * @param string $langKey TYPO3 language key, eg. "dk" or "de" or "default"
  4005. * @param string $charset Character set (optional)
  4006. * @return array LOCAL_LANG array in return.
  4007. * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - use t3lib_l10n_parser_Llxml::getParsedData() from now on
  4008. */
  4009. public static function readLLXMLfile($fileRef, $langKey, $charset = '') {
  4010. t3lib_div::logDeprecatedFunction();
  4011. if (is_object($GLOBALS['LANG'])) {
  4012. $csConvObj = $GLOBALS['LANG']->csConvObj;
  4013. } elseif (is_object($GLOBALS['TSFE'])) {
  4014. $csConvObj = $GLOBALS['TSFE']->csConvObj;
  4015. } else {
  4016. $csConvObj = self::makeInstance('t3lib_cs');
  4017. }
  4018. $LOCAL_LANG = NULL;
  4019. if (@is_file($fileRef) && $langKey) {
  4020. // Set charset:
  4021. if ($charset) {
  4022. $targetCharset = $csConvObj->parse_charset($charset);
  4023. } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
  4024. // when forceCharset is set, we store ALL labels in this charset!!!
  4025. $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
  4026. } else {
  4027. $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  4028. }
  4029. // Cache file name:
  4030. $hashSource = substr($fileRef, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
  4031. $cacheFileName = PATH_site . 'typo3temp/llxml/' .
  4032. substr(basename($fileRef), 10, 15) .
  4033. '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
  4034. // Check if cache file exists...
  4035. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4036. // Read XML, parse it.
  4037. $xmlString = self::getUrl($fileRef);
  4038. $xmlContent = self::xml2array($xmlString);
  4039. if (!is_array($xmlContent)) {
  4040. $fileName = substr($fileRef, strlen(PATH_site));
  4041. throw new RuntimeException(
  4042. 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
  4043. 1270853902
  4044. );
  4045. }
  4046. // Set default LOCAL_LANG array content:
  4047. $LOCAL_LANG = array();
  4048. $LOCAL_LANG['default'] = $xmlContent['data']['default'];
  4049. // converting the default language (English)
  4050. // this needs to be done for a few accented loan words and extension names
  4051. // NOTE: no conversion is done when in UTF-8 mode!
  4052. if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
  4053. foreach ($LOCAL_LANG['default'] as &$labelValue) {
  4054. $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
  4055. }
  4056. unset($labelValue);
  4057. }
  4058. // converting other languages to their "native" charsets
  4059. // NOTE: no conversion is done when in UTF-8 mode!
  4060. if ($langKey != 'default') {
  4061. // 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:
  4062. $LOCAL_LANG[$langKey] = self::llXmlAutoFileName($fileRef, $langKey);
  4063. $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
  4064. if (!@is_file($localized_file) && isset($xmlContent['data'][$langKey])) {
  4065. $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
  4066. }
  4067. // Checking if charset should be converted.
  4068. if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
  4069. foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
  4070. $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
  4071. }
  4072. unset($labelValue);
  4073. }
  4074. }
  4075. // Cache the content now:
  4076. $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
  4077. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4078. if ($res) {
  4079. throw new RuntimeException(
  4080. 'TYPO3 Fatal Error: ' . $res,
  4081. 1270853903
  4082. );
  4083. }
  4084. } else {
  4085. // Get content from cache:
  4086. $serContent = unserialize(self::getUrl($cacheFileName));
  4087. $LOCAL_LANG = $serContent['LOCAL_LANG'];
  4088. }
  4089. // Checking for EXTERNAL file for non-default language:
  4090. if ($langKey != 'default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
  4091. // Look for localized file:
  4092. $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
  4093. if ($localized_file && @is_file($localized_file)) {
  4094. // Cache file name:
  4095. $hashSource = substr($localized_file, strlen(PATH_site)) . '|' . date('d-m-Y H:i:s', filemtime($localized_file)) . '|version=2.3';
  4096. $cacheFileName = PATH_site . 'typo3temp/llxml/EXT_' .
  4097. substr(basename($localized_file), 10, 15) .
  4098. '_' . self::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
  4099. // Check if cache file exists...
  4100. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4101. // Read and parse XML content:
  4102. $local_xmlString = self::getUrl($localized_file);
  4103. $local_xmlContent = self::xml2array($local_xmlString);
  4104. if (!is_array($local_xmlContent)) {
  4105. $fileName = substr($localized_file, strlen(PATH_site));
  4106. throw new RuntimeException(
  4107. 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
  4108. 1270853904
  4109. );
  4110. }
  4111. $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
  4112. // Checking if charset should be converted.
  4113. if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
  4114. foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
  4115. $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
  4116. }
  4117. unset($labelValue);
  4118. }
  4119. // Cache the content now:
  4120. $serContent = array('extlang' => $langKey, 'origFile' => $hashSource, 'EXT_DATA' => $LOCAL_LANG[$langKey]);
  4121. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4122. if ($res) {
  4123. throw new RuntimeException(
  4124. 'TYPO3 Fatal Error: ' . $res,
  4125. 1270853905
  4126. );
  4127. }
  4128. } else {
  4129. // Get content from cache:
  4130. $serContent = unserialize(self::getUrl($cacheFileName));
  4131. $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
  4132. }
  4133. } else {
  4134. $LOCAL_LANG[$langKey] = array();
  4135. }
  4136. }
  4137. // Convert the $LOCAL_LANG array to XLIFF structure
  4138. foreach ($LOCAL_LANG as &$keysLabels) {
  4139. foreach ($keysLabels as &$label) {
  4140. $label = array(0 => array(
  4141. 'target' => $label,
  4142. ));
  4143. }
  4144. unset($label);
  4145. }
  4146. unset($keysLabels);
  4147. return $LOCAL_LANG;
  4148. }
  4149. }
  4150. /**
  4151. * Returns auto-filename for locallang-XML localizations.
  4152. *
  4153. * @param string $fileRef Absolute file reference to locallang-XML file. Must be inside system/global/local extension
  4154. * @param string $language Language key
  4155. * @param boolean $sameLocation if TRUE, then locallang-XML localization file name will be returned with same directory as $fileRef
  4156. * @return string Returns the filename reference for the language unless error occurred (or local mode is used) in which case it will be NULL
  4157. */
  4158. public static function llXmlAutoFileName($fileRef, $language, $sameLocation = FALSE) {
  4159. if ($sameLocation) {
  4160. $location = 'EXT:';
  4161. } else {
  4162. $location = 'typo3conf/l10n/' . $language . '/'; // Default location of translations
  4163. }
  4164. // Analyse file reference:
  4165. if (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'sysext/')) { // Is system:
  4166. $validatedPrefix = PATH_typo3 . 'sysext/';
  4167. #$location = 'EXT:csh_'.$language.'/'; // For system extensions translations are found in "csh_*" extensions (language packs)
  4168. } elseif (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'ext/')) { // Is global:
  4169. $validatedPrefix = PATH_typo3 . 'ext/';
  4170. } elseif (self::isFirstPartOfStr($fileRef, PATH_typo3conf . 'ext/')) { // Is local:
  4171. $validatedPrefix = PATH_typo3conf . 'ext/';
  4172. } elseif (self::isFirstPartOfStr($fileRef, PATH_site . 'typo3_src/tests/')) { // Is test:
  4173. $validatedPrefix = PATH_site . 'typo3_src/tests/';
  4174. $location = $validatedPrefix;
  4175. } else {
  4176. $validatedPrefix = '';
  4177. }
  4178. if ($validatedPrefix) {
  4179. // Divide file reference into extension key, directory (if any) and base name:
  4180. list($file_extKey, $file_extPath) = explode('/', substr($fileRef, strlen($validatedPrefix)), 2);
  4181. $temp = self::revExplode('/', $file_extPath, 2);
  4182. if (count($temp) == 1) {
  4183. array_unshift($temp, '');
  4184. } // Add empty first-entry if not there.
  4185. list($file_extPath, $file_fileName) = $temp;
  4186. // If $fileRef is already prefix with "[language key]" then we should return it as this
  4187. if (substr($file_fileName, 0, strlen($language) + 1) === $language . '.') {
  4188. return $fileRef;
  4189. }
  4190. // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
  4191. return $location .
  4192. $file_extKey . '/' .
  4193. ($file_extPath ? $file_extPath . '/' : '') .
  4194. $language . '.' . $file_fileName;
  4195. } else {
  4196. return NULL;
  4197. }
  4198. }
  4199. /**
  4200. * Loads the $GLOBALS['TCA'] (Table Configuration Array) for the $table
  4201. *
  4202. * Requirements:
  4203. * 1) must be configured table (the ctrl-section configured),
  4204. * 2) columns must not be an array (which it is always if whole table loaded), and
  4205. * 3) there is a value for dynamicConfigFile (filename in typo3conf)
  4206. *
  4207. * Note: For the frontend this loads only 'ctrl' and 'feInterface' parts.
  4208. * For complete TCA use $GLOBALS['TSFE']->includeTCA() instead.
  4209. *
  4210. * @param string $table Table name for which to load the full TCA array part into $GLOBALS['TCA']
  4211. * @return void
  4212. */
  4213. public static function loadTCA($table) {
  4214. //needed for inclusion of the dynamic config files.
  4215. global $TCA;
  4216. if (isset($TCA[$table])) {
  4217. $tca = &$TCA[$table];
  4218. if (!$tca['columns']) {
  4219. $dcf = $tca['ctrl']['dynamicConfigFile'];
  4220. if ($dcf) {
  4221. if (!strcmp(substr($dcf, 0, 6), 'T3LIB:')) {
  4222. include(PATH_t3lib . 'stddb/' . substr($dcf, 6));
  4223. } elseif (self::isAbsPath($dcf) && @is_file($dcf)) { // Absolute path...
  4224. include($dcf);
  4225. } else {
  4226. include(PATH_typo3conf . $dcf);
  4227. }
  4228. }
  4229. }
  4230. }
  4231. }
  4232. /**
  4233. * 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).
  4234. * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
  4235. *
  4236. * @param array $dataStructArray Input data structure, possibly with a sheet-definition and references to external data source files.
  4237. * @param string $sheet The sheet to return, preferably.
  4238. * @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!
  4239. */
  4240. public static function resolveSheetDefInDS($dataStructArray, $sheet = 'sDEF') {
  4241. if (!is_array($dataStructArray)) {
  4242. return 'Data structure must be an array';
  4243. }
  4244. if (is_array($dataStructArray['sheets'])) {
  4245. $singleSheet = FALSE;
  4246. if (!isset($dataStructArray['sheets'][$sheet])) {
  4247. $sheet = 'sDEF';
  4248. }
  4249. $dataStruct = $dataStructArray['sheets'][$sheet];
  4250. // If not an array, but still set, then regard it as a relative reference to a file:
  4251. if ($dataStruct && !is_array($dataStruct)) {
  4252. $file = self::getFileAbsFileName($dataStruct);
  4253. if ($file && @is_file($file)) {
  4254. $dataStruct = self::xml2array(self::getUrl($file));
  4255. }
  4256. }
  4257. } else {
  4258. $singleSheet = TRUE;
  4259. $dataStruct = $dataStructArray;
  4260. if (isset($dataStruct['meta'])) {
  4261. unset($dataStruct['meta']);
  4262. } // Meta data should not appear there.
  4263. $sheet = 'sDEF'; // Default sheet
  4264. }
  4265. return array($dataStruct, $sheet, $singleSheet);
  4266. }
  4267. /**
  4268. * Resolves ALL sheet definitions in dataStructArray
  4269. * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
  4270. *
  4271. * @param array $dataStructArray Input data structure, possibly with a sheet-definition and references to external data source files.
  4272. * @return array Output data structure with all sheets resolved as arrays.
  4273. */
  4274. public static function resolveAllSheetsInDS(array $dataStructArray) {
  4275. if (is_array($dataStructArray['sheets'])) {
  4276. $out = array('sheets' => array());
  4277. foreach ($dataStructArray['sheets'] as $sheetId => $sDat) {
  4278. list($ds, $aS) = self::resolveSheetDefInDS($dataStructArray, $sheetId);
  4279. if ($sheetId == $aS) {
  4280. $out['sheets'][$aS] = $ds;
  4281. }
  4282. }
  4283. } else {
  4284. list($ds) = self::resolveSheetDefInDS($dataStructArray);
  4285. $out = array('sheets' => array('sDEF' => $ds));
  4286. }
  4287. return $out;
  4288. }
  4289. /**
  4290. * Calls a user-defined function/method in class
  4291. * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
  4292. *
  4293. * @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").
  4294. * @param mixed $params Parameters to be pass along (typically an array) (REFERENCE!)
  4295. * @param mixed $ref Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
  4296. * @param string $checkPrefix Alternative allowed prefix of class or function name
  4297. * @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)
  4298. * @return mixed Content from method/function call or FALSE if the class/method/function was not found
  4299. * @see getUserObj()
  4300. */
  4301. public static function callUserFunction($funcName, &$params, &$ref, $checkPrefix = 'user_', $errorMode = 0) {
  4302. $content = FALSE;
  4303. // Check persistent object and if found, call directly and exit.
  4304. if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
  4305. return call_user_func_array(
  4306. array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
  4307. $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
  4308. array(&$params, &$ref)
  4309. );
  4310. }
  4311. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  4312. if (strpos($funcName, ':') !== FALSE) {
  4313. list($file, $funcRef) = self::revExplode(':', $funcName, 2);
  4314. $requireFile = self::getFileAbsFileName($file);
  4315. if ($requireFile) {
  4316. self::requireOnce($requireFile);
  4317. }
  4318. } else {
  4319. $funcRef = $funcName;
  4320. }
  4321. // Check for persistent object token, "&"
  4322. if (substr($funcRef, 0, 1) == '&') {
  4323. $funcRef = substr($funcRef, 1);
  4324. $storePersistentObject = TRUE;
  4325. } else {
  4326. $storePersistentObject = FALSE;
  4327. }
  4328. // Check prefix is valid:
  4329. if ($checkPrefix && !self::hasValidClassPrefix($funcRef, array($checkPrefix))) {
  4330. $errorMsg = "Function/class '$funcRef' was not prepended with '$checkPrefix'";
  4331. if ($errorMode == 2) {
  4332. throw new InvalidArgumentException($errorMsg, 1294585864);
  4333. } elseif (!$errorMode) {
  4334. debug($errorMsg, 't3lib_div::callUserFunction');
  4335. }
  4336. return FALSE;
  4337. }
  4338. // Call function or method:
  4339. $parts = explode('->', $funcRef);
  4340. if (count($parts) == 2) { // Class
  4341. // Check if class/method exists:
  4342. if (class_exists($parts[0])) {
  4343. // Get/Create object of class:
  4344. if ($storePersistentObject) { // Get reference to current instance of class:
  4345. if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
  4346. $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = self::makeInstance($parts[0]);
  4347. }
  4348. $classObj = $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
  4349. } else { // Create new object:
  4350. $classObj = self::makeInstance($parts[0]);
  4351. }
  4352. if (method_exists($classObj, $parts[1])) {
  4353. // If persistent object should be created, set reference:
  4354. if ($storePersistentObject) {
  4355. $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array(
  4356. 'method' => $parts[1],
  4357. 'obj' => &$classObj
  4358. );
  4359. }
  4360. // Call method:
  4361. $content = call_user_func_array(
  4362. array(&$classObj, $parts[1]),
  4363. array(&$params, &$ref)
  4364. );
  4365. } else {
  4366. $errorMsg = "No method name '" . $parts[1] . "' in class " . $parts[0];
  4367. if ($errorMode == 2) {
  4368. throw new InvalidArgumentException($errorMsg, 1294585865);
  4369. } elseif (!$errorMode) {
  4370. debug($errorMsg, 't3lib_div::callUserFunction');
  4371. }
  4372. }
  4373. } else {
  4374. $errorMsg = 'No class named ' . $parts[0];
  4375. if ($errorMode == 2) {
  4376. throw new InvalidArgumentException($errorMsg, 1294585866);
  4377. } elseif (!$errorMode) {
  4378. debug($errorMsg, 't3lib_div::callUserFunction');
  4379. }
  4380. }
  4381. } else { // Function
  4382. if (function_exists($funcRef)) {
  4383. $content = call_user_func_array($funcRef, array(&$params, &$ref));
  4384. } else {
  4385. $errorMsg = 'No function named: ' . $funcRef;
  4386. if ($errorMode == 2) {
  4387. throw new InvalidArgumentException($errorMsg, 1294585867);
  4388. } elseif (!$errorMode) {
  4389. debug($errorMsg, 't3lib_div::callUserFunction');
  4390. }
  4391. }
  4392. }
  4393. return $content;
  4394. }
  4395. /**
  4396. * Creates and returns reference to a user defined object.
  4397. * 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.
  4398. *
  4399. * @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!).
  4400. * @param string $checkPrefix Required prefix of class name. By default "tx_" and "Tx_" are allowed.
  4401. * @param boolean $silent If set, no debug() error message is shown if class/function is not present.
  4402. * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
  4403. * @see callUserFunction()
  4404. */
  4405. public static function getUserObj($classRef, $checkPrefix = 'user_', $silent = FALSE) {
  4406. // Check persistent object and if found, call directly and exit.
  4407. if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
  4408. return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
  4409. } else {
  4410. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  4411. if (strpos($classRef, ':') !== FALSE) {
  4412. list($file, $class) = self::revExplode(':', $classRef, 2);
  4413. $requireFile = self::getFileAbsFileName($file);
  4414. if ($requireFile) {
  4415. self::requireOnce($requireFile);
  4416. }
  4417. } else {
  4418. $class = $classRef;
  4419. }
  4420. // Check for persistent object token, "&"
  4421. if (substr($class, 0, 1) == '&') {
  4422. $class = substr($class, 1);
  4423. $storePersistentObject = TRUE;
  4424. } else {
  4425. $storePersistentObject = FALSE;
  4426. }
  4427. // Check prefix is valid:
  4428. if ($checkPrefix && !self::hasValidClassPrefix($class, array($checkPrefix))) {
  4429. if (!$silent) {
  4430. debug("Class '" . $class . "' was not prepended with '" . $checkPrefix . "'", 't3lib_div::getUserObj');
  4431. }
  4432. return FALSE;
  4433. }
  4434. // Check if class exists:
  4435. if (class_exists($class)) {
  4436. $classObj = self::makeInstance($class);
  4437. // If persistent object should be created, set reference:
  4438. if ($storePersistentObject) {
  4439. $GLOBALS['T3_VAR']['getUserObj'][$classRef] = $classObj;
  4440. }
  4441. return $classObj;
  4442. } else {
  4443. if (!$silent) {
  4444. debug("<strong>ERROR:</strong> No class named: " . $class, 't3lib_div::getUserObj');
  4445. }
  4446. }
  4447. }
  4448. }
  4449. /**
  4450. * Checks if a class or function has a valid prefix: tx_, Tx_ or custom, e.g. user_
  4451. *
  4452. * @param string $classRef The class or function to check
  4453. * @param array $additionalPrefixes Additional allowed prefixes, mostly this will be user_
  4454. * @return bool TRUE if name is allowed
  4455. */
  4456. public static function hasValidClassPrefix($classRef, array $additionalPrefixes = array()) {
  4457. if (empty($classRef)) {
  4458. return FALSE;
  4459. }
  4460. if (!is_string($classRef)) {
  4461. throw new InvalidArgumentException('$classRef has to be of type string', 1313917992);
  4462. }
  4463. $hasValidPrefix = FALSE;
  4464. $validPrefixes = self::getValidClassPrefixes();
  4465. $classRef = trim($classRef);
  4466. if (count($additionalPrefixes)) {
  4467. $validPrefixes = array_merge($validPrefixes, $additionalPrefixes);
  4468. }
  4469. foreach ($validPrefixes as $prefixToCheck) {
  4470. if (self::isFirstPartOfStr($classRef, $prefixToCheck) || $prefixToCheck === '') {
  4471. $hasValidPrefix = TRUE;
  4472. break;
  4473. }
  4474. }
  4475. return $hasValidPrefix;
  4476. }
  4477. /**
  4478. * Returns all valid class prefixes.
  4479. *
  4480. * @return array Array of valid prefixed of class names
  4481. */
  4482. public static function getValidClassPrefixes() {
  4483. $validPrefixes = array('tx_', 'Tx_', 'user_', 'User_');
  4484. if (
  4485. isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
  4486. && is_string($GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
  4487. ) {
  4488. $validPrefixes = array_merge(
  4489. $validPrefixes,
  4490. t3lib_div::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
  4491. );
  4492. }
  4493. return $validPrefixes;
  4494. }
  4495. /**
  4496. * Creates an instance of a class taking into account the class-extensions
  4497. * API of TYPO3. USE THIS method instead of the PHP "new" keyword.
  4498. * Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
  4499. *
  4500. * You can also pass arguments for a constructor:
  4501. * t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
  4502. *
  4503. * @throws InvalidArgumentException if classname is an empty string
  4504. * @param string $className
  4505. * name of the class to instantiate, must not be empty
  4506. * @return object the created instance
  4507. */
  4508. public static function makeInstance($className) {
  4509. if (!is_string($className) || empty($className)) {
  4510. throw new InvalidArgumentException('$className must be a non empty string.', 1288965219);
  4511. }
  4512. // Determine final class name which must be instantiated, this takes XCLASS handling
  4513. // into account. Cache in a local array to save some cycles for consecutive calls.
  4514. if (!isset(self::$finalClassNameRegister[$className])) {
  4515. self::$finalClassNameRegister[$className] = self::getClassName($className);
  4516. }
  4517. $finalClassName = self::$finalClassNameRegister[$className];
  4518. // Return singleton instance if it is already registered
  4519. if (isset(self::$singletonInstances[$finalClassName])) {
  4520. return self::$singletonInstances[$finalClassName];
  4521. }
  4522. // Return instance if it has been injected by addInstance()
  4523. if (isset(self::$nonSingletonInstances[$finalClassName])
  4524. && !empty(self::$nonSingletonInstances[$finalClassName])
  4525. ) {
  4526. return array_shift(self::$nonSingletonInstances[$finalClassName]);
  4527. }
  4528. // Create new instance and call constructor with parameters
  4529. if (func_num_args() > 1) {
  4530. $constructorArguments = func_get_args();
  4531. array_shift($constructorArguments);
  4532. $reflectedClass = new ReflectionClass($finalClassName);
  4533. $instance = $reflectedClass->newInstanceArgs($constructorArguments);
  4534. } else {
  4535. $instance = new $finalClassName;
  4536. }
  4537. // Register new singleton instance
  4538. if ($instance instanceof t3lib_Singleton) {
  4539. self::$singletonInstances[$finalClassName] = $instance;
  4540. }
  4541. return $instance;
  4542. }
  4543. /**
  4544. * Returns the class name for a new instance, taking into account the
  4545. * class-extension API.
  4546. *
  4547. * @param string $className Base class name to evaluate
  4548. * @return string Final class name to instantiate with "new [classname]"
  4549. */
  4550. protected static function getClassName($className) {
  4551. if (class_exists($className)) {
  4552. while (class_exists('ux_' . $className, FALSE)) {
  4553. $className = 'ux_' . $className;
  4554. }
  4555. }
  4556. return $className;
  4557. }
  4558. /**
  4559. * Sets the instance of a singleton class to be returned by makeInstance.
  4560. *
  4561. * If this function is called multiple times for the same $className,
  4562. * makeInstance will return the last set instance.
  4563. *
  4564. * Warning: This is a helper method for unit tests. Do not call this directly in production code!
  4565. *
  4566. * @see makeInstance
  4567. * @param string $className
  4568. * the name of the class to set, must not be empty
  4569. * @param t3lib_Singleton $instance
  4570. * the instance to set, must be an instance of $className
  4571. * @return void
  4572. */
  4573. public static function setSingletonInstance($className, t3lib_Singleton $instance) {
  4574. self::checkInstanceClassName($className, $instance);
  4575. self::$singletonInstances[$className] = $instance;
  4576. }
  4577. /**
  4578. * Sets the instance of a non-singleton class to be returned by makeInstance.
  4579. *
  4580. * If this function is called multiple times for the same $className,
  4581. * makeInstance will return the instances in the order in which they have
  4582. * been added (FIFO).
  4583. *
  4584. * Warning: This is a helper method for unit tests. Do not call this directly in production code!
  4585. *
  4586. * @see makeInstance
  4587. * @throws InvalidArgumentException if class extends t3lib_Singleton
  4588. * @param string $className
  4589. * the name of the class to set, must not be empty
  4590. * @param object $instance
  4591. * the instance to set, must be an instance of $className
  4592. * @return void
  4593. */
  4594. public static function addInstance($className, $instance) {
  4595. self::checkInstanceClassName($className, $instance);
  4596. if ($instance instanceof t3lib_Singleton) {
  4597. throw new InvalidArgumentException(
  4598. '$instance must not be an instance of t3lib_Singleton. ' .
  4599. 'For setting singletons, please use setSingletonInstance.',
  4600. 1288969325
  4601. );
  4602. }
  4603. if (!isset(self::$nonSingletonInstances[$className])) {
  4604. self::$nonSingletonInstances[$className] = array();
  4605. }
  4606. self::$nonSingletonInstances[$className][] = $instance;
  4607. }
  4608. /**
  4609. * Checks that $className is non-empty and that $instance is an instance of
  4610. * $className.
  4611. *
  4612. * @throws InvalidArgumentException if $className is empty or if $instance is no instance of $className
  4613. * @param string $className a class name
  4614. * @param object $instance an object
  4615. * @return void
  4616. */
  4617. protected static function checkInstanceClassName($className, $instance) {
  4618. if ($className === '') {
  4619. throw new InvalidArgumentException('$className must not be empty.', 1288967479);
  4620. }
  4621. if (!($instance instanceof $className)) {
  4622. throw new InvalidArgumentException(
  4623. '$instance must be an instance of ' . $className . ', but actually is an instance of ' . get_class($instance) . '.',
  4624. 1288967686
  4625. );
  4626. }
  4627. }
  4628. /**
  4629. * Purge all instances returned by makeInstance.
  4630. *
  4631. * This function is most useful when called from tearDown in a test case
  4632. * to drop any instances that have been created by the tests.
  4633. *
  4634. * Warning: This is a helper method for unit tests. Do not call this directly in production code!
  4635. *
  4636. * @see makeInstance
  4637. * @return void
  4638. */
  4639. public static function purgeInstances() {
  4640. self::$singletonInstances = array();
  4641. self::$nonSingletonInstances = array();
  4642. }
  4643. /**
  4644. * Find the best service and check if it works.
  4645. * Returns object of the service class.
  4646. *
  4647. * @param string $serviceType Type of service (service key).
  4648. * @param string $serviceSubType Sub type like file extensions or similar. Defined by the service.
  4649. * @param mixed $excludeServiceKeys List of service keys which should be excluded in the search for a service. Array or comma list.
  4650. * @return object The service object or an array with error info's.
  4651. */
  4652. public static function makeInstanceService($serviceType, $serviceSubType = '', $excludeServiceKeys = array()) {
  4653. $error = FALSE;
  4654. if (!is_array($excludeServiceKeys)) {
  4655. $excludeServiceKeys = self::trimExplode(',', $excludeServiceKeys, 1);
  4656. }
  4657. $requestInfo = array(
  4658. 'requestedServiceType' => $serviceType,
  4659. 'requestedServiceSubType' => $serviceSubType,
  4660. 'requestedExcludeServiceKeys' => $excludeServiceKeys,
  4661. );
  4662. while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
  4663. // provide information about requested service to service object
  4664. $info = array_merge($info, $requestInfo);
  4665. // Check persistent object and if found, call directly and exit.
  4666. if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
  4667. // update request info in persistent object
  4668. $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->info = $info;
  4669. // reset service and return object
  4670. $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->reset();
  4671. return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
  4672. // include file and create object
  4673. } else {
  4674. $requireFile = self::getFileAbsFileName($info['classFile']);
  4675. if (@is_file($requireFile)) {
  4676. self::requireOnce($requireFile);
  4677. $obj = self::makeInstance($info['className']);
  4678. if (is_object($obj)) {
  4679. if (!@is_callable(array($obj, 'init'))) {
  4680. // use silent logging??? I don't think so.
  4681. die ('Broken service:' . t3lib_utility_Debug::viewArray($info));
  4682. }
  4683. $obj->info = $info;
  4684. if ($obj->init()) { // service available?
  4685. // create persistent object
  4686. $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']] = $obj;
  4687. // needed to delete temp files
  4688. register_shutdown_function(array(&$obj, '__destruct'));
  4689. return $obj; // object is passed as reference by function definition
  4690. }
  4691. $error = $obj->getLastErrorArray();
  4692. unset($obj);
  4693. }
  4694. }
  4695. }
  4696. // deactivate the service
  4697. t3lib_extMgm::deactivateService($info['serviceType'], $info['serviceKey']);
  4698. }
  4699. return $error;
  4700. }
  4701. /**
  4702. * Require a class for TYPO3
  4703. * Useful to require classes from inside other classes (not global scope). A limited set of global variables are available (see function)
  4704. *
  4705. * @param string $requireFile: Path of the file to be included
  4706. * @return void
  4707. */
  4708. public static function requireOnce($requireFile) {
  4709. // Needed for require_once
  4710. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4711. require_once ($requireFile);
  4712. }
  4713. /**
  4714. * Requires a class for TYPO3
  4715. * Useful to require classes from inside other classes (not global scope).
  4716. * A limited set of global variables are available (see function)
  4717. *
  4718. * @param string $requireFile: Path of the file to be included
  4719. * @return void
  4720. */
  4721. public static function requireFile($requireFile) {
  4722. // Needed for require
  4723. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4724. require $requireFile;
  4725. }
  4726. /**
  4727. * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
  4728. * The fifth parameter ($encoding) will allow you to specify 'base64' encryption for the output (set $encoding=base64)
  4729. * Further the output has the charset set to ISO-8859-1 by default.
  4730. *
  4731. * @param string $email Email address to send to. (see PHP function mail())
  4732. * @param string $subject Subject line, non-encoded. (see PHP function mail())
  4733. * @param string $message Message content, non-encoded. (see PHP function mail())
  4734. * @param string $headers Headers, separated by LF
  4735. * @param string $encoding Encoding type: "base64", "quoted-printable", "8bit". Default value is "quoted-printable".
  4736. * @param string $charset Charset used in encoding-headers (only if $encoding is set to a valid value which produces such a header)
  4737. * @param boolean $dontEncodeHeader If set, the header content will not be encoded.
  4738. * @return boolean TRUE if mail was accepted for delivery, FALSE otherwise
  4739. */
  4740. public static function plainMailEncoded($email, $subject, $message, $headers = '', $encoding = 'quoted-printable', $charset = '', $dontEncodeHeader = FALSE) {
  4741. if (!$charset) {
  4742. $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1';
  4743. }
  4744. $email = self::normalizeMailAddress($email);
  4745. if (!$dontEncodeHeader) {
  4746. // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
  4747. $newHeaders = array();
  4748. foreach (explode(LF, $headers) as $line) { // Split the header in lines and convert each line separately
  4749. $parts = explode(': ', $line, 2); // Field tags must not be encoded
  4750. if (count($parts) == 2) {
  4751. if (0 == strcasecmp($parts[0], 'from')) {
  4752. $parts[1] = self::normalizeMailAddress($parts[1]);
  4753. }
  4754. $parts[1] = self::encodeHeader($parts[1], $encoding, $charset);
  4755. $newHeaders[] = implode(': ', $parts);
  4756. } else {
  4757. $newHeaders[] = $line; // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
  4758. }
  4759. }
  4760. $headers = implode(LF, $newHeaders);
  4761. unset($newHeaders);
  4762. $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>")
  4763. $subject = self::encodeHeader($subject, $encoding, $charset);
  4764. }
  4765. switch ((string) $encoding) {
  4766. case 'base64':
  4767. $headers = trim($headers) . LF .
  4768. 'Mime-Version: 1.0' . LF .
  4769. 'Content-Type: text/plain; charset="' . $charset . '"' . LF .
  4770. 'Content-Transfer-Encoding: base64';
  4771. $message = trim(chunk_split(base64_encode($message . LF))) . LF; // Adding LF because I think MS outlook 2002 wants it... may be removed later again.
  4772. break;
  4773. case '8bit':
  4774. $headers = trim($headers) . LF .
  4775. 'Mime-Version: 1.0' . LF .
  4776. 'Content-Type: text/plain; charset=' . $charset . LF .
  4777. 'Content-Transfer-Encoding: 8bit';
  4778. break;
  4779. case 'quoted-printable':
  4780. default:
  4781. $headers = trim($headers) . LF .
  4782. 'Mime-Version: 1.0' . LF .
  4783. 'Content-Type: text/plain; charset=' . $charset . LF .
  4784. 'Content-Transfer-Encoding: quoted-printable';
  4785. $message = self::quoted_printable($message);
  4786. break;
  4787. }
  4788. // Headers must be separated by CRLF according to RFC 2822, not just LF.
  4789. // But many servers (Gmail, for example) behave incorrectly and want only LF.
  4790. // So we stick to LF in all cases.
  4791. $headers = trim(implode(LF, self::trimExplode(LF, $headers, TRUE))); // Make sure no empty lines are there.
  4792. return t3lib_utility_Mail::mail($email, $subject, $message, $headers);
  4793. }
  4794. /**
  4795. * Implementation of quoted-printable encode.
  4796. * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
  4797. *
  4798. * @param string $string Content to encode
  4799. * @param integer $maxlen Length of the lines, default is 76
  4800. * @return string The QP encoded string
  4801. */
  4802. public static function quoted_printable($string, $maxlen = 76) {
  4803. // Make sure the string contains only Unix line breaks
  4804. $string = str_replace(CRLF, LF, $string); // Replace Windows breaks (\r\n)
  4805. $string = str_replace(CR, LF, $string); // Replace Mac breaks (\r)
  4806. $linebreak = LF; // Default line break for Unix systems.
  4807. if (TYPO3_OS == 'WIN') {
  4808. $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.
  4809. }
  4810. $newString = '';
  4811. $theLines = explode(LF, $string); // Split lines
  4812. foreach ($theLines as $val) {
  4813. $newVal = '';
  4814. $theValLen = strlen($val);
  4815. $len = 0;
  4816. for ($index = 0; $index < $theValLen; $index++) { // Walk through each character of this line
  4817. $char = substr($val, $index, 1);
  4818. $ordVal = ord($char);
  4819. if ($len > ($maxlen - 4) || ($len > ($maxlen - 14) && $ordVal == 32)) {
  4820. $newVal .= '=' . $linebreak; // Add a line break
  4821. $len = 0; // Reset the length counter
  4822. }
  4823. if (($ordVal >= 33 && $ordVal <= 60) || ($ordVal >= 62 && $ordVal <= 126) || $ordVal == 9 || $ordVal == 32) {
  4824. $newVal .= $char; // This character is ok, add it to the message
  4825. $len++;
  4826. } else {
  4827. $newVal .= sprintf('=%02X', $ordVal); // Special character, needs to be encoded
  4828. $len += 3;
  4829. }
  4830. }
  4831. $newVal = preg_replace('/' . chr(32) . '$/', '=20', $newVal); // Replaces a possible SPACE-character at the end of a line
  4832. $newVal = preg_replace('/' . TAB . '$/', '=09', $newVal); // Replaces a possible TAB-character at the end of a line
  4833. $newString .= $newVal . $linebreak;
  4834. }
  4835. return preg_replace('/' . $linebreak . '$/', '', $newString); // Remove last newline
  4836. }
  4837. /**
  4838. * Encode header lines
  4839. * Email headers must be ASCII, therefore they will be encoded to quoted_printable (default) or base64.
  4840. *
  4841. * @param string $line Content to encode
  4842. * @param string $enc Encoding type: "base64" or "quoted-printable". Default value is "quoted-printable".
  4843. * @param string $charset Charset used for encoding
  4844. * @return string The encoded string
  4845. */
  4846. public static function encodeHeader($line, $enc = 'quoted-printable', $charset = 'iso-8859-1') {
  4847. // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
  4848. if (strpos($line, '###') !== FALSE) {
  4849. return $line;
  4850. }
  4851. // Check if any non-ASCII characters are found - otherwise encoding is not needed
  4852. if (!preg_match('/[^' . chr(32) . '-' . chr(127) . ']/', $line)) {
  4853. return $line;
  4854. }
  4855. // Wrap email addresses in a special marker
  4856. $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
  4857. $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
  4858. foreach ($matches as $part) {
  4859. $oldPart = $part;
  4860. $partWasQuoted = ($part{0} == '"');
  4861. $part = trim($part, '"');
  4862. switch ((string) $enc) {
  4863. case 'base64':
  4864. $part = '=?' . $charset . '?B?' . base64_encode($part) . '?=';
  4865. break;
  4866. case 'quoted-printable':
  4867. default:
  4868. $qpValue = self::quoted_printable($part, 1000);
  4869. if ($part != $qpValue) {
  4870. // Encoded words in the header should not contain non-encoded:
  4871. // * spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
  4872. // * question mark. See RFC 1342 (http://tools.ietf.org/html/rfc1342)
  4873. $search = array(' ', '?');
  4874. $replace = array('_', '=3F');
  4875. $qpValue = str_replace($search, $replace, $qpValue);
  4876. $part = '=?' . $charset . '?Q?' . $qpValue . '?=';
  4877. }
  4878. break;
  4879. }
  4880. if ($partWasQuoted) {
  4881. $part = '"' . $part . '"';
  4882. }
  4883. $line = str_replace($oldPart, $part, $line);
  4884. }
  4885. $line = preg_replace('/###(.+?)###/', '$1', $line); // Remove the wrappers
  4886. return $line;
  4887. }
  4888. /**
  4889. * 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.
  4890. * This function is about preserving long links in messages.
  4891. *
  4892. * @param string $message Message content
  4893. * @param string $urlmode URL mode; "76" or "all"
  4894. * @param string $index_script_url URL of index script (see makeRedirectUrl())
  4895. * @return string Processed message content
  4896. * @see makeRedirectUrl()
  4897. */
  4898. public static function substUrlsInPlainText($message, $urlmode = '76', $index_script_url = '') {
  4899. // Substitute URLs with shorter links:
  4900. foreach (array('http', 'https') as $protocol) {
  4901. $urlSplit = explode($protocol . '://', $message);
  4902. foreach ($urlSplit as $c => &$v) {
  4903. if ($c) {
  4904. $newParts = preg_split('/\s|[<>"{}|\\\^`()\']/', $v, 2);
  4905. $newURL = $protocol . '://' . $newParts[0];
  4906. switch ((string) $urlmode) {
  4907. case 'all':
  4908. $newURL = self::makeRedirectUrl($newURL, 0, $index_script_url);
  4909. break;
  4910. case '76':
  4911. $newURL = self::makeRedirectUrl($newURL, 76, $index_script_url);
  4912. break;
  4913. }
  4914. $v = $newURL . substr($v, strlen($newParts[0]));
  4915. }
  4916. }
  4917. unset($v);
  4918. $message = implode('', $urlSplit);
  4919. }
  4920. return $message;
  4921. }
  4922. /**
  4923. * Sub-function for substUrlsInPlainText() above.
  4924. *
  4925. * @param string $inUrl Input URL
  4926. * @param integer $l URL string length limit
  4927. * @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'
  4928. * @return string Processed URL
  4929. */
  4930. public static function makeRedirectUrl($inUrl, $l = 0, $index_script_url = '') {
  4931. if (strlen($inUrl) > $l) {
  4932. $md5 = substr(md5($inUrl), 0, 20);
  4933. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
  4934. '*',
  4935. 'cache_md5params',
  4936. 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params')
  4937. );
  4938. if (!$count) {
  4939. $insertFields = array(
  4940. 'md5hash' => $md5,
  4941. 'tstamp' => $GLOBALS['EXEC_TIME'],
  4942. 'type' => 2,
  4943. 'params' => $inUrl
  4944. );
  4945. $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
  4946. }
  4947. $inUrl = ($index_script_url ? $index_script_url : self::getIndpEnv('TYPO3_REQUEST_DIR') . 'index.php') .
  4948. '?RDCT=' . $md5;
  4949. }
  4950. return $inUrl;
  4951. }
  4952. /**
  4953. * Function to compensate for FreeType2 96 dpi
  4954. *
  4955. * @param integer $font_size Fontsize for freetype function call
  4956. * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
  4957. */
  4958. public static function freetypeDpiComp($font_size) {
  4959. $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
  4960. if ($dpi != 72) {
  4961. $font_size = $font_size / $dpi * 72;
  4962. }
  4963. return $font_size;
  4964. }
  4965. /**
  4966. * Initialize the system log.
  4967. *
  4968. * @return void
  4969. * @see sysLog()
  4970. */
  4971. public static function initSysLog() {
  4972. // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
  4973. // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
  4974. if (defined('TYPO3_cliMode') && TYPO3_cliMode) {
  4975. $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getHostname($requestHost = FALSE) . ':' . PATH_site;
  4976. }
  4977. // for Web logging name is <protocol>://<request-hostame>/<site-path>
  4978. else {
  4979. $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getIndpEnv('TYPO3_SITE_URL');
  4980. }
  4981. // init custom logging
  4982. if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
  4983. $params = array('initLog' => TRUE);
  4984. $fakeThis = FALSE;
  4985. foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
  4986. self::callUserFunction($hookMethod, $params, $fakeThis);
  4987. }
  4988. }
  4989. // init TYPO3 logging
  4990. foreach (explode(';', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'], 2) as $log) {
  4991. list($type, $destination) = explode(',', $log, 3);
  4992. if ($type == 'syslog') {
  4993. if (TYPO3_OS == 'WIN') {
  4994. $facility = LOG_USER;
  4995. } else {
  4996. $facility = constant('LOG_' . strtoupper($destination));
  4997. }
  4998. openlog($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
  4999. }
  5000. }
  5001. $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] = t3lib_utility_Math::forceIntegerInRange($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'], 0, 4);
  5002. $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
  5003. }
  5004. /**
  5005. * Logs message to the system log.
  5006. * This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
  5007. * If you want to implement the sysLog in your applications, simply add lines like:
  5008. * t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
  5009. *
  5010. * @param string $msg Message (in English).
  5011. * @param string $extKey Extension key (from which extension you are calling the log) or "Core"
  5012. * @param integer $severity Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
  5013. * @return void
  5014. */
  5015. public static function sysLog($msg, $extKey, $severity = 0) {
  5016. $severity = t3lib_utility_Math::forceIntegerInRange($severity, 0, 4);
  5017. // is message worth logging?
  5018. if (intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel']) > $severity) {
  5019. return;
  5020. }
  5021. // initialize logging
  5022. if (!$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
  5023. self::initSysLog();
  5024. }
  5025. // do custom logging
  5026. if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) &&
  5027. is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
  5028. $params = array('msg' => $msg, 'extKey' => $extKey, 'backTrace' => debug_backtrace(), 'severity' => $severity);
  5029. $fakeThis = FALSE;
  5030. foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
  5031. self::callUserFunction($hookMethod, $params, $fakeThis);
  5032. }
  5033. }
  5034. // TYPO3 logging enabled?
  5035. if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog']) {
  5036. return;
  5037. }
  5038. $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
  5039. $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
  5040. // use all configured logging options
  5041. foreach (explode(';', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'], 2) as $log) {
  5042. list($type, $destination, $level) = explode(',', $log, 4);
  5043. // is message worth logging for this log type?
  5044. if (intval($level) > $severity) {
  5045. continue;
  5046. }
  5047. $msgLine = ' - ' . $extKey . ': ' . $msg;
  5048. // write message to a file
  5049. if ($type == 'file') {
  5050. $lockObject = t3lib_div::makeInstance('t3lib_lock', $destination, $GLOBALS['TYPO3_CONF_VARS']['SYS']['lockingMode']);
  5051. /** @var t3lib_lock $lockObject */
  5052. $lockObject->setEnableLogging(FALSE);
  5053. $lockObject->acquire();
  5054. $file = fopen($destination, 'a');
  5055. if ($file) {
  5056. fwrite($file, date($dateFormat . ' ' . $timeFormat) . $msgLine . LF);
  5057. fclose($file);
  5058. self::fixPermissions($destination);
  5059. }
  5060. $lockObject->release();
  5061. }
  5062. // send message per mail
  5063. elseif ($type == 'mail') {
  5064. list($to, $from) = explode('/', $destination);
  5065. if (!t3lib_div::validEmail($from)) {
  5066. $from = t3lib_utility_Mail::getSystemFrom();
  5067. }
  5068. /** @var $mail t3lib_mail_Message */
  5069. $mail = t3lib_div::makeInstance('t3lib_mail_Message');
  5070. $mail->setTo($to)
  5071. ->setFrom($from)
  5072. ->setSubject('Warning - error in TYPO3 installation')
  5073. ->setBody('Host: ' . $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . LF .
  5074. 'Extension: ' . $extKey . LF .
  5075. 'Severity: ' . $severity . LF .
  5076. LF . $msg
  5077. );
  5078. $mail->send();
  5079. }
  5080. // use the PHP error log
  5081. elseif ($type == 'error_log') {
  5082. error_log($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . $msgLine, 0);
  5083. }
  5084. // use the system log
  5085. elseif ($type == 'syslog') {
  5086. $priority = array(LOG_INFO, LOG_NOTICE, LOG_WARNING, LOG_ERR, LOG_CRIT);
  5087. syslog($priority[(int) $severity], $msgLine);
  5088. }
  5089. }
  5090. }
  5091. /**
  5092. * Logs message to the development log.
  5093. * 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.
  5094. * The result is meant to make sense to developers during development or debugging of a site.
  5095. * 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.
  5096. * If you want to implement the devLog in your applications, simply add lines like:
  5097. * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
  5098. *
  5099. * @param string $msg Message (in english).
  5100. * @param string $extKey Extension key (from which extension you are calling the log)
  5101. * @param integer $severity Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
  5102. * @param mixed $dataVar Additional data you want to pass to the logger.
  5103. * @return void
  5104. */
  5105. public static function devLog($msg, $extKey, $severity = 0, $dataVar = FALSE) {
  5106. if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
  5107. $params = array('msg' => $msg, 'extKey' => $extKey, 'severity' => $severity, 'dataVar' => $dataVar);
  5108. $fakeThis = FALSE;
  5109. foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
  5110. self::callUserFunction($hookMethod, $params, $fakeThis);
  5111. }
  5112. }
  5113. }
  5114. /**
  5115. * Writes a message to the deprecation log.
  5116. *
  5117. * @param string $msg Message (in English).
  5118. * @return void
  5119. */
  5120. public static function deprecationLog($msg) {
  5121. if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
  5122. return;
  5123. }
  5124. $log = $GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog'];
  5125. $date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': ');
  5126. // legacy values (no strict comparison, $log can be boolean, string or int)
  5127. if ($log === TRUE || $log == '1') {
  5128. $log = 'file';
  5129. }
  5130. if (stripos($log, 'file') !== FALSE) {
  5131. // In case lock is acquired before autoloader was defined:
  5132. if (class_exists('t3lib_lock') === FALSE) {
  5133. require_once PATH_t3lib . 'class.t3lib_lock.php';
  5134. }
  5135. // write a longer message to the deprecation log
  5136. $destination = self::getDeprecationLogFileName();
  5137. $lockObject = t3lib_div::makeInstance('t3lib_lock', $destination, $GLOBALS['TYPO3_CONF_VARS']['SYS']['lockingMode']);
  5138. /** @var t3lib_lock $lockObject */
  5139. $lockObject->setEnableLogging(FALSE);
  5140. $lockObject->acquire();
  5141. $file = @fopen($destination, 'a');
  5142. if ($file) {
  5143. @fwrite($file, $date . $msg . LF);
  5144. @fclose($file);
  5145. self::fixPermissions($destination);
  5146. }
  5147. $lockObject->release();
  5148. }
  5149. if (stripos($log, 'devlog') !== FALSE) {
  5150. // copy message also to the developer log
  5151. self::devLog($msg, 'Core', self::SYSLOG_SEVERITY_WARNING);
  5152. }
  5153. // do not use console in login screen
  5154. if (stripos($log, 'console') !== FALSE && isset($GLOBALS['BE_USER']->user['uid'])) {
  5155. t3lib_utility_Debug::debug($msg, $date, 'Deprecation Log');
  5156. }
  5157. }
  5158. /**
  5159. * Gets the absolute path to the deprecation log file.
  5160. *
  5161. * @return string absolute path to the deprecation log file
  5162. */
  5163. public static function getDeprecationLogFileName() {
  5164. return PATH_typo3conf .
  5165. 'deprecation_' .
  5166. self::shortMD5(
  5167. PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
  5168. ) .
  5169. '.log';
  5170. }
  5171. /**
  5172. * Logs a call to a deprecated function.
  5173. * The log message will be taken from the annotation.
  5174. * @return void
  5175. */
  5176. public static function logDeprecatedFunction() {
  5177. if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
  5178. return;
  5179. }
  5180. $trail = debug_backtrace();
  5181. if ($trail[1]['type']) {
  5182. $function = new ReflectionMethod($trail[1]['class'], $trail[1]['function']);
  5183. } else {
  5184. $function = new ReflectionFunction($trail[1]['function']);
  5185. }
  5186. $msg = '';
  5187. if (preg_match('/@deprecated\s+(.*)/', $function->getDocComment(), $match)) {
  5188. $msg = $match[1];
  5189. }
  5190. // trigger PHP error with a short message: <function> is deprecated (called from <source>, defined in <source>)
  5191. $errorMsg = 'Function ' . $trail[1]['function'];
  5192. if ($trail[1]['class']) {
  5193. $errorMsg .= ' of class ' . $trail[1]['class'];
  5194. }
  5195. $errorMsg .= ' is deprecated (called from ' . $trail[1]['file'] . '#' . $trail[1]['line'] . ', defined in ' . $function->getFileName() . '#' . $function->getStartLine() . ')';
  5196. // write a longer message to the deprecation log: <function> <annotion> - <trace> (<source>)
  5197. $logMsg = $trail[1]['class'] . $trail[1]['type'] . $trail[1]['function'];
  5198. $logMsg .= '() - ' . $msg.' - ' . t3lib_utility_Debug::debugTrail();
  5199. $logMsg .= ' (' . substr($function->getFileName(), strlen(PATH_site)) . '#' . $function->getStartLine() . ')';
  5200. self::deprecationLog($logMsg);
  5201. }
  5202. /**
  5203. * Converts a one dimensional array to a one line string which can be used for logging or debugging output
  5204. * Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;"
  5205. *
  5206. * @param array $arr Data array which should be outputted
  5207. * @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.
  5208. * @param integer $valueLength Long string values are shortened to this length. Default: 20
  5209. * @return string Output string with key names and their value as string
  5210. */
  5211. public static function arrayToLogString(array $arr, $valueList = array(), $valueLength = 20) {
  5212. $str = '';
  5213. if (!is_array($valueList)) {
  5214. $valueList = self::trimExplode(',', $valueList, 1);
  5215. }
  5216. $valListCnt = count($valueList);
  5217. foreach ($arr as $key => $value) {
  5218. if (!$valListCnt || in_array($key, $valueList)) {
  5219. $str .= (string) $key . trim(': ' . self::fixed_lgd_cs(str_replace(LF, '|', (string) $value), $valueLength)) . '; ';
  5220. }
  5221. }
  5222. return $str;
  5223. }
  5224. /**
  5225. * Compile the command for running ImageMagick/GraphicsMagick.
  5226. *
  5227. * @param string $command Command to be run: identify, convert or combine/composite
  5228. * @param string $parameters The parameters string
  5229. * @param string $path Override the default path (e.g. used by the install tool)
  5230. * @return string Compiled command that deals with IM6 & GraphicsMagick
  5231. */
  5232. public static function imageMagickCommand($command, $parameters, $path = '') {
  5233. return t3lib_utility_Command::imageMagickCommand($command, $parameters, $path);
  5234. }
  5235. /**
  5236. * 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.
  5237. *
  5238. * @param string $parameters The whole parameters string
  5239. * @param boolean $unQuote If set, the elements of the resulting array are unquoted.
  5240. * @return array Exploded parameters
  5241. */
  5242. public static function unQuoteFilenames($parameters, $unQuote = FALSE) {
  5243. $paramsArr = explode(' ', trim($parameters));
  5244. $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.
  5245. foreach ($paramsArr as $k => $v) {
  5246. if ($quoteActive > -1) {
  5247. $paramsArr[$quoteActive] .= ' ' . $v;
  5248. unset($paramsArr[$k]);
  5249. if (substr($v, -1) === $paramsArr[$quoteActive][0]) {
  5250. $quoteActive = -1;
  5251. }
  5252. } elseif (!trim($v)) {
  5253. unset($paramsArr[$k]); // Remove empty elements
  5254. } elseif (preg_match('/^(["\'])/', $v) && substr($v, -1) !== $v[0]) {
  5255. $quoteActive = $k;
  5256. }
  5257. }
  5258. if ($unQuote) {
  5259. foreach ($paramsArr as $key => &$val) {
  5260. $val = preg_replace('/(^"|"$)/', '', $val);
  5261. $val = preg_replace('/(^\'|\'$)/', '', $val);
  5262. }
  5263. unset($val);
  5264. }
  5265. // return reindexed array
  5266. return array_values($paramsArr);
  5267. }
  5268. /**
  5269. * Quotes a string for usage as JS parameter. Depends whether the value is
  5270. * used in script tags (it doesn't need/must not get htmlspecialchar'ed in
  5271. * this case).
  5272. *
  5273. * @param string $value the string to encode, may be empty
  5274. * @param boolean $withinCData
  5275. * whether the escaped data is expected to be used as CDATA and thus
  5276. * does not need to be htmlspecialchared
  5277. *
  5278. * @return string the encoded value already quoted (with single quotes),
  5279. * will not be empty
  5280. */
  5281. static public function quoteJSvalue($value, $withinCData = FALSE) {
  5282. $escapedValue = addcslashes(
  5283. $value, '\'' . '"' . '\\' . TAB . LF . CR
  5284. );
  5285. if (!$withinCData) {
  5286. $escapedValue = htmlspecialchars($escapedValue);
  5287. }
  5288. return '\'' . $escapedValue . '\'';
  5289. }
  5290. /**
  5291. * Ends and cleans all output buffers
  5292. *
  5293. * @return void
  5294. */
  5295. public static function cleanOutputBuffers() {
  5296. while (ob_end_clean()) {
  5297. ;
  5298. }
  5299. header('Content-Encoding: None', TRUE);
  5300. }
  5301. /**
  5302. * Ends and flushes all output buffers
  5303. *
  5304. * @return void
  5305. */
  5306. public static function flushOutputBuffers() {
  5307. $obContent = '';
  5308. while ($obContent .= ob_get_clean()) {
  5309. ;
  5310. }
  5311. // if previously a "Content-Encoding: whatever" has been set, we have to unset it
  5312. if (!headers_sent()) {
  5313. $headersList = headers_list();
  5314. foreach ($headersList as $header) {
  5315. // split it up at the :
  5316. list($key, $value) = self::trimExplode(':', $header, TRUE);
  5317. // check if we have a Content-Encoding other than 'None'
  5318. if (strtolower($key) === 'content-encoding' && strtolower($value) !== 'none') {
  5319. header('Content-Encoding: None');
  5320. break;
  5321. }
  5322. }
  5323. }
  5324. echo $obContent;
  5325. }
  5326. }
  5327. ?>