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