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