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