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