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