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