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