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