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