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