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