PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/MoodleWebRole/lib/typo3/class.t3lib_div.php

#
PHP | 3870 lines | 2071 code | 398 blank | 1401 comment | 423 complexity | 013f70fe32726de82f092d31e8b80e4f MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, LGPL-2.0, GPL-2.0
  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 1999-2005 Kasper Skaarhoj (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: class.t3lib_div.php,v 1.2.22.2 2009/11/19 10:10:50 skodak Exp $
  31. * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
  32. * XHTML compliant
  33. * Usage counts are based on search 22/2 2003 through whole source including tslib/
  34. *
  35. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  36. */
  37. /**
  38. * [CLASS/FUNCTION INDEX of SCRIPT]
  39. *
  40. *
  41. *
  42. * 211: class t3lib_div
  43. *
  44. * SECTION: GET/POST Variables
  45. * 241: function _GP($var)
  46. * 259: function _GET($var=NULL)
  47. * 276: function _POST($var=NULL)
  48. * 292: function _GETset($inputGet,$key='')
  49. * 315: function GPvar($var,$strip=0)
  50. * 332: function GParrayMerged($var)
  51. *
  52. * SECTION: IMAGE FUNCTIONS
  53. * 376: function gif_compress($theFile, $type)
  54. * 402: function png_to_gif_by_imagemagick($theFile)
  55. * 426: function read_png_gif($theFile,$output_png=0)
  56. *
  57. * SECTION: STRING FUNCTIONS
  58. * 475: function fixed_lgd($string,$origChars,$preStr='...')
  59. * 500: function fixed_lgd_pre($string,$chars)
  60. * 514: function fixed_lgd_cs($string,$chars)
  61. * 531: function breakTextForEmail($str,$implChar="\n",$charWidth=76)
  62. * 550: function breakLinesForEmail($str,$implChar="\n",$charWidth=76)
  63. * 585: function cmpIP($baseIP, $list)
  64. * 627: function cmpFQDN($baseIP, $list)
  65. * 657: function inList($list,$item)
  66. * 669: function rmFromList($element,$list)
  67. * 687: function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)
  68. * 703: function intval_positive($theInt)
  69. * 716: function int_from_ver($verNumberStr)
  70. * 728: function md5int($str)
  71. * 741: function shortMD5($input, $len=10)
  72. * 754: function uniqueList($in_list, $secondParameter=NULL)
  73. * 768: function split_fileref($fileref)
  74. * 805: function dirname($path)
  75. * 821: function modifyHTMLColor($color,$R,$G,$B)
  76. * 841: function modifyHTMLColorAll($color,$all)
  77. * 852: function rm_endcomma($string)
  78. * 865: function danish_strtoupper($string)
  79. * 880: function convUmlauts($str)
  80. * 893: function testInt($var)
  81. * 905: function isFirstPartOfStr($str,$partStr)
  82. * 921: function formatSize($sizeInBytes,$labels='')
  83. * 956: function convertMicrotime($microtime)
  84. * 970: function splitCalc($string,$operators)
  85. * 992: function calcPriority($string)
  86. * 1032: function calcParenthesis($string)
  87. * 1058: function htmlspecialchars_decode($value)
  88. * 1073: function deHSCentities($str)
  89. * 1086: function slashJS($string,$extended=0,$char="'")
  90. * 1099: function rawUrlEncodeJS($str)
  91. * 1111: function rawUrlEncodeFP($str)
  92. * 1122: function validEmail($email)
  93. * 1137: function formatForTextarea($content)
  94. *
  95. * SECTION: ARRAY FUNCTIONS
  96. * 1168: function inArray($in_array,$item)
  97. * 1185: function intExplode($delim, $string)
  98. * 1204: function revExplode($delim, $string, $count=0)
  99. * 1224: function trimExplode($delim, $string, $onlyNonEmptyValues=0)
  100. * 1246: function uniqueArray($valueArray)
  101. * 1258: function removeArrayEntryByValue($array,$cmpValue)
  102. * 1286: function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)
  103. * 1313: function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)
  104. * 1336: function addSlashesOnArray(&$theArray)
  105. * 1360: function stripSlashesOnArray(&$theArray)
  106. * 1382: function slashArray($arr,$cmd)
  107. * 1399: function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true)
  108. * 1432: function array_merge($arr1,$arr2)
  109. * 1445: function csvValues($row,$delim=',',$quote='"')
  110. *
  111. * SECTION: HTML/XML PROCESSING
  112. * 1487: function get_tag_attributes($tag)
  113. * 1524: function split_tag_attributes($tag)
  114. * 1558: function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
  115. * 1585: function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
  116. * 1600: function wrapJS($string, $linebreak=TRUE)
  117. * 1630: function xml2tree($string,$depth=999)
  118. * 1716: function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())
  119. * 1830: function xml2array($string,$NSprefix='',$reportDocTag=FALSE)
  120. * 1940: function xmlRecompileFromStructValArray($vals)
  121. * 1984: function xmlGetHeaderAttribs($xmlData)
  122. *
  123. * SECTION: FILES FUNCTIONS
  124. * 2016: function getURL($url)
  125. * 2058: function writeFile($file,$content)
  126. * 2075: function fixPermissions($file)
  127. * 2092: function writeFileToTypo3tempDir($filepath,$content)
  128. * 2135: function mkdir($theNewFolder)
  129. * 2155: function get_dirs($path)
  130. * 2180: function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')
  131. * 2234: function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)
  132. * 2257: function removePrefixPathFromList($fileArr,$prefixToRemove)
  133. * 2273: function fixWindowsFilePath($theFile)
  134. * 2285: function resolveBackPath($pathStr)
  135. * 2312: function locationHeaderUrl($path)
  136. *
  137. * SECTION: DEBUG helper FUNCTIONS
  138. * 2352: function debug_ordvalue($string,$characters=100)
  139. * 2369: function view_array($array_in)
  140. * 2397: function print_array($array_in)
  141. * 2412: function debug($var="",$brOrHeader=0)
  142. *
  143. * SECTION: SYSTEM INFORMATION
  144. * 2481: function getThisUrl()
  145. * 2497: function linkThisScript($getParams=array())
  146. * 2521: function linkThisUrl($url,$getParams=array())
  147. * 2546: function getIndpEnv($getEnvName)
  148. * 2735: function milliseconds()
  149. * 2747: function clientInfo($useragent='')
  150. *
  151. * SECTION: TYPO3 SPECIFIC FUNCTIONS
  152. * 2834: function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)
  153. * 2870: function validPathStr($theFile)
  154. * 2881: function isAbsPath($path)
  155. * 2892: function isAllowedAbsPath($path)
  156. * 2909: function verifyFilenameAgainstDenyPattern($filename)
  157. * 2927: function upload_copy_move($source,$destination)
  158. * 2953: function upload_to_tempfile($uploadedFileName)
  159. * 2971: function unlink_tempfile($uploadedTempFileName)
  160. * 2987: function tempnam($filePrefix)
  161. * 3000: function stdAuthCode($uid_or_record,$fields='')
  162. * 3030: function cHashParams($addQueryParams)
  163. * 3059: function loadTCA($table)
  164. * 3079: function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')
  165. * 3109: function resolveAllSheetsInDS($dataStructArray)
  166. * 3138: function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)
  167. * 3237: function &getUserObj($classRef,$checkPrefix='user_',$silent=0)
  168. * 3295: function &makeInstance($className)
  169. * 3307: function makeInstanceClassName($className)
  170. * 3321: function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())
  171. * 3382: function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)
  172. * 3427: function quoted_printable($string,$maxlen=76)
  173. * 3471: function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')
  174. * 3505: function makeRedirectUrl($inUrl,$l=0,$index_script_url='')
  175. * 3532: function freetypeDpiComp($font_size)
  176. * 3551: function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)
  177. * 3572: function arrayToLogString($arr, $valueList=array(), $valueLength=20)
  178. *
  179. * TOTAL FUNCTIONS: 117
  180. * (This index is automatically created/updated by the extension "extdeveval")
  181. *
  182. */
  183. /**
  184. * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
  185. * Most of the functions does not relate specifically to TYPO3
  186. * However a section of functions requires certain TYPO3 features available
  187. * See comments in the source.
  188. * You are encouraged to use this library in your own scripts!
  189. *
  190. * USE:
  191. * The class is intended to be used without creating an instance of it.
  192. * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
  193. * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
  194. *
  195. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  196. * @package TYPO3
  197. * @subpackage t3lib
  198. */
  199. class t3lib_div {
  200. /*************************
  201. *
  202. * GET/POST Variables
  203. *
  204. * Background:
  205. * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
  206. * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
  207. * But the clean solution is that quotes are never escaped and that is what the functions below offers.
  208. * Eventually TYPO3 should provide this in the global space as well.
  209. * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
  210. *
  211. *************************/
  212. /**
  213. * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
  214. * Strips slashes from all output, both strings and arrays.
  215. * This function substitutes t3lib_div::GPvar()
  216. * 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!
  217. * Usage: 537
  218. *
  219. * @param string GET/POST var to return
  220. * @return mixed POST var named $var and if not set, the GET var of the same name.
  221. * @see GPvar()
  222. */
  223. function _GP($var) {
  224. if(empty($var)) return;
  225. $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
  226. if (isset($value)) {
  227. if (is_array($value)) { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
  228. }
  229. return $value;
  230. }
  231. /**
  232. * Returns the global GET array (or value from) normalized to contain un-escaped values.
  233. * ALWAYS use this API function to acquire the GET variables!
  234. * Usage: 27
  235. *
  236. * @param string Optional pointer to value in GET array (basically name of GET var)
  237. * @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!*
  238. * @see _POST(), _GP(), _GETset()
  239. */
  240. function _GET($var=NULL) {
  241. $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
  242. if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
  243. if (is_array($value)) { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
  244. }
  245. return $value;
  246. }
  247. /**
  248. * Returns the global POST array (or value from) normalized to contain un-escaped values.
  249. * ALWAYS use this API function to acquire the POST variables!
  250. * Usage: 41
  251. *
  252. * @param string Optional pointer to value in POST array (basically name of POST var)
  253. * @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!*
  254. * @see _GET(), _GP()
  255. */
  256. function _POST($var=NULL) {
  257. $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
  258. if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
  259. if (is_array($value)) { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
  260. }
  261. return $value;
  262. }
  263. /**
  264. * Writes input value to $_GET
  265. * Usage: 2
  266. *
  267. * @param array Array to write to $_GET. Values should NOT be escaped at input time (but will be escaped before writing according to TYPO3 standards).
  268. * @param string Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value!
  269. * @return void
  270. */
  271. function _GETset($inputGet,$key='') {
  272. // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
  273. if (strcmp($key,'')) {
  274. if (is_array($inputGet)) { t3lib_div::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
  275. $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
  276. } elseif (is_array($inputGet)){
  277. t3lib_div::addSlashesOnArray($inputGet);
  278. $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
  279. }
  280. }
  281. /**
  282. * GET/POST variable
  283. * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
  284. * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
  285. * Usage: 2
  286. *
  287. * @param string GET/POST var to return
  288. * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
  289. * @return mixed POST var named $var and if not set, the GET var of the same name.
  290. * @deprecated Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
  291. * @see _GP()
  292. */
  293. function GPvar($var,$strip=0) {
  294. if(empty($var)) return;
  295. $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
  296. if (isset($value) && is_string($value)) { $value = stripslashes($value); } // Originally check '&& get_magic_quotes_gpc() ' but the values of $_GET are always slashed regardless of get_magic_quotes_gpc() because HTTP_POST/GET_VARS are run through addSlashesOnArray in the very beginning of index_ts.php eg.
  297. if ($strip && isset($value) && is_array($value)) { t3lib_div::stripSlashesOnArray($value); }
  298. return $value;
  299. }
  300. /**
  301. * Returns the GET/POST global arrays merged with POST taking precedence.
  302. * Usage: 1
  303. *
  304. * @param string Key (variable name) from GET or POST vars
  305. * @return array Returns the GET vars merged recursively onto the POST vars.
  306. * @ignore
  307. * @deprecated
  308. */
  309. function GParrayMerged($var) {
  310. $postA = is_array($_POST[$var]) ? $_POST[$var] : array();
  311. $getA = is_array($_GET[$var]) ? $_GET[$var] : array();
  312. $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA);
  313. t3lib_div::stripSlashesOnArray($mergedA);
  314. return $mergedA;
  315. }
  316. /*************************
  317. *
  318. * IMAGE FUNCTIONS
  319. *
  320. *************************/
  321. /**
  322. * Compressing a GIF file if not already LZW compressed
  323. * 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)
  324. *
  325. * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
  326. * GIF:
  327. * 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!)
  328. * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
  329. * PNG:
  330. * No changes.
  331. *
  332. * $theFile is expected to be a valid GIF-file!
  333. * The function returns a code for the operation.
  334. * Usage: 9
  335. *
  336. * @param string Filepath
  337. * @param string See description of function
  338. * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
  339. * @internal
  340. */
  341. function gif_compress($theFile, $type) {
  342. $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
  343. $returnCode='';
  344. if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF...
  345. if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
  346. $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
  347. exec($cmd);
  348. $returnCode='IM';
  349. } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
  350. $tempImage = imageCreateFromGif($theFile);
  351. imageGif($tempImage, $theFile);
  352. imageDestroy($tempImage);
  353. $returnCode='GD';
  354. }
  355. }
  356. return $returnCode;
  357. }
  358. /**
  359. * Converts a png file to gif
  360. * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
  361. * Usage: 5
  362. *
  363. * @param string $theFile the filename with path
  364. * @return string new filename
  365. * @internal
  366. */
  367. function png_to_gif_by_imagemagick($theFile) {
  368. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
  369. && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
  370. && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
  371. && strtolower(substr($theFile,-4,4))=='.png'
  372. && @is_file($theFile)) { // IM
  373. $newFile = substr($theFile,0,-4).'.gif';
  374. $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $gfxConf['im_path_lzw']);
  375. exec($cmd);
  376. $theFile = $newFile;
  377. // 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!!
  378. }
  379. return $theFile;
  380. }
  381. /**
  382. * Returns filename of the png/gif version of the input file (which can be png or gif).
  383. * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
  384. * Usage: 2
  385. *
  386. * @param string Filepath of image file
  387. * @param boolean If set, then input file is converted to PNG, otherwise to GIF
  388. * @return string If the new image file exists, it's filepath is returned
  389. * @internal
  390. */
  391. function read_png_gif($theFile,$output_png=0) {
  392. if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) {
  393. $ext = strtolower(substr($theFile,-4,4));
  394. if (
  395. ((string)$ext=='.png' && $output_png) ||
  396. ((string)$ext=='.gif' && !$output_png)
  397. ) {
  398. return $theFile;
  399. } else {
  400. $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
  401. exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
  402. if (@is_file($newFile)) return $newFile;
  403. }
  404. }
  405. }
  406. /*************************
  407. *
  408. * STRING FUNCTIONS
  409. *
  410. *************************/
  411. /**
  412. * Truncate string
  413. * Returns a new string of max. $chars length.
  414. * If the string is longer, it will be truncated and appended with '...'.
  415. * DEPRECIATED. Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
  416. * Usage: 39
  417. *
  418. * @param string $string string to truncate
  419. * @param integer $chars must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
  420. * @param string String to append to the output if it is truncated, default is '...'
  421. * @return string new string
  422. * @see fixed_lgd_pre()
  423. */
  424. function fixed_lgd($string,$origChars,$preStr='...') {
  425. $chars = abs($origChars);
  426. if ($chars >= 4) {
  427. if(strlen($string)>$chars) {
  428. return $origChars < 0 ?
  429. $preStr.trim(substr($string, -($chars-3))) :
  430. trim(substr($string, 0, $chars-3)).$preStr;
  431. }
  432. }
  433. return $string;
  434. }
  435. /**
  436. * Truncate string
  437. * Returns a new string of max. $chars length.
  438. * If the string is longer, it will be truncated and prepended with '...'.
  439. * This works like fixed_lgd, but is truncated in the start of the string instead of the end
  440. * DEPRECIATED. Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
  441. * Usage: 6
  442. *
  443. * @param string $string string to truncate
  444. * @param integer $chars must be an integer of at least 4
  445. * @return string new string
  446. * @see fixed_lgd()
  447. */
  448. function fixed_lgd_pre($string,$chars) {
  449. return strrev(t3lib_div::fixed_lgd(strrev($string),$chars));
  450. }
  451. /**
  452. * Truncates a string with appended/prepended "..." and takes backend character set into consideration
  453. * Use only from backend!
  454. * Usage: 75
  455. *
  456. * @param string $string string to truncate
  457. * @param integer $chars must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
  458. * @return string New string
  459. * @see fixed_lgd()
  460. */
  461. function fixed_lgd_cs($string,$chars) {
  462. if (is_object($GLOBALS['LANG'])) {
  463. return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet,$string,$chars,'...');
  464. } else {
  465. return t3lib_div::fixed_lgd($string, $chars);
  466. }
  467. }
  468. /**
  469. * Breaks up the text for emails
  470. * Usage: 1
  471. *
  472. * @param string The string to break up
  473. * @param string The string to implode the broken lines with (default/typically \n)
  474. * @param integer The line length
  475. * @return string
  476. */
  477. function breakTextForEmail($str,$implChar="\n",$charWidth=76) {
  478. $lines = explode(chr(10),$str);
  479. $outArr=array();
  480. while(list(,$lStr)=each($lines)) {
  481. $outArr = array_merge($outArr,t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth));
  482. }
  483. return implode(chr(10),$outArr);
  484. }
  485. /**
  486. * Breaks up a single line of text for emails
  487. * Usage: 5
  488. *
  489. * @param string The string to break up
  490. * @param string The string to implode the broken lines with (default/typically \n)
  491. * @param integer The line length
  492. * @return string
  493. * @see breakTextForEmail()
  494. */
  495. function breakLinesForEmail($str,$implChar="\n",$charWidth=76) {
  496. $lines=array();
  497. $l=$charWidth;
  498. $p=0;
  499. while(strlen($str)>$p) {
  500. $substr=substr($str,$p,$l);
  501. if (strlen($substr)==$l) {
  502. $count = count(explode(' ',trim(strrev($substr))));
  503. if ($count>1) { // OK...
  504. $parts = explode(' ',strrev($substr),2);
  505. $theLine = strrev($parts[1]);
  506. } else {
  507. $afterParts = explode(' ',substr($str,$l+$p),2);
  508. $theLine = $substr.$afterParts[0];
  509. }
  510. if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop.
  511. } else {
  512. $theLine=$substr;
  513. }
  514. $lines[]=trim($theLine);
  515. $p+=strlen($theLine);
  516. if (!trim(substr($str,$p,$l))) break; // added...
  517. }
  518. return implode($implChar,$lines);
  519. }
  520. /**
  521. * Match IP number with list of numbers with wildcard
  522. * Usage: 10
  523. *
  524. * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
  525. * @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)
  526. * @return boolean True if an IP-mask from $list matches $baseIP
  527. */
  528. function cmpIP($baseIP, $list) {
  529. $IPpartsReq = explode('.',$baseIP);
  530. if (count($IPpartsReq)==4) {
  531. $values = t3lib_div::trimExplode(',',$list,1);
  532. foreach($values as $test) {
  533. list($test,$mask) = explode('/',$test);
  534. if(intval($mask)) {
  535. // "192.168.3.0/24"
  536. $lnet = ip2long($test);
  537. $lip = ip2long($baseIP);
  538. $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
  539. $firstpart = substr($binnet,0,$mask);
  540. $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
  541. $firstip = substr($binip,0,$mask);
  542. $yes = (strcmp($firstpart,$firstip)==0);
  543. } else {
  544. // "192.168.*.*"
  545. $IPparts = explode('.',$test);
  546. $yes = 1;
  547. reset($IPparts);
  548. while(list($index,$val)=each($IPparts)) {
  549. $val = trim($val);
  550. if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
  551. $yes=0;
  552. }
  553. }
  554. }
  555. if ($yes) return true;
  556. }
  557. }
  558. return false;
  559. }
  560. /**
  561. * Match fully qualified domain name with list of strings with wildcard
  562. *
  563. * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
  564. * @param string $list is 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)
  565. * @return boolean True if a domain name mask from $list matches $baseIP
  566. */
  567. function cmpFQDN($baseIP, $list) {
  568. if (count(explode('.',$baseIP))==4) {
  569. $resolvedHostName = explode('.', gethostbyaddr($baseIP));
  570. $values = t3lib_div::trimExplode(',',$list,1);
  571. foreach($values as $test) {
  572. $hostNameParts = explode('.',$test);
  573. $yes = 1;
  574. foreach($hostNameParts as $index => $val) {
  575. $val = trim($val);
  576. if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
  577. $yes=0;
  578. }
  579. }
  580. if ($yes) return true;
  581. }
  582. }
  583. return false;
  584. }
  585. /**
  586. * Check for item in list
  587. * Check if an item exists in a comma-separated list of items.
  588. * Usage: 163
  589. *
  590. * @param string comma-separated list of items (string)
  591. * @param string item to check for
  592. * @return boolean true if $item is in $list
  593. */
  594. function inList($list,$item) {
  595. return strstr(','.$list.',', ','.$item.',') ? true : false;
  596. }
  597. /**
  598. * Removes an item from a comma-separated list of items.
  599. * Usage: 1
  600. *
  601. * @param string $element element to remove
  602. * @param string $list comma-separated list of items (string)
  603. * @return string new comma-separated list of items
  604. */
  605. function rmFromList($element,$list) {
  606. $items = explode(',',$list);
  607. while(list($k,$v)=each($items)) {
  608. if ($v==$element) {unset($items[$k]);}
  609. }
  610. return implode(',',$items);
  611. }
  612. /**
  613. * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
  614. * Ranges are limited to 1000 values per range.
  615. *
  616. * @param string $list comma-separated list of integers with ranges (string)
  617. * @return string new comma-separated list of items
  618. * @author Martin Kutschker <martin.kutschker@activesolution.at>
  619. */
  620. function expandList($list) {
  621. $items = explode(',',$list);
  622. $list = array();
  623. while(list(,$item)=each($items)) {
  624. $range = explode('-',$item);
  625. if (isset($range[1])) {
  626. $runAwayBrake = 1000;
  627. for ($n=$range[0]; $n<=$range[1]; $n++) {
  628. $list[] = $n;
  629. $runAwayBrake--;
  630. if ($runAwayBrake<=0) break;
  631. }
  632. } else {
  633. $list[] = $item;
  634. }
  635. }
  636. return implode(',',$list);
  637. }
  638. /**
  639. * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
  640. * Usage: 224
  641. *
  642. * @param integer Input value
  643. * @param integer Lower limit
  644. * @param integer Higher limit
  645. * @param integer Default value if input is false.
  646. * @return integer The input value forced into the boundaries of $min and $max
  647. */
  648. function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
  649. // Returns $theInt as an integer in the integerspace from $min to $max
  650. $theInt = intval($theInt);
  651. if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
  652. if ($theInt<$min){$theInt=$min;}
  653. if ($theInt>$max){$theInt=$max;}
  654. return $theInt;
  655. }
  656. /**
  657. * Returns the $integer if greater than zero, otherwise returns zero.
  658. * Usage: 1
  659. *
  660. * @param integer Integer string to process
  661. * @return integer
  662. */
  663. function intval_positive($theInt) {
  664. $theInt = intval($theInt);
  665. if ($theInt<0){$theInt=0;}
  666. return $theInt;
  667. }
  668. /**
  669. * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
  670. * Usage: 2
  671. *
  672. * @param string Version number on format x.x.x
  673. * @return integer Integer version of version number (where each part can count to 999)
  674. */
  675. function int_from_ver($verNumberStr) {
  676. $verParts = explode('.',$verNumberStr);
  677. 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));
  678. }
  679. /**
  680. * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
  681. * Usage: 5
  682. *
  683. * @param string String to md5-hash
  684. * @return integer Returns 28bit integer-hash
  685. */
  686. function md5int($str) {
  687. return hexdec(substr(md5($str),0,7));
  688. }
  689. /**
  690. * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
  691. *
  692. * Usage: 37
  693. *
  694. * @param string Input string to be md5-hashed
  695. * @param integer The string-length of the output
  696. * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
  697. */
  698. function shortMD5($input, $len=10) {
  699. return substr(md5($input),0,$len);
  700. }
  701. /**
  702. * Takes comma-separated lists and arrays and removes all duplicates
  703. * If a value in the list is trim(empty), the value is ignored.
  704. * Usage: 16
  705. *
  706. * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
  707. * @param mixed $secondParameter: Dummy field, which is set will show a warning!
  708. * @return string Returns the list without any duplicates of values, space around values are trimmed
  709. */
  710. function uniqueList($in_list, $secondParameter=NULL) {
  711. if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
  712. if (isset($secondParameter)) die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
  713. return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1)));
  714. }
  715. /**
  716. * Splits a reference to a file in 5 parts
  717. * Usage: 43
  718. *
  719. * @param string Filename/filepath to be analysed
  720. * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
  721. */
  722. function split_fileref($fileref) {
  723. if ( ereg('(.*/)(.*)$',$fileref,$reg) ) {
  724. $info['path'] = $reg[1];
  725. $info['file'] = $reg[2];
  726. } else {
  727. $info['path'] = '';
  728. $info['file'] = $fileref;
  729. }
  730. $reg='';
  731. if ( ereg('(.*)\.([^\.]*$)',$info['file'],$reg) ) {
  732. $info['filebody'] = $reg[1];
  733. $info['fileext'] = strtolower($reg[2]);
  734. $info['realFileext'] = $reg[2];
  735. } else {
  736. $info['filebody'] = $info['file'];
  737. $info['fileext'] = '';
  738. }
  739. reset($info);
  740. return $info;
  741. }
  742. /**
  743. * Returns the directory part of a path without trailing slash
  744. * If there is no dir-part, then an empty string is returned.
  745. * Behaviour:
  746. *
  747. * '/dir1/dir2/script.php' => '/dir1/dir2'
  748. * '/dir1/' => '/dir1'
  749. * 'dir1/script.php' => 'dir1'
  750. * 'd/script.php' => 'd'
  751. * '/script.php' => ''
  752. * '' => ''
  753. * Usage: 5
  754. *
  755. * @param string Directory name / path
  756. * @return string Processed input value. See function description.
  757. */
  758. function dirname($path) {
  759. $p=t3lib_div::revExplode('/',$path,2);
  760. return count($p)==2?$p[0]:'';
  761. }
  762. /**
  763. * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
  764. * Usage: 11
  765. *
  766. * @param string A hexadecimal color code, #xxxxxx
  767. * @param integer Offset value 0-255
  768. * @param integer Offset value 0-255
  769. * @param integer Offset value 0-255
  770. * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
  771. * @see modifyHTMLColorAll()
  772. */
  773. function modifyHTMLColor($color,$R,$G,$B) {
  774. // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
  775. $nR = t3lib_div::intInRange(hexdec(substr($color,1,2))+$R,0,255);
  776. $nG = t3lib_div::intInRange(hexdec(substr($color,3,2))+$G,0,255);
  777. $nB = t3lib_div::intInRange(hexdec(substr($color,5,2))+$B,0,255);
  778. return '#'.
  779. substr('0'.dechex($nR),-2).
  780. substr('0'.dechex($nG),-2).
  781. substr('0'.dechex($nB),-2);
  782. }
  783. /**
  784. * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
  785. * Usage: 6
  786. *
  787. * @param string A hexadecimal color code, #xxxxxx
  788. * @param integer Offset value 0-255 for all three channels.
  789. * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
  790. * @see modifyHTMLColor()
  791. */
  792. function modifyHTMLColorAll($color,$all) {
  793. return t3lib_div::modifyHTMLColor($color,$all,$all,$all);
  794. }
  795. /**
  796. * Removes comma (if present) in the end of string
  797. * Usage: 2
  798. *
  799. * @param string String from which the comma in the end (if any) will be removed.
  800. * @return string
  801. */
  802. function rm_endcomma($string) {
  803. return ereg_replace(',$','',$string);
  804. }
  805. /**
  806. * strtoupper which converts danish (and other characters) characters as well
  807. * (DEPRECIATED, use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
  808. * Usage: 0
  809. *
  810. * @param string String to process
  811. * @return string
  812. * @ignore
  813. */
  814. function danish_strtoupper($string) {
  815. $value = strtoupper($string);
  816. return strtr($value, 'áéúíâęűôîćřĺäöü', 'ÁÉÚÍÄËÜÖĎĆŘĹÄÖÜ');
  817. }
  818. /**
  819. * Change umlaut characters to plain ASCII with normally two character target
  820. * Only known characters will be converted, so don't expect a result for any character.
  821. * (DEPRECIATED: Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!)
  822. *
  823. * ä => ae, Ö => Oe
  824. *
  825. * @param string String to convert.
  826. * @return string
  827. */
  828. function convUmlauts($str) {
  829. $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/ĺ/', '/Ĺ/', '/ř/', '/Ř/', '/ć/', '/Ć/' );
  830. $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
  831. return preg_replace($pat,$repl,$str);
  832. }
  833. /**
  834. * Tests if the input is an integer.
  835. * Usage: 77
  836. *
  837. * @param mixed Any input variable to test.
  838. * @return boolean Returns true if string is an integer
  839. */
  840. function testInt($var) {
  841. return !strcmp($var,intval($var));
  842. }
  843. /**
  844. * Returns true if the first part of $str matches the string $partStr
  845. * Usage: 59
  846. *
  847. * @param string Full string to check
  848. * @param string Reference string which must be found as the "first part" of the full string
  849. * @return boolean True if $partStr was found to be equal to the first part of $str
  850. */
  851. function isFirstPartOfStr($str,$partStr) {
  852. // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
  853. $psLen = strlen($partStr);
  854. if ($psLen) {
  855. return substr($str,0,$psLen)==(string)$partStr;
  856. } else return false;
  857. }
  858. /**
  859. * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
  860. * Usage: 53
  861. *
  862. * @param integer Number of bytes to format.
  863. * @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)
  864. * @return string Formatted representation of the byte number, for output.
  865. */
  866. function formatSize($sizeInBytes,$labels='') {
  867. // Set labels:
  868. if (strlen($labels) == 0) {
  869. $labels = ' | K| M| G';
  870. } else {
  871. $labels = str_replace('"','',$labels);
  872. }
  873. $labelArr = explode('|',$labels);
  874. // Find size:
  875. if ($sizeInBytes>900) {
  876. if ($sizeInBytes>900000000) { // GB
  877. $val = $sizeInBytes/(1024*1024*1024);
  878. return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
  879. }
  880. elseif ($sizeInBytes>900000) { // MB
  881. $val = $sizeInBytes/(1024*1024);
  882. return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
  883. } else { // KB
  884. $val = $sizeInBytes/(1024);
  885. return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
  886. }
  887. } else { // Bytes
  888. return $sizeInBytes.$labelArr[0];
  889. }
  890. }
  891. /**
  892. * Returns microtime input to milliseconds
  893. * Usage: 2
  894. *
  895. * @param string Microtime
  896. * @return integer Microtime input string converted to an integer (milliseconds)
  897. */
  898. function convertMicrotime($microtime) {
  899. $parts = explode(' ',$microtime);
  900. return round(($parts[0]+$parts[1])*1000);
  901. }
  902. /**
  903. * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
  904. * Usage: 2
  905. *
  906. * @param string Input string, eg "123 + 456 / 789 - 4"
  907. * @param string Operators to split by, typically "/+-*"
  908. * @return array Array with operators and operands separated.
  909. * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
  910. */
  911. function splitCalc($string,$operators) {
  912. $res = Array();
  913. $sign='+';
  914. while($string) {
  915. $valueLen=strcspn($string,$operators);
  916. $value=substr($string,0,$valueLen);
  917. $res[] = Array($sign,trim($value));
  918. $sign=substr($string,$valueLen,1);
  919. $string=substr($string,$valueLen+1);
  920. }
  921. reset($res);
  922. return $res;
  923. }
  924. /**
  925. * Calculates the input by +,-,*,/,%,^ with priority to + and -
  926. * Usage: 1
  927. *
  928. * @param string Input string, eg "123 + 456 / 789 - 4"
  929. * @return integer Calculated value. Or error string.
  930. * @see calcParenthesis()
  931. */
  932. function calcPriority($string) {
  933. $string=ereg_replace('[[:space:]]*','',$string); // removing all whitespace
  934. $string='+'.$string; // Ensuring an operator for the first entrance
  935. $qm='\*\/\+-^%';
  936. $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
  937. // split the expression here:
  938. preg_match_all('/'.$regex.'/',$string,$reg);
  939. reset($reg[2]);
  940. $number=0;
  941. $Msign='+';
  942. $err='';
  943. $buffer=doubleval(current($reg[2]));
  944. next($reg[2]); // Advance pointer
  945. while(list($k,$v)=each($reg[2])) {
  946. $v=doubleval($v);
  947. $sign = $reg[1][$k];
  948. if ($sign=='+' || $sign=='-') {
  949. $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
  950. $Msign = $sign;
  951. $buffer=$v;
  952. } else {
  953. if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
  954. if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
  955. if ($sign=='*') {$buffer*=$v;}
  956. if ($sign=='^') {$buffer=pow($buffer,$v);}
  957. }
  958. }
  959. $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
  960. return $err ? 'ERROR: '.$err : $number;
  961. }
  962. /**
  963. * Calculates the input with parenthesis levels
  964. * Usage: 2
  965. *
  966. * @param string Input string, eg "(123 + 456) / 789 - 4"
  967. * @return integer Calculated value. Or error string.
  968. * @see calcPriority(), tslib_cObj::stdWrap()
  969. */
  970. function calcParenthesis($string) {
  971. $securC=100;
  972. do {
  973. $valueLenO=strcspn($string,'(');
  974. $valueLenC=strcspn($string,')');
  975. if ($valueLenC==strlen($string) || $valueLenC < $valueLenO) {
  976. $value = t3lib_div::calcPriority(substr($string,0,$valueLenC));
  977. $string = $value.substr($string,$valueLenC+1);
  978. return $string;
  979. } else {
  980. $string = substr($string,0,$valueLenO).t3lib_div::calcParenthesis(substr($string,$valueLenO+1));
  981. }
  982. // Security:
  983. $securC--;
  984. if ($securC<=0) break;
  985. } while($valueLenO<strlen($string));
  986. return $string;
  987. }
  988. /**
  989. * Inverse version of htmlspecialchars()
  990. * Usage: 4
  991. *
  992. * @param string Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
  993. * @return string Converted result.
  994. */
  995. function htmlspecialchars_decode($value) {
  996. $value = str_replace('&gt;','>',$value);
  997. $value = str_replace('&lt;','<',$value);
  998. $value = str_replace('&quot;','"',$value);
  999. $value = str_replace('&amp;','&',$value);
  1000. return $value;
  1001. }
  1002. /**
  1003. * Re-converts HTML entities if they have been converted by htmlspecialchars()
  1004. * Usage: 10
  1005. *
  1006. * @param string String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;"
  1007. * @return string Converted result.
  1008. */
  1009. function deHSCentities($str) {
  1010. return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
  1011. }
  1012. /**
  1013. * This function is used to escape any ' -characters when transferring text to JavaScript!
  1014. * Usage: 3
  1015. *
  1016. * @param string String to escape
  1017. * @param boolean If set, also backslashes are escaped.
  1018. * @param string The character to escape, default is ' (single-quote)
  1019. * @return string Processed input string
  1020. */
  1021. function slashJS($string,$extended=0,$char="'") {
  1022. if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
  1023. return str_replace ($char, "\\".$char, $string);
  1024. }
  1025. /**
  1026. * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
  1027. * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
  1028. * Usage: 4
  1029. *
  1030. * @param string String to raw-url-encode with spaces preserved
  1031. * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
  1032. */
  1033. function rawUrlEncodeJS($str) {
  1034. return str_replace('%20',' ',rawurlencode($str));
  1035. }
  1036. /**
  1037. * rawurlencode which preserves "/" chars
  1038. * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
  1039. * Usage: 5
  1040. *
  1041. * @param string Input string
  1042. * @return string Output string
  1043. */
  1044. function rawUrlEncodeFP($str) {
  1045. return str_replace('%2F','/',rawurlencode($str));
  1046. }
  1047. /**
  1048. * Checking syntax of input email address
  1049. * Usage: 5
  1050. *
  1051. * @param string Input string to evaluate
  1052. * @return boolean Returns true if the $email address (input string) is valid; Has a "@", domain name with at least one period and only allowed a-z characters.
  1053. */
  1054. function validEmail($email) {
  1055. $email = trim ($email);
  1056. if (strstr($email,' ')) return FALSE;
  1057. return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
  1058. }
  1059. /**
  1060. * Formats a string for output between <textarea>-tags
  1061. * All content outputted in a textarea form should be passed through this function
  1062. * 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!
  1063. * Usage: 23
  1064. *
  1065. * @param string Input string to be formatted.
  1066. * @return string Formatted for <textarea>-tags
  1067. */
  1068. function formatForTextarea($content) {
  1069. return chr(10).htmlspecialchars($content);
  1070. }
  1071. /*************************
  1072. *
  1073. * ARRAY FUNCTIONS
  1074. *
  1075. *************************/
  1076. /**
  1077. * Check if an item exists in an array
  1078. * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
  1079. * Usage: 3
  1080. *
  1081. * @param array $in_array one-dimensional array of items
  1082. * @param string $item item to check for
  1083. * @return boolean true if $item is in the one-dimensional array $in_array
  1084. * @internal
  1085. */
  1086. function inArray($in_array,$item) {
  1087. if (is_array($in_array)) {
  1088. while (list(,$val)=each($in_array)) {
  1089. if (!is_array($val) && !strcmp($val,$item)) return true;
  1090. }
  1091. }
  1092. }
  1093. /**
  1094. * Explodes a $string delimited by $delim and passes each item in the array through intval().
  1095. * Corresponds to explode(), but with conversion to integers for all values.
  1096. * Usage: 76
  1097. *
  1098. * @param string Delimiter string to explode with
  1099. * @param string The string to explode
  1100. * @return array Exploded values, all converted to integers
  1101. */
  1102. function intExplode($delim, $string) {
  1103. $temp = explode($delim,$string);
  1104. while(list($key,$val)=each($temp)) {
  1105. $temp[$key]=intval($val);
  1106. }
  1107. reset($temp);
  1108. return $temp;
  1109. }
  1110. /**
  1111. * Reverse explode which explodes the string counting from behind.
  1112. * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
  1113. * Usage: 8
  1114. *
  1115. * @param string Delimiter string to explode with
  1116. * @param string The string to explode
  1117. * @param integer Number of array entries
  1118. * @return array Exploded values
  1119. */
  1120. function revExplode($delim, $string, $count=0) {
  1121. $temp = explode($delim,strrev($string),$count);
  1122. while(list($key,$val)=each($temp)) {
  1123. $temp[$key]=strrev($val);
  1124. }
  1125. $temp=array_reverse($temp);
  1126. reset($temp);
  1127. return $temp;
  1128. }
  1129. /**
  1130. * Explodes a string and trims all values for whitespace in the ends.
  1131. * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
  1132. * Usage: 256
  1133. *
  1134. * @param string Delimiter string to explode with
  1135. * @param string The string to explode
  1136. * @param boolean If set, all empty values (='') will NOT be set in output
  1137. * @return array Exploded values
  1138. */
  1139. function trimExplode($delim, $string, $onlyNonEmptyValues=0) {
  1140. $temp = explode($delim,$string);
  1141. $newtemp=array();
  1142. while(list($key,$val)=each($temp)) {
  1143. if (!$onlyNonEmptyValues || strcmp('',trim($val))) {
  1144. $newtemp[]=trim($val);
  1145. }
  1146. }
  1147. reset($newtemp);
  1148. return $newtemp;
  1149. }
  1150. /**
  1151. * Remove duplicate values from an array
  1152. * This function is deprecated, use the PHP function array_unique instead
  1153. * Usage: 0
  1154. *
  1155. * @param array Array of values to make unique
  1156. * @return array
  1157. * @ignore
  1158. * @deprecated
  1159. */
  1160. function uniqueArray($valueArray) {
  1161. return array_unique($valueArray);
  1162. }
  1163. /**
  1164. * Removes the value $cmpValue from the $array if found there. Returns the modified array
  1165. * Usage: 3
  1166. *
  1167. * @param array Array containing the values
  1168. * @param string Value to search for and if found remove array entry where found.
  1169. * @return array Output array with entries removed if search string is found
  1170. */
  1171. function removeArrayEntryByValue($array,$cmpValue) {
  1172. if (is_array($array)) {
  1173. reset($array);
  1174. while(list($k,$v)=each($array)) {
  1175. if (is_array($v)) {
  1176. $array[$k] = t3lib_div::removeArrayEntryByValue($v,$cmpValue);
  1177. } else {
  1178. if (!strcmp($v,$cmpValue)) {
  1179. unset($array[$k]);
  1180. }
  1181. }
  1182. }
  1183. }
  1184. reset($array);
  1185. return $array;
  1186. }
  1187. /**
  1188. * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
  1189. * Usage: 24
  1190. *
  1191. * @param string Name prefix for entries. Set to blank if you wish none.
  1192. * @param array The (multidim) array to implode
  1193. * @param string (keep blank)
  1194. * @param boolean If set, parameters which were blank strings would be removed.
  1195. * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
  1196. * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
  1197. * @see explodeUrl2Array()
  1198. */
  1199. function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) {
  1200. if (is_array($theArray)) {
  1201. foreach($theArray as $Akey => $AVal) {
  1202. $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
  1203. if (is_array($AVal)) {
  1204. $str = t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
  1205. } else {
  1206. if (!$skipBlank || strcmp($AVal,'')) {
  1207. $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
  1208. '='.rawurlencode($AVal);
  1209. }
  1210. }
  1211. }
  1212. }
  1213. return $str;
  1214. }
  1215. /**
  1216. * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
  1217. *
  1218. * @param string GETvars string
  1219. * @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())
  1220. * @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!
  1221. * @see implodeArrayForUrl()
  1222. */
  1223. function explodeUrl2Array($string,$multidim=FALSE) {
  1224. if ($multidim) {
  1225. parse_str($string,$tempGetVars);
  1226. return $tempGetVars;
  1227. } else {
  1228. $output = array();
  1229. $p = explode('&',$string);
  1230. foreach($p as $v) {
  1231. if (strlen($v)) {
  1232. list($pK,$pV) = explode('=',$v,2);
  1233. $output[rawurldecode($pK)] = rawurldecode($pV);
  1234. }
  1235. }
  1236. return $output;
  1237. }
  1238. }
  1239. /**
  1240. * Returns an array with selected keys from incoming data.
  1241. * (Better read source code if you want to find out...)
  1242. * Usage: 3
  1243. *
  1244. * @param string List of variable/key names
  1245. * @param array Array from where to get values based on the keys in $varList
  1246. * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
  1247. * @return array Output array with selected variables.
  1248. */
  1249. function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1) {
  1250. $keys = t3lib_div::trimExplode(',',$varList,1);
  1251. $outArr=array();
  1252. foreach($keys as $v) {
  1253. if (isset($getArray[$v])) {
  1254. $outArr[$v]=$getArray[$v];
  1255. } elseif ($GPvarAlt) {
  1256. $outArr[$v]=t3lib_div::_GP($v);
  1257. }
  1258. }
  1259. return $outArr;
  1260. }
  1261. /**
  1262. * AddSlash array
  1263. * This function traverses a multidimentional array and adds slashes to the values.
  1264. * NOTE that the input array is and argument by reference.!!
  1265. * Twin-function to stripSlashesOnArray
  1266. * Usage: 8
  1267. *
  1268. * @param array Multidimensional input array, (REFERENCE!)
  1269. * @return array
  1270. */
  1271. function addSlashesOnArray(&$theArray) {
  1272. if (is_array($theArray)) {
  1273. reset($theArray);
  1274. while(list($Akey,$AVal)=each($theArray)) {
  1275. if (is_array($AVal)) {
  1276. t3lib_div::addSlashesOnArray($theArray[$Akey]);
  1277. } else {
  1278. $theArray[$Akey] = addslashes($AVal);
  1279. }
  1280. }
  1281. reset($theArray);
  1282. }
  1283. }
  1284. /**
  1285. * StripSlash array
  1286. * This function traverses a multidimentional array and strips slashes to the values.
  1287. * NOTE that the input array is and argument by reference.!!
  1288. * Twin-function to addSlashesOnArray
  1289. * Usage: 10
  1290. *
  1291. * @param array Multidimensional input array, (REFERENCE!)
  1292. * @return array
  1293. */
  1294. function stripSlashesOnArray(&$theArray) {
  1295. if (is_array($theArray)) {
  1296. reset($theArray);
  1297. while(list($Akey,$AVal)=each($theArray)) {
  1298. if (is_array($AVal)) {
  1299. t3lib_div::stripSlashesOnArray($theArray[$Akey]);
  1300. } else {
  1301. $theArray[$Akey] = stripslashes($AVal);
  1302. }
  1303. }
  1304. reset($theArray);
  1305. }
  1306. }
  1307. /**
  1308. * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
  1309. * Usage: 0
  1310. *
  1311. * @param array Multidimensional input array
  1312. * @param string "add" or "strip", depending on usage you wish.
  1313. * @return array
  1314. */
  1315. function slashArray($arr,$cmd) {
  1316. if ($cmd=='strip') t3lib_div::stripSlashesOnArray($arr);
  1317. if ($cmd=='add') t3lib_div::addSlashesOnArray($arr);
  1318. return $arr;
  1319. }
  1320. /**
  1321. * Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the first array ($arr0) with the values of the second array ($arr1)
  1322. * In case of identical keys, ie. keeping the values of the second.
  1323. * Usage: 0
  1324. *
  1325. * @param array First array
  1326. * @param array Second array, overruling the first array
  1327. * @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.
  1328. * @param boolean If set, values from $arr1 will overrule if they are empty. Default: true
  1329. * @return array Resulting array where $arr1 values has overruled $arr0 values
  1330. */
  1331. function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
  1332. reset($arr1);
  1333. while(list($key,$val) = each($arr1)) {
  1334. if(is_array($arr0[$key])) {
  1335. if (is_array($arr1[$key])) {
  1336. $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
  1337. }
  1338. } else {
  1339. if ($notAddKeys) {
  1340. if (isset($arr0[$key])) {
  1341. if ($includeEmtpyValues OR $val) {
  1342. $arr0[$key] = $val;
  1343. }
  1344. }
  1345. } else {
  1346. if ($includeEmtpyValues OR $val) {
  1347. $arr0[$key] = $val;
  1348. }
  1349. }
  1350. }
  1351. }
  1352. reset($arr0);
  1353. return $arr0;
  1354. }
  1355. /**
  1356. * 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.
  1357. * Usage: 16
  1358. *
  1359. * @param array First array
  1360. * @param array Second array
  1361. * @return array Merged result.
  1362. */
  1363. function array_merge($arr1,$arr2) {
  1364. return $arr2+$arr1;
  1365. }
  1366. /**
  1367. * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
  1368. * Usage: 5
  1369. *
  1370. * @param array Input array of values
  1371. * @param string Delimited, default is comman
  1372. * @param string Quote-character to wrap around the values.
  1373. * @return string A single line of CSV
  1374. */
  1375. function csvValues($row,$delim=',',$quote='"') {
  1376. reset($row);
  1377. $out=array();
  1378. while(list(,$value)=each($row)) {
  1379. list($valPart) = explode(chr(10),$value);
  1380. $valPart = trim($valPart);
  1381. $out[]=str_replace($quote,$quote.$quote,$valPart);
  1382. }
  1383. $str = $quote.implode($quote.$delim.$quote,$out).$quote;
  1384. return $str;
  1385. }
  1386. /*************************
  1387. *
  1388. * HTML/XML PROCESSING
  1389. *
  1390. *************************/
  1391. /**
  1392. * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
  1393. * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
  1394. * If a attribute is empty (I call it 'an option'), then the value for the key is empty. You can check if it existed with isset()
  1395. * Usage: 8
  1396. *
  1397. * @param string HTML-tag string (or attributes only)
  1398. * @return array Array with the attribute values.
  1399. */
  1400. function get_tag_attributes($tag) {
  1401. $components = t3lib_div::split_tag_attributes($tag);
  1402. $name = ''; // attribute name is stored here
  1403. $valuemode = '';
  1404. if (is_array($components)) {
  1405. while (list($key,$val) = each ($components)) {
  1406. 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
  1407. if ($valuemode) {
  1408. if ($name) {
  1409. $attributes[$name] = $val;
  1410. $name = '';
  1411. }
  1412. } else {
  1413. if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val))) {
  1414. $attributes[$key] = '';
  1415. $name = $key;
  1416. }
  1417. }
  1418. $valuemode = '';
  1419. } else {
  1420. $valuemode = 'on';
  1421. }
  1422. }
  1423. if (is_array($attributes)) reset($attributes);
  1424. return $attributes;
  1425. }
  1426. }
  1427. /**
  1428. * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
  1429. * Removes tag-name if found
  1430. * Usage: 2
  1431. *
  1432. * @param string HTML-tag string (or attributes only)
  1433. * @return array Array with the attribute values.
  1434. * @internal
  1435. */
  1436. function split_tag_attributes($tag) {
  1437. $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
  1438. // Removes any > in the end of the string
  1439. $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
  1440. while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
  1441. $firstChar=substr($tag_tmp,0,1);
  1442. if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
  1443. $reg=explode($firstChar,$tag_tmp,3);
  1444. $value[]=$reg[1];
  1445. $tag_tmp=trim($reg[2]);
  1446. } elseif (!strcmp($firstChar,'=')) {
  1447. $value[] = '=';
  1448. $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
  1449. } else {
  1450. // There are '' around the value. We look for the next ' ' or '>'
  1451. $reg = split('[[:space:]=]',$tag_tmp,2);
  1452. $value[] = trim($reg[0]);
  1453. $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
  1454. }
  1455. }
  1456. if (is_array($value)) reset($value);
  1457. return $value;
  1458. }
  1459. /**
  1460. * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
  1461. * Usage: 14
  1462. *
  1463. * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
  1464. * @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!
  1465. * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
  1466. * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
  1467. */
  1468. function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
  1469. if (is_array($arr)) {
  1470. if ($xhtmlSafe) {
  1471. $newArr=array();
  1472. foreach($arr as $p => $v) {
  1473. if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
  1474. }
  1475. $arr = $newArr;
  1476. }
  1477. $list = array();
  1478. foreach($arr as $p => $v) {
  1479. if (strcmp($v,'') || $dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
  1480. }
  1481. return implode(' ',$list);
  1482. }
  1483. }
  1484. /**
  1485. * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
  1486. *
  1487. * @param array See implodeAttributes()
  1488. * @param boolean See implodeAttributes()
  1489. * @param boolean See implodeAttributes()
  1490. * @return string See implodeAttributes()
  1491. * @deprecated Name was changed into implodeAttributes
  1492. * @see implodeAttributes()
  1493. */
  1494. function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
  1495. return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
  1496. }
  1497. /**
  1498. * Wraps JavaScript code XHTML ready with <script>-tags
  1499. * Automatic re-identing of the JS code is done by using the first line as ident reference.
  1500. * This is nice for identing JS code with PHP code on the same level.
  1501. *
  1502. * @param string JavaScript code
  1503. * @param boolean Wrap script element in linebreaks? Default is TRUE.
  1504. * @return string The wrapped JS code, ready to put into a XHTML page
  1505. * @author Ingmar Schlecht <ingmars@web.de>
  1506. * @author René Fritz <r.fritz@colorcube.de>
  1507. */
  1508. function wrapJS($string, $linebreak=TRUE) {
  1509. if(trim($string)) {
  1510. // <script wrapped in nl?
  1511. $cr = $linebreak? "\n" : '';
  1512. // remove nl from the beginning
  1513. $string = preg_replace ('/^\n+/', '', $string);
  1514. // re-ident to one tab using the first line as reference
  1515. if(preg_match('/^(\t+)/',$string,$match)) {
  1516. $string = str_replace($match[1],"\t", $string);
  1517. }
  1518. $string = $cr.'<script type="text/javascript">
  1519. /*<![CDATA[*/
  1520. '.$string.'
  1521. /*]]>*/
  1522. </script>'.$cr;
  1523. }
  1524. return trim($string);
  1525. }
  1526. /**
  1527. * Parses XML input into a PHP array with associative keys
  1528. * Usage: 0
  1529. *
  1530. * @param string XML data input
  1531. * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
  1532. * @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.
  1533. * @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
  1534. */
  1535. function xml2tree($string,$depth=999) {
  1536. $parser = xml_parser_create();
  1537. $vals = array();
  1538. $index = array();
  1539. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  1540. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  1541. xml_parse_into_struct($parser, $string, $vals, $index);
  1542. if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
  1543. xml_parser_free($parser);
  1544. $stack = array( array() );
  1545. $stacktop = 0;
  1546. $startPoint=0;
  1547. unset($tagi);
  1548. foreach($vals as $key => $val) {
  1549. $type = $val['type'];
  1550. // open tag:
  1551. if ($type=='open' || $type=='complete') {
  1552. $stack[$stacktop++] = $tagi;
  1553. if ($depth==$stacktop) {
  1554. $startPoint=$key;
  1555. }
  1556. $tagi = array('tag' => $val['tag']);
  1557. if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
  1558. if(isset($val['value'])) $tagi['values'][] = $val['value'];
  1559. }
  1560. // finish tag:
  1561. if ($type=='complete' || $type=='close') {
  1562. $oldtagi = $tagi;
  1563. $tagi = $stack[--$stacktop];
  1564. $oldtag = $oldtagi['tag'];
  1565. unset($oldtagi['tag']);
  1566. if ($depth==($stacktop+1)) {
  1567. if ($key-$startPoint > 0) {
  1568. $partArray = array_slice(
  1569. $vals,
  1570. $startPoint+1,
  1571. $key-$startPoint-1
  1572. );
  1573. #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
  1574. $oldtagi['XMLvalue']=t3lib_div::xmlRecompileFromStructValArray($partArray);
  1575. } else {
  1576. $oldtagi['XMLvalue']=$oldtagi['values'][0];
  1577. }
  1578. }
  1579. $tagi['ch'][$oldtag][] = $oldtagi;
  1580. unset($oldtagi);
  1581. }
  1582. // cdata
  1583. if($type=='cdata') {
  1584. $tagi['values'][] = $val['value'];
  1585. }
  1586. }
  1587. return $tagi['ch'];
  1588. }
  1589. /**
  1590. * Converts a PHP array into an XML string.
  1591. * The XML output is optimized for readability since associative keys are used as tagnames.
  1592. * 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.
  1593. * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
  1594. * 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
  1595. * 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.
  1596. * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances.
  1597. * 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...
  1598. * Usage: 5
  1599. *
  1600. * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
  1601. * @param string tag-prefix, eg. a namespace prefix like "T3:"
  1602. * @param integer Current recursion level. Don't change, stay at zero!
  1603. * @param string Alternative document tag. Default is "phparray".
  1604. * @param integer If set, the number of spaces corresponding to this number is used for indenting, otherwise a single chr(9) (TAB) is used
  1605. * @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')
  1606. * @param string Stack data. Don't touch.
  1607. * @return string An XML string made from the input content in the array.
  1608. * @see xml2array()
  1609. */
  1610. function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array()) {
  1611. // 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
  1612. $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
  1613. chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
  1614. chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
  1615. chr(30).chr(31);
  1616. // Set indenting mode:
  1617. $indentChar = $spaceInd ? ' ' : chr(9);
  1618. $indentN = $spaceInd>0 ? $spaceInd : 1;
  1619. // Init output variable:
  1620. $output='';
  1621. // Traverse the input array
  1622. if (is_array($array)) {
  1623. foreach($array as $k=>$v) {
  1624. $attr = '';
  1625. $tagName = $k;
  1626. // Construct the tag name.
  1627. if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
  1628. $attr.=' index="'.htmlspecialchars($tagName).'"';
  1629. $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
  1630. }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
  1631. $attr.=' index="'.htmlspecialchars($tagName).'"';
  1632. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
  1633. } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
  1634. $attr.=' index="'.htmlspecialchars($tagName).'"';
  1635. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
  1636. } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
  1637. if ($options['useNindex']) { // If numeric key, prefix "n"
  1638. $tagName = 'n'.$tagName;
  1639. } else { // Use special tag for num. keys:
  1640. $attr.=' index="'.$tagName.'"';
  1641. $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
  1642. }
  1643. } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
  1644. $attr.=' index="'.htmlspecialchars($tagName).'"';
  1645. $tagName = $options['useIndexTagForAssoc'];
  1646. }
  1647. // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
  1648. $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
  1649. // If the value is an array then we will call this function recursively:
  1650. if (is_array($v)) {
  1651. // Sub elements:
  1652. if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
  1653. $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
  1654. $clearStackPath = $subOptions['clearStackPath'];
  1655. } else {
  1656. $subOptions = $options;
  1657. $clearStackPath = FALSE;
  1658. }
  1659. $content = chr(10).
  1660. t3lib_div::array2xml(
  1661. $v,
  1662. $NSprefix,
  1663. $level+1,
  1664. '',
  1665. $spaceInd,
  1666. $subOptions,
  1667. array(
  1668. 'parentTagName' => $tagName,
  1669. 'grandParentTagName' => $stackData['parentTagName'],
  1670. 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
  1671. )
  1672. ).
  1673. str_pad('',($level+1)*$indentN,$indentChar);
  1674. $attr.=' type="array"';
  1675. } else { // Just a value:
  1676. // Look for binary chars:
  1677. if (strcspn($v,$binaryChars) != strlen($v)) { // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
  1678. // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
  1679. $content = chr(10).chunk_split(base64_encode($v));
  1680. $attr.=' base64="1"';
  1681. } else {
  1682. // Otherwise, just htmlspecialchar the stuff:
  1683. $content = htmlspecialchars($v);
  1684. $dType = gettype($v);
  1685. if ($dType!='string' && !$options['disableTypeAttrib']) { $attr.=' type="'.$dType.'"'; }
  1686. }
  1687. }
  1688. // Add the element to the output string:
  1689. $output.=str_pad('',($level+1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
  1690. }
  1691. }
  1692. // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
  1693. if (!$level) {
  1694. $output =
  1695. '<'.$docTag.'>'.chr(10).
  1696. $output.
  1697. '</'.$docTag.'>';
  1698. }
  1699. return $output;
  1700. }
  1701. /**
  1702. * Converts an XML string to a PHP array.
  1703. * This is the reverse function of array2xml()
  1704. * Usage: 17
  1705. *
  1706. * @param string XML content to convert into an array
  1707. * @param string The tag-prefix resolve, eg. a namespace like "T3:"
  1708. * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
  1709. * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
  1710. * @see array2xml()
  1711. */
  1712. function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
  1713. global $TYPO3_CONF_VARS;
  1714. // Create parser:
  1715. $parser = xml_parser_create();
  1716. $vals = array();
  1717. $index = array();
  1718. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  1719. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  1720. // PHP5 fix of charset awareness:
  1721. // Problem is: PHP5 apparently detects the charset of the XML file (or defaults to utf-8) and will AUTOMATICALLY convert the content to either utf-8, iso-8859-1 or us-ascii. PHP4 just passed the content through without taking action regarding the charset.
  1722. // In TYPO3 we expect that the charset of XML content is NOT handled in the parser but internally in TYPO3 instead. Therefore it would be very nice if PHP5 could be configured to NOT process the charset of the files. But this is not possible for now.
  1723. // What we do here fixes the problem but ONLY if the charset is utf-8, iso-8859-1 or us-ascii. That should work for most TYPO3 installations, in particular if people use utf-8 which we highly recommend.
  1724. if ((double)phpversion()>=5) {
  1725. unset($ereg_result);
  1726. ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
  1727. $theCharset = $ereg_result[1] ? $ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
  1728. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
  1729. }
  1730. // Parse content:
  1731. xml_parse_into_struct($parser, $string, $vals, $index);
  1732. // If error, return error message:
  1733. if (xml_get_error_code($parser)) {
  1734. return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
  1735. }
  1736. xml_parser_free($parser);
  1737. // Init vars:
  1738. $stack = array(array());
  1739. $stacktop = 0;
  1740. $current=array();
  1741. $tagName = '';
  1742. $documentTag = '';
  1743. // Traverse the parsed XML structure:
  1744. foreach($vals as $key => $val) {
  1745. // First, process the tag-name (which is used in both cases, whether "complete" or "close")
  1746. $tagName = $val['tag'];
  1747. if (!$documentTag) $documentTag = $tagName;
  1748. // Test for name space:
  1749. $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
  1750. // Test for numeric tag, encoded on the form "nXXX":
  1751. $testNtag = substr($tagName,1); // Closing tag.
  1752. $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
  1753. // Test for alternative index value:
  1754. if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
  1755. // Setting tag-values, manage stack:
  1756. switch($val['type']) {
  1757. case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
  1758. $current[$tagName] = array(); // Setting blank place holder
  1759. $stack[$stacktop++] = $current;
  1760. $current = array();
  1761. break;
  1762. case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
  1763. $oldCurrent = $current;
  1764. $current = $stack[--$stacktop];
  1765. end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
  1766. $current[key($current)] = $oldCurrent;
  1767. unset($oldCurrent);
  1768. break;
  1769. case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
  1770. if ($val['attributes']['base64']) {
  1771. $current[$tagName] = base64_decode($val['value']);
  1772. } else {
  1773. $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
  1774. // Cast type:
  1775. switch((string)$val['attributes']['type']) {
  1776. case 'integer':
  1777. $current[$tagName] = (integer)$current[$tagName];
  1778. break;
  1779. case 'double':
  1780. $current[$tagName] = (double)$current[$tagName];
  1781. break;
  1782. case 'boolean':
  1783. $current[$tagName] = (bool)$current[$tagName];
  1784. break;
  1785. case 'array':
  1786. $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...
  1787. break;
  1788. }
  1789. }
  1790. break;
  1791. }
  1792. }
  1793. if ($reportDocTag) {
  1794. $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
  1795. }
  1796. // Finally return the content of the document tag.
  1797. return $current[$tagName];
  1798. }
  1799. /**
  1800. * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
  1801. * Usage: 2
  1802. *
  1803. * @param array A array of XML parts, see xml2tree
  1804. * @return string Re-compiled XML data.
  1805. */
  1806. function xmlRecompileFromStructValArray($vals) {
  1807. $XMLcontent='';
  1808. foreach($vals as $val) {
  1809. $type = $val['type'];
  1810. // open tag:
  1811. if ($type=='open' || $type=='complete') {
  1812. $XMLcontent.='<'.$val['tag'];
  1813. if(isset($val['attributes'])) {
  1814. foreach($val['attributes'] as $k => $v) {
  1815. $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
  1816. }
  1817. }
  1818. if ($type=='complete') {
  1819. if(isset($val['value'])) {
  1820. $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
  1821. } else $XMLcontent.='/>';
  1822. } else $XMLcontent.='>';
  1823. if ($type=='open' && isset($val['value'])) {
  1824. $XMLcontent.=htmlspecialchars($val['value']);
  1825. }
  1826. }
  1827. // finish tag:
  1828. if ($type=='close') {
  1829. $XMLcontent.='</'.$val['tag'].'>';
  1830. }
  1831. // cdata
  1832. if($type=='cdata') {
  1833. $XMLcontent.=htmlspecialchars($val['value']);
  1834. }
  1835. }
  1836. return $XMLcontent;
  1837. }
  1838. /**
  1839. * Extract the encoding scheme as found in the first line of an XML document (typically)
  1840. * Usage: 1
  1841. *
  1842. * @param string XML data
  1843. * @return string Encoding scheme (lowercase), if found.
  1844. */
  1845. function xmlGetHeaderAttribs($xmlData) {
  1846. $xmlHeader = substr(trim($xmlData),0,200);
  1847. $reg=array();
  1848. if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg)) {
  1849. return t3lib_div::get_tag_attributes($reg[1]);
  1850. }
  1851. }
  1852. /*************************
  1853. *
  1854. * FILES FUNCTIONS
  1855. *
  1856. *************************/
  1857. /**
  1858. * Reads the file or url $url and returns the content
  1859. * 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.
  1860. * Usage: 83
  1861. *
  1862. * @param string Filepath/URL to read
  1863. * @return string The content from the resource given as input.
  1864. */
  1865. function getURL($url) {
  1866. $content = '';
  1867. // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
  1868. if((substr($url,0,7)=='http://') && ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse']=='1')) {
  1869. //external URL without error checking.
  1870. $ch = curl_init();
  1871. curl_setopt ($ch,CURLOPT_URL, $url);
  1872. curl_setopt ($ch,CURLOPT_HEADER, 0);
  1873. curl_setopt ($ch,CURLOPT_RETURNTRANSFER, 1);
  1874. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
  1875. curl_setopt ($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
  1876. // I don't know if it will be needed
  1877. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
  1878. curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'] );
  1879. }
  1880. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
  1881. curl_setopt ($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'] );
  1882. }
  1883. }
  1884. $content=curl_exec ($ch);
  1885. curl_close ($ch);
  1886. return $content;
  1887. } elseif($fd = fopen($url,'rb')) {
  1888. while (!feof($fd)) {
  1889. $content.=fread($fd, 5000);
  1890. }
  1891. fclose($fd);
  1892. return $content;
  1893. }
  1894. }
  1895. /**
  1896. * Writes $content to the file $file
  1897. * Usage: 30
  1898. *
  1899. * @param string Filepath to write to
  1900. * @param string Content to write
  1901. * @return boolean True if the file was successfully opened and written to.
  1902. */
  1903. function writeFile($file,$content) {
  1904. if($fd = fopen($file,'wb')) {
  1905. fwrite( $fd, $content);
  1906. fclose( $fd );
  1907. t3lib_div::fixPermissions($file); // Change the permissions of the file
  1908. return true;
  1909. }
  1910. }
  1911. /**
  1912. * Setting file system mode & group ownership of file
  1913. *
  1914. * @param string Filepath of newly created file
  1915. * @return void
  1916. */
  1917. function fixPermissions($file) {
  1918. if (@is_file($file) && TYPO3_OS!='WIN') {
  1919. @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
  1920. if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
  1921. @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
  1922. }
  1923. }
  1924. }
  1925. /**
  1926. * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
  1927. * Accepts an additional subdirectory in the file path!
  1928. *
  1929. * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
  1930. * @param string Content string to write
  1931. * @return string Returns false on success, otherwise an error string telling about the problem.
  1932. */
  1933. function writeFileToTypo3tempDir($filepath,$content) {
  1934. // Parse filepath into directory and basename:
  1935. $fI = pathinfo($filepath);
  1936. $fI['dirname'].= '/';
  1937. // Check parts:
  1938. if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
  1939. if (defined('PATH_site')) {
  1940. $dirName = PATH_site.'typo3temp/'; // Setting main temporary directory name (standard)
  1941. if (@is_dir($dirName)) {
  1942. if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName)) {
  1943. // Checking if the "subdir" is found:
  1944. $subdir = substr($fI['dirname'],strlen($dirName));
  1945. if ($subdir) {
  1946. if (ereg('^[[:alnum:]_]+\/$',$subdir)) {
  1947. $dirName.= $subdir;
  1948. if (!@is_dir($dirName)) {
  1949. t3lib_div::mkdir($dirName);
  1950. }
  1951. } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
  1952. }
  1953. // Checking dir-name again (sub-dir might have been created):
  1954. if (@is_dir($dirName)) {
  1955. if ($filepath == $dirName.$fI['basename']) {
  1956. t3lib_div::writeFile($filepath, $content);
  1957. if (!@is_file($filepath)) return 'File not written to disk! Write permission error in filesystem?';
  1958. } else return 'Calculated filelocation didn\'t match input $filepath!';
  1959. } else return '"'.$dirName.'" is not a directory!';
  1960. } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
  1961. } else return 'PATH_site + "typo3temp/" was not a directory!';
  1962. } else return 'PATH_site constant was NOT defined!';
  1963. } else return 'Input filepath "'.$filepath.'" was generally invalid!';
  1964. }
  1965. /**
  1966. * Wrapper function for mkdir, setting folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
  1967. * Usage: 6
  1968. *
  1969. * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
  1970. * @return boolean TRUE if @mkdir went well!
  1971. */
  1972. function mkdir($theNewFolder) {
  1973. $theNewFolder = ereg_replace('\/$','',$theNewFolder);
  1974. if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
  1975. chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
  1976. if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
  1977. chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
  1978. }
  1979. return TRUE;
  1980. }
  1981. }
  1982. /**
  1983. * Returns an array with the names of folders in a specific path
  1984. * Will return 'error' (string) if there were an error with reading directory content.
  1985. * Usage: 11
  1986. *
  1987. * @param string Path to list directories from
  1988. * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
  1989. */
  1990. function get_dirs($path) {
  1991. if ($path) {
  1992. $d = @dir($path);
  1993. if (is_object($d)) {
  1994. while($entry=$d->read()) {
  1995. if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
  1996. $filearray[]=$entry;
  1997. }
  1998. }
  1999. $d->close();
  2000. } else return 'error';
  2001. return $filearray;
  2002. }
  2003. }
  2004. /**
  2005. * Returns an array with the names of files in a specific path
  2006. * Usage: 18
  2007. *
  2008. * @param string $path: Is the path to the file
  2009. * @param string $extensionList is the comma list of extensions to read only (blank = all)
  2010. * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
  2011. * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
  2012. * @return array Array of the files found
  2013. */
  2014. function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') {
  2015. // Initialize variabels:
  2016. $filearray = array();
  2017. $sortarray = array();
  2018. $path = ereg_replace('\/$','',$path);
  2019. // Find files+directories:
  2020. if (@is_dir($path)) {
  2021. $extensionList = strtolower($extensionList);
  2022. $d = dir($path);
  2023. if (is_object($d)) {
  2024. while($entry=$d->read()) {
  2025. if (@is_file($path.'/'.$entry)) {
  2026. $fI = pathinfo($entry);
  2027. $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)
  2028. if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension']))) {
  2029. $filearray[$key]=($prependPath?$path.'/':'').$entry;
  2030. if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
  2031. elseif ($order) {$sortarray[$key]=$entry;}
  2032. }
  2033. }
  2034. }
  2035. $d->close();
  2036. } else return 'error opening path: "'.$path.'"';
  2037. }
  2038. // Sort them:
  2039. if ($order) {
  2040. asort($sortarray);
  2041. reset($sortarray);
  2042. $newArr=array();
  2043. while(list($k,$v)=each($sortarray)) {
  2044. $newArr[$k]=$filearray[$k];
  2045. }
  2046. $filearray=$newArr;
  2047. }
  2048. // Return result
  2049. reset($filearray);
  2050. return $filearray;
  2051. }
  2052. /**
  2053. * Recursively gather all files and folders of a path.
  2054. * Usage: 5
  2055. *
  2056. * @param array $fileArr: Empty input array (will have files added to it)
  2057. * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
  2058. * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
  2059. * @param boolean $regDirs: If set, directories are also included in output.
  2060. * @param integer $recursivityLevels: The number of levels to dig down...
  2061. * @return array An array with the found files/directories.
  2062. */
  2063. function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) {
  2064. if ($regDirs) $fileArr[] = $path;
  2065. $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1));
  2066. $dirs = t3lib_div::get_dirs($path);
  2067. if (is_array($dirs) && $recursivityLevels>0) {
  2068. foreach ($dirs as $subdirs) {
  2069. if ((string)$subdirs!='') {
  2070. $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
  2071. }
  2072. }
  2073. }
  2074. return $fileArr;
  2075. }
  2076. /**
  2077. * Removes the absolute part of all files/folders in fileArr
  2078. * Usage: 2
  2079. *
  2080. * @param array $fileArr: The file array to remove the prefix from
  2081. * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
  2082. * @return array The input $fileArr processed.
  2083. */
  2084. function removePrefixPathFromList($fileArr,$prefixToRemove) {
  2085. foreach($fileArr as $k => $absFileRef) {
  2086. if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
  2087. $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
  2088. } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
  2089. }
  2090. return $fileArr;
  2091. }
  2092. /**
  2093. * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
  2094. * Usage: 2
  2095. *
  2096. * @param string File path to process
  2097. * @return string
  2098. */
  2099. function fixWindowsFilePath($theFile) {
  2100. return str_replace('//','/', str_replace('\\','/', $theFile));
  2101. }
  2102. /**
  2103. * Resolves "../" sections in the input path string.
  2104. * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
  2105. * Usage: 2
  2106. *
  2107. * @param string File path in which "/../" is resolved
  2108. * @return string
  2109. */
  2110. function resolveBackPath($pathStr) {
  2111. $parts = explode('/',$pathStr);
  2112. $output=array();
  2113. foreach($parts as $pV) {
  2114. if ($pV=='..') {
  2115. if ($c) {
  2116. array_pop($output);
  2117. $c--;
  2118. } else $output[]=$pV;
  2119. } else {
  2120. $c++;
  2121. $output[]=$pV;
  2122. }
  2123. }
  2124. return implode('/',$output);
  2125. }
  2126. /**
  2127. * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
  2128. * - If already having a scheme, nothing is prepended
  2129. * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
  2130. * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
  2131. * Usage: 30
  2132. *
  2133. * @param string URL / path to prepend full URL addressing to.
  2134. * @return string
  2135. */
  2136. function locationHeaderUrl($path) {
  2137. $uI = parse_url($path);
  2138. if (substr($path,0,1)=='/') { // relative to HOST
  2139. $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
  2140. } elseif (!$uI['scheme']) { // No scheme either
  2141. $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
  2142. }
  2143. return $path;
  2144. }
  2145. /*************************
  2146. *
  2147. * DEBUG helper FUNCTIONS
  2148. *
  2149. *************************/
  2150. /**
  2151. * Returns a string with a list of ascii-values for the first $characters characters in $string
  2152. * Usage: 0
  2153. *
  2154. * @param string String to show ASCII value for
  2155. * @param integer Number of characters to show
  2156. * @return string The string with ASCII values in separated by a space char.
  2157. * @internal
  2158. */
  2159. function debug_ordvalue($string,$characters=100) {
  2160. if(strlen($string) < $characters) $characters = strlen($string);
  2161. for ($i=0; $i<$characters; $i++) {
  2162. $valuestring.=' '.ord(substr($string,$i,1));
  2163. }
  2164. return trim($valuestring);
  2165. }
  2166. /**
  2167. * Returns HTML-code, which is a visual representation of a multidimensional array
  2168. * use t3lib_div::print_array() in order to print an array
  2169. * Returns false if $array_in is not an array
  2170. * Usage: 31
  2171. *
  2172. * @param array Array to view
  2173. * @return string HTML output
  2174. */
  2175. function view_array($array_in) {
  2176. if (is_array($array_in)) {
  2177. $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
  2178. if (!count($array_in)) {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
  2179. while (list($key,$val)=each($array_in)) {
  2180. $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
  2181. if (is_array($array_in[$key])) {
  2182. $result.=t3lib_div::view_array($array_in[$key]);
  2183. } else
  2184. $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
  2185. $result.= '</td></tr>';
  2186. }
  2187. $result.= '</table>';
  2188. } else {
  2189. $result = false;
  2190. }
  2191. return $result;
  2192. }
  2193. /**
  2194. * Prints an array
  2195. * Usage: 6
  2196. *
  2197. * @param array Array to print visually (in a table).
  2198. * @return void
  2199. * @internal
  2200. * @see view_array()
  2201. */
  2202. function print_array($array_in) {
  2203. echo t3lib_div::view_array($array_in);
  2204. }
  2205. /**
  2206. * Makes debug output
  2207. * Prints $var in bold between two vertical lines
  2208. * If not $var the word 'debug' is printed
  2209. * If $var is an array, the array is printed by t3lib_div::print_array()
  2210. * Usage: 8
  2211. *
  2212. * @param mixed Variable to print
  2213. * @param mixed If the parameter is a string it will be used as header. Otherwise number of break tags to apply after (positive integer) or before (negative integer) the output.
  2214. * @return void
  2215. */
  2216. function debug($var="",$brOrHeader=0) {
  2217. if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
  2218. echo '<table border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;"><tr><td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">'.htmlspecialchars((string)$brOrHeader).'</td></tr><td>';
  2219. } elseif ($brOrHeader<0) {
  2220. for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
  2221. }
  2222. if (is_array($var)) {
  2223. t3lib_div::print_array($var);
  2224. } elseif (is_object($var)) {
  2225. echo '<b>|Object:<pre>';
  2226. print_r($var);
  2227. echo '</pre>|</b>';
  2228. } elseif ((string)$var!='') {
  2229. echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
  2230. } else {
  2231. echo '<b>| debug |</b>';
  2232. }
  2233. if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
  2234. echo '</td></tr></table>';
  2235. } elseif ($brOrHeader>0) {
  2236. for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
  2237. }
  2238. }
  2239. /*************************
  2240. *
  2241. * SYSTEM INFORMATION
  2242. *
  2243. *************************/
  2244. /**
  2245. * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
  2246. * Usage: 1
  2247. *
  2248. * @return string
  2249. */
  2250. function getThisUrl() {
  2251. $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
  2252. $dir=t3lib_div::dirname($p['path']).'/'; // Strip file
  2253. $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
  2254. return $url;
  2255. }
  2256. /**
  2257. * Returns the link-url to the current script.
  2258. * 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.
  2259. * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
  2260. * Usage: 52
  2261. *
  2262. * @param array Array of GET parameters to include
  2263. * @return string
  2264. */
  2265. function linkThisScript($getParams=array()) {
  2266. $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
  2267. $params = t3lib_div::_GET();
  2268. foreach($getParams as $k => $v) {
  2269. if (strcmp($v,'')) {
  2270. $params[$k]=$v;
  2271. } else unset($params[$k]);
  2272. }
  2273. $pString = t3lib_div::implodeArrayForUrl('',$params);
  2274. return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
  2275. }
  2276. /**
  2277. * 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.
  2278. * So basically it adds the parameters in $getParams to an existing URL, $url
  2279. * Usage: 2
  2280. *
  2281. * @param string URL string
  2282. * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
  2283. * @return string Output URL with added getParams.
  2284. */
  2285. function linkThisUrl($url,$getParams=array()) {
  2286. $parts = parse_url($url);
  2287. if ($parts['query']) {
  2288. parse_str($parts['query'],$getP);
  2289. } else {
  2290. $getP = array();
  2291. }
  2292. $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
  2293. $uP = explode('?',$url);
  2294. $params = t3lib_div::implodeArrayForUrl('',$getP);
  2295. $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
  2296. return $outurl;
  2297. }
  2298. /**
  2299. * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
  2300. * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
  2301. * Usage: 221
  2302. *
  2303. * @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
  2304. * @return string Value based on the input key, independent of server/os environment.
  2305. */
  2306. function getIndpEnv($getEnvName) {
  2307. /*
  2308. Conventions:
  2309. output from parse_url():
  2310. 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
  2311. [scheme] => 'http'
  2312. [user] => 'username'
  2313. [pass] => 'password'
  2314. [host] => '192.168.1.4'
  2315. [port] => '8080'
  2316. [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
  2317. [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
  2318. [fragment] => 'link1'
  2319. Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
  2320. [path_dir] = '/typo3/32/temp/phpcheck/'
  2321. [path_info] = '/arg1/arg2/arg3/'
  2322. [path] = [path_script/path_dir][path_info]
  2323. Keys supported:
  2324. URI______:
  2325. REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
  2326. HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
  2327. 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')!
  2328. PATH_INFO = [path_info] = /arg1/arg2/arg3/
  2329. QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
  2330. 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
  2331. (Notice: NO username/password + NO fragment)
  2332. CLIENT____:
  2333. REMOTE_ADDR = (client IP)
  2334. REMOTE_HOST = (client host)
  2335. HTTP_USER_AGENT = (client user agent)
  2336. HTTP_ACCEPT_LANGUAGE = (client accept language)
  2337. SERVER____:
  2338. SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
  2339. Special extras:
  2340. TYPO3_HOST_ONLY = [host] = 192.168.1.4
  2341. TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
  2342. TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
  2343. TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (sheme will by default be 'http' until we can detect if it's https -
  2344. TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
  2345. TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
  2346. TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
  2347. TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
  2348. TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
  2349. Notice: [fragment] is apparently NEVER available to the script!
  2350. Testing suggestions:
  2351. - Output all the values.
  2352. - 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
  2353. - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
  2354. */
  2355. # if ($getEnvName=='HTTP_REFERER') return '';
  2356. switch((string)$getEnvName) {
  2357. case 'SCRIPT_NAME':
  2358. return (php_sapi_name()=='cgi'||php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) ? ($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) : ($_SERVER['ORIG_SCRIPT_NAME']?$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);
  2359. break;
  2360. case 'SCRIPT_FILENAME':
  2361. return str_replace('//','/', str_replace('\\','/', (php_sapi_name()=='cgi'||php_sapi_name()=='isapi' ||php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED'])? ($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED']):($_SERVER['ORIG_SCRIPT_FILENAME']?$_SERVER['ORIG_SCRIPT_FILENAME']:$_SERVER['SCRIPT_FILENAME'])));
  2362. break;
  2363. case 'REQUEST_URI':
  2364. // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
  2365. if (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
  2366. return '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
  2367. ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
  2368. } else return $_SERVER['REQUEST_URI'];
  2369. break;
  2370. case 'PATH_INFO':
  2371. // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
  2372. // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
  2373. // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, then 'php_sapi_name()=='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_name()=='cgi' (see above)
  2374. // if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
  2375. if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi') {
  2376. return $_SERVER['PATH_INFO'];
  2377. } else return '';
  2378. break;
  2379. // These are let through without modification
  2380. case 'REMOTE_ADDR':
  2381. case 'REMOTE_HOST':
  2382. case 'HTTP_REFERER':
  2383. case 'HTTP_HOST':
  2384. case 'HTTP_USER_AGENT':
  2385. case 'HTTP_ACCEPT_LANGUAGE':
  2386. case 'QUERY_STRING':
  2387. return $_SERVER[$getEnvName];
  2388. break;
  2389. case 'TYPO3_DOCUMENT_ROOT':
  2390. // 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.
  2391. // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
  2392. $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
  2393. $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
  2394. $SFN_A = explode('/',strrev($SFN));
  2395. $acc = array();
  2396. while(list($kk,$vv)=each($SN_A)) {
  2397. if (!strcmp($SFN_A[$kk],$vv)) {
  2398. $acc[] = $vv;
  2399. } else break;
  2400. }
  2401. $commonEnd=strrev(implode('/',$acc));
  2402. if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
  2403. return $DR;
  2404. break;
  2405. case 'TYPO3_HOST_ONLY':
  2406. $p = explode(':',$_SERVER['HTTP_HOST']);
  2407. return $p[0];
  2408. break;
  2409. case 'TYPO3_PORT':
  2410. $p = explode(':',$_SERVER['HTTP_HOST']);
  2411. return $p[1];
  2412. break;
  2413. case 'TYPO3_REQUEST_HOST':
  2414. return (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
  2415. $_SERVER['HTTP_HOST'];
  2416. break;
  2417. case 'TYPO3_REQUEST_URL':
  2418. return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
  2419. break;
  2420. case 'TYPO3_REQUEST_SCRIPT':
  2421. return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
  2422. break;
  2423. case 'TYPO3_REQUEST_DIR':
  2424. return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
  2425. break;
  2426. case 'TYPO3_SITE_URL':
  2427. if (defined('PATH_thisScript') && defined('PATH_site')) {
  2428. $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
  2429. $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
  2430. $siteUrl = substr($url,0,-strlen($lPath));
  2431. if (substr($siteUrl,-1)!='/') $siteUrl.='/';
  2432. return $siteUrl;
  2433. } else return '';
  2434. break;
  2435. case 'TYPO3_SITE_SCRIPT':
  2436. return substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
  2437. break;
  2438. case 'TYPO3_SSL':
  2439. return $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') ? TRUE : FALSE;
  2440. break;
  2441. case '_ARRAY':
  2442. $out = array();
  2443. // Here, list ALL possible keys to this function for debug display.
  2444. $envTestVars = t3lib_div::trimExplode(',','
  2445. HTTP_HOST,
  2446. TYPO3_HOST_ONLY,
  2447. TYPO3_PORT,
  2448. PATH_INFO,
  2449. QUERY_STRING,
  2450. REQUEST_URI,
  2451. HTTP_REFERER,
  2452. TYPO3_REQUEST_HOST,
  2453. TYPO3_REQUEST_URL,
  2454. TYPO3_REQUEST_SCRIPT,
  2455. TYPO3_REQUEST_DIR,
  2456. TYPO3_SITE_URL,
  2457. TYPO3_SITE_SCRIPT,
  2458. TYPO3_SSL,
  2459. SCRIPT_NAME,
  2460. TYPO3_DOCUMENT_ROOT,
  2461. SCRIPT_FILENAME,
  2462. REMOTE_ADDR,
  2463. REMOTE_HOST,
  2464. HTTP_USER_AGENT,
  2465. HTTP_ACCEPT_LANGUAGE',1);
  2466. reset($envTestVars);
  2467. while(list(,$v)=each($envTestVars)) {
  2468. $out[$v]=t3lib_div::getIndpEnv($v);
  2469. }
  2470. reset($out);
  2471. return $out;
  2472. break;
  2473. }
  2474. }
  2475. /**
  2476. * milliseconds
  2477. * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
  2478. * Usage: 20
  2479. *
  2480. * @return integer
  2481. */
  2482. function milliseconds() {
  2483. $p=explode(' ',microtime());
  2484. return round(($p[0]+$p[1])*1000);
  2485. }
  2486. /**
  2487. * Client Browser Information
  2488. * Usage: 4
  2489. *
  2490. * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
  2491. * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
  2492. */
  2493. function clientInfo($useragent='') {
  2494. if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
  2495. $bInfo=array();
  2496. // Which browser?
  2497. if (strstr($useragent,'Konqueror')) {
  2498. $bInfo['BROWSER']= 'konqu';
  2499. } elseif (strstr($useragent,'Opera')) {
  2500. $bInfo['BROWSER']= 'opera';
  2501. } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6')) {
  2502. $bInfo['BROWSER']= 'msie';
  2503. } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5')) {
  2504. $bInfo['BROWSER']='net';
  2505. }
  2506. if ($bInfo['BROWSER']) {
  2507. // Browser version
  2508. switch($bInfo['BROWSER']) {
  2509. case 'net':
  2510. $bInfo['VERSION']= doubleval(substr($useragent,8));
  2511. if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
  2512. if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
  2513. break;
  2514. case 'msie':
  2515. $tmp = strstr($useragent,'MSIE');
  2516. $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
  2517. break;
  2518. case 'opera':
  2519. $tmp = strstr($useragent,'Opera');
  2520. $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
  2521. break;
  2522. case 'konqu':
  2523. $tmp = strstr($useragent,'Konqueror/');
  2524. $bInfo['VERSION'] = doubleval(substr($tmp,10));
  2525. break;
  2526. }
  2527. // Client system
  2528. if (strstr($useragent,'Win')) {
  2529. $bInfo['SYSTEM'] = 'win';
  2530. } elseif (strstr($useragent,'Mac')) {
  2531. $bInfo['SYSTEM'] = 'mac';
  2532. } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX ')) {
  2533. $bInfo['SYSTEM'] = 'unix';
  2534. }
  2535. }
  2536. // Is true if the browser supports css to format forms, especially the width
  2537. $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
  2538. return $bInfo;
  2539. }
  2540. /*************************
  2541. *
  2542. * TYPO3 SPECIFIC FUNCTIONS
  2543. *
  2544. *************************/
  2545. /**
  2546. * 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.
  2547. * Usage: 24
  2548. *
  2549. * @param string The input filename/filepath to evaluate
  2550. * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
  2551. * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
  2552. * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
  2553. */
  2554. function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) {
  2555. if (!strcmp($filename,'')) return '';
  2556. if ($relToTYPO3_mainDir) {
  2557. if (!defined('PATH_typo3')) return '';
  2558. $relPathPrefix = PATH_typo3;
  2559. } else {
  2560. $relPathPrefix = PATH_site;
  2561. }
  2562. if (substr($filename,0,4)=='EXT:') { // extension
  2563. list($extKey,$local) = explode('/',substr($filename,4),2);
  2564. $filename='';
  2565. if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
  2566. $filename = t3lib_extMgm::extPath($extKey).$local;
  2567. }
  2568. } elseif (!t3lib_div::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
  2569. $filename=$relPathPrefix.$filename;
  2570. } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
  2571. $filename='';
  2572. }
  2573. if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) { // checks backpath.
  2574. return $filename;
  2575. }
  2576. }
  2577. /**
  2578. * Checks for malicious file paths.
  2579. * Returns true if no '//', '..' or '\' is in the $theFile
  2580. * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
  2581. * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
  2582. * Usage: 14
  2583. *
  2584. * @param string Filepath to evaluate
  2585. * @return boolean True, if no '//', '..' or '\' is in the $theFile
  2586. * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
  2587. */
  2588. function validPathStr($theFile) {
  2589. if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
  2590. }
  2591. /**
  2592. * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
  2593. * Usage: 8
  2594. *
  2595. * @param string Filepath to evaluate
  2596. * @return boolean
  2597. */
  2598. function isAbsPath($path) {
  2599. return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' : substr($path,0,1)=='/';
  2600. }
  2601. /**
  2602. * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
  2603. * Usage: 5
  2604. *
  2605. * @param string Filepath to evaluate
  2606. * @return boolean
  2607. */
  2608. function isAllowedAbsPath($path) {
  2609. if (t3lib_div::isAbsPath($path) &&
  2610. t3lib_div::validPathStr($path) &&
  2611. ( t3lib_div::isFirstPartOfStr($path,PATH_site)
  2612. ||
  2613. ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
  2614. )
  2615. ) return true;
  2616. }
  2617. /**
  2618. * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
  2619. * Usage: 2
  2620. *
  2621. * @param string Filepath to evaluate
  2622. * @return boolean
  2623. */
  2624. function verifyFilenameAgainstDenyPattern($filename) {
  2625. if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
  2626. $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
  2627. if ($result) return false; // so if a matching filename is found, return false;
  2628. }
  2629. return true;
  2630. }
  2631. /**
  2632. * Moves $source file to $destination if uploaded, otherwise try to make a copy
  2633. * Usage: 4
  2634. *
  2635. * @param string Source file, absolute path
  2636. * @param string Destination file, absolute path
  2637. * @return boolean Returns true if the file was moved.
  2638. * @coauthor Dennis Petersen <fessor@software.dk>
  2639. * @see upload_to_tempfile()
  2640. */
  2641. function upload_copy_move($source,$destination) {
  2642. if (is_uploaded_file($source)) {
  2643. $uploaded = TRUE;
  2644. // 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:
  2645. $uploadedResult = move_uploaded_file($source, $destination);
  2646. } else {
  2647. $uploaded = FALSE;
  2648. @copy($source,$destination);
  2649. }
  2650. t3lib_div::fixPermissions($destination); // Change the permissions of the file
  2651. // 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
  2652. return $uploaded ? $uploadedResult : FALSE;
  2653. }
  2654. /**
  2655. * 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.
  2656. * Use this function to move uploaded files to where you can work on them.
  2657. * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
  2658. * Usage: 6
  2659. *
  2660. * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
  2661. * @return string If a new file was successfully created, return its filename, otherwise blank string.
  2662. * @see unlink_tempfile(), upload_copy_move()
  2663. */
  2664. function upload_to_tempfile($uploadedFileName) {
  2665. if (is_uploaded_file($uploadedFileName)) {
  2666. $tempFile = t3lib_div::tempnam('upload_temp_');
  2667. move_uploaded_file($uploadedFileName, $tempFile);
  2668. return @is_file($tempFile) ? $tempFile : '';
  2669. }
  2670. }
  2671. /**
  2672. * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
  2673. * 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.
  2674. * Use this after upload_to_tempfile() or tempnam() from this class!
  2675. * Usage: 9
  2676. *
  2677. * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
  2678. * @return boolean Returns true if the file was unlink()'ed
  2679. * @see upload_to_tempfile(), tempnam()
  2680. */
  2681. function unlink_tempfile($uploadedTempFileName) {
  2682. if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName)) {
  2683. if (unlink($uploadedTempFileName)) return TRUE;
  2684. }
  2685. }
  2686. /**
  2687. * Create temporary filename (Create file with unique file name)
  2688. * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
  2689. * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
  2690. * Usage: 7
  2691. *
  2692. * @param string Prefix to temp file (which will have no extension btw)
  2693. * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
  2694. * @see unlink_tempfile(), upload_to_tempfile()
  2695. */
  2696. function tempnam($filePrefix) {
  2697. return tempnam(PATH_site.'typo3temp/',$filePrefix);
  2698. }
  2699. /**
  2700. * standard authentication code - can't remember what it's used for.
  2701. * Usage: 2
  2702. *
  2703. * @param mixed Uid (integer) or record (array)
  2704. * @param string List of fields from the record if that is given.
  2705. * @return string MD5 hash of 8 chars.
  2706. * @internal
  2707. */
  2708. function stdAuthCode($uid_or_record,$fields='') {
  2709. if (is_array($uid_or_record)) {
  2710. $recCopy_temp=array();
  2711. if ($fields) {
  2712. $fieldArr = t3lib_div::trimExplode(',',$fields,1);
  2713. reset($fieldArr);
  2714. while(list($k,$v)=each($fieldArr)) {
  2715. $recCopy_temp[$k]=$recCopy[$v];
  2716. }
  2717. } else {
  2718. $recCopy_temp=$recCopy;
  2719. }
  2720. $preKey = implode('|',$recCopy_temp);
  2721. } else {
  2722. $preKey = $uid_or_record;
  2723. }
  2724. $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  2725. $authCode = substr(md5($authCode),0,8);
  2726. return $authCode;
  2727. }
  2728. /**
  2729. * Splits the input query-parameters into an array with certain parameters filtered out.
  2730. * Used to create the cHash value
  2731. *
  2732. * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
  2733. * @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
  2734. * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink()
  2735. */
  2736. function cHashParams($addQueryParams) {
  2737. $params = explode('&',substr($addQueryParams,1)); // Splitting parameters up
  2738. // Make array:
  2739. $pA = array();
  2740. foreach($params as $theP) {
  2741. $pKV = explode('=', $theP); // Splitting single param by '=' sign
  2742. if (!t3lib_div::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0])) {
  2743. $pA[$pKV[0]] = (string)rawurldecode($pKV[1]);
  2744. }
  2745. }
  2746. $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  2747. ksort($pA);
  2748. return $pA;
  2749. }
  2750. /**
  2751. * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
  2752. *
  2753. * @param integer Value from "l18n_cfg" field of a page record
  2754. * @return boolean True if the page should be hidden
  2755. */
  2756. function hideIfNotTranslated($l18n_cfg_fieldValue) {
  2757. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
  2758. return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
  2759. } else {
  2760. return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
  2761. }
  2762. }
  2763. /**
  2764. * Includes a locallang file and returns the $LOCAL_LANG array found inside.
  2765. *
  2766. * @param string Input is a file-reference (see t3lib_div::getFileAbsFileName) which, if exists, is included. That file is expected to be a 'local_lang' file containing a $LOCAL_LANG array.
  2767. * @param string Language key
  2768. * @return array Value of $LOCAL_LANG found in the included file. If that array is found it's returned. Otherwise an empty array
  2769. */
  2770. function readLLfile($fileRef,$langKey) {
  2771. $file = t3lib_div::getFileAbsFileName($fileRef);
  2772. if ($file) {
  2773. $baseFile = ereg_replace('\.(php|xml)$', '', $file);
  2774. if (@is_file($baseFile.'.xml')) {
  2775. $LOCAL_LANG = t3lib_div::readLLXMLfile($baseFile.'.xml', $langKey);
  2776. } elseif (@is_file($baseFile.'.php')) {
  2777. include($baseFile.'.php');
  2778. } else die('Filereference, "'.$file.'", not found!');
  2779. }
  2780. return is_array($LOCAL_LANG)?$LOCAL_LANG:array();
  2781. }
  2782. /**
  2783. * Includes a locallang-xml file and returns the $LOCAL_LANG array
  2784. * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
  2785. *
  2786. * @param string Absolute reference to locallang-XML file
  2787. * @param string TYPO3 language key, eg. "dk" or "de" or "default"
  2788. * @return array LOCAL_LANG array in return.
  2789. */
  2790. function readLLXMLfile($fileRef,$langKey) {
  2791. if (is_object($GLOBALS['LANG'])) {
  2792. $csConvObj = &$GLOBALS['LANG']->csConvObj;
  2793. } elseif (is_object($GLOBALS['TSFE'])) {
  2794. $csConvObj = &$GLOBALS['TSFE']->csConvObj;
  2795. } else $csConvObj = NULL;
  2796. if (@is_file($fileRef) && $langKey && is_object($csConvObj)) {
  2797. // Set charset:
  2798. $origCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  2799. // Cache file name:
  2800. $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef));
  2801. $cacheFileName = PATH_site.'typo3temp/llxml/'.
  2802. #str_replace('_','',ereg_replace('^.*\/','',dirname($fileRef))).
  2803. #'_'.basename($fileRef).
  2804. substr(basename($fileRef),10,15).
  2805. '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
  2806. // Check if cache file exists...
  2807. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  2808. // Read XML, parse it.
  2809. $xmlString = t3lib_div::getUrl($fileRef);
  2810. $xmlContent = t3lib_div::xml2array($xmlString);
  2811. // Set default LOCAL_LANG array content:
  2812. $LOCAL_LANG = array();
  2813. $LOCAL_LANG['default'] = $xmlContent['data']['default'];
  2814. // Specific language, convert from utf-8 to backend language charset:
  2815. // NOTICE: Converting from utf-8 back to "native" language may be a temporary solution until we can totally discard "locallang.php" files altogether (and use utf-8 for everything). But doing this conversion is the quickest way to migrate now and the source is in utf-8 anyway which is the main point.
  2816. if ($langKey!='default') {
  2817. $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
  2818. // Checking if charset should be converted.
  2819. if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8') {
  2820. foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
  2821. $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
  2822. }
  2823. }
  2824. }
  2825. // Cache the content now:
  2826. $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>$LOCAL_LANG);
  2827. $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  2828. if ($res) die('ERROR: '.$res);
  2829. } else {
  2830. // Get content from cache:
  2831. $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
  2832. $LOCAL_LANG = $serContent['LOCAL_LANG'];
  2833. }
  2834. // Checking for EXTERNAL file for non-default language:
  2835. if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
  2836. // Look for localized file:
  2837. $localized_file = t3lib_div::getFileAbsFileName($LOCAL_LANG[$langKey]);
  2838. if ($localized_file && @is_file($localized_file)) {
  2839. // Cache file name:
  2840. $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file));
  2841. $cacheFileName = PATH_site.'typo3temp/llxml/ext_'.
  2842. substr(basename($localized_file),10,15).
  2843. '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
  2844. // Check if cache file exists...
  2845. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  2846. // Read and parse XML content:
  2847. $local_xmlString = t3lib_div::getUrl($localized_file);
  2848. $local_xmlContent = t3lib_div::xml2array($local_xmlString);
  2849. $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
  2850. // Checking if charset should be converted.
  2851. if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8') {
  2852. foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
  2853. $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
  2854. }
  2855. }
  2856. // Cache the content now:
  2857. $serContent = array('extlang'=>$langKey, 'origFile'=>$LOCAL_LANG[$langKey], 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
  2858. $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  2859. if ($res) die('ERROR: '.$res);
  2860. } else {
  2861. // Get content from cache:
  2862. $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
  2863. $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
  2864. }
  2865. } else {
  2866. $LOCAL_LANG[$langKey] = array();
  2867. }
  2868. }
  2869. return $LOCAL_LANG;
  2870. }
  2871. }
  2872. /**
  2873. * Loads the $TCA (Table Configuration Array) for the $table
  2874. *
  2875. * Requirements:
  2876. * 1) must be configured table (the ctrl-section configured),
  2877. * 2) columns must not be an array (which it is always if whole table loaded), and
  2878. * 3) there is a value for dynamicConfigFile (filename in typo3conf)
  2879. * Usage: 84
  2880. *
  2881. * @param string Table name for which to load the full TCA array part into the global $TCA
  2882. * @return void
  2883. */
  2884. function loadTCA($table) {
  2885. global $TCA,$LANG_GENERAL_LABELS;
  2886. if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile']) {
  2887. if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:')) {
  2888. include(PATH_t3lib.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
  2889. } elseif (t3lib_div::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file($TCA[$table]['ctrl']['dynamicConfigFile'])) { // Absolute path...
  2890. include($TCA[$table]['ctrl']['dynamicConfigFile']);
  2891. } else include(PATH_typo3conf.$TCA[$table]['ctrl']['dynamicConfigFile']);
  2892. }
  2893. }
  2894. /**
  2895. * 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).
  2896. * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
  2897. * Usage: 5
  2898. *
  2899. * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
  2900. * @param string The sheet to return, preferably.
  2901. * @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!
  2902. */
  2903. function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
  2904. if (is_array($dataStructArray['sheets'])) {
  2905. $singleSheet = FALSE;
  2906. if (!isset($dataStructArray['sheets'][$sheet])) {
  2907. $sheet='sDEF';
  2908. }
  2909. $dataStruct = $dataStructArray['sheets'][$sheet];
  2910. // If not an array, but still set, then regard it as a relative reference to a file:
  2911. if ($dataStruct && !is_array($dataStruct)) {
  2912. $file = t3lib_div::getFileAbsFileName($dataStruct);
  2913. if ($file && @is_file($file)) {
  2914. $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
  2915. }
  2916. }
  2917. } else {
  2918. $singleSheet = TRUE;
  2919. $dataStruct = $dataStructArray;
  2920. unset($dataStruct['meta']); // Meta data should not appear there.
  2921. $sheet = 'sDEF'; // Default sheet
  2922. }
  2923. return array($dataStruct,$sheet,$singleSheet);
  2924. }
  2925. /**
  2926. * Resolves ALL sheet definitions in dataStructArray
  2927. * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
  2928. *
  2929. * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
  2930. * @return array Output data structure with all sheets resolved as arrays.
  2931. */
  2932. function resolveAllSheetsInDS($dataStructArray) {
  2933. if (is_array($dataStructArray['sheets'])) {
  2934. $out=array('sheets'=>array());
  2935. foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
  2936. list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
  2937. if ($sheetId==$aS) {
  2938. $out['sheets'][$aS]=$ds;
  2939. }
  2940. }
  2941. } else {
  2942. list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
  2943. $out = array('sheets' => array('sDEF' => $ds));
  2944. }
  2945. return $out;
  2946. }
  2947. /**
  2948. * Calls a userdefined function/method in class
  2949. * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
  2950. * Usage: 17
  2951. *
  2952. * @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").
  2953. * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
  2954. * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
  2955. * @param string Required prefix of class or function name
  2956. * @param boolean If set, no debug() error message is shown if class/function is not present.
  2957. * @return mixed Content from method/function call
  2958. * @see getUserObj()
  2959. */
  2960. function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) {
  2961. global $TYPO3_CONF_VARS;
  2962. // Check persistent object and if found, call directly and exit.
  2963. if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
  2964. return call_user_method(
  2965. $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
  2966. $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
  2967. $params,
  2968. $ref
  2969. );
  2970. }
  2971. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  2972. if (strstr($funcName,':')) {
  2973. list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
  2974. $requireFile = t3lib_div::getFileAbsFileName($file);
  2975. if ($requireFile) require_once($requireFile);
  2976. } else {
  2977. $funcRef = $funcName;
  2978. }
  2979. // Check for persistent object token, "&"
  2980. if (substr($funcRef,0,1)=='&') {
  2981. $funcRef = substr($funcRef,1);
  2982. $storePersistentObject = TRUE;
  2983. } else {
  2984. $storePersistentObject = FALSE;
  2985. }
  2986. // Check prefix is valid:
  2987. if ($checkPrefix &&
  2988. !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
  2989. !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
  2990. ) {
  2991. if (!$silent) debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
  2992. return FALSE;
  2993. }
  2994. // Call function or method:
  2995. $parts = explode('->',$funcRef);
  2996. if (count($parts)==2) { // Class
  2997. // Check if class/method exists:
  2998. if (class_exists($parts[0])) {
  2999. // Get/Create object of class:
  3000. if ($storePersistentObject) { // Get reference to current instance of class:
  3001. if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
  3002. $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div::makeInstance($parts[0]);
  3003. }
  3004. $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
  3005. } else { // Create new object:
  3006. $classObj = &t3lib_div::makeInstance($parts[0]);
  3007. }
  3008. if (method_exists($classObj, $parts[1])) {
  3009. // If persistent object should be created, set reference:
  3010. if ($storePersistentObject) {
  3011. $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
  3012. 'method' => $parts[1],
  3013. 'obj' => &$classObj
  3014. );
  3015. }
  3016. // Call method:
  3017. $content = call_user_method(
  3018. $parts[1],
  3019. $classObj,
  3020. $params,
  3021. $ref
  3022. );
  3023. } else {
  3024. if (!$silent) debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
  3025. }
  3026. } else {
  3027. if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
  3028. }
  3029. } else { // Function
  3030. if (function_exists($funcRef)) {
  3031. $content = call_user_func($funcRef, $params, $ref);
  3032. } else {
  3033. if (!$silent) debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
  3034. }
  3035. }
  3036. return $content;
  3037. }
  3038. /**
  3039. * Creates and returns reference to a user defined object.
  3040. * 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.
  3041. * Usage: 5
  3042. *
  3043. * @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!).
  3044. * @param string Required prefix of class name. By default "tx_" is allowed.
  3045. * @param boolean If set, no debug() error message is shown if class/function is not present.
  3046. * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
  3047. * @see callUserFunction()
  3048. */
  3049. function &getUserObj($classRef,$checkPrefix='user_',$silent=0) {
  3050. global $TYPO3_CONF_VARS;
  3051. // Check persistent object and if found, call directly and exit.
  3052. if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
  3053. return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
  3054. } else {
  3055. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  3056. if (strstr($classRef,':')) {
  3057. list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
  3058. $requireFile = t3lib_div::getFileAbsFileName($file);
  3059. if ($requireFile) require_once($requireFile);
  3060. } else {
  3061. $class = $classRef;
  3062. }
  3063. // Check for persistent object token, "&"
  3064. if (substr($class,0,1)=='&') {
  3065. $class = substr($class,1);
  3066. $storePersistentObject = TRUE;
  3067. } else {
  3068. $storePersistentObject = FALSE;
  3069. }
  3070. // Check prefix is valid:
  3071. if ($checkPrefix &&
  3072. !t3lib_div::isFirstPartOfStr(trim($class),$checkPrefix) &&
  3073. !t3lib_div::isFirstPartOfStr(trim($class),'tx_')
  3074. ) {
  3075. if (!$silent) debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
  3076. return FALSE;
  3077. }
  3078. // Check if class exists:
  3079. if (class_exists($class)) {
  3080. $classObj = &t3lib_div::makeInstance($class);
  3081. // If persistent object should be created, set reference:
  3082. if ($storePersistentObject) {
  3083. $GLOBALS['T3_VAR']['getUserObj'][$classRef] = &$classObj;
  3084. }
  3085. return $classObj;
  3086. } else {
  3087. if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$class,1);
  3088. }
  3089. }
  3090. }
  3091. /**
  3092. * Make instance of class
  3093. * Takes the class-extensions API of TYPO3 into account
  3094. * Please USE THIS instead of the PHP "new" keyword. Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
  3095. * Usage: 447
  3096. *
  3097. * @param string Class name to instantiate
  3098. * @return object The object
  3099. */
  3100. function &makeInstance($className) {
  3101. return class_exists('ux_'.$className) ? t3lib_div::makeInstance('ux_'.$className) : new $className;
  3102. }
  3103. /**
  3104. * Return classname for new instance
  3105. * Takes the class-extensions API of TYPO3 into account
  3106. * Usage: 17
  3107. *
  3108. * @param string Base Class name to evaluate
  3109. * @return string Final class name to instantiate with "new [classname]"
  3110. */
  3111. function makeInstanceClassName($className) {
  3112. return class_exists('ux_'.$className) ? t3lib_div::makeInstanceClassName('ux_'.$className) : $className;
  3113. }
  3114. /**
  3115. * Find the best service and check if it works.
  3116. * Returns object of the service class.
  3117. *
  3118. * @param string Type of service (service key).
  3119. * @param string Sub type like file extensions or similar. Defined by the service.
  3120. * @param mixed List of service keys which should be exluded in the search for a service. Array or comma list.
  3121. * @return object The service object or an array with error info's.
  3122. * @author René Fritz <r.fritz@colorcube.de>
  3123. */
  3124. function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) {
  3125. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  3126. $error = FALSE;
  3127. if (!is_array($excludeServiceKeys) ) {
  3128. $excludeServiceKeys = t3lib_div::trimExplode(',', $excludeServiceKeys, 1);
  3129. }
  3130. while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
  3131. // Check persistent object and if found, call directly and exit.
  3132. if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
  3133. // reset service and return object
  3134. $T3_VAR['makeInstanceService'][$info['className']]->reset();
  3135. return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
  3136. // include file and create object
  3137. } else {
  3138. $requireFile = t3lib_div::getFileAbsFileName($info['classFile']);
  3139. if (@is_file($requireFile)) {
  3140. require_once ($requireFile);
  3141. $obj = t3lib_div::makeInstance($info['className']);
  3142. if (is_object($obj)) {
  3143. if(!@is_callable(array($obj,'init'))) {
  3144. // use silent logging??? I don't think so.
  3145. die ('Broken service:'.t3lib_div::view_array($info));
  3146. }
  3147. $obj->info = $info;
  3148. if ($obj->init()) { // service available?
  3149. // create persistent object
  3150. $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
  3151. // needed to delete temp files
  3152. register_shutdown_function(array(&$obj, '__destruct'));
  3153. return $obj; // object is passed as reference by function definition
  3154. }
  3155. $error = $obj->getLastErrorArray();
  3156. unset($obj);
  3157. }
  3158. }
  3159. }
  3160. // deactivate the service
  3161. t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
  3162. }
  3163. return $error;
  3164. }
  3165. /**
  3166. * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
  3167. * The fifth parameter, $enc, will allow you to specify 'base64' encryption for the output (set $enc=base64)
  3168. * Further the output has the charset set to ISO-8859-1 by default.
  3169. * Usage: 4
  3170. *
  3171. * @param string Email address to send to. (see PHP function mail())
  3172. * @param string Subject line, non-encoded. (see PHP function mail())
  3173. * @param string Message content, non-encoded. (see PHP function mail())
  3174. * @param string Headers, separated by chr(10)
  3175. * @param string Encoding type: "base64", "quoted-printable", "8bit". If blank, no encoding will be used, no encoding headers set.
  3176. * @param string Charset used in encoding-headers (only if $enc is set to a valid value which produces such a header)
  3177. * @param boolean If set, the content of $subject will not be encoded.
  3178. * @return void
  3179. */
  3180. function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0) {
  3181. switch((string)$enc) {
  3182. case 'base64':
  3183. $headers=trim($headers).chr(10).
  3184. 'Mime-Version: 1.0'.chr(10).
  3185. 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
  3186. 'Content-Transfer-Encoding: base64';
  3187. $message=trim(chunk_split(base64_encode($message.chr(10)))).chr(10); // Adding chr(10) because I think MS outlook 2002 wants it... may be removed later again.
  3188. if (!$dontEncodeSubject) $subject='=?'.$charset.'?B?'.base64_encode($subject).'?=';
  3189. break;
  3190. case 'quoted-printable':
  3191. $headers=trim($headers).chr(10).
  3192. 'Mime-Version: 1.0'.chr(10).
  3193. 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
  3194. 'Content-Transfer-Encoding: quoted-printable';
  3195. $message=t3lib_div::quoted_printable($message);
  3196. if (!$dontEncodeSubject) $subject='=?'.$charset.'?Q?'.trim(t3lib_div::quoted_printable(ereg_replace('[[:space:]]','_',$subject),1000)).'?=';
  3197. break;
  3198. case '8bit':
  3199. $headers=trim($headers).chr(10).
  3200. 'Mime-Version: 1.0'.chr(10).
  3201. 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
  3202. 'Content-Transfer-Encoding: 8bit';
  3203. break;
  3204. }
  3205. $headers=trim(implode(chr(10),t3lib_div::trimExplode(chr(10),$headers,1))); // make sure no empty lines are there.
  3206. mail($email,$subject,$message,$headers);
  3207. }
  3208. /**
  3209. * Implementation of quoted-printable encode.
  3210. * 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!
  3211. * Important: For the ease of use, this function internally uses Unix linebreaks ("\n") for breaking lines, but the output must use "\r\n" instead!
  3212. * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
  3213. * Usage: 2
  3214. *
  3215. * @param string Content to encode
  3216. * @param integer Length of the lines, default is 76
  3217. * @return string The QP encoded string
  3218. */
  3219. function quoted_printable($string,$maxlen=76) {
  3220. // Make sure the string contains only Unix linebreaks
  3221. $string = str_replace(chr(13).chr(10), chr(10), $string); // Replace Windows breaks (\r\n)
  3222. $string = str_replace(chr(13), chr(10), $string); // Replace Mac breaks (\r)
  3223. $newString = '';
  3224. $theLines = explode(chr(10),$string); // Split lines
  3225. foreach($theLines as $val) {
  3226. $newVal = '';
  3227. $theValLen = strlen($val);
  3228. $len = 0;
  3229. for ($index=0; $index < $theValLen; $index++) { // Walk through each character of this line
  3230. $char = substr($val,$index,1);
  3231. $ordVal = ord($char);
  3232. if ($len>($maxlen-4) || ($len>(($maxlen-10)-4)&&$ordVal==32)) {
  3233. $newVal.='='.chr(13).chr(10); // Add a line break
  3234. $len=0; // Reset the length counter
  3235. }
  3236. if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
  3237. $newVal.=$char; // This character is ok, add it to the message
  3238. $len++;
  3239. } else {
  3240. $newVal.=sprintf('=%02X',$ordVal); // Special character, needs to be encoded
  3241. $len+=3;
  3242. }
  3243. }
  3244. $newVal = ereg_replace(chr(32).'$','=20',$newVal); // Replaces a possible SPACE-character at the end of a line
  3245. $newVal = ereg_replace(chr(9).'$','=09',$newVal); // Replaces a possible TAB-character at the end of a line
  3246. $newString.=$newVal.chr(13).chr(10);
  3247. }
  3248. return ereg_replace(chr(13).chr(10).'$','',$newString);
  3249. }
  3250. /**
  3251. * 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.
  3252. * This function is about preserving long links in messages.
  3253. * Usage: 3
  3254. *
  3255. * @param string Message content
  3256. * @param string URL mode; "76" or "all"
  3257. * @param string URL of index script (see makeRedirectUrl())
  3258. * @return string Processed message content
  3259. * @see makeRedirectUrl()
  3260. */
  3261. function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') {
  3262. // Substitute URLs with shorter links:
  3263. $urlSplit=explode('http://',$message);
  3264. reset($urlSplit);
  3265. while(list($c,$v)=each($urlSplit)) {
  3266. if ($c) {
  3267. $newParts = split('[[:space:]]|\)|\(',$v,2);
  3268. $newURL='http://'.$newParts[0];
  3269. switch((string)$urlmode) {
  3270. case 'all':
  3271. $newURL=t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
  3272. break;
  3273. case '76':
  3274. $newURL=t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
  3275. break;
  3276. }
  3277. $urlSplit[$c]=$newURL.substr($v,strlen($newParts[0]));
  3278. }
  3279. }
  3280. $message=implode('',$urlSplit);
  3281. return $message;
  3282. }
  3283. /**
  3284. * Subfunction for substUrlsInPlainText() above.
  3285. * Usage: 2
  3286. *
  3287. * @param string Input URL
  3288. * @param integer URL string length limit
  3289. * @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')
  3290. * @return string Processed URL
  3291. * @internal
  3292. */
  3293. function makeRedirectUrl($inUrl,$l=0,$index_script_url='') {
  3294. if (strlen($inUrl)>$l) {
  3295. $md5 = substr(md5($inUrl),0,20);
  3296. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params'));
  3297. if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
  3298. $insertFields = array(
  3299. 'md5hash' => $md5,
  3300. 'tstamp' => time(),
  3301. 'type' => 2,
  3302. 'params' => $inUrl
  3303. );
  3304. $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
  3305. }
  3306. $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')).
  3307. '?RDCT='.$md5;
  3308. }
  3309. return $inUrl;
  3310. }
  3311. /**
  3312. * Function to compensate for FreeType2 96 dpi
  3313. * Usage: 21
  3314. *
  3315. * @param integer Fontsize for freetype function call
  3316. * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
  3317. */
  3318. function freetypeDpiComp($font_size) {
  3319. $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
  3320. if ($dpi!=72) $font_size = $font_size/$dpi*72;
  3321. return $font_size;
  3322. }
  3323. /**
  3324. * Developer log; 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.
  3325. * The result is meant to make sense to developers during development or debugging of a site.
  3326. * 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.
  3327. * If you want to implement the devLog in your applications, simply add lines like:
  3328. * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
  3329. *
  3330. * @param string Message (in english).
  3331. * @param string Extension key (from which extension you are calling the log)
  3332. * @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
  3333. * @param array Additional data you want to pass to the logger.
  3334. * @return void
  3335. */
  3336. function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) {
  3337. global $TYPO3_CONF_VARS;
  3338. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
  3339. $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
  3340. $fakeThis = FALSE;
  3341. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
  3342. t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
  3343. }
  3344. }
  3345. }
  3346. /**
  3347. * Converts a one dimensional array to a one line string which can be used for logging or debugging output
  3348. * Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;"
  3349. *
  3350. * @param array Data array which should be outputted
  3351. * @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.
  3352. * @param integer Long string values are shortened to this length. Default: 20
  3353. * @return string Output string with key names and their value as string
  3354. */
  3355. function arrayToLogString($arr, $valueList=array(), $valueLength=20) {
  3356. $str = '';
  3357. if(is_array($arr)) {
  3358. if (!is_array($valueList)) {
  3359. $valueList = explode(',', $valueList);
  3360. }
  3361. foreach($arr as $key => $value) {
  3362. if (!count($valueList) OR (count($valueList) AND in_array($key, $valueList))) {
  3363. $str .= (string)$key.trim(': '.t3lib_div::fixed_lgd(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
  3364. }
  3365. }
  3366. }
  3367. return $str;
  3368. }
  3369. /**
  3370. * Compile the command for running ImageMagick/GraphicsMagick.
  3371. *
  3372. * @param string Command to be run
  3373. * @param string The parameters string
  3374. * @param string Override the default path
  3375. * @return string Compiled command that deals with IM6 & GraphicsMagick
  3376. */
  3377. function imageMagickCommand($command, $parameters, $path='') {
  3378. $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
  3379. $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
  3380. $switchCompositeParameters=false;
  3381. if(!$path) { $path = $gfxConf['im_path']; }
  3382. $im_version = strtolower($gfxConf['im_version_5']);
  3383. $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
  3384. if($command==='combine') { // This is only used internally, has no effect outside
  3385. $command = 'composite';
  3386. }
  3387. // Compile the path & command
  3388. if($im_version==='gm') {
  3389. $switchCompositeParameters=true;
  3390. $path .= 'gm'.$isExt.' '.$command;
  3391. } else {
  3392. if($im_version==='im6') { $switchCompositeParameters=true; }
  3393. $path .= (($command=='composite') ? $combineScript : $command).$isExt;
  3394. }
  3395. $cmdLine = $path.' '.$parameters;
  3396. if($command=='composite' && $switchCompositeParameters) { // Because of some weird incompatibilities between ImageMagick 4 and 6 (plus GraphicsMagick), it is needed to change the parameters order under some preconditions
  3397. $paramsArr = t3lib_div::unQuoteFilenames($parameters);
  3398. if(count($paramsArr)==6) { // The mask image has been specified => swap the parameters
  3399. $tmp = $paramsArr[3];
  3400. $paramsArr[3] = $paramsArr[2];
  3401. $paramsArr[2] = $tmp;
  3402. }
  3403. $cmdLine = $path.' '.implode(' ', $paramsArr);
  3404. }
  3405. return $cmdLine;
  3406. }
  3407. /**
  3408. * 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.
  3409. *
  3410. * @param string The whole parameters string
  3411. * @return array Exploded parameters
  3412. */
  3413. function unQuoteFilenames($parameters) {
  3414. $paramsArr = explode(' ', trim($parameters));
  3415. $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.
  3416. foreach($paramsArr as $k=>$v) {
  3417. if($quoteActive > -1) {
  3418. $paramsArr[$quoteActive] .= ' '.$v;
  3419. unset($paramsArr[$k]);
  3420. if(ereg('"$', $v)) { $quoteActive = -1; }
  3421. } elseif(!trim($v)) {
  3422. unset($paramsArr[$k]); // Remove empty elements
  3423. } elseif(ereg('^"', $v)) {
  3424. $quoteActive = $k;
  3425. }
  3426. }
  3427. return $paramsArr;
  3428. }
  3429. }
  3430. ?>