dc9a3f05954f036ef42d349a91471313d146ec74
[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 while(list(,$lStr)=each($lines)) {
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 (strstr($baseIP, ':') && 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 reset($IPparts);
669 while(list($index,$val)=each($IPparts)) {
670 $val = trim($val);
671 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
672 $yes=0;
673 }
674 }
675 }
676 if ($yes) return true;
677 }
678 }
679 return false;
680 }
681
682 /**
683 * Match IPv6 address with a list of IPv6 prefixes
684 *
685 * @param string $baseIP is the current remote IP address for instance
686 * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
687 * @return boolean True if an baseIP matches any prefix
688 */
689 public static function cmpIPv6($baseIP, $list) {
690 $success = false; // Policy default: Deny connection
691 $baseIP = t3lib_div::normalizeIPv6($baseIP);
692
693 $values = t3lib_div::trimExplode(',',$list,1);
694 foreach ($values as $test) {
695 list($test,$mask) = explode('/',$test);
696 if (t3lib_div::validIPv6($test)) {
697 $test = t3lib_div::normalizeIPv6($test);
698 if (intval($mask)) {
699 switch ($mask) { // test on /48 /64
700 case '48':
701 $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 48);
702 $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 48);
703 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
704 break;
705 case '64':
706 $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 64);
707 $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 64);
708 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
709 break;
710 default:
711 $success = false;
712 }
713 } else {
714 if (t3lib_div::validIPv6($test)) { // test on full ip address 128 bits
715 $testBin = t3lib_div::IPv6Hex2Bin($test);
716 $baseIPBin = t3lib_div::IPv6Hex2Bin($baseIP);
717 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
718 }
719 }
720 }
721 if ($success) return true;
722 }
723 return false;
724 }
725
726 /**
727 * [Describe function...]
728 *
729 * @param [type] $hex: ...
730 * @return [type] ...
731 */
732 public static function IPv6Hex2Bin ($hex) {
733 $bin = '';
734 $hex = str_replace(':', '', $hex); // Replace colon to nothing
735 for ($i=0; $i<strlen($hex); $i=$i+2) {
736 $bin.= chr(hexdec(substr($hex, $i, 2)));
737 }
738 return $bin;
739 }
740
741 /**
742 * Normalize an IPv6 address to full length
743 *
744 * @param string Given IPv6 address
745 * @return string Normalized address
746 */
747 public static function normalizeIPv6($address) {
748 $normalizedAddress = '';
749 $stageOneAddress = '';
750
751 $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks
752 if (count($chunks)==2) {
753 $chunksLeft = explode(':', $chunks[0]);
754 $chunksRight = explode(':', $chunks[1]);
755 $left = count($chunksLeft);
756 $right = count($chunksRight);
757
758 // Special case: leading zero-only blocks count to 1, should be 0
759 if ($left==1 && strlen($chunksLeft[0])==0) $left=0;
760
761 $hiddenBlocks = 8 - ($left + $right);
762 $hiddenPart = '';
763 while ($h<$hiddenBlocks) {
764 $hiddenPart .= '0000:';
765 $h++;
766 }
767
768 if ($left == 0) {
769 $stageOneAddress = $hiddenPart . $chunks[1];
770 } else {
771 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
772 }
773 } else $stageOneAddress = $address;
774
775 // normalize the blocks:
776 $blocks = explode(':', $stageOneAddress);
777 $divCounter = 0;
778 foreach ($blocks as $block) {
779 $tmpBlock = '';
780 $i = 0;
781 $hiddenZeros = 4 - strlen($block);
782 while ($i < $hiddenZeros) {
783 $tmpBlock .= '0';
784 $i++;
785 }
786 $normalizedAddress .= $tmpBlock . $block;
787 if ($divCounter < 7) {
788 $normalizedAddress .= ':';
789 $divCounter++;
790 }
791 }
792 return $normalizedAddress;
793 }
794
795 /**
796 * Validate a given IP address to the IPv6 address format.
797 *
798 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
799 *
800 * @param string IP address to be tested
801 * @return boolean True if $ip is of IPv6 format.
802 */
803 public static function validIPv6($ip) {
804 $uppercaseIP = strtoupper($ip);
805
806 $regex = '/^(';
807 $regex.= '(([\dA-F]{1,4}:){7}[\dA-F]{1,4})|';
808 $regex.= '(([\dA-F]{1,4}){1}::([\dA-F]{1,4}:){1,5}[\dA-F]{1,4})|';
809 $regex.= '(([\dA-F]{1,4}:){2}:([\dA-F]{1,4}:){1,4}[\dA-F]{1,4})|';
810 $regex.= '(([\dA-F]{1,4}:){3}:([\dA-F]{1,4}:){1,3}[\dA-F]{1,4})|';
811 $regex.= '(([\dA-F]{1,4}:){4}:([\dA-F]{1,4}:){1,2}[\dA-F]{1,4})|';
812 $regex.= '(([\dA-F]{1,4}:){5}:([\dA-F]{1,4}:){0,1}[\dA-F]{1,4})|';
813 $regex.= '(::([\dA-F]{1,4}:){0,6}[\dA-F]{1,4})';
814 $regex.= ')$/';
815
816 return preg_match($regex, $uppercaseIP) ? true : false;
817 }
818
819 /**
820 * Match fully qualified domain name with list of strings with wildcard
821 *
822 * @param string The current remote IP address for instance, typ. REMOTE_ADDR
823 * @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)
824 * @return boolean True if a domain name mask from $list matches $baseIP
825 */
826 public static function cmpFQDN($baseIP, $list) {
827 if (count(explode('.',$baseIP))==4) {
828 $resolvedHostName = explode('.', gethostbyaddr($baseIP));
829 $values = t3lib_div::trimExplode(',',$list,1);
830
831 foreach($values as $test) {
832 $hostNameParts = explode('.',$test);
833 $yes = 1;
834
835 foreach($hostNameParts as $index => $val) {
836 $val = trim($val);
837 if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
838 $yes=0;
839 }
840 }
841 if ($yes) return true;
842 }
843 }
844 return false;
845 }
846
847 /**
848 * Check for item in list
849 * Check if an item exists in a comma-separated list of items.
850 * Usage: 163
851 *
852 * @param string comma-separated list of items (string)
853 * @param string item to check for
854 * @return boolean true if $item is in $list
855 */
856 public static function inList($list,$item) {
857 return strstr(','.$list.',', ','.$item.',') ? true : false;
858 }
859
860 /**
861 * Removes an item from a comma-separated list of items.
862 * Usage: 1
863 *
864 * @param string element to remove
865 * @param string comma-separated list of items (string)
866 * @return string new comma-separated list of items
867 */
868 public static function rmFromList($element,$list) {
869 $items = explode(',',$list);
870 while(list($k,$v)=each($items)) {
871 if ($v==$element) {unset($items[$k]);}
872 }
873 return implode(',',$items);
874 }
875
876 /**
877 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
878 * Ranges are limited to 1000 values per range.
879 *
880 * @param string comma-separated list of integers with ranges (string)
881 * @return string new comma-separated list of items
882 * @author Martin Kutschker <martin.kutschker@activesolution.at>
883 */
884 public static function expandList($list) {
885 $items = explode(',',$list);
886 $list = array();
887 while(list(,$item)=each($items)) {
888 $range = explode('-',$item);
889 if (isset($range[1])) {
890 $runAwayBrake = 1000;
891 for ($n=$range[0]; $n<=$range[1]; $n++) {
892 $list[] = $n;
893
894 $runAwayBrake--;
895 if ($runAwayBrake<=0) break;
896 }
897 } else {
898 $list[] = $item;
899 }
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(current($reg[2]));
1254 next($reg[2]); // Advance pointer
1255 while(list($k,$v)=each($reg[2])) {
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 (strstr($email,' ')) return FALSE;
1374 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
1375 }
1376
1377 /**
1378 * Formats a string for output between <textarea>-tags
1379 * All content outputted in a textarea form should be passed through this function
1380 * 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!
1381 * Usage: 23
1382 *
1383 * @param string Input string to be formatted.
1384 * @return string Formatted for <textarea>-tags
1385 */
1386 public static function formatForTextarea($content) {
1387 return chr(10).htmlspecialchars($content);
1388 }
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401 /*************************
1402 *
1403 * ARRAY FUNCTIONS
1404 *
1405 *************************/
1406
1407 /**
1408 * Check if an item exists in an array
1409 * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
1410 * Usage: 3
1411 *
1412 * @param array one-dimensional array of items
1413 * @param string item to check for
1414 * @return boolean true if $item is in the one-dimensional array $in_array
1415 * @internal
1416 */
1417 public static function inArray(array $in_array,$item) {
1418 while (list(,$val)=each($in_array)) {
1419 if (!is_array($val) && !strcmp($val,$item)) return true;
1420 }
1421 }
1422
1423 /**
1424 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1425 * Corresponds to explode(), but with conversion to integers for all values.
1426 * Usage: 76
1427 *
1428 * @param string Delimiter string to explode with
1429 * @param string The string to explode
1430 * @return array Exploded values, all converted to integers
1431 */
1432 public static function intExplode($delim, $string) {
1433 $temp = explode($delim,$string);
1434 while(list($key,$val)=each($temp)) {
1435 $temp[$key]=intval($val);
1436 }
1437 reset($temp);
1438 return $temp;
1439 }
1440
1441 /**
1442 * Reverse explode which explodes the string counting from behind.
1443 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1444 * Usage: 8
1445 *
1446 * @param string Delimiter string to explode with
1447 * @param string The string to explode
1448 * @param integer Number of array entries
1449 * @return array Exploded values
1450 */
1451 public static function revExplode($delim, $string, $count=0) {
1452 $temp = explode($delim,strrev($string),$count);
1453 while(list($key,$val)=each($temp)) {
1454 $temp[$key]=strrev($val);
1455 }
1456 $temp = array_reverse($temp);
1457 reset($temp);
1458 return $temp;
1459 }
1460
1461 /**
1462 * Explodes a string and trims all values for whitespace in the ends.
1463 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1464 * Usage: 256
1465 *
1466 * @param string Delimiter string to explode with
1467 * @param string The string to explode
1468 * @param boolean If set, all empty values (='') will NOT be set in output
1469 * @return array Exploded values
1470 */
1471 public static function trimExplode($delim, $string, $onlyNonEmptyValues=0) {
1472 $array = explode($delim, $string);
1473 // for two perfomance reasons the loop is duplicated
1474 // a) avoid check for $onlyNonEmptyValues in foreach loop
1475 // b) avoid unnecessary code when $onlyNonEmptyValues is not set
1476 if ($onlyNonEmptyValues) {
1477 $new_array = array();
1478 foreach($array as $value) {
1479 $value = trim($value);
1480 if ($value != '') {
1481 $new_array[] = $value;
1482 }
1483 }
1484 // direct return for perfomance reasons
1485 return $new_array;
1486 }
1487
1488 foreach($array as &$value) {
1489 $value = trim($value);
1490 }
1491
1492 return $array;
1493 }
1494
1495 /**
1496 * Remove duplicate values from an array
1497 * Usage: 0
1498 *
1499 * @param array Array of values to make unique
1500 * @return array
1501 * @ignore
1502 * @deprecated Use the PHP function array_unique instead
1503 */
1504 public static function uniqueArray(array $valueArray) {
1505 return array_unique($valueArray);
1506 }
1507
1508 /**
1509 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1510 * Usage: 3
1511 *
1512 * @param array Array containing the values
1513 * @param string Value to search for and if found remove array entry where found.
1514 * @return array Output array with entries removed if search string is found
1515 */
1516 public static function removeArrayEntryByValue(array $array, $cmpValue) {
1517 reset($array);
1518 while(list($k,$v)=each($array)) {
1519 if (is_array($v)) {
1520 $array[$k] = t3lib_div::removeArrayEntryByValue($v,$cmpValue);
1521 } else {
1522 if (!strcmp($v,$cmpValue)) {
1523 unset($array[$k]);
1524 }
1525 }
1526 }
1527 reset($array);
1528 return $array;
1529 }
1530
1531 /**
1532 * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1533 * Usage: 24
1534 *
1535 * @param string Name prefix for entries. Set to blank if you wish none.
1536 * @param array The (multidim) array to implode
1537 * @param string (keep blank)
1538 * @param boolean If set, parameters which were blank strings would be removed.
1539 * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1540 * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1541 * @see explodeUrl2Array()
1542 */
1543 public static function implodeArrayForUrl($name,array $theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) {
1544 foreach($theArray as $Akey => $AVal) {
1545 $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
1546 if (is_array($AVal)) {
1547 $str = t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
1548 } else {
1549 if (!$skipBlank || strcmp($AVal,'')) {
1550 $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
1551 '='.rawurlencode($AVal);
1552 }
1553 }
1554 }
1555 return $str;
1556 }
1557
1558 /**
1559 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1560 *
1561 * @param string GETvars string
1562 * @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())
1563 * @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!
1564 * @see implodeArrayForUrl()
1565 */
1566 public static function explodeUrl2Array($string,$multidim=FALSE) {
1567 $output = array();
1568 if ($multidim) {
1569 parse_str($string,$output);
1570 } else {
1571 $p = explode('&',$string);
1572 foreach($p as $v) {
1573 if (strlen($v)) {
1574 list($pK,$pV) = explode('=',$v,2);
1575 $output[rawurldecode($pK)] = rawurldecode($pV);
1576 }
1577 }
1578 }
1579 return $output;
1580 }
1581
1582 /**
1583 * Returns an array with selected keys from incoming data.
1584 * (Better read source code if you want to find out...)
1585 * Usage: 3
1586 *
1587 * @param string List of variable/key names
1588 * @param array Array from where to get values based on the keys in $varList
1589 * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1590 * @return array Output array with selected variables.
1591 */
1592 public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1) {
1593 $keys = t3lib_div::trimExplode(',',$varList,1);
1594 $outArr = array();
1595 foreach($keys as $v) {
1596 if (isset($getArray[$v])) {
1597 $outArr[$v] = $getArray[$v];
1598 } elseif ($GPvarAlt) {
1599 $outArr[$v] = t3lib_div::_GP($v);
1600 }
1601 }
1602 return $outArr;
1603 }
1604
1605 /**
1606 * AddSlash array
1607 * This function traverses a multidimentional array and adds slashes to the values.
1608 * NOTE that the input array is and argument by reference.!!
1609 * Twin-function to stripSlashesOnArray
1610 * Usage: 8
1611 *
1612 * @param array Multidimensional input array, (REFERENCE!)
1613 * @return array
1614 */
1615 public static function addSlashesOnArray(array &$theArray) {
1616 reset($theArray);
1617 while(list($Akey,$AVal)=each($theArray)) {
1618 if (is_array($AVal)) {
1619 t3lib_div::addSlashesOnArray($theArray[$Akey]);
1620 } else {
1621 $theArray[$Akey] = addslashes($AVal);
1622 }
1623 }
1624 reset($theArray);
1625 }
1626
1627 /**
1628 * StripSlash array
1629 * This function traverses a multidimentional array and strips slashes to the values.
1630 * NOTE that the input array is and argument by reference.!!
1631 * Twin-function to addSlashesOnArray
1632 * Usage: 10
1633 *
1634 * @param array Multidimensional input array, (REFERENCE!)
1635 * @return array
1636 */
1637 public static function stripSlashesOnArray(array &$theArray) {
1638 reset($theArray);
1639 while(list($Akey,$AVal)=each($theArray)) {
1640 if (is_array($AVal)) {
1641 t3lib_div::stripSlashesOnArray($theArray[$Akey]);
1642 } else {
1643 $theArray[$Akey] = stripslashes($AVal);
1644 }
1645 }
1646 reset($theArray);
1647 }
1648
1649 /**
1650 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1651 * Usage: 0
1652 *
1653 * @param array Multidimensional input array
1654 * @param string "add" or "strip", depending on usage you wish.
1655 * @return array
1656 */
1657 public static function slashArray(array $arr,$cmd) {
1658 if ($cmd=='strip') t3lib_div::stripSlashesOnArray($arr);
1659 if ($cmd=='add') t3lib_div::addSlashesOnArray($arr);
1660 return $arr;
1661 }
1662
1663 /**
1664 * 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)
1665 * In case of identical keys, ie. keeping the values of the second.
1666 * Usage: 0
1667 *
1668 * @param array First array
1669 * @param array Second array, overruling the first array
1670 * @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.
1671 * @param boolean If set, values from $arr1 will overrule if they are empty or zero. Default: true
1672 * @return array Resulting array where $arr1 values has overruled $arr0 values
1673 */
1674 public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) {
1675 reset($arr1);
1676 while(list($key,$val) = each($arr1)) {
1677 if(is_array($arr0[$key])) {
1678 if (is_array($arr1[$key])) {
1679 $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
1680 }
1681 } else {
1682 if ($notAddKeys) {
1683 if (isset($arr0[$key])) {
1684 if ($includeEmtpyValues || $val) {
1685 $arr0[$key] = $val;
1686 }
1687 }
1688 } else {
1689 if ($includeEmtpyValues || $val) {
1690 $arr0[$key] = $val;
1691 }
1692 }
1693 }
1694 }
1695 reset($arr0);
1696 return $arr0;
1697 }
1698
1699 /**
1700 * 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.
1701 * Usage: 16
1702 *
1703 * @param array First array
1704 * @param array Second array
1705 * @return array Merged result.
1706 */
1707 public static function array_merge(array $arr1,array $arr2) {
1708 return $arr2+$arr1;
1709 }
1710
1711 /**
1712 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1713 * Usage: 5
1714 *
1715 * @param array Input array of values
1716 * @param string Delimited, default is comman
1717 * @param string Quote-character to wrap around the values.
1718 * @return string A single line of CSV
1719 */
1720 public static function csvValues(array $row,$delim=',',$quote='"') {
1721 reset($row);
1722 $out=array();
1723 foreach ($row as $value) {
1724 $out[] = str_replace($quote, $quote.$quote, $value);
1725 }
1726 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
1727 return $str;
1728 }
1729
1730 /**
1731 * Creates recursively a JSON literal from a mulidimensional associative array.
1732 * Uses Services_JSON (http://mike.teczno.com/JSON/doc/)
1733 *
1734 * @param array $jsonArray: The array to be transformed to JSON
1735 * @return string JSON string
1736 */
1737 public static function array2json(array $jsonArray) {
1738 if (!$GLOBALS['JSON']) {
1739 require_once(PATH_typo3.'contrib/json/json.php');
1740 $GLOBALS['JSON'] = t3lib_div::makeInstance('Services_JSON');
1741 }
1742 return $GLOBALS['JSON']->encode($jsonArray);
1743 }
1744
1745 /**
1746 * Removes dots "." from end of a key identifier of TypoScript styled array.
1747 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1748 *
1749 * @param array $ts: TypoScript configuration array
1750 * @return array TypoScript configuration array without dots at the end of all keys
1751 */
1752 public static function removeDotsFromTS(array $ts) {
1753 $out = array();
1754 if (is_array($ts)) {
1755 foreach ($ts as $key => $value) {
1756 if (is_array($value)) {
1757 $key = rtrim($key, '.');
1758 $out[$key] = t3lib_div::removeDotsFromTS($value);
1759 } else {
1760 $out[$key] = $value;
1761 }
1762 }
1763 }
1764 return $out;
1765 }
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782 /*************************
1783 *
1784 * HTML/XML PROCESSING
1785 *
1786 *************************/
1787
1788 /**
1789 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1790 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
1791 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1792 * Usage: 8
1793 *
1794 * @param string HTML-tag string (or attributes only)
1795 * @return array Array with the attribute values.
1796 */
1797 public static function get_tag_attributes($tag) {
1798 $components = t3lib_div::split_tag_attributes($tag);
1799 $name = ''; // attribute name is stored here
1800 $valuemode = false;
1801 $attributes = array();
1802 foreach ($components as $key => $val) {
1803 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
1804 if ($valuemode) {
1805 if ($name) {
1806 $attributes[$name] = $val;
1807 $name = '';
1808 }
1809 } else {
1810 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val))) {
1811 $attributes[$key] = '';
1812 $name = $key;
1813 }
1814 }
1815 $valuemode = false;
1816 } else {
1817 $valuemode = true;
1818 }
1819 }
1820 return $attributes;
1821 }
1822
1823 /**
1824 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1825 * Removes tag-name if found
1826 * Usage: 2
1827 *
1828 * @param string HTML-tag string (or attributes only)
1829 * @return array Array with the attribute values.
1830 * @internal
1831 */
1832 public static function split_tag_attributes($tag) {
1833 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
1834 // Removes any > in the end of the string
1835 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
1836
1837 $value = array();
1838 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
1839 $firstChar=substr($tag_tmp,0,1);
1840 if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
1841 $reg=explode($firstChar,$tag_tmp,3);
1842 $value[]=$reg[1];
1843 $tag_tmp=trim($reg[2]);
1844 } elseif (!strcmp($firstChar,'=')) {
1845 $value[] = '=';
1846 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
1847 } else {
1848 // There are '' around the value. We look for the next ' ' or '>'
1849 $reg = split('[[:space:]=]',$tag_tmp,2);
1850 $value[] = trim($reg[0]);
1851 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
1852 }
1853 }
1854 reset($value);
1855 return $value;
1856 }
1857
1858 /**
1859 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1860 * Usage: 14
1861 *
1862 * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1863 * @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!
1864 * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
1865 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1866 */
1867 public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1868 if ($xhtmlSafe) {
1869 $newArr=array();
1870 foreach($arr as $p => $v) {
1871 if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
1872 }
1873 $arr = $newArr;
1874 }
1875 $list = array();
1876 foreach($arr as $p => $v) {
1877 if (strcmp($v,'') || $dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
1878 }
1879 return implode(' ',$list);
1880 }
1881
1882 /**
1883 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1884 *
1885 * @param array See implodeAttributes()
1886 * @param boolean See implodeAttributes()
1887 * @param boolean See implodeAttributes()
1888 * @return string See implodeAttributes()
1889 * @deprecated Name was changed into implodeAttributes
1890 * @see implodeAttributes()
1891 */
1892 public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1893 return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
1894 }
1895
1896 /**
1897 * Wraps JavaScript code XHTML ready with <script>-tags
1898 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1899 * This is nice for identing JS code with PHP code on the same level.
1900 *
1901 * @param string JavaScript code
1902 * @param boolean Wrap script element in linebreaks? Default is TRUE.
1903 * @return string The wrapped JS code, ready to put into a XHTML page
1904 * @author Ingmar Schlecht <ingmars@web.de>
1905 * @author René Fritz <r.fritz@colorcube.de>
1906 */
1907 public static function wrapJS($string, $linebreak=TRUE) {
1908 if(trim($string)) {
1909 // <script wrapped in nl?
1910 $cr = $linebreak? "\n" : '';
1911
1912 // remove nl from the beginning
1913 $string = preg_replace ('/^\n+/', '', $string);
1914 // re-ident to one tab using the first line as reference
1915 $match = array();
1916 if(preg_match('/^(\t+)/',$string,$match)) {
1917 $string = str_replace($match[1],"\t", $string);
1918 }
1919 $string = $cr.'<script type="text/javascript">
1920 /*<![CDATA[*/
1921 '.$string.'
1922 /*]]>*/
1923 </script>'.$cr;
1924 }
1925 return trim($string);
1926 }
1927
1928
1929 /**
1930 * Parses XML input into a PHP array with associative keys
1931 * Usage: 0
1932 *
1933 * @param string XML data input
1934 * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1935 * @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.
1936 * @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
1937 */
1938 public static function xml2tree($string,$depth=999) {
1939 $parser = xml_parser_create();
1940 $vals = array();
1941 $index = array();
1942
1943 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1944 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1945 xml_parse_into_struct($parser, $string, $vals, $index);
1946
1947 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
1948 xml_parser_free($parser);
1949
1950 $stack = array( array() );
1951 $stacktop = 0;
1952 $startPoint=0;
1953
1954 // FIXME don't use unset() - what does that mean? Use NULL or similar.
1955 unset($tagi);
1956 foreach($vals as $key => $val) {
1957 $type = $val['type'];
1958
1959 // open tag:
1960 if ($type=='open' || $type=='complete') {
1961 $stack[$stacktop++] = $tagi;
1962
1963 if ($depth==$stacktop) {
1964 $startPoint=$key;
1965 }
1966
1967 $tagi = array('tag' => $val['tag']);
1968
1969 if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
1970 if(isset($val['value'])) $tagi['values'][] = $val['value'];
1971 }
1972 // finish tag:
1973 if ($type=='complete' || $type=='close') {
1974 $oldtagi = $tagi;
1975 $tagi = $stack[--$stacktop];
1976 $oldtag = $oldtagi['tag'];
1977 unset($oldtagi['tag']);
1978
1979 if ($depth==($stacktop+1)) {
1980 if ($key-$startPoint > 0) {
1981 $partArray = array_slice(
1982 $vals,
1983 $startPoint+1,
1984 $key-$startPoint-1
1985 );
1986 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
1987 $oldtagi['XMLvalue']=t3lib_div::xmlRecompileFromStructValArray($partArray);
1988 } else {
1989 $oldtagi['XMLvalue']=$oldtagi['values'][0];
1990 }
1991 }
1992
1993 $tagi['ch'][$oldtag][] = $oldtagi;
1994 unset($oldtagi);
1995 }
1996 // cdata
1997 if($type=='cdata') {
1998 $tagi['values'][] = $val['value'];
1999 }
2000 }
2001 return $tagi['ch'];
2002 }
2003
2004 /**
2005 * Turns PHP array into XML. See array2xml()
2006 *
2007 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2008 * @param string Alternative document tag. Default is "phparray".
2009 * @param array Options for the compilation. See array2xml() for description.
2010 * @param string Forced charset to prologue
2011 * @return string An XML string made from the input content in the array.
2012 * @see xml2array(),array2xml()
2013 */
2014 public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') {
2015
2016 // Figure out charset if not given explicitly:
2017 if (!$charset) {
2018 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
2019 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
2020 } elseif (is_object($GLOBALS['LANG'])) {
2021 $charset = $GLOBALS['LANG']->charSet; // If "LANG" is around, that will hold the current charset
2022 } else {
2023 $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
2024 }
2025 }
2026
2027 // Return XML:
2028 return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.chr(10).
2029 t3lib_div::array2xml($array,'',0,$docTag,0, $options);
2030 }
2031
2032 /**
2033 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2034 *
2035 * Converts a PHP array into an XML string.
2036 * The XML output is optimized for readability since associative keys are used as tagnames.
2037 * 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.
2038 * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
2039 * 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
2040 * 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.
2041 * 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!
2042 * 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...
2043 * Usage: 5
2044 *
2045 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2046 * @param string tag-prefix, eg. a namespace prefix like "T3:"
2047 * @param integer Current recursion level. Don't change, stay at zero!
2048 * @param string Alternative document tag. Default is "phparray".
2049 * @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
2050 * @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')
2051 * @param string Stack data. Don't touch.
2052 * @return string An XML string made from the input content in the array.
2053 * @see xml2array()
2054 */
2055 public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array()) {
2056 // 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
2057 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
2058 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
2059 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
2060 chr(30).chr(31);
2061 // Set indenting mode:
2062 $indentChar = $spaceInd ? ' ' : chr(9);
2063 $indentN = $spaceInd>0 ? $spaceInd : 1;
2064 $nl = ($spaceInd >= 0 ? chr(10) : '');
2065
2066 // Init output variable:
2067 $output='';
2068
2069 // Traverse the input array
2070 foreach($array as $k=>$v) {
2071 $attr = '';
2072 $tagName = $k;
2073
2074 // Construct the tag name.
2075 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
2076 $attr.=' index="'.htmlspecialchars($tagName).'"';
2077 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
2078 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && t3lib_div::testInt($tagName)) { // Use tag based on parent tag name + if current tag is numeric
2079 $attr.=' index="'.htmlspecialchars($tagName).'"';
2080 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
2081 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
2082 $attr.=' index="'.htmlspecialchars($tagName).'"';
2083 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
2084 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
2085 $attr.=' index="'.htmlspecialchars($tagName).'"';
2086 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
2087 } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
2088 if ($options['useNindex']) { // If numeric key, prefix "n"
2089 $tagName = 'n'.$tagName;
2090 } else { // Use special tag for num. keys:
2091 $attr.=' index="'.$tagName.'"';
2092 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
2093 }
2094 } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
2095 $attr.=' index="'.htmlspecialchars($tagName).'"';
2096 $tagName = $options['useIndexTagForAssoc'];
2097 }
2098
2099 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2100 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
2101
2102 // If the value is an array then we will call this function recursively:
2103 if (is_array($v)) {
2104
2105 // Sub elements:
2106 if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
2107 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
2108 $clearStackPath = $subOptions['clearStackPath'];
2109 } else {
2110 $subOptions = $options;
2111 $clearStackPath = FALSE;
2112 }
2113
2114 $content = $nl .
2115 t3lib_div::array2xml(
2116 $v,
2117 $NSprefix,
2118 $level+1,
2119 '',
2120 $spaceInd,
2121 $subOptions,
2122 array(
2123 'parentTagName' => $tagName,
2124 'grandParentTagName' => $stackData['parentTagName'],
2125 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
2126 )
2127 ).
2128 ($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '');
2129 if ((int)$options['disableTypeAttrib']!=2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2130 $attr.=' type="array"';
2131 }
2132 } else { // Just a value:
2133
2134 // Look for binary chars:
2135 $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2136 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!
2137 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2138 $content = $nl.chunk_split(base64_encode($v));
2139 $attr.=' base64="1"';
2140 } else {
2141 // Otherwise, just htmlspecialchar the stuff:
2142 $content = htmlspecialchars($v);
2143 $dType = gettype($v);
2144 if ($dType == 'string') {
2145 if ($options['useCDATA'] && $content != $v) {
2146 $content = '<![CDATA[' . $v . ']]>';
2147 }
2148 } elseif (!$options['disableTypeAttrib']) {
2149 $attr.= ' type="'.$dType.'"';
2150 }
2151 }
2152 }
2153
2154 // Add the element to the output string:
2155 $output.=($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
2156 }
2157
2158 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2159 if (!$level) {
2160 $output =
2161 '<'.$docTag.'>'.$nl.
2162 $output.
2163 '</'.$docTag.'>';
2164 }
2165
2166 return $output;
2167 }
2168
2169 /**
2170 * Converts an XML string to a PHP array.
2171 * This is the reverse function of array2xml()
2172 * Usage: 17
2173 *
2174 * @param string XML content to convert into an array
2175 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
2176 * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2177 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2178 * @see array2xml()
2179 */
2180 public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
2181 global $TYPO3_CONF_VARS;
2182
2183 // Create parser:
2184 $parser = xml_parser_create();
2185 $vals = array();
2186 $index = array();
2187
2188 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2189 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2190
2191 // PHP 5.0.0 & 5.0.1: default output charset is ISO-8859-1, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2192 // PHP 5.0.2+: default output charset is UTF-8 , only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2193 $match = array();
2194 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
2195 $theCharset = $match[1] ? $match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
2196 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
2197
2198 // Parse content:
2199 xml_parse_into_struct($parser, $string, $vals, $index);
2200
2201 // If error, return error message:
2202 if (xml_get_error_code($parser)) {
2203 return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
2204 }
2205 xml_parser_free($parser);
2206
2207 // Init vars:
2208 $stack = array(array());
2209 $stacktop = 0;
2210 $current = array();
2211 $tagName = '';
2212 $documentTag = '';
2213
2214 // Traverse the parsed XML structure:
2215 foreach($vals as $key => $val) {
2216
2217 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2218 $tagName = $val['tag'];
2219 if (!$documentTag) $documentTag = $tagName;
2220
2221 // Test for name space:
2222 $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
2223
2224 // Test for numeric tag, encoded on the form "nXXX":
2225 $testNtag = substr($tagName,1); // Closing tag.
2226 $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
2227
2228 // Test for alternative index value:
2229 if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
2230
2231 // Setting tag-values, manage stack:
2232 switch($val['type']) {
2233 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2234 $current[$tagName] = array(); // Setting blank place holder
2235 $stack[$stacktop++] = $current;
2236 $current = array();
2237 break;
2238 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2239 $oldCurrent = $current;
2240 $current = $stack[--$stacktop];
2241 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
2242 $current[key($current)] = $oldCurrent;
2243 unset($oldCurrent);
2244 break;
2245 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2246 if ($val['attributes']['base64']) {
2247 $current[$tagName] = base64_decode($val['value']);
2248 } else {
2249 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
2250
2251 // Cast type:
2252 switch((string)$val['attributes']['type']) {
2253 case 'integer':
2254 $current[$tagName] = (integer)$current[$tagName];
2255 break;
2256 case 'double':
2257 $current[$tagName] = (double)$current[$tagName];
2258 break;
2259 case 'boolean':
2260 $current[$tagName] = (bool)$current[$tagName];
2261 break;
2262 case 'array':
2263 $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...
2264 break;
2265 }
2266 }
2267 break;
2268 }
2269 }
2270
2271 if ($reportDocTag) {
2272 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2273 }
2274
2275 // Finally return the content of the document tag.
2276 return $current[$tagName];
2277 }
2278
2279 /**
2280 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2281 * Usage: 2
2282 *
2283 * @param array A array of XML parts, see xml2tree
2284 * @return string Re-compiled XML data.
2285 */
2286 public static function xmlRecompileFromStructValArray(array $vals) {
2287 $XMLcontent='';
2288
2289 foreach($vals as $val) {
2290 $type = $val['type'];
2291
2292 // open tag:
2293 if ($type=='open' || $type=='complete') {
2294 $XMLcontent.='<'.$val['tag'];
2295 if(isset($val['attributes'])) {
2296 foreach($val['attributes'] as $k => $v) {
2297 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
2298 }
2299 }
2300 if ($type=='complete') {
2301 if(isset($val['value'])) {
2302 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
2303 } else $XMLcontent.='/>';
2304 } else $XMLcontent.='>';
2305
2306 if ($type=='open' && isset($val['value'])) {
2307 $XMLcontent.=htmlspecialchars($val['value']);
2308 }
2309 }
2310 // finish tag:
2311 if ($type=='close') {
2312 $XMLcontent.='</'.$val['tag'].'>';
2313 }
2314 // cdata
2315 if($type=='cdata') {
2316 $XMLcontent.=htmlspecialchars($val['value']);
2317 }
2318 }
2319
2320 return $XMLcontent;
2321 }
2322
2323 /**
2324 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2325 * Usage: 1
2326 *
2327 * @param string XML data
2328 * @return array Attributes of the xml prologue (header)
2329 */
2330 public static function xmlGetHeaderAttribs($xmlData) {
2331 $match = array();
2332 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
2333 return t3lib_div::get_tag_attributes($match[1]);
2334 }
2335 }
2336
2337 /**
2338 * Minifies JavaScript
2339 *
2340 * @param string $script Script to minify
2341 * @param string $error Error message (if any)
2342 * @return string Minified script or source string if error happened
2343 */
2344 public static function minifyJavaScript($script, &$error = '') {
2345 require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
2346 try {
2347 $error = '';
2348 $script = trim(JSMin::minify(str_replace(chr(13), '', $script)));
2349 }
2350 catch(JSMinException $e) {
2351 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
2352 t3lib_div::devLog($error, 't3lib_div', 2,
2353 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
2354 }
2355 return $script;
2356 }
2357
2358
2359
2360
2361
2362
2363
2364
2365 /*************************
2366 *
2367 * FILES FUNCTIONS
2368 *
2369 *************************/
2370
2371 /**
2372 * Reads the file or url $url and returns the content
2373 * 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.
2374 * Usage: 83
2375 *
2376 * @param string Filepath/URL to read
2377 * @param integer Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2378 * @param array HTTP headers to be used in the request
2379 * @return string The content from the resource given as input.
2380 */
2381 public static function getURL($url, $includeHeader = 0, $requestHeaders = false) {
2382 $content = false;
2383
2384 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2385 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^https?:\/\//', $url)) {
2386 // External URL without error checking.
2387 $ch = curl_init();
2388 if (!$ch) {
2389 return false;
2390 }
2391
2392 curl_setopt($ch, CURLOPT_URL, $url);
2393 curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
2394 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
2395 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
2396 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2397 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
2398 if (is_array($requestHeaders)) {
2399 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
2400 }
2401
2402 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2403 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2404
2405 // Not sure if this is needed
2406 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2407 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2408 }
2409 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2410 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2411 }
2412 }
2413 $content = curl_exec($ch);
2414 curl_close($ch);
2415
2416 } elseif ($includeHeader) {
2417 $parsedURL = parse_url($url);
2418 if (!t3lib_div::inList('ftp,ftps,http,https,gopher,telnet', $parsedURL['scheme'])) {
2419 return false;
2420 }
2421
2422 $fp = @fsockopen($parsedURL['host'], ($parsedURL['port'] > 0 ? $parsedURL['port'] : 80), $errno, $errstr, 2.0);
2423 if (!$fp) {
2424 return false;
2425 }
2426
2427 $msg = 'GET ' . $parsedURL['path'] .
2428 ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
2429 ' HTTP/1.0' . "\r\n" . 'Host: ' .
2430 $parsedURL['host'] . "\r\n\r\n";
2431 fputs($fp, $msg);
2432 while (!feof($fp)) {
2433 $line = fgets($fp, 2048);
2434 $content.= $line;
2435 if ($includeHeader == 2 && !strlen(trim($line))) {
2436 break; // Stop at the first empty line (= end of header)
2437 }
2438 }
2439 fclose($fp);
2440
2441 } elseif (is_array($requestHeaders)) {
2442 $ctx = stream_context_create(array(
2443 'http' => array(
2444 'header' => implode("\r\n", $requestHeaders)
2445 )
2446 )
2447 );
2448 $content = @file_get_contents($url, false, $ctx);
2449 }
2450 else {
2451 $content = @file_get_contents($url);
2452 }
2453
2454 return $content;
2455 }
2456
2457 /**
2458 * Writes $content to the file $file
2459 * Usage: 30
2460 *
2461 * @param string Filepath to write to
2462 * @param string Content to write
2463 * @return boolean True if the file was successfully opened and written to.
2464 */
2465 public static function writeFile($file,$content) {
2466 if (!@is_file($file)) $changePermissions = true;
2467
2468 if ($fd = fopen($file,'wb')) {
2469 $res = fwrite($fd,$content);
2470 fclose($fd);
2471
2472 if ($res===false) return false;
2473
2474 if ($changePermissions) { // Change the permissions only if the file has just been created
2475 t3lib_div::fixPermissions($file);
2476 }
2477
2478 return true;
2479 }
2480
2481 return false;
2482 }
2483
2484 /**
2485 * Setting file system mode & group ownership of file
2486 *
2487 * @param string Filepath of newly created file
2488 * @return void
2489 */
2490 public static function fixPermissions($file) {
2491 if (@is_file($file) && TYPO3_OS!='WIN') {
2492 @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2493 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2494 @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2495 }
2496 }
2497 }
2498
2499 /**
2500 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2501 * Accepts an additional subdirectory in the file path!
2502 *
2503 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2504 * @param string Content string to write
2505 * @return string Returns false on success, otherwise an error string telling about the problem.
2506 */
2507 public static function writeFileToTypo3tempDir($filepath,$content) {
2508
2509 // Parse filepath into directory and basename:
2510 $fI = pathinfo($filepath);
2511 $fI['dirname'].= '/';
2512
2513 // Check parts:
2514 if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2515 if (defined('PATH_site')) {
2516 $dirName = PATH_site.'typo3temp/'; // Setting main temporary directory name (standard)
2517 if (@is_dir($dirName)) {
2518 if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName)) {
2519
2520 // Checking if the "subdir" is found:
2521 $subdir = substr($fI['dirname'],strlen($dirName));
2522 if ($subdir) {
2523 if (ereg('^[[:alnum:]_]+\/$',$subdir) || ereg('^[[:alnum:]_]+\/[[:alnum:]_]+\/$',$subdir)) {
2524 $dirName.= $subdir;
2525 if (!@is_dir($dirName)) {
2526 t3lib_div::mkdir_deep(PATH_site.'typo3temp/', $subdir);
2527 }
2528 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2529 }
2530 // Checking dir-name again (sub-dir might have been created):
2531 if (@is_dir($dirName)) {
2532 if ($filepath == $dirName.$fI['basename']) {
2533 t3lib_div::writeFile($filepath, $content);
2534 if (!@is_file($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2535 } else return 'Calculated filelocation didn\'t match input $filepath!';
2536 } else return '"'.$dirName.'" is not a directory!';
2537 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2538 } else return 'PATH_site + "typo3temp/" was not a directory!';
2539 } else return 'PATH_site constant was NOT defined!';
2540 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2541 }
2542
2543 /**
2544 * 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']
2545 * Usage: 6
2546 *
2547 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2548 * @return boolean TRUE if @mkdir went well!
2549 */
2550 public static function mkdir($theNewFolder) {
2551 $theNewFolder = preg_replace('|/$|','',$theNewFolder);
2552 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2553 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2554
2555 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2556 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2557 }
2558 return TRUE;
2559 }
2560 }
2561
2562 /**
2563 * Creates a directory - including parent directories if necessary - in the file system
2564 *
2565 * @param string Base folder. This must exist! Must have trailing slash! Example "/root/typo3site/"
2566 * @param string Deep directory to create, eg. "xx/yy/" which creates "/root/typo3site/xx/yy/" if $destination is "/root/typo3site/"
2567 * @return string If error, returns error string.
2568 */
2569 public static function mkdir_deep($destination,$deepDir) {
2570 $allParts = t3lib_div::trimExplode('/',$deepDir,1);
2571 $root = '';
2572 foreach($allParts as $part) {
2573 $root.= $part.'/';
2574 if (!is_dir($destination.$root)) {
2575 t3lib_div::mkdir($destination.$root);
2576 if (!@is_dir($destination.$root)) {
2577 return 'Error: The directory "'.$destination.$root.'" could not be created...';
2578 }
2579 }
2580 }
2581 }
2582
2583 /**
2584 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2585 *
2586 * @param string Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2587 * @param boolean Allow deletion of non-empty directories
2588 * @return boolean true if @rmdir went well!
2589 */
2590 public static function rmdir($path,$removeNonEmpty=false) {
2591 $OK = false;
2592 $path = preg_replace('|/$|','',$path); // Remove trailing slash
2593
2594 if (file_exists($path)) {
2595 $OK = true;
2596
2597 if (is_dir($path)) {
2598 if ($removeNonEmpty==true && $handle = opendir($path)) {
2599 while ($OK && false !== ($file = readdir($handle))) {
2600 if ($file=='.' || $file=='..') continue;
2601 $OK = t3lib_div::rmdir($path.'/'.$file,$removeNonEmpty);
2602 }
2603 closedir($handle);
2604 }
2605 if ($OK) { $OK = rmdir($path); }
2606
2607 } else { // If $dirname is a file, simply remove it
2608 $OK = unlink($path);
2609 }
2610
2611 clearstatcache();
2612 }
2613
2614 return $OK;
2615 }
2616
2617 /**
2618 * Returns an array with the names of folders in a specific path
2619 * Will return 'error' (string) if there were an error with reading directory content.
2620 * Usage: 11
2621 *
2622 * @param string Path to list directories from
2623 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2624 */
2625 public static function get_dirs($path) {
2626 if ($path) {
2627 $d = @dir($path);
2628 if (is_object($d)) {
2629 while($entry=$d->read()) {
2630 if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2631 $filearray[]=$entry;
2632 }
2633 }
2634 $d->close();
2635 } else return 'error';
2636 return $filearray;
2637 }
2638 }
2639
2640 /**
2641 * Returns an array with the names of files in a specific path
2642 * Usage: 18
2643 *
2644 * @param string $path: Is the path to the file
2645 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2646 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2647 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2648 * @param string A comma seperated list of filenames to exclude, no wildcards
2649 * @return array Array of the files found
2650 */
2651 public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='') {
2652
2653 // Initialize variabels:
2654 $filearray = array();
2655 $sortarray = array();
2656 $path = ereg_replace('\/$','',$path);
2657
2658 // Find files+directories:
2659 if (@is_dir($path)) {
2660 $extensionList = strtolower($extensionList);
2661 $d = dir($path);
2662 if (is_object($d)) {
2663 while($entry=$d->read()) {
2664 if (@is_file($path.'/'.$entry)) {
2665 $fI = pathinfo($entry);
2666 $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)
2667 if ((!strlen($extensionList) || t3lib_div::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry))) {
2668 $filearray[$key]=($prependPath?$path.'/':'').$entry;
2669 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2670 elseif ($order) {$sortarray[$key]=$entry;}
2671 }
2672 }
2673 }
2674 $d->close();
2675 } else return 'error opening path: "'.$path.'"';
2676 }
2677
2678 // Sort them:
2679 if ($order) {
2680 asort($sortarray);
2681 reset($sortarray);
2682 $newArr=array();
2683 while(list($k,$v)=each($sortarray)) {
2684 $newArr[$k]=$filearray[$k];
2685 }
2686 $filearray=$newArr;
2687 }
2688
2689 // Return result
2690 reset($filearray);
2691 return $filearray;
2692 }
2693
2694 /**
2695 * Recursively gather all files and folders of a path.
2696 * Usage: 5
2697 *
2698 * @param array $fileArr: Empty input array (will have files added to it)
2699 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2700 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2701 * @param boolean $regDirs: If set, directories are also included in output.
2702 * @param integer $recursivityLevels: The number of levels to dig down...
2703 * @param string $excludePattern: regex pattern of files/directories to exclude
2704 * @return array An array with the found files/directories.
2705 */
2706 public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='') {
2707 if ($regDirs) $fileArr[] = $path;
2708 $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1,$excludePattern));
2709
2710 $dirs = t3lib_div::get_dirs($path);
2711 if (is_array($dirs) && $recursivityLevels>0) {
2712 foreach ($dirs as $subdirs) {
2713 if ((string)$subdirs!='' && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$subdirs))) {
2714 $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
2715 }
2716 }
2717 }
2718 return $fileArr;
2719 }
2720
2721 /**
2722 * Removes the absolute part of all files/folders in fileArr
2723 * Usage: 2
2724 *
2725 * @param array $fileArr: The file array to remove the prefix from
2726 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2727 * @return array The input $fileArr processed.
2728 */
2729 public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) {
2730 foreach($fileArr as $k => $absFileRef) {
2731 if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
2732 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
2733 } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2734 }
2735 return $fileArr;
2736 }
2737
2738 /**
2739 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2740 * Usage: 2
2741 *
2742 * @param string File path to process
2743 * @return string
2744 */
2745 public static function fixWindowsFilePath($theFile) {
2746 return str_replace('//','/', str_replace('\\','/', $theFile));
2747 }
2748
2749 /**
2750 * Resolves "../" sections in the input path string.
2751 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2752 * Usage: 2
2753 *
2754 * @param string File path in which "/../" is resolved
2755 * @return string
2756 */
2757 public static function resolveBackPath($pathStr) {
2758 $parts = explode('/',$pathStr);
2759 $output=array();
2760 $c = 0;
2761 foreach($parts as $pV) {
2762 if ($pV=='..') {
2763 if ($c) {
2764 array_pop($output);
2765 $c--;
2766 } else $output[]=$pV;
2767 } else {
2768 $c++;
2769 $output[]=$pV;
2770 }
2771 }
2772 return implode('/',$output);
2773 }
2774
2775 /**
2776 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2777 * - If already having a scheme, nothing is prepended
2778 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2779 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2780 * Usage: 30
2781 *
2782 * @param string URL / path to prepend full URL addressing to.
2783 * @return string
2784 */
2785 public static function locationHeaderUrl($path) {
2786 $uI = parse_url($path);
2787 if (substr($path,0,1)=='/') { // relative to HOST
2788 $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2789 } elseif (!$uI['scheme']) { // No scheme either
2790 $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2791 }
2792 return $path;
2793 }
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810 /*************************
2811 *
2812 * DEBUG helper FUNCTIONS
2813 *
2814 *************************/
2815
2816 /**
2817 * Returns a string with a list of ascii-values for the first $characters characters in $string
2818 * Usage: 0
2819 *
2820 * @param string String to show ASCII value for
2821 * @param integer Number of characters to show
2822 * @return string The string with ASCII values in separated by a space char.
2823 * @internal
2824 */
2825 public static function debug_ordvalue($string,$characters=100) {
2826 if(strlen($string) < $characters) $characters = strlen($string);
2827 for ($i=0; $i<$characters; $i++) {
2828 $valuestring.=' '.ord(substr($string,$i,1));
2829 }
2830 return trim($valuestring);
2831 }
2832
2833 /**
2834 * Returns HTML-code, which is a visual representation of a multidimensional array
2835 * use t3lib_div::print_array() in order to print an array
2836 * Returns false if $array_in is not an array
2837 * Usage: 31
2838 *
2839 * @param mixed Array to view
2840 * @return string HTML output
2841 */
2842 public static function view_array($array_in) {
2843 if (is_array($array_in)) {
2844 $result='
2845 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
2846 if (count($array_in) == 0) {
2847 $result.= '<tr><td><font face="Verdana,Arial" size="1"><b>EMPTY!</b></font></td></tr>';
2848 } else {
2849 foreach ($array_in as $key => $val) {
2850 $result.= '<tr>
2851 <td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td>
2852 <td>';
2853 if (is_array($val)) {
2854 $result.=t3lib_div::view_array($val);
2855 } elseif (is_object($val)) {
2856 $string = get_class($val);
2857 if (method_exists($val, '__toString')) {
2858 $string .= ': '.(string)$val;
2859 }
2860 $result .= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
2861 } else {
2862 if (gettype($val) == 'object') {
2863 $string = 'Unknown object';
2864 } else {
2865 $string = (string)$val;
2866 }
2867 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
2868 }
2869 $result.= '</td>
2870 </tr>';
2871 }
2872 }
2873 $result.= '</table>';
2874 } else {
2875 $result = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
2876 <tr>
2877 <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
2878 </tr>
2879 </table>'; // Output it as a string.
2880 }
2881 return $result;
2882 }
2883
2884 /**
2885 * Prints an array
2886 * Usage: 6
2887 *
2888 * @param mixed Array to print visually (in a table).
2889 * @return void
2890 * @internal
2891 * @see view_array()
2892 */
2893 public static function print_array($array_in) {
2894 echo t3lib_div::view_array($array_in);
2895 }
2896
2897 /**
2898 * Makes debug output
2899 * Prints $var in bold between two vertical lines
2900 * If not $var the word 'debug' is printed
2901 * If $var is an array, the array is printed by t3lib_div::print_array()
2902 * Usage: 8
2903 *
2904 * @param mixed Variable to print
2905 * @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.
2906 * @return void
2907 */
2908 public static function debug($var='',$brOrHeader=0) {
2909 // buffer the output of debug if no buffering started before
2910 if (ob_get_level()==0) {
2911 ob_start();
2912 }
2913
2914 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
2915 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>';
2916 } elseif ($brOrHeader<0) {
2917 for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
2918 }
2919
2920 if (is_array($var)) {
2921 t3lib_div::print_array($var);
2922 } elseif (is_object($var)) {
2923 echo '<b>|Object:<pre>';
2924 print_r($var);
2925 echo '</pre>|</b>';
2926 } elseif ((string)$var!='') {
2927 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
2928 } else {
2929 echo '<b>| debug |</b>';
2930 }
2931
2932 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
2933 echo '</td></tr></table>';
2934 } elseif ($brOrHeader>0) {
2935 for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
2936 }
2937 }
2938
2939 /**
2940 * Displays the "path" of the function call stack in a string, using debug_backtrace
2941 *
2942 * @return string
2943 */
2944 public static function debug_trail() {
2945 $trail = debug_backtrace();
2946 $trail = array_reverse($trail);
2947 array_pop($trail);
2948
2949 $path = array();
2950 foreach($trail as $dat) {
2951 $path[] = $dat['class'].$dat['type'].$dat['function'];
2952 }
2953
2954 return implode(' // ',$path);
2955 }
2956
2957 /**
2958 * Displays an array as rows in a table. Useful to debug output like an array of database records.
2959 *
2960 * @param mixed Array of arrays with similar keys
2961 * @param string Table header
2962 * @param boolean If TRUE, will return content instead of echo'ing out.
2963 * @return void Outputs to browser.
2964 */
2965 public static function debugRows($rows,$header='',$returnHTML=FALSE) {
2966 if (is_array($rows)) {
2967 reset($rows);
2968 $firstEl = current($rows);
2969 if (is_array($firstEl)) {
2970 $headerColumns = array_keys($firstEl);
2971 $tRows = array();
2972
2973 // Header:
2974 $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>';
2975 $tCells = array();
2976 foreach($headerColumns as $key) {
2977 $tCells[] = '
2978 <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
2979 }
2980 $tRows[] = '
2981 <tr>'.implode('',$tCells).'
2982 </tr>';
2983
2984 // Rows:
2985 foreach($rows as $singleRow) {
2986 $tCells = array();
2987 foreach($headerColumns as $key) {
2988 $tCells[] = '
2989 <td><font face="Verdana,Arial" size="1">'.(is_array($singleRow[$key]) ? t3lib_div::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).'</font></td>';
2990 }
2991 $tRows[] = '
2992 <tr>'.implode('',$tCells).'
2993 </tr>';
2994 }
2995
2996 $table = '
2997 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
2998 </table>';
2999 if ($returnHTML) return $table; else echo $table;
3000 } else debug('Empty array of rows',$header);
3001 } else {
3002 debug('No array of rows',$header);
3003 }
3004 }
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033 /*************************
3034 *
3035 * SYSTEM INFORMATION
3036 *
3037 *************************/
3038
3039 /**
3040 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
3041 * Usage: 1
3042 *
3043 * @return string
3044 */
3045 public static function getThisUrl() {
3046 $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
3047 $dir=t3lib_div::dirname($p['path']).'/'; // Strip file
3048 $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
3049 return $url;
3050 }
3051
3052 /**
3053 * Returns the link-url to the current script.
3054 * 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.
3055 * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
3056 * Usage: 52
3057 *
3058 * @param array Array of GET parameters to include
3059 * @return string
3060 */
3061 public static function linkThisScript(array $getParams=array()) {
3062 $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
3063 $params = t3lib_div::_GET();
3064
3065 foreach($getParams as $k => $v) {
3066 if (strcmp($v,'')) {
3067 $params[$k]=$v;
3068 } else unset($params[$k]);
3069 }
3070
3071 $pString = t3lib_div::implodeArrayForUrl('',$params);
3072
3073 return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
3074 }
3075
3076 /**
3077 * 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.
3078 * So basically it adds the parameters in $getParams to an existing URL, $url
3079 * Usage: 2
3080 *
3081 * @param string URL string
3082 * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
3083 * @return string Output URL with added getParams.
3084 */
3085 public static function linkThisUrl($url,array $getParams=array()) {
3086 $parts = parse_url($url);
3087 $getP = array();
3088 if ($parts['query']) {
3089 parse_str($parts['query'],$getP);
3090 }
3091 $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
3092 $uP = explode('?',$url);
3093
3094 $params = t3lib_div::implodeArrayForUrl('',$getP);
3095 $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
3096
3097 return $outurl;
3098 }
3099
3100 /**
3101 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
3102 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
3103 * Usage: 221
3104 *
3105 * @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
3106 * @return string Value based on the input key, independent of server/os environment.
3107 */
3108 public static function getIndpEnv($getEnvName) {
3109 /*
3110 Conventions:
3111 output from parse_url():
3112 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
3113 [scheme] => 'http'
3114 [user] => 'username'
3115 [pass] => 'password'
3116 [host] => '192.168.1.4'
3117 [port] => '8080'
3118 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
3119 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
3120 [fragment] => 'link1'
3121
3122 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
3123 [path_dir] = '/typo3/32/temp/phpcheck/'
3124 [path_info] = '/arg1/arg2/arg3/'
3125 [path] = [path_script/path_dir][path_info]
3126
3127
3128 Keys supported:
3129
3130 URI______:
3131 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
3132 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
3133 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')!
3134 PATH_INFO = [path_info] = /arg1/arg2/arg3/
3135 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
3136 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
3137 (Notice: NO username/password + NO fragment)
3138
3139 CLIENT____:
3140 REMOTE_ADDR = (client IP)
3141 REMOTE_HOST = (client host)
3142 HTTP_USER_AGENT = (client user agent)
3143 HTTP_ACCEPT_LANGUAGE = (client accept language)
3144
3145 SERVER____:
3146 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
3147
3148 Special extras:
3149 TYPO3_HOST_ONLY = [host] = 192.168.1.4
3150 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
3151 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
3152 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
3153 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
3154 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
3155 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
3156 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
3157 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
3158 TYPO3_SSL = Returns TRUE if this session uses SSL (HTTPS)
3159
3160 Notice: [fragment] is apparently NEVER available to the script!
3161
3162
3163 Testing suggestions:
3164 - Output all the values.
3165 - 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
3166 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
3167
3168 */
3169
3170 # if ($getEnvName=='HTTP_REFERER') return '';
3171
3172 $retVal = '';
3173
3174 switch ((string)$getEnvName) {
3175 case 'SCRIPT_NAME':
3176 $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']);
3177 break;
3178 case 'SCRIPT_FILENAME':
3179 $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'])));
3180 break;
3181 case 'REQUEST_URI':
3182 // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
3183 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)
3184 list($v,$n) = explode('|',$GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
3185 $retVal = $GLOBALS[$v][$n];
3186 } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
3187 $retVal = '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
3188 ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
3189 } else $retVal = $_SERVER['REQUEST_URI'];
3190 break;
3191 case 'PATH_INFO':
3192 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
3193 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
3194 // 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)
3195 // if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
3196 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi') {
3197 $retVal = $_SERVER['PATH_INFO'];
3198 }
3199 break;
3200 // These are let through without modification
3201 case 'REMOTE_ADDR':
3202 case 'REMOTE_HOST':
3203 case 'HTTP_REFERER':
3204 case 'HTTP_HOST':
3205 case 'HTTP_USER_AGENT':
3206 case 'HTTP_ACCEPT_ENCODING':
3207 case 'HTTP_ACCEPT_LANGUAGE':
3208 case 'QUERY_STRING':
3209 $retVal = $_SERVER[$getEnvName];
3210 break;
3211 case 'TYPO3_DOCUMENT_ROOT':
3212 // 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.
3213 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
3214 $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
3215 $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
3216 $SFN_A = explode('/',strrev($SFN));
3217 $acc = array();
3218 while(list($kk,$vv)=each($SN_A)) {
3219 if (!strcmp($SFN_A[$kk],$vv)) {
3220 $acc[] = $vv;
3221 } else break;
3222 }
3223 $commonEnd=strrev(implode('/',$acc));
3224 if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
3225 $retVal = $DR;
3226 break;
3227 case 'TYPO3_HOST_ONLY':
3228 $p = explode(':',$_SERVER['HTTP_HOST']);
3229 $retVal = $p[0];
3230 break;
3231 case 'TYPO3_PORT':
3232 $p = explode(':',$_SERVER['HTTP_HOST']);
3233 $retVal = $p[1];
3234 break;
3235 case 'TYPO3_REQUEST_HOST':
3236 $retVal = (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
3237 $_SERVER['HTTP_HOST'];
3238 break;
3239 case 'TYPO3_REQUEST_URL':
3240 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
3241 break;
3242 case 'TYPO3_REQUEST_SCRIPT':
3243 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
3244 break;
3245 case 'TYPO3_REQUEST_DIR':
3246 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
3247 break;
3248 case 'TYPO3_SITE_URL':
324