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