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