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