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