*** empty log message ***
[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']));
1989 }
1990
1991 return true;
1992 }
1993 }
1994
1995 /**
1996 * Returns an array with the names of folders in a specific path
1997 * Will return 'error' (string) if there were an error with reading directory content.
1998 *
1999 * Usage: 13
2000 *
2001 * @param string Path to list directories from
2002 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2003 */
2004 function get_dirs($path) {
2005 if ($path) {
2006 $d = @dir($path);
2007 if (is_object($d)) {
2008 while($entry=$d->read()) {
2009 if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2010 $filearray[]=$entry;
2011 }
2012 }
2013 $d->close();
2014 } else return 'error';
2015 return $filearray;
2016 }
2017 }
2018
2019 /**
2020 * Returns an array with the names of files in a specific path
2021 *
2022 * Usage: 17
2023 *
2024 * @param string $path: Is the path to the file
2025 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2026 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2027 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2028 * @return array Array of the files found
2029 */
2030 function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') {
2031 $filearray=array();
2032 $sortarray=array();
2033 if ($path) {
2034 $path = ereg_replace('/$','',$path);
2035 $extensionList = strtolower($extensionList);
2036 $d = @dir($path);
2037 if (is_object($d)) {
2038 while($entry=$d->read()) {
2039 if (@is_file($path.'/'.$entry)) {
2040 $fI = pathinfo($entry);
2041 $key = md5($path.'/'.$entry);
2042 if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension']))) {
2043 $filearray[$key]=($prependPath?$path.'/':'').$entry;
2044 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2045 elseif ($order) {$sortarray[$key]=$entry;}
2046 }
2047 }
2048 }
2049 $d->close();
2050 } else return 'error';
2051 }
2052 if ($order) {
2053 asort($sortarray);
2054 reset($sortarray);
2055 $newArr=array();
2056 while(list($k,$v)=each($sortarray)) {
2057 $newArr[$k]=$filearray[$k];
2058 }
2059 $filearray=$newArr;
2060 }
2061 reset($filearray);
2062 return $filearray;
2063 }
2064
2065 /**
2066 * Recursively gather all files and folders of a path.
2067 *
2068 * @param array $fileArr: Empty input array (will have files added to it)
2069 * @param string $path: The path to read recursively from (absolute)
2070 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2071 * @param boolean $regDirs: If set, directories are also included in output.
2072 * @param integer $recursivityLevels: The number of levels to dig down...
2073 * @return array An array with the found files/directories.
2074 */
2075 function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) {
2076 if ($regDirs) $fileArr[]=$path;
2077 $fileArr = array_merge($fileArr,t3lib_div::getFilesInDir($path,$extList,1,1));
2078
2079 $dirs = t3lib_div::get_dirs($path);
2080 if (is_array($dirs) && $recursivityLevels>0) {
2081 foreach ($dirs as $subdirs) {
2082 if ((string)$subdirs!='') {
2083 $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
2084 }
2085 }
2086 }
2087 return $fileArr;
2088 }
2089
2090 /**
2091 * Removes the absolute part of all files/folders in fileArr
2092 *
2093 * @param array $fileArr: The file array to remove the prefix from
2094 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2095 * @return array The input $fileArr processed.
2096 */
2097 function removePrefixPathFromList($fileArr,$prefixToRemove) {
2098 foreach($fileArr as $k => $absFileRef) {
2099 if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
2100 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
2101 } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2102 }
2103 return $fileArr;
2104 }
2105
2106 /**
2107 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2108 *
2109 * Usage: 2
2110 *
2111 * @param string File path to process
2112 * @return string
2113 */
2114 function fixWindowsFilePath($theFile) {
2115 return str_replace('//','/', str_replace('\\','/', $theFile));
2116 }
2117
2118 /**
2119 * Resolves "../" sections in the input path string
2120 *
2121 * @param string File path in which "/../" is resolved
2122 * @return string
2123 */
2124 function resolveBackPath($pathStr) {
2125 $parts = explode('/',$pathStr);
2126 $output=array();
2127 foreach($parts as $pV) {
2128 if ($pV=='..') {
2129 if ($c) {
2130 array_pop($output);
2131 $c--;
2132 } else $output[]=$pV;
2133 } else {
2134 $c++;
2135 $output[]=$pV;
2136 }
2137 }
2138 return implode('/',$output);
2139 }
2140
2141 /**
2142 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2143 * - If already having a scheme, nothing is prepended
2144 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2145 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2146 *
2147 * Usage: 31
2148 *
2149 * @param string URL / path to prepend full URL addressing to.
2150 * @return string
2151 */
2152 function locationHeaderUrl($path) {
2153 $uI = parse_url($path);
2154 if (substr($path,0,1)=='/') { // relative to HOST
2155 $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2156 } elseif (!$uI['scheme']) { // No scheme either
2157 $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2158 }
2159 return $path;
2160 }
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177 /*************************
2178 *
2179 * DEBUG helper FUNCTIONS
2180 *
2181 *************************/
2182
2183 /**
2184 * Returns a string with a list of ascii-values for the first $characters characters in $string
2185 * Usage: 5
2186 *
2187 * @param string String to show ASCII value for
2188 * @param integer Number of characters to show
2189 * @return string The string with ASCII values in separated by a space char.
2190 * @internal
2191 */
2192 function debug_ordvalue($string,$characters=100) {
2193 if(strlen($string) < $characters) $characters = strlen($string);
2194 for ($i=0; $i<$characters; $i++) {
2195 $valuestring.=' '.ord(substr($string,$i,1));
2196 }
2197 return trim($valuestring);
2198 }
2199
2200 /**
2201 * Returns HTML-code, which is a visual representation of a multidimensional array
2202 * use t3lib_div::print_array() in order to print an array
2203 * Returns false if $array_in is not an array
2204 * Usage: 27
2205 *
2206 * @param array Array to view
2207 * @return string HTML output
2208 */
2209 function view_array($array_in) {
2210 if (is_array($array_in)) {
2211 $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
2212 if (!count($array_in)) {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.HTMLSpecialChars("EMPTY!").'</b></font></td></tr>';}
2213 while (list($key,$val)=each($array_in)) {
2214 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.HTMLSpecialChars((string)$key).'</font></td><td>';
2215 if (is_array($array_in[$key])) {
2216 $result.=t3lib_div::view_array($array_in[$key]);
2217 } else
2218 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(HTMLSpecialChars((string)$val)).'<br /></font>';
2219 $result.= '</td></tr>';
2220 }
2221 $result.= '</table>';
2222 } else {
2223 $result = false;
2224 }
2225 return $result;
2226 }
2227
2228 /**
2229 * Prints an array
2230 * Usage: 28
2231 *
2232 * @param array Array to print visually (in a table).
2233 * @return void
2234 * @internal
2235 * @see view_array()
2236 */
2237 function print_array($array_in) {
2238 echo t3lib_div::view_array($array_in);
2239 }
2240
2241 /**
2242 * Makes debug output
2243 * Prints $var in bold between two vertical lines
2244 * If not $var the word 'debug' is printed
2245 * If $var is an array, the array is printed by t3lib_div::print_array()
2246 *
2247 * Usage: 8
2248 *
2249 * @param mixed Variable to print
2250 * @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.
2251 * @return void
2252 */
2253 function debug($var="",$brOrHeader=0) {
2254 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
2255 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>';
2256 } elseif ($brOrHeader<0) {
2257 for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
2258 }
2259
2260 if (is_array($var)) {
2261 t3lib_div::print_array($var);
2262 } elseif (is_object($var)) {
2263 echo '<b>|Object:<pre>';
2264 print_r($var);
2265 echo '</pre>|</b>';
2266 } elseif ((string)$var!='') {
2267 echo '<b>|'.HTMLSpecialChars((string)$var).'|</b>';
2268 } else {
2269 echo '<b>| debug |</b>';
2270 }
2271
2272 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
2273 echo '</td></tr></table>';
2274 } elseif ($brOrHeader>0) {
2275 for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
2276 }
2277 }
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310 /*************************
2311 *
2312 * SYSTEM INFORMATION
2313 *
2314 *************************/
2315
2316 /**
2317 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
2318 * Usage: 1
2319 *
2320 * @return string
2321 */
2322 function getThisUrl() {
2323 $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
2324 $dir=t3lib_div::dirname($p['path']).'/'; // Strip file
2325 $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
2326 return $url;
2327 }
2328
2329 /**
2330 * Returns the link-url to the current script.
2331 * 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.
2332 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2333 *
2334 * Usage: 54
2335 *
2336 * @param array Array of GET parameters to include
2337 * @return string
2338 */
2339 function linkThisScript($getParams=array()) {
2340 $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
2341 $params = t3lib_div::_GET();
2342
2343 foreach($getParams as $k => $v) {
2344 if (strcmp($v,'')) {
2345 $params[$k]=$v;
2346 } else unset($params[$k]);
2347 }
2348
2349 $pString = t3lib_div::implodeArrayForUrl('',$params);
2350
2351 return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
2352 }
2353
2354 /**
2355 * 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.
2356 * So basically it adds the parameters in $getParams to an existing URL, $url
2357 * Usage: 2
2358 *
2359 * @param string URL string
2360 * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
2361 * @return string Output URL with added getParams.
2362 */
2363 function linkThisUrl($url,$getParams=array()) {
2364 $parts = parse_url($url);
2365 if ($parts['query']) {
2366 parse_str($parts['query'],$getP);
2367 } else $getP=array();
2368
2369 $getP=t3lib_div::array_merge_recursive_overrule($getP,$getParams);
2370 $uP = explode('?',$url);
2371 $outurl = $uP[0].'?'.t3lib_div::implodeArrayForUrl('',$getP);
2372
2373 return $outurl;
2374 }
2375
2376 /**
2377 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2378 * This should be used instead of getEnv() and HTTP_SERVER_VARS/ENV_VARS to get reliable values for all situations.
2379 *
2380 * Usage: 226
2381 *
2382 * @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
2383 * @return string Value based on the input key, independent of server/os environment.
2384 */
2385 function getIndpEnv($getEnvName) {
2386 global $HTTP_SERVER_VARS;
2387 /*
2388 Conventions:
2389 output from parse_url():
2390 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
2391 [scheme] => 'http'
2392 [user] => 'username'
2393 [pass] => 'password'
2394 [host] => '192.168.1.4'
2395 [port] => '8080'
2396 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2397 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2398 [fragment] => 'link1'
2399
2400 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2401 [path_dir] = '/typo3/32/temp/phpcheck/'
2402 [path_info] = '/arg1/arg2/arg3/'
2403 [path] = [path_script/path_dir][path_info]
2404
2405
2406 Keys supported:
2407
2408 URI______:
2409 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2410 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
2411 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')!
2412 PATH_INFO = [path_info] = /arg1/arg2/arg3/
2413 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
2414 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
2415 (Notice: NO username/password + NO fragment)
2416
2417 CLIENT____:
2418 REMOTE_ADDR = (client IP)
2419 REMOTE_HOST = (client host)
2420 HTTP_USER_AGENT = (client user agent)
2421 HTTP_ACCEPT_LANGUAGE = (client accept language)
2422
2423 SERVER____:
2424 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
2425
2426 Special extras:
2427 TYPO3_HOST_ONLY = [host] = 192.168.1.4
2428 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
2429 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
2430 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (sheme will by default be 'http' until we can detect if it's https -
2431 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
2432 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
2433 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website
2434 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2435
2436 Notice: [fragment] is apparently NEVER available to the script!
2437
2438
2439 Testing suggestions:
2440 - Output all the values.
2441 - 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
2442 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2443
2444 */
2445
2446 # if ($getEnvName=='HTTP_REFERER') return '';
2447 switch((string)$getEnvName) {
2448 case 'SCRIPT_NAME':
2449 return php_sapi_name()=='cgi' ? $HTTP_SERVER_VARS['PATH_INFO'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
2450 break;
2451 case 'SCRIPT_FILENAME':
2452 return str_replace('//','/', str_replace('\\','/', php_sapi_name()=='cgi'||php_sapi_name()=='isapi' ? $HTTP_SERVER_VARS['PATH_TRANSLATED']:$HTTP_SERVER_VARS['SCRIPT_FILENAME']));
2453 break;
2454 case 'REQUEST_URI':
2455 // Typical application of REQUEST_URI is return urls, forms submitting to itselt etc. Eg: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
2456 if (!$HTTP_SERVER_VARS['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
2457 return '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
2458 ($HTTP_SERVER_VARS['QUERY_STRING']?'?'.$HTTP_SERVER_VARS['QUERY_STRING']:'');
2459 } else return $HTTP_SERVER_VARS['REQUEST_URI'];
2460 break;
2461 case 'PATH_INFO':
2462 // $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
2463 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2464 // 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)
2465 // if (strcmp($HTTP_SERVER_VARS['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$HTTP_SERVER_VARS['PATH_INFO']))>1) {
2466 if (php_sapi_name()!='cgi') {
2467 return $HTTP_SERVER_VARS['PATH_INFO'];
2468 } else return '';
2469 break;
2470 // These are let through without modification
2471 case 'REMOTE_ADDR':
2472 case 'REMOTE_HOST':
2473 case 'HTTP_REFERER':
2474 case 'HTTP_HOST':
2475 case 'HTTP_USER_AGENT':
2476 case 'HTTP_ACCEPT_LANGUAGE':
2477 case 'QUERY_STRING':
2478 return $HTTP_SERVER_VARS[$getEnvName];
2479 break;
2480 case 'TYPO3_DOCUMENT_ROOT':
2481 // 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.
2482 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2483 $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
2484 $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
2485 $SFN_A = explode('/',strrev($SFN));
2486 $acc = array();
2487 while(list($kk,$vv)=each($SN_A)) {
2488 if (!strcmp($SFN_A[$kk],$vv)) {
2489 $acc[] = $vv;
2490 } else break;
2491 }
2492 $commonEnd=strrev(implode('/',$acc));
2493 if (strcmp($commonEnd,'')) $DR = substr($SFN,0,-(strlen($commonEnd)+1));
2494 return $DR;
2495 break;
2496 case 'TYPO3_HOST_ONLY':
2497 $p = explode(':',$HTTP_SERVER_VARS['HTTP_HOST']);
2498 return $p[0];
2499 break;
2500 case 'TYPO3_PORT':
2501 $p = explode(':',$HTTP_SERVER_VARS['HTTP_HOST']);
2502 return $p[1];
2503 break;
2504 case 'TYPO3_REQUEST_HOST':
2505 return 'http'.($HTTP_SERVER_VARS['SSL_SESSION_ID']?'s':'').'://'. // I hope this: ($HTTP_SERVER_VARS['SSL_SESSION_ID']?'s':'') - is sufficient to detect https...
2506 $HTTP_SERVER_VARS['HTTP_HOST'];
2507 break;
2508 case 'TYPO3_REQUEST_URL':
2509 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
2510 break;
2511 case 'TYPO3_REQUEST_SCRIPT':
2512 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
2513 break;
2514 case 'TYPO3_REQUEST_DIR':
2515 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
2516 break;
2517 case 'TYPO3_SITE_URL':
2518 if (defined('PATH_thisScript') && defined('PATH_site')) {
2519 $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
2520 $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
2521 $siteUrl = substr($url,0,-strlen($lPath));
2522 if (substr($siteUrl,-1)!='/') $siteUrl.='/';
2523 return $siteUrl;
2524 } else return '';
2525
2526 break;
2527 case '_ARRAY':
2528 $out = array();
2529 // Here, list ALL possible keys to this function for debug display.
2530 $envTestVars = t3lib_div::trimExplode(',','
2531 HTTP_HOST,
2532 TYPO3_HOST_ONLY,
2533 TYPO3_PORT,
2534 PATH_INFO,
2535 QUERY_STRING,
2536 REQUEST_URI,
2537 HTTP_REFERER,
2538 TYPO3_REQUEST_HOST,
2539 TYPO3_REQUEST_URL,
2540 TYPO3_REQUEST_SCRIPT,
2541 TYPO3_REQUEST_DIR,
2542 TYPO3_SITE_URL,
2543 SCRIPT_NAME,
2544 TYPO3_DOCUMENT_ROOT,
2545 SCRIPT_FILENAME,
2546 REMOTE_ADDR,
2547 REMOTE_HOST,
2548 HTTP_USER_AGENT,
2549 HTTP_ACCEPT_LANGUAGE',1);
2550 reset($envTestVars);
2551 while(list(,$v)=each($envTestVars)) {
2552 $out[$v]=t3lib_div::getIndpEnv($v);
2553 }
2554 reset($out);
2555 return $out;
2556 break;
2557 }
2558 }
2559
2560 /**
2561 * milliseconds
2562 *
2563 * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
2564 *
2565 * Usage: 39
2566 *
2567 * @return integer
2568 */
2569 function milliseconds() {
2570 $p=explode(' ',microtime());
2571 return round(($p[0]+$p[1])*1000);
2572 }
2573
2574 /**
2575 * Client Browser Information
2576 *
2577 * Usage: 4
2578 *
2579 * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
2580 * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
2581 */
2582 function clientInfo($useragent='') {
2583 if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
2584
2585 $bInfo=array();
2586 // Which browser?
2587 if (strstr($useragent,'Konqueror')) {
2588 $bInfo['BROWSER']= 'konqu';
2589 } elseif (strstr($useragent,'Opera')) {
2590 $bInfo['BROWSER']= 'opera';
2591 } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6')) {
2592 $bInfo['BROWSER']= 'msie';
2593 } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5')) {
2594 $bInfo['BROWSER']='net';
2595 }
2596 if ($bInfo['BROWSER']) {
2597 // Browser version
2598 switch($bInfo['BROWSER']) {
2599 case 'net':
2600 $bInfo['VERSION']= doubleval(substr($useragent,8));
2601 if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
2602 if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
2603 break;
2604 case 'msie':
2605 $tmp = strstr($useragent,'MSIE');
2606 $bInfo['VERSION'] = doubleval(substr($tmp,4));
2607 break;
2608 case 'opera':
2609 $tmp = strstr($useragent,'Opera');
2610 $bInfo['VERSION'] = doubleval(substr($tmp,5));
2611 break;
2612 case 'konqu':
2613 $tmp = strstr($useragent,'Konqueror/');
2614 $bInfo['VERSION'] = doubleval(substr($tmp,10));
2615 break;
2616 }
2617 // Client system
2618 if (strstr($useragent,'Win')) {
2619 $bInfo['SYSTEM'] = 'win';
2620 } elseif (strstr($useragent,'Mac')) {
2621 $bInfo['SYSTEM'] = 'mac';
2622 } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX ')) {
2623 $bInfo['SYSTEM'] = 'unix';
2624 }
2625 }
2626 // Is true if the browser supports css to format forms, especially the width
2627 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
2628
2629 return $bInfo;
2630 }
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654 /*************************
2655 *
2656 * TYPO3 SPECIFIC FUNCTIONS
2657 *
2658 *************************/
2659
2660 /**
2661 * Returns the absolute filename of $filename.
2662 * Decodes the prefix EXT: for TYPO3 Extensions.
2663 *
2664 * Usage: 9
2665 *
2666 * @param string The input filename/filepath to evaluate
2667 * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
2668 * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
2669 * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
2670 */
2671 function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) {
2672 if (!strcmp($filename,'')) return '';
2673
2674 if ($relToTYPO3_mainDir) {
2675 if (!defined('PATH_typo3')) return '';
2676 $relPathPrefix = PATH_typo3;
2677 } else {
2678 $relPathPrefix = PATH_site;
2679 }
2680 if (substr($filename,0,4)=='EXT:') { // extension
2681 list($extKey,$local) = explode('/',substr($filename,4),2);
2682 $filename='';
2683 if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
2684 $filename = t3lib_extMgm::extPath($extKey).$local;
2685 }
2686 } elseif (!t3lib_div::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
2687 $filename=$relPathPrefix.$filename;
2688 } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
2689 $filename='';
2690 }
2691 if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) { // checks backpath.
2692 return $filename;
2693 }
2694 }
2695
2696 /**
2697 * Returns true if no '//', '..' or '\' is in the $theFile
2698 * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2699 * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2700 *
2701 * Usage: 8
2702 *
2703 * @param string Filepath to evaluate
2704 * @return boolean True, if no '//', '..' or '\' is in the $theFile
2705 * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
2706 */
2707 function validPathStr($theFile) {
2708 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
2709 }
2710
2711 /**
2712 * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
2713 *
2714 * Usage: 9
2715 *
2716 * @param string Filepath to evaluate
2717 * @return boolean
2718 */
2719 function isAbsPath($path) {
2720 return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' : substr($path,0,1)=='/';
2721 }
2722
2723 /**
2724 * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
2725 *
2726 * Usage: 1
2727 *
2728 * @param string Filepath to evaluate
2729 * @return boolean
2730 */
2731 function isAllowedAbsPath($path) {
2732 if (t3lib_div::isAbsPath($path) &&
2733 t3lib_div::validPathStr($path) &&
2734 ( t3lib_div::isFirstPartOfStr($path,PATH_site)
2735 ||
2736 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
2737 )
2738 ) return true;
2739 }
2740
2741 /**
2742 * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
2743 *
2744 * Usage: 2
2745 *
2746 * @param string Filepath to evaluate
2747 * @return boolean
2748 */
2749 function verifyFilenameAgainstDenyPattern($filename) {
2750 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
2751 $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
2752 if ($result) return false; // so if a matching filename is found, return false;
2753 }
2754 return true;
2755 }
2756
2757 /**
2758 * Moves $source file to $destination if uploaded, otherwise try to make a copy
2759 * Usage: 3
2760 *
2761 * @param string Source file, absolute path
2762 * @param string Destination file, absolute path
2763 * @return boolean Returns true if the file was moved.
2764 * @coauthor Dennis Petersen <fessor@software.dk>
2765 * @see upload_to_tempfile()
2766 */
2767 function upload_copy_move($source,$destination) {
2768 if (is_uploaded_file($source)) {
2769 $uploaded = TRUE;
2770 // 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:
2771 $uploadedResult = move_uploaded_file($source, $destination);
2772 } else {
2773 $uploaded = FALSE;
2774 @copy($source,$destination);
2775 }
2776
2777 // Setting file system mode of file:
2778 if (@is_file($destination) && TYPO3_OS!='WIN') {
2779 @chmod ($destination, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
2780 }
2781
2782 // 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
2783 return $uploaded ? $uploadedResult : FALSE;
2784 }
2785
2786 /**
2787 * 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.
2788 * Use this function to move uploaded files to where you can work on them.
2789 * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
2790 *
2791 * @param string The temporary uploaded filename, eg. $GLOBALS['HTTP_POST_FILES']['[upload field name here]']['tmp_name']
2792 * @return string If a new file was successfully created, return its filename, otherwise blank string.
2793 * @see unlink_tempfile(), upload_copy_move()
2794 */
2795 function upload_to_tempfile($uploadedFileName) {
2796 if (is_uploaded_file($uploadedFileName)) {
2797 $tempFile = t3lib_div::tempnam('upload_temp_');
2798 move_uploaded_file($uploadedFileName, $tempFile);
2799 return @is_file($tempFile) ? $tempFile : '';
2800 }
2801 }
2802
2803 /**
2804 * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
2805 * 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.
2806 * Use this after upload_to_tempfile() or tempnam() from this class!
2807 *
2808 * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
2809 * @return boolean Returns true if the file was unlink()'ed
2810 * @see upload_to_tempfile(), tempnam()
2811 */
2812 function unlink_tempfile($uploadedTempFileName) {
2813 if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName)) {
2814 if (unlink($uploadedTempFileName)) return TRUE;
2815 }
2816 }
2817
2818 /**
2819 * Create temporary filename (Create file with unique file name)
2820 * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
2821 * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
2822 *
2823 * @param string Prefix to temp file (which will have no extension btw)
2824 * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
2825 * @see unlink_tempfile()
2826 */
2827 function tempnam($filePrefix) {
2828 return tempnam(PATH_site.'typo3temp/',$filePrefix);
2829 }
2830
2831 /**
2832 * standard authentication code - can't remember what it's used for.
2833 * Usage: 2
2834 *
2835 * @param mixed Uid (integer) or record (array)
2836 * @param string List of fields from the record if that is given.
2837 * @return string MD5 hash of 8 chars.
2838 * @internal
2839 */
2840 function stdAuthCode($uid_or_record,$fields='') {
2841 if (is_array($uid_or_record)) {
2842 $recCopy_temp=array();
2843 if ($fields) {
2844 $fieldArr = t3lib_div::trimExplode(',',$fields,1);
2845 reset($fieldArr);
2846 while(list($k,$v)=each($fieldArr)) {
2847 $recCopy_temp[$k]=$recCopy[$v];
2848 }
2849 } else {
2850 $recCopy_temp=$recCopy;
2851 }
2852 $preKey = implode('|',$recCopy_temp);
2853 } else {
2854 $preKey = $uid_or_record;
2855 }
2856
2857 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
2858 $authCode = substr(md5($authCode),0,8);
2859 return $authCode;
2860 }
2861
2862 /**
2863 * Loads the $TCA (Table Configuration Array) for the $table
2864 *
2865 * Requirements:
2866 * 1) must be configured table (the ctrl-section configured),
2867 * 2) columns must not be an array (which it is always if whole table loaded), and
2868 * 3) there is a value for dynamicConfigFile (filename in typo3conf)
2869 * Usage: 92
2870 *
2871 * @param string Table name for which to load the full TCA array part into the global $TCA
2872 * @return void
2873 */
2874 function loadTCA($table) {
2875 global $TCA,$LANG_GENERAL_LABELS;
2876 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile']) {
2877 if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:')) {
2878 include(PATH_t3lib.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
2879 } elseif (t3lib_div::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file($TCA[$table]['ctrl']['dynamicConfigFile'])) { // Absolute path...
2880 include($TCA[$table]['ctrl']['dynamicConfigFile']);
2881 } else include(PATH_typo3conf.$TCA[$table]['ctrl']['dynamicConfigFile']);
2882 }
2883 }
2884
2885 /**
2886 * 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).
2887 * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
2888 *
2889 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
2890 * @param string The sheet to return, preferably.
2891 * @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!
2892 */
2893 function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
2894 if (is_array($dataStructArray['sheets'])) {
2895 if (!isset($dataStructArray['sheets'][$sheet])) {
2896 $sheet='sDEF';
2897 }
2898 $dataStruct = $dataStructArray['sheets'][$sheet];
2899
2900 // If not an array, but still set, then regard it as a relative reference to a file:
2901 if ($dataStruct && !is_array($dataStruct)) {
2902 $file = t3lib_div::getFileAbsFileName($dataStruct);
2903 if ($file && @is_file($file)) {
2904 $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
2905 }
2906 }
2907 } else {
2908 $dataStruct = $dataStructArray;
2909 $sheet = 'sDEF'; // Default sheet
2910 }
2911 return array($dataStruct,$sheet);
2912 }
2913
2914 /**
2915 * Resolves ALL sheet definitions in dataStructArray
2916 * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
2917 *
2918 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
2919 * @return array Output data structure with all sheets resolved as arrays.
2920 */
2921 function resolveAllSheetsInDS($dataStructArray) {
2922 if (is_array($dataStructArray['sheets'])) {
2923 $out=array('sheets'=>array());
2924 foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
2925 list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
2926 if ($sheetId==$aS) {
2927 $out['sheets'][$aS]=$ds;
2928 }
2929 }
2930 } else {
2931 list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
2932 $out = array('sheets' => array('sDEF' => $ds));
2933 }
2934 return $out;
2935 }
2936
2937 /**
2938 * Calls a userdefined function/method in class
2939 * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
2940 *
2941 * Usage: 3
2942 *
2943 * @param string Method reference, [class]->[method] or [function]. 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; for method references the normal operator "->" creates a new instance each time; if you use "->>" instead you will reuse the previous instance of the object identified by the full reference string (meaning; if you call another method in the same class another object is created for that).
2944 * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
2945 * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
2946 * @param string Required prefix of class or function name
2947 * @param boolean If set, not debug() error message is shown if class/function is not present.
2948 * @return mixed Content from method/function call
2949 */
2950 function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) {
2951
2952 // Check persistent object and if found, call directly and exit.
2953 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
2954 return call_user_method(
2955 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
2956 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
2957 $params,
2958 $ref
2959 );
2960 }
2961
2962 // Check file-reference prefix; if found, require_once() the file (should be library of code)
2963 if (strstr($funcName,':')) {
2964 list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
2965 $requireFile = t3lib_div::getFileAbsFileName($file);
2966 require_once($requireFile);
2967 } else {
2968 $funcRef = $funcName;
2969 }
2970
2971 // Check prefix is valid:
2972 if ($checkPrefix &&
2973 !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
2974 !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
2975 ) {
2976 if (!$silent) debug("Function '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
2977 return $content;
2978 }
2979
2980 // Call function or method:
2981 $parts = explode('->',$funcRef);
2982 if (count($parts)==2) { // Class
2983
2984 // Check for persistent object token, "->>"
2985 if (substr($parts[1],0,1)=='>') {
2986 $parts[1] = substr($parts[1],1);
2987 $storePersistentObject = TRUE;
2988 } else $storePersistentObject = FALSE;
2989
2990 // Check if class/method exists:
2991 if (class_exists($parts[0])) {
2992 $classObj = new $parts[0];
2993 if (method_exists($classObj, $parts[1])) {
2994
2995 // If persistent object should be created, set reference:
2996 if ($storePersistentObject) {
2997 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
2998 'method' => $parts[1],
2999 'obj' => &$classObj
3000 );
3001 }
3002 // Call method:
3003 $content = call_user_method(
3004 $parts[1],
3005 $classObj,
3006 $params,
3007 $ref
3008 );
3009 } else {
3010 if (!$silent) debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
3011 }
3012 } else {
3013 if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
3014 }
3015 } else { // Function
3016 if (function_exists($funcRef)) {
3017 $content = call_user_func($funcRef, $params, $ref);
3018 } else {
3019 if (!$silent) debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
3020 }
3021 }
3022 return $content;
3023 }
3024
3025 /**
3026 * Make instance of class
3027 * Takes the class-extensions API of TYPO3 into account
3028 * Please USE THIS instead of the PHP "new" keyword. Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
3029 *
3030 * Usage: 455
3031 *
3032 * @param string Class name to instantiate
3033 * @return object The object
3034 */
3035 function &makeInstance($className) {
3036 if (class_exists('ux_'.$className)) {
3037 return t3lib_div::makeInstance('ux_'.$className);
3038 } else {
3039 return new $className;
3040 }
3041 }
3042
3043 /**
3044 * Find the best service and check if it works.
3045 * Returns object of the service class.
3046 *
3047 * @param string Type of service (service key).
3048 * @param string Sub type like file extensions or similar. Defined by the service.
3049 * @param string List of service keys which should be exluded in the search for a service.
3050 * @return object The service object or an array with error info's.
3051 * @author René Fritz <r.fritz@colorcube.de>
3052 */
3053 function makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys='') {
3054 global $T3_SERVICES;
3055
3056 $error = FALSE;
3057
3058 while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
3059
3060 if (@is_file($info['classFile'])) {
3061 require_once ($info['classFile']);
3062 $obj = t3lib_div::makeInstance($info['className']);
3063 if (is_object($obj)) {
3064 if(!@is_callable(array($obj,'init'))) {
3065 // use silent logging???
3066 die ('Broken service:'.t3lib_div::view_array($info));
3067 }
3068 if ($obj->init()) { // service available?
3069
3070 $obj->info = $info;
3071 return $obj; // objects are passed always as reference - right?
3072 }
3073 $error = $obj->getLastErrorArray();
3074 unset($obj);
3075 }
3076 }
3077 // deactivate the service
3078 t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
3079 }
3080 return $error;
3081 }
3082
3083 /**
3084 * Return classname for new instance
3085 * Takes the class-extensions API of TYPO3 into account
3086 *
3087 * Usage: 18
3088 *
3089 * @param string Base Class name to evaluate
3090 * @return string Final class name to instantiate with "new [classname]"
3091 */
3092 function makeInstanceClassName($className) {
3093 return class_exists('ux_'.$className)?t3lib_div::makeInstanceClassName('ux_'.$className):$className;
3094 }
3095
3096 /**
3097 * Simple substitute for the PHP function mail().
3098 * The fifth parameter, $enc, will allow you to specify 'base64' encryption for the output (set $enc=base64)
3099 * Further the output has the charset set to ISO-8859-1 by default.
3100 *
3101 * Usage: 4
3102 *
3103 * @param string Email address to send to. (see PHP function mail())
3104 * @param string Subject line, non-encoded. (see PHP function mail())
3105 * @param string Message content, non-encoded. (see PHP function mail())
3106 * @param string Headers, separated by chr(10)
3107 * @param string Encoding type: "base64", "quoted-printable", "8bit". If blank, no encoding will be used, no encoding headers set.
3108 * @param string Charset used in encoding-headers (only if $enc is set to a valid value which produces such a header)
3109 * @param boolean If set, the content of $subject will not be encoded.
3110 * @return void
3111 */
3112 function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0) {
3113 switch((string)$enc) {
3114 case 'base64':
3115 $headers=trim($headers).chr(10).
3116 'Mime-Version: 1.0'.chr(10).
3117 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
3118 'Content-Transfer-Encoding: base64';
3119
3120 $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.
3121
3122 if (!$dontEncodeSubject) $subject='=?'.$charset.'?B?'.base64_encode($subject).'?=';
3123 break;
3124 case 'quoted-printable':
3125 $headers=trim($headers).chr(10).
3126 'Mime-Version: 1.0'.chr(10).
3127 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
3128 'Content-Transfer-Encoding: quoted-printable';
3129
3130 $message=t3lib_div::quoted_printable($message);
3131
3132 if (!$dontEncodeSubject) $subject='=?'.$charset.'?Q?'.trim(t3lib_div::quoted_printable(ereg_replace('[[:space:]]','_',$subject),1000)).'?=';
3133 break;
3134 case '8bit':
3135 $headers=trim($headers).chr(10).
3136 'Mime-Version: 1.0'.chr(10).
3137 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
3138 'Content-Transfer-Encoding: 8bit';
3139 break;
3140 }
3141 $headers=trim(implode(chr(10),t3lib_div::trimExplode(chr(10),$headers,1))); // make sure no empty lines are there.
3142 #debug(array($email,$subject,$message,$headers));
3143
3144 mail($email,$subject,$message,$headers);
3145 }
3146
3147 /**
3148 * Implementation of quoted-printable encode.
3149 * 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!
3150 * (Originally taken from class.t3lib_htmlmail.php - which may be updated if this function should ever be improved!
3151 * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
3152 *
3153 * Usage: 2
3154 *
3155 * @param string Content to encode
3156 * @param integer Length of the lines, default is 76
3157 * @return string The QP encoded string
3158 */
3159 function quoted_printable($string,$maxlen=76) {
3160 $newString = '';
3161 $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
3162 while (list(,$val)=each($theLines)) {
3163 $val = ereg_replace(chr(13).'$','',$val); // removes possible character 13 at the end of line
3164
3165 $newVal = '';
3166 $theValLen = strlen($val);
3167 $len = 0;
3168 for ($index=0;$index<$theValLen;$index++) {
3169 $char = substr($val,$index,1);
3170 $ordVal =Ord($char);
3171 if ($len>($maxlen-4) || ($len>(($maxlen-10)-4)&&$ordVal==32)) {
3172 $len=0;
3173 $newVal.='='.chr(13).chr(10);
3174 }
3175 if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
3176 $newVal.=$char;
3177 $len++;
3178 } else {
3179 $newVal.=sprintf('=%02X',$ordVal);
3180 $len+=3;
3181 }
3182 }
3183 $newVal = ereg_replace(chr(32).'$','=20',$newVal); // replaces a possible SPACE-character at the end of a line
3184 $newVal = ereg_replace(chr(9).'$','=09',$newVal); // replaces a possible TAB-character at the end of a line
3185 $newString.=$newVal.chr(13).chr(10);
3186 }
3187 return ereg_replace(chr(13).chr(10).'$','',$newString);
3188 }
3189
3190 /**
3191 * Takes a clear-text message body for a plain text email, finds all 'http://' links and if they are longer than 76 chars they are converted to a shorter URL with a hash parameter. The real parameter is stored in the database and the hash-parameter/URL will be redirected to the real parameter when the link is clicked.
3192 * This function is about preserving long links in messages.
3193 *
3194 * Usage: 3
3195 *
3196 * @param string Message content
3197 * @param string URL mode; "76" or "all"
3198 * @param string URL of index script (see makeRedirectUrl())
3199 * @return string Processed message content
3200 * @see makeRedirectUrl()
3201 */
3202 function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') {
3203 // Substitute URLs with shorter links:
3204 $urlSplit=explode('http://',$message);
3205 reset($urlSplit);
3206 while(list($c,$v)=each($urlSplit)) {
3207 if ($c) {
3208 $newParts = split('[[:space:]]|\)|\(',$v,2);
3209 $newURL='http://'.$newParts[0];
3210 switch((string)$urlmode) {
3211 case 'all':
3212 $newURL=t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
3213 break;
3214 case '76':
3215 $newURL=t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
3216 break;
3217 }
3218 $urlSplit[$c]=$newURL.substr($v,strlen($newParts[0]));
3219 }
3220 }
3221
3222 $message=implode('',$urlSplit);
3223 return $message;
3224 }
3225
3226 /**
3227 * Subfunction for substUrlsInPlainText() above.
3228 *
3229 * Usage: 2
3230 *
3231 * @param string Input URL
3232 * @param integer URL string length limit
3233 * @param string URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplyed it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')
3234 * @return string Processed URL
3235 * @internal
3236 */
3237 function makeRedirectUrl($inUrl,$l=0,$index_script_url='') {
3238 if (strlen($inUrl)>$l) {
3239 $md5 = substr(md5($inUrl),0,20);
3240 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($md5, 'cache_md5params').'"');
3241 if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
3242 $insertFields = array(
3243 'md5hash' => $md5,
3244 'tstamp' => time(),
3245 'type' => 2,
3246 'params' => $inUrl
3247 );
3248
3249 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
3250 }
3251 $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')).
3252 '?RDCT='.$md5;
3253 }
3254 return $inUrl;
3255 }
3256
3257 /**
3258 * Function to compensate for FreeType2 96 dpi
3259 *
3260 * Usage: 16
3261 *
3262 * @param integer Fontsize for freetype function call
3263 * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
3264 */
3265 function freetypeDpiComp($font_size) {
3266 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
3267 if ($dpi!=72) $font_size = $font_size/$dpi*72;
3268 return $font_size;
3269 }
3270
3271 /**
3272 * Developer log; This should be implemented around the source code, both frontend and backend, logging everything from the flow through an application, messages, results from comparisons to fatal errors.
3273 * The result is meant to make sense to developers during development or debugging of a site.
3274 * The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like.
3275 * If you want to implement the devLog in your applications, simply add lines like:
3276 * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
3277 *
3278 * @param string Message (in english).
3279 * @param string Extension key (from which extension you are calling the log)
3280 * @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
3281 * @param array Additional data you want to pass to the logger.
3282 * @return void
3283 */
3284 function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) {
3285 global $TYPO3_CONF_VARS;
3286
3287 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
3288 $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity