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