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