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