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