PageRenderTime 56ms CodeModel.GetById 19ms 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

Large files files are truncated, but you can click here to view the full file

  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" o…

Large files files are truncated, but you can click here to view the full file