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