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