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