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