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