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