PageRenderTime 83ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/t3lib/class.t3lib_div.php

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