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