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