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