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