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