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