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