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