PageRenderTime 45ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/typo3/class.t3lib_div.php

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