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