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