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