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