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