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