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