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