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