112e2252dc09e0c387f4fda0ce8fc0d9c199eee1
[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 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 string (keep blank)
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 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 t3lib_div::fixPermissions($file); // Change the permissions of the file
2062
2063 return true;
2064 }
2065 }
2066
2067 /**
2068 * Setting file system mode & group ownership of file
2069 *
2070 * @param string Filepath of newly created file
2071 */
2072 function fixPermissions($file) {
2073 if (@is_file($file) && TYPO3_OS!='WIN') {
2074 @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2075 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2076 @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2077 }
2078 }
2079 }
2080
2081 /**
2082 * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
2083 * Accepts an additional subdirectory in the file path!
2084 *
2085 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2086 * @param string Content string to write
2087 * @return string Returns false on success, otherwise an error string telling about the problem.
2088 */
2089 function writeFileToTypo3tempDir($filepath,$content) {
2090
2091 // Parse filepath into directory and basename:
2092 $fI = pathinfo($filepath);
2093 $fI['dirname'].= '/';
2094
2095 // Check parts:
2096 if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2097 if (defined('PATH_site')) {
2098 $dirName = PATH_site.'typo3temp/'; // Setting main temporary directory name (standard)
2099 if (@is_dir($dirName)) {
2100 if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName)) {
2101
2102 // Checking if the "subdir" is found:
2103 $subdir = substr($fI['dirname'],strlen($dirName));
2104 if ($subdir) {
2105 if (ereg('^[[:alnum:]_]+\/$',$subdir)) {
2106 $dirName.= $subdir;
2107 if (!@is_dir($dirName)) {
2108 t3lib_div::mkdir($dirName);
2109 }
2110 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
2111 }
2112 // Checking dir-name again (sub-dir might have been created):
2113 if (@is_dir($dirName)) {
2114 if ($filepath == $dirName.$fI['basename']) {
2115 t3lib_div::writeFile($filepath, $content);
2116 if (!@is_file($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2117 } else return 'Calculated filelocation didn\'t match input $filepath!';
2118 } else return '"'.$dirName.'" is not a directory!';
2119 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2120 } else return 'PATH_site + "typo3temp/" was not a directory!';
2121 } else return 'PATH_site constant was NOT defined!';
2122 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2123 }
2124
2125 /**
2126 * 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']
2127 * Usage: 6
2128 *
2129 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2130 * @return boolean TRUE if @mkdir went well!
2131 */
2132 function mkdir($theNewFolder) {
2133 $theNewFolder = ereg_replace('\/$','',$theNewFolder);
2134 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2135 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2136
2137 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2138 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2139 }
2140 return TRUE;
2141 }
2142 }
2143
2144 /**
2145 * Returns an array with the names of folders in a specific path
2146 * Will return 'error' (string) if there were an error with reading directory content.
2147 * Usage: 11
2148 *
2149 * @param string Path to list directories from
2150 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2151 */
2152 function get_dirs($path) {
2153 if ($path) {
2154 $d = @dir($path);
2155 if (is_object($d)) {
2156 while($entry=$d->read()) {
2157 if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2158 $filearray[]=$entry;
2159 }
2160 }
2161 $d->close();
2162 } else return 'error';
2163 return $filearray;
2164 }
2165 }
2166
2167 /**
2168 * Returns an array with the names of files in a specific path
2169 * Usage: 18
2170 *
2171 * @param string $path: Is the path to the file
2172 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2173 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2174 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2175 * @return array Array of the files found
2176 */
2177 function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') {
2178
2179 // Initialize variabels:
2180 $filearray = array();
2181 $sortarray = array();
2182 $path = ereg_replace('\/$','',$path);
2183
2184 // Find files+directories:
2185 if (@is_dir($path)) {
2186 $extensionList = strtolower($extensionList);
2187 $d = dir($path);
2188 if (is_object($d)) {
2189 while($entry=$d->read()) {
2190 if (@is_file($path.'/'.$entry)) {
2191 $fI = pathinfo($entry);
2192 $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)
2193 if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension']))) {
2194 $filearray[$key]=($prependPath?$path.'/':'').$entry;
2195 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2196 elseif ($order) {$sortarray[$key]=$entry;}
2197 }
2198 }
2199 }
2200 $d->close();
2201 } else return 'error opening path: "'.$path.'"';
2202 }
2203
2204 // Sort them:
2205 if ($order) {
2206 asort($sortarray);
2207 reset($sortarray);
2208 $newArr=array();
2209 while(list($k,$v)=each($sortarray)) {
2210 $newArr[$k]=$filearray[$k];
2211 }
2212 $filearray=$newArr;
2213 }
2214
2215 // Return result
2216 reset($filearray);
2217 return $filearray;
2218 }
2219
2220 /**
2221 * Recursively gather all files and folders of a path.
2222 * Usage: 5
2223 *
2224 * @param array $fileArr: Empty input array (will have files added to it)
2225 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2226 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2227 * @param boolean $regDirs: If set, directories are also included in output.
2228 * @param integer $recursivityLevels: The number of levels to dig down...
2229 * @return array An array with the found files/directories.
2230 */
2231 function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) {
2232 if ($regDirs) $fileArr[] = $path;
2233 $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1));
2234
2235 $dirs = t3lib_div::get_dirs($path);
2236 if (is_array($dirs) && $recursivityLevels>0) {
2237 foreach ($dirs as $subdirs) {
2238 if ((string)$subdirs!='') {
2239 $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
2240 }
2241 }
2242 }
2243 return $fileArr;
2244 }
2245
2246 /**
2247 * Removes the absolute part of all files/folders in fileArr
2248 * Usage: 2
2249 *
2250 * @param array $fileArr: The file array to remove the prefix from
2251 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2252 * @return array The input $fileArr processed.
2253 */
2254 function removePrefixPathFromList($fileArr,$prefixToRemove) {
2255 foreach($fileArr as $k => $absFileRef) {
2256 if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
2257 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
2258 } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2259 }
2260 return $fileArr;
2261 }
2262
2263 /**
2264 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2265 * Usage: 2
2266 *
2267 * @param string File path to process
2268 * @return string
2269 */
2270 function fixWindowsFilePath($theFile) {
2271 return str_replace('//','/', str_replace('\\','/', $theFile));
2272 }
2273
2274 /**
2275 * Resolves "../" sections in the input path string.
2276 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2277 * Usage: 2
2278 *
2279 * @param string File path in which "/../" is resolved
2280 * @return string
2281 */
2282 function resolveBackPath($pathStr) {
2283 $parts = explode('/',$pathStr);
2284 $output=array();
2285 foreach($parts as $pV) {
2286 if ($pV=='..') {
2287 if ($c) {
2288 array_pop($output);
2289 $c--;
2290 } else $output[]=$pV;
2291 } else {
2292 $c++;
2293 $output[]=$pV;
2294 }
2295 }
2296 return implode('/',$output);
2297 }
2298
2299 /**
2300 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2301 * - If already having a scheme, nothing is prepended
2302 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2303 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2304 * Usage: 30
2305 *
2306 * @param string URL / path to prepend full URL addressing to.
2307 * @return string
2308 */
2309 function locationHeaderUrl($path) {
2310 $uI = parse_url($path);
2311 if (substr($path,0,1)=='/') { // relative to HOST
2312 $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2313 } elseif (!$uI['scheme']) { // No scheme either
2314 $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2315 }
2316 return $path;
2317 }
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334 /*************************
2335 *
2336 * DEBUG helper FUNCTIONS
2337 *
2338 *************************/
2339
2340 /**
2341 * Returns a string with a list of ascii-values for the first $characters characters in $string
2342 * Usage: 0
2343 *
2344 * @param string String to show ASCII value for
2345 * @param integer Number of characters to show
2346 * @return string The string with ASCII values in separated by a space char.
2347 * @internal
2348 */
2349 function debug_ordvalue($string,$characters=100) {
2350 if(strlen($string) < $characters) $characters = strlen($string);
2351 for ($i=0; $i<$characters; $i++) {
2352 $valuestring.=' '.ord(substr($string,$i,1));
2353 }
2354 return trim($valuestring);
2355 }
2356
2357 /**
2358 * Returns HTML-code, which is a visual representation of a multidimensional array
2359 * use t3lib_div::print_array() in order to print an array
2360 * Returns false if $array_in is not an array
2361 * Usage: 31
2362 *
2363 * @param array Array to view
2364 * @return string HTML output
2365 */
2366 function view_array($array_in) {
2367 if (is_array($array_in)) {
2368 $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
2369 if (!count($array_in)) {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
2370 while (list($key,$val)=each($array_in)) {
2371 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
2372 if (is_array($array_in[$key])) {
2373 $result.=t3lib_div::view_array($array_in[$key]);
2374 } else
2375 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
2376 $result.= '</td></tr>';
2377 }
2378 $result.= '</table>';
2379 } else {
2380 $result = false;
2381 }
2382 return $result;
2383 }
2384
2385 /**
2386 * Prints an array
2387 * Usage: 6
2388 *
2389 * @param array Array to print visually (in a table).
2390 * @return void
2391 * @internal
2392 * @see view_array()
2393 */
2394 function print_array($array_in) {
2395 echo t3lib_div::view_array($array_in);
2396 }
2397
2398 /**
2399 * Makes debug output
2400 * Prints $var in bold between two vertical lines
2401 * If not $var the word 'debug' is printed
2402 * If $var is an array, the array is printed by t3lib_div::print_array()
2403 * Usage: 8
2404 *
2405 * @param mixed Variable to print
2406 * @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.
2407 * @return void
2408 */
2409 function debug($var="",$brOrHeader=0) {
2410 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
2411 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>';
2412 } elseif ($brOrHeader<0) {
2413 for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
2414 }
2415
2416 if (is_array($var)) {
2417 t3lib_div::print_array($var);
2418 } elseif (is_object($var)) {
2419 echo '<b>|Object:<pre>';
2420 print_r($var);
2421 echo '</pre>|</b>';
2422 } elseif ((string)$var!='') {
2423 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
2424 } else {
2425 echo '<b>| debug |</b>';
2426 }
2427
2428 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
2429 echo '</td></tr></table>';
2430 } elseif ($brOrHeader>0) {
2431 for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
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
2461
2462
2463
2464
2465
2466 /*************************
2467 *
2468 * SYSTEM INFORMATION
2469 *
2470 *************************/
2471
2472 /**
2473 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
2474 * Usage: 1
2475 *
2476 * @return string
2477 */
2478 function getThisUrl() {
2479 $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
2480 $dir=t3lib_div::dirname($p['path']).'/'; // Strip file
2481 $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
2482 return $url;
2483 }
2484
2485 /**
2486 * Returns the link-url to the current script.
2487 * 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.
2488 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2489 * Usage: 52
2490 *
2491 * @param array Array of GET parameters to include
2492 * @return string
2493 */
2494 function linkThisScript($getParams=array()) {
2495 $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
2496 $params = t3lib_div::_GET();
2497
2498 foreach($getParams as $k => $v) {
2499 if (strcmp($v,'')) {
2500 $params[$k]=$v;
2501 } else unset($params[$k]);
2502 }
2503
2504 $pString = t3lib_div::implodeArrayForUrl('',$params);
2505
2506 return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
2507 }
2508
2509 /**
2510 * 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.
2511 * So basically it adds the parameters in $getParams to an existing URL, $url
2512 * Usage: 2
2513 *
2514 * @param string URL string
2515 * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
2516 * @return string Output URL with added getParams.
2517 */
2518 function linkThisUrl($url,$getParams=array()) {
2519 $parts = parse_url($url);
2520 if ($parts['query']) {
2521 parse_str($parts['query'],$getP);
2522 } else {
2523 $getP = array();
2524 }
2525
2526 $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
2527 $uP = explode('?',$url);
2528
2529 $params = t3lib_div::implodeArrayForUrl('',$getP);
2530 $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
2531
2532 return $outurl;
2533 }
2534
2535 /**
2536 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2537 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2538 * Usage: 221
2539 *
2540 * @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
2541 * @return string Value based on the input key, independent of server/os environment.
2542 */
2543 function getIndpEnv($getEnvName) {
2544 /*
2545 Conventions:
2546 output from parse_url():
2547 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
2548 [scheme] => 'http'
2549 [user] => 'username'
2550 [pass] => 'password'
2551 [host] => '192.168.1.4'
2552 [port] => '8080'
2553 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2554 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2555 [fragment] => 'link1'
2556
2557 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2558 [path_dir] = '/typo3/32/temp/phpcheck/'
2559 [path_info] = '/arg1/arg2/arg3/'
2560 [path] = [path_script/path_dir][path_info]
2561
2562
2563 Keys supported:
2564
2565 URI______:
2566 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2567 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
2568 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')!
2569 PATH_INFO = [path_info] = /arg1/arg2/arg3/
2570 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
2571 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
2572 (Notice: NO username/password + NO fragment)
2573
2574 CLIENT____:
2575 REMOTE_ADDR = (client IP)
2576 REMOTE_HOST = (client host)
2577 HTTP_USER_AGENT = (client user agent)
2578 HTTP_ACCEPT_LANGUAGE = (client accept language)
2579
2580 SERVER____:
2581 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
2582
2583 Special extras:
2584 TYPO3_HOST_ONLY = [host] = 192.168.1.4
2585 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
2586 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
2587 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (sheme will by default be 'http' until we can detect if it's https -
2588 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
2589 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
2590 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2591 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
2592 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2593
2594 Notice: [fragment] is apparently NEVER available to the script!
2595
2596
2597 Testing suggestions:
2598 - Output all the values.
2599 - 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
2600 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2601
2602 */
2603
2604 # if ($getEnvName=='HTTP_REFERER') return '';
2605 switch((string)$getEnvName) {
2606 case 'SCRIPT_NAME':
2607 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']);
2608 break;
2609 case 'SCRIPT_FILENAME':
2610 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'])));
2611 break;
2612 case 'REQUEST_URI':
2613 // Typical application of REQUEST_URI is return urls, forms submitting to itselt etc. Eg: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
2614 if (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
2615 return '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
2616 ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
2617 } else return $_SERVER['REQUEST_URI'];
2618 break;
2619 case 'PATH_INFO':
2620 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
2621 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2622 // 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)
2623 // if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
2624 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi') {
2625 return $_SERVER['PATH_INFO'];
2626 } else return '';
2627 break;
2628 // These are let through without modification
2629 case 'REMOTE_ADDR':
2630 case 'REMOTE_HOST':
2631 case 'HTTP_REFERER':
2632 case 'HTTP_HOST':
2633 case 'HTTP_USER_AGENT':
2634 case 'HTTP_ACCEPT_LANGUAGE':
2635 case 'QUERY_STRING':
2636 return $_SERVER[$getEnvName];
2637 break;
2638 case 'TYPO3_DOCUMENT_ROOT':
2639 // 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.
2640 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2641 $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
2642 $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
2643 $SFN_A = explode('/',strrev($SFN));
2644 $acc = array();
2645 while(list($kk,$vv)=each($SN_A)) {
2646 if (!strcmp($SFN_A[$kk],$vv)) {
2647 $acc[] = $vv;
2648 } else break;
2649 }
2650 $commonEnd=strrev(implode('/',$acc));
2651 if (strcmp($commonEnd,'')) $DR = substr($SFN,0,-(strlen($commonEnd)+1));
2652 return $DR;
2653 break;
2654 case 'TYPO3_HOST_ONLY':
2655 $p = explode(':',$_SERVER['HTTP_HOST']);
2656 return $p[0];
2657 break;
2658 case 'TYPO3_PORT':
2659 $p = explode(':',$_SERVER['HTTP_HOST']);
2660 return $p[1];
2661 break;
2662 case 'TYPO3_REQUEST_HOST':
2663 return (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
2664 $_SERVER['HTTP_HOST'];
2665 break;
2666 case 'TYPO3_REQUEST_URL':
2667 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
2668 break;
2669 case 'TYPO3_REQUEST_SCRIPT':
2670 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
2671 break;
2672 case 'TYPO3_REQUEST_DIR':
2673 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
2674 break;
2675 case 'TYPO3_SITE_URL':
2676 if (defined('PATH_thisScript') && defined('PATH_site')) {
2677 $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
2678 $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
2679 $siteUrl = substr($url,0,-strlen($lPath));
2680 if (substr($siteUrl,-1)!='/') $siteUrl.='/';
2681 return $siteUrl;
2682 } else return '';
2683 break;
2684 case 'TYPO3_SITE_SCRIPT':
2685 return substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
2686 break;
2687 case 'TYPO3_SSL':
2688 return $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') ? TRUE : FALSE;
2689 break;
2690 case '_ARRAY':
2691 $out = array();
2692 // Here, list ALL possible keys to this function for debug display.
2693 $envTestVars = t3lib_div::trimExplode(',','
2694 HTTP_HOST,
2695 TYPO3_HOST_ONLY,
2696 TYPO3_PORT,
2697 PATH_INFO,
2698 QUERY_STRING,
2699 REQUEST_URI,
2700 HTTP_REFERER,
2701 TYPO3_REQUEST_HOST,
2702 TYPO3_REQUEST_URL,
2703 TYPO3_REQUEST_SCRIPT,
2704 TYPO3_REQUEST_DIR,
2705 TYPO3_SITE_URL,
2706 TYPO3_SITE_SCRIPT,
2707 TYPO3_SSL,
2708 SCRIPT_NAME,
2709 TYPO3_DOCUMENT_ROOT,
2710 SCRIPT_FILENAME,
2711 REMOTE_ADDR,
2712 REMOTE_HOST,
2713 HTTP_USER_AGENT,
2714 HTTP_ACCEPT_LANGUAGE',1);
2715 reset($envTestVars);
2716 while(list(,$v)=each($envTestVars)) {
2717 $out[$v]=t3lib_div::getIndpEnv($v);
2718 }
2719 reset($out);
2720 return $out;
2721 break;
2722 }
2723 }
2724
2725 /**
2726 * milliseconds
2727 * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
2728 * Usage: 20
2729 *
2730 * @return integer
2731 */
2732 function milliseconds() {
2733 $p=explode(' ',microtime());
2734 return round(($p[0]+$p[1])*1000);
2735 }
2736
2737 /**
2738 * Client Browser Information
2739 * Usage: 4
2740 *
2741 * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
2742 * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
2743 */
2744 function clientInfo($useragent='') {
2745 if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
2746
2747 $bInfo=array();
2748 // Which browser?
2749 if (strstr($useragent,'Konqueror')) {
2750 $bInfo['BROWSER']= 'konqu';
2751 } elseif (strstr($useragent,'Opera')) {
2752 $bInfo['BROWSER']= 'opera';
2753 } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6')) {
2754 $bInfo['BROWSER']= 'msie';
2755 } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5')) {
2756 $bInfo['BROWSER']='net';
2757 }
2758 if ($bInfo['BROWSER']) {
2759 // Browser version
2760 switch($bInfo['BROWSER']) {
2761 case 'net':
2762 $bInfo['VERSION']= doubleval(substr($useragent,8));
2763 if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
2764 if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
2765 break;
2766 case 'msie':
2767 $tmp = strstr($useragent,'MSIE');
2768 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
2769 break;
2770 case 'opera':
2771 $tmp = strstr($useragent,'Opera');
2772 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
2773 break;
2774 case 'konqu':
2775 $tmp = strstr($useragent,'Konqueror/');
2776 $bInfo['VERSION'] = doubleval(substr($tmp,10));
2777 break;
2778 }
2779 // Client system
2780 if (strstr($useragent,'Win')) {
2781 $bInfo['SYSTEM'] = 'win';
2782 } elseif (strstr($useragent,'Mac')) {
2783 $bInfo['SYSTEM'] = 'mac';
2784 } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX ')) {
2785 $bInfo['SYSTEM'] = 'unix';
2786 }
2787 }
2788 // Is true if the browser supports css to format forms, especially the width
2789 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
2790
2791 return $bInfo;
2792 }
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816 /*************************
2817 *
2818 * TYPO3 SPECIFIC FUNCTIONS
2819 *
2820 *************************/
2821
2822 /**
2823 * 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.
2824 * Usage: 24
2825 *
2826 * @param string The input filename/filepath to evaluate
2827 * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
2828 * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
2829 * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
2830 */
2831 function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) {
2832 if (!strcmp($filename,'')) return '';
2833
2834 if ($relToTYPO3_mainDir) {
2835 if (!defined('PATH_typo3')) return '';
2836 $relPathPrefix = PATH_typo3;
2837 } else {
2838 $relPathPrefix = PATH_site;
2839 }
2840 if (substr($filename,0,4)=='EXT:') { // extension
2841 list($extKey,$local) = explode('/',substr($filename,4),2);
2842 $filename='';
2843 if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
2844 $filename = t3lib_extMgm::extPath($extKey).$local;
2845 }
2846 } elseif (!t3lib_div::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
2847 $filename=$relPathPrefix.$filename;
2848 } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
2849 $filename='';
2850 }
2851 if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) { // checks backpath.
2852 return $filename;
2853 }
2854 }
2855
2856 /**
2857 * Checks for malicious file paths.
2858 * Returns true if no '//', '..' or '\' is in the $theFile
2859 * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2860 * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2861 * Usage: 14
2862 *
2863 * @param string Filepath to evaluate
2864 * @return boolean True, if no '//', '..' or '\' is in the $theFile
2865 * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
2866 */
2867 function validPathStr($theFile) {
2868 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
2869 }
2870
2871 /**
2872 * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
2873 * Usage: 8
2874 *
2875 * @param string Filepath to evaluate
2876 * @return boolean
2877 */
2878 function isAbsPath($path) {
2879 return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' : substr($path,0,1)=='/';
2880 }
2881
2882 /**
2883 * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
2884 * Usage: 5
2885 *
2886 * @param string Filepath to evaluate
2887 * @return boolean
2888 */
2889 function isAllowedAbsPath($path) {
2890 if (t3lib_div::isAbsPath($path) &&
2891 t3lib_div::validPathStr($path) &&
2892 ( t3lib_div::isFirstPartOfStr($path,PATH_site)
2893 ||
2894 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
2895 )
2896 ) return true;
2897 }
2898
2899 /**
2900 * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
2901 * Usage: 2
2902 *
2903 * @param string Filepath to evaluate
2904 * @return boolean
2905 */
2906 function verifyFilenameAgainstDenyPattern($filename) {
2907 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
2908 $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
2909 if ($result) return false; // so if a matching filename is found, return false;
2910 }
2911 return true;
2912 }
2913
2914 /**
2915 * Moves $source file to $destination if uploaded, otherwise try to make a copy
2916 * Usage: 4
2917 *
2918 * @param string Source file, absolute path
2919 * @param string Destination file, absolute path
2920 * @return boolean Returns true if the file was moved.
2921 * @coauthor Dennis Petersen <fessor@software.dk>
2922 * @see upload_to_tempfile()
2923 */
2924 function upload_copy_move($source,$destination) {
2925 if (is_uploaded_file($source)) {
2926 $uploaded = TRUE;
2927 // 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:
2928 $uploadedResult = move_uploaded_file($source, $destination);
2929 } else {
2930 $uploaded = FALSE;
2931 @copy($source,$destination);
2932 }
2933
2934 t3lib_div::fixPermissions($destination); // Change the permissions of the file
2935
2936 // 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
2937 return $uploaded ? $uploadedResult : FALSE;
2938 }
2939
2940 /**
2941 * 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.
2942 * Use this function to move uploaded files to where you can work on them.
2943 * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
2944 * Usage: 6
2945 *
2946 * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
2947 * @return string If a new file was successfully created, return its filename, otherwise blank string.
2948 * @see unlink_tempfile(), upload_copy_move()
2949 */
2950 function upload_to_tempfile($uploadedFileName) {
2951 if (is_uploaded_file($uploadedFileName)) {
2952 $tempFile = t3lib_div::tempnam('upload_temp_');
2953 move_uploaded_file($uploadedFileName, $tempFile);
2954 return @is_file($tempFile) ? $tempFile : '';
2955 }
2956 }
2957
2958 /**
2959 * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
2960 * 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.
2961 * Use this after upload_to_tempfile() or tempnam() from this class!
2962 * Usage: 9
2963 *
2964 * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
2965 * @return boolean Returns true if the file was unlink()'ed
2966 * @see upload_to_tempfile(), tempnam()
2967 */
2968 function unlink_tempfile($uploadedTempFileName) {
2969 if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName)) {
2970 if (unlink($uploadedTempFileName)) return TRUE;
2971 }
2972 }
2973
2974 /**
2975 * Create temporary filename (Create file with unique file name)
2976 * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
2977 * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
2978 * Usage: 7
2979 *
2980 * @param string Prefix to temp file (which will have no extension btw)
2981 * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
2982 * @see unlink_tempfile(), upload_to_tempfile()
2983 */
2984 function tempnam($filePrefix) {
2985 return tempnam(PATH_site.'typo3temp/',$filePrefix);
2986 }
2987
2988 /**
2989 * standard authentication code - can't remember what it's used for.
2990 * Usage: 2
2991 *
2992 * @param mixed Uid (integer) or record (array)
2993 * @param string List of fields from the record if that is given.
2994 * @return string MD5 hash of 8 chars.
2995 * @internal
2996 */
2997 function stdAuthCode($uid_or_record,$fields='') {
2998 if (is_array($uid_or_record)) {
2999 $recCopy_temp=array();
3000 if ($fields) {
3001 $fieldArr = t3lib_div::trimExplode(',',$fields,1);
3002 reset($fieldArr);
3003 while(list($k,$v)=each($fieldArr)) {
3004 $recCopy_temp[$k]=$recCopy[$v];
3005 }
3006 } else {
3007 $recCopy_temp=$recCopy;
3008 }
3009 $preKey = implode('|',$recCopy_temp);
3010 } else {
3011 $preKey = $uid_or_record;
3012 }
3013
3014 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
3015 $authCode = substr(md5($authCode),0,8);
3016 return $authCode;
3017 }
3018
3019 /**
3020 * Loads the $TCA (Table Configuration Array) for the $table
3021 *
3022 * Requirements:
3023 * 1) must be configured table (the ctrl-section configured),
3024 * 2) columns must not be an array (which it is always if whole table loaded), and
3025 * 3) there is a value for dynamicConfigFile (filename in typo3conf)
3026 * Usage: 84
3027 *
3028 * @param string Table name for which to load the full TCA array part into the global $TCA
3029 * @return void
3030 */
3031 function loadTCA($table) {
3032 global $TCA,$LANG_GENERAL_LABELS;
3033 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile']) {
3034 if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:')) {
3035 include(PATH_t3lib.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
3036 } elseif (t3lib_div::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file($TCA[$table]['ctrl']['dynamicConfigFile'])) { // Absolute path...
3037 include($TCA[$table]['ctrl']['dynamicConfigFile']);
3038 } else include(PATH_typo3conf.$TCA[$table]['ctrl']['dynamicConfigFile']);
3039 }
3040 }
3041
3042 /**
3043 * 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).
3044 * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
3045 * Usage: 5
3046 *
3047 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3048 * @param string The sheet to return, preferably.
3049 * @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!
3050 */
3051 function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
3052 if (is_array($dataStructArray['sheets'])) {
3053 $singleSheet = FALSE;
3054 if (!isset($dataStructArray['sheets'][$sheet])) {
3055 $sheet='sDEF';
3056 }
3057 $dataStruct = $dataStructArray['sheets'][$sheet];
3058
3059 // If not an array, but still set, then regard it as a relative reference to a file:
3060 if ($dataStruct && !is_array($dataStruct)) {
3061 $file = t3lib_div::getFileAbsFileName($dataStruct);
3062 if ($file && @is_file($file)) {
3063 $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
3064 }
3065 }
3066 } else {
3067 $singleSheet = TRUE;
3068 $dataStruct = $dataStructArray;
3069 $sheet = 'sDEF'; // Default sheet
3070 }
3071 return array($dataStruct,$sheet,$singleSheet);
3072 }
3073
3074 /**
3075 * Resolves ALL sheet definitions in dataStructArray
3076 * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
3077 *
3078 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3079 * @return array Output data structure with all sheets resolved as arrays.
3080 */
3081 function resolveAllSheetsInDS($dataStructArray) {
3082 if (is_array($dataStructArray['sheets'])) {
3083 $out=array('sheets'=>array());
3084 foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
3085 list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
3086 if ($sheetId==$aS) {
3087 $out['sheets'][$aS]=$ds;
3088 }
3089 }
3090 } else {
3091 list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
3092 $out = array('sheets' => array('sDEF' => $ds));
3093 }
3094 return $out;
3095 }
3096
3097 /**
3098 * Calls a userdefined function/method in class
3099 * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
3100 * Usage: 17
3101 *
3102 * @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").
3103 * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
3104 * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
3105 * @param string Required prefix of class or function name
3106 * @param boolean If set, no debug() error message is shown if class/function is not present.
3107 * @return mixed Content from method/function call
3108 * @see getUserObj()
3109 */
3110 function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) {
3111 global $TYPO3_CONF_VARS;
3112
3113 // Check persistent object and if found, call directly and exit.
3114 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
3115 return call_user_method(
3116 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
3117 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
3118 $params,
3119 $ref
3120 );
3121 }
3122
3123 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3124 if (strstr($funcName,':')) {
3125 list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
3126 $requireFile = t3lib_div::getFileAbsFileName($file);
3127 if ($requireFile) require_once($requireFile);
3128 } else {
3129 $funcRef = $funcName;
3130 }
3131
3132 // Check for persistent object token, "&"
3133 if (substr($funcRef,0,1)=='&') {
3134 $funcRef = substr($funcRef,1);
3135 $storePersistentObject = TRUE;
3136 } else {
3137 $storePersistentObject = FALSE;
3138 }
3139
3140 // Check prefix is valid:
3141 if ($checkPrefix &&
3142 !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
3143 !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
3144 ) {
3145 if (!$silent) debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
3146 return FALSE;
3147 }
3148
3149 // Call function or method:
3150 $parts = explode('->',$funcRef);
3151 if (count($parts)==2) { // Class
3152
3153 // Check if class/method exists:
3154 if (class_exists($parts[0])) {
3155
3156 // Get/Create object of class:
3157 if ($storePersistentObject) { // Get reference to current instance of class:
3158 if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
3159 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div::makeInstance($parts[0]);
3160 }
3161 $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
3162 } else { // Create new object:
3163 $classObj = &t3lib_div::makeInstance($parts[0]);
3164 }
3165
3166 if (method_exists($classObj, $parts[1])) {
3167
3168 // If persistent object should be created, set reference:
3169 if ($storePersistentObject) {
3170 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
3171 'method' => $parts[1],
3172 'obj' => &$classObj
3173 );
3174 }
3175 // Call method:
3176 $content = call_user_method(
3177 $parts[1],
3178 $classObj,
3179 $params,
3180 $ref
3181 );
3182 } else {
3183 if (!$silent) debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
3184 }
3185 } else {
3186 if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
3187 }
3188 } else { // Function
3189 if (function_exists($funcRef)) {
3190 $content = call_user_func($funcRef, $params, $ref);
3191 } else {
3192 if (!$silent) debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
3193 }
3194 }
3195 return $content;
3196 }
3197
3198 /**
3199 * Creates and returns reference to a user defined object.
3200 * 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.
3201 * Usage: 5
3202 *
3203 * @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!).
3204 * @param string Required prefix of class name. By default "tx_" is allowed.
3205 * @param boolean If set, no debug() error message is shown if class/function is not present.
3206 * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
3207 * @see callUserFunction()
3208 */
3209 function &getUserObj($classRef,$checkPrefix='user_',$silent=0) {
3210 global $TYPO3_CONF_VARS;
3211 // Check persistent object and if found, call directly and exit.
3212 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
3213 return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
3214 } else {
3215
3216 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3217 if (strstr($classRef,':')) {
3218 list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
3219 $requireFile = t3lib_div::getFileAbsFileName($file);
3220 if ($requireFile) require_once($requireFile);
3221 } else {
3222 $class = $classRef;
3223 }
3224
3225 // Check for persistent object token, "&"
3226 if (substr($class,0,1)=='&') {
3227 $class = substr($class,1);
3228 $storePersistentObject = TRUE;
3229 } else {
3230 $storePersistentObject = FALSE;
3231 }
3232
3233 // Check prefix is valid:
3234 if ($checkPrefix &&
3235 !t3lib_div::isFirstPartOfStr(trim($class),$checkPrefix) &&
3236 !t3lib_div::isFirstPartOfStr(trim($class),'tx_')
3237 ) {
3238 if (!$silent) debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
3239 return FALSE;
3240 }
3241
3242 // Check if class exists: