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