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