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