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