00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206 define('TAB', chr(9));
00207
00208 define('LF', chr(10));
00209
00210 define('CR', chr(13));
00211
00212 define('CRLF', CR . LF);
00213
00214
00215
00216
00217
00218
00219
00220
00221
00222
00223
00224
00225
00226
00227
00228
00229
00230 final class t3lib_div {
00231
00232
00233 const SYSLOG_SEVERITY_INFO = 0;
00234 const SYSLOG_SEVERITY_NOTICE = 1;
00235 const SYSLOG_SEVERITY_WARNING = 2;
00236 const SYSLOG_SEVERITY_ERROR = 3;
00237 const SYSLOG_SEVERITY_FATAL = 4;
00238
00239
00240
00241
00242
00243
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263 public static function _GP($var) {
00264 if(empty($var)) return;
00265 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00266 if (isset($value)) {
00267 if (is_array($value)) { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00268 }
00269 return $value;
00270 }
00271
00272
00273
00274
00275
00276
00277
00278 public static function _GPmerged($parameter) {
00279 $postParameter = (isset($_POST[$parameter]) && is_array($_POST[$parameter])) ? $_POST[$parameter] : array();
00280 $getParameter = (isset($_GET[$parameter]) && is_array($_GET[$parameter])) ? $_GET[$parameter] : array();
00281
00282 $mergedParameters = self::array_merge_recursive_overrule($getParameter, $postParameter);
00283 self::stripSlashesOnArray($mergedParameters);
00284
00285 return $mergedParameters;
00286 }
00287
00288
00289
00290
00291
00292
00293
00294
00295
00296
00297 public static function _GET($var=NULL) {
00298 $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
00299 if (isset($value)) {
00300 if (is_array($value)) { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00301 }
00302 return $value;
00303 }
00304
00305
00306
00307
00308
00309
00310
00311
00312
00313
00314 public static function _POST($var=NULL) {
00315 $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
00316 if (isset($value)) {
00317 if (is_array($value)) { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00318 }
00319 return $value;
00320 }
00321
00322
00323
00324
00325
00326
00327
00328
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339
00340 public static function _GETset($inputGet, $key = '') {
00341
00342
00343 if (is_array($inputGet)) {
00344 self::addSlashesOnArray($inputGet);
00345 } else {
00346 $inputGet = addslashes($inputGet);
00347 }
00348
00349 if ($key != '') {
00350 if (strpos($key, '|') !== FALSE) {
00351 $pieces = explode('|', $key);
00352 $newGet = array();
00353 $pointer =& $newGet;
00354 foreach ($pieces as $piece) {
00355 $pointer =& $pointer[$piece];
00356 }
00357 $pointer = $inputGet;
00358 $mergedGet = self::array_merge_recursive_overrule(
00359 $_GET, $newGet
00360 );
00361
00362 $_GET = $mergedGet;
00363 $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
00364 } else {
00365 $_GET[$key] = $inputGet;
00366 $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
00367 }
00368 } elseif (is_array($inputGet)) {
00369 $_GET = $inputGet;
00370 $GLOBALS['HTTP_GET_VARS'] = $inputGet;
00371 }
00372 }
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385 public static function GPvar($var,$strip=0) {
00386 self::logDeprecatedFunction();
00387
00388 if(empty($var)) return;
00389 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00390 if (isset($value) && is_string($value)) { $value = stripslashes($value); }
00391 if ($strip && isset($value) && is_array($value)) { self::stripSlashesOnArray($value); }
00392 return $value;
00393 }
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404 public static function GParrayMerged($var) {
00405 self::logDeprecatedFunction();
00406
00407 return self::_GPmerged($var);
00408 }
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419 public static function removeXSS($string) {
00420 require_once(PATH_typo3.'contrib/RemoveXSS/RemoveXSS.php');
00421 $string = RemoveXSS::process($string);
00422 return $string;
00423 }
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451
00452
00453
00454
00455
00456
00457
00458
00459
00460 public static function gif_compress($theFile, $type) {
00461 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
00462 $returnCode='';
00463 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') {
00464 if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) {
00465 $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
00466 exec($cmd);
00467
00468 $returnCode='IM';
00469 } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) {
00470 $tempImage = imageCreateFromGif($theFile);
00471 imageGif($tempImage, $theFile);
00472 imageDestroy($tempImage);
00473 $returnCode='GD';
00474 }
00475 }
00476 return $returnCode;
00477 }
00478
00479
00480
00481
00482
00483
00484
00485
00486
00487 public static function png_to_gif_by_imagemagick($theFile) {
00488 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
00489 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
00490 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
00491 && strtolower(substr($theFile,-4,4))=='.png'
00492 && @is_file($theFile)) {
00493 $newFile = substr($theFile,0,-4).'.gif';
00494 $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
00495 exec($cmd);
00496 $theFile = $newFile;
00497
00498 }
00499 return $theFile;
00500 }
00501
00502
00503
00504
00505
00506
00507
00508
00509
00510
00511 public static function read_png_gif($theFile,$output_png=0) {
00512 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) {
00513 $ext = strtolower(substr($theFile,-4,4));
00514 if (
00515 ((string)$ext=='.png' && $output_png) ||
00516 ((string)$ext=='.gif' && !$output_png)
00517 ) {
00518 return $theFile;
00519 } else {
00520 $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
00521 $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
00522 exec($cmd);
00523 if (@is_file($newFile)) return $newFile;
00524 }
00525 }
00526 }
00527
00528
00529
00530
00531
00532
00533
00534
00535
00536
00537
00538
00539
00540
00541
00542
00543
00544
00545
00546
00547
00548
00549
00550
00551
00552
00553
00554
00555
00556
00557
00558
00559
00560
00561 public static function fixed_lgd($string,$origChars,$preStr='...') {
00562 self::logDeprecatedFunction();
00563
00564 $chars = abs($origChars);
00565 if ($chars >= 4) {
00566 if(strlen($string)>$chars) {
00567 return $origChars < 0 ?
00568 $preStr.trim(substr($string, -($chars-3))) :
00569 trim(substr($string, 0, $chars-3)).$preStr;
00570 }
00571 }
00572 return $string;
00573 }
00574
00575
00576
00577
00578
00579
00580
00581
00582
00583
00584
00585
00586
00587
00588 public static function fixed_lgd_pre($string,$chars) {
00589 self::logDeprecatedFunction();
00590
00591 return strrev(self::fixed_lgd(strrev($string),$chars));
00592 }
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603 public static function fixed_lgd_cs($string, $chars, $appendString='...') {
00604 if (is_object($GLOBALS['LANG'])) {
00605 return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
00606 } elseif (is_object($GLOBALS['TSFE'])) {
00607 $charSet = ($GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet);
00608 return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString);
00609 } else {
00610
00611 $csConvObj = self::makeInstance('t3lib_cs');
00612 return $csConvObj->crop('iso-8859-1', $string, $chars, $appendString);
00613 }
00614 }
00615
00616
00617
00618
00619
00620
00621
00622
00623
00624
00625
00626 public static function breakTextForEmail($str,$implChar=LF,$charWidth=76) {
00627 self::logDeprecatedFunction();
00628
00629 $lines = explode(LF,$str);
00630 $outArr=array();
00631 foreach ($lines as $lStr) {
00632 $outArr[] = self::breakLinesForEmail($lStr,$implChar,$charWidth);
00633 }
00634 return implode(LF,$outArr);
00635 }
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647 public static function breakLinesForEmail($str,$implChar=LF,$charWidth=76) {
00648 $lines=array();
00649 $l=$charWidth;
00650 $p=0;
00651 while(strlen($str)>$p) {
00652 $substr=substr($str,$p,$l);
00653 if (strlen($substr)==$l) {
00654 $count = count(explode(' ',trim(strrev($substr))));
00655 if ($count>1) {
00656 $parts = explode(' ',strrev($substr),2);
00657 $theLine = strrev($parts[1]);
00658 } else {
00659 $afterParts = explode(' ',substr($str,$l+$p),2);
00660 $theLine = $substr.$afterParts[0];
00661 }
00662 if (!strlen($theLine)) {break; }
00663 } else {
00664 $theLine=$substr;
00665 }
00666
00667 $lines[]=trim($theLine);
00668 $p+=strlen($theLine);
00669 if (!trim(substr($str,$p,$l))) break;
00670 }
00671 return implode($implChar,$lines);
00672 }
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682
00683 public static function cmpIP($baseIP, $list) {
00684 $list = trim($list);
00685 if ($list === '') {
00686 return false;
00687 } elseif ($list === '*') {
00688 return true;
00689 }
00690 if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
00691 return self::cmpIPv6($baseIP, $list);
00692 } else {
00693 return self::cmpIPv4($baseIP, $list);
00694 }
00695 }
00696
00697
00698
00699
00700
00701
00702
00703
00704 public static function cmpIPv4($baseIP, $list) {
00705 $IPpartsReq = explode('.',$baseIP);
00706 if (count($IPpartsReq)==4) {
00707 $values = self::trimExplode(',',$list,1);
00708
00709 foreach($values as $test) {
00710 list($test,$mask) = explode('/',$test);
00711
00712 if(intval($mask)) {
00713
00714 $lnet = ip2long($test);
00715 $lip = ip2long($baseIP);
00716 $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
00717 $firstpart = substr($binnet,0,$mask);
00718 $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
00719 $firstip = substr($binip,0,$mask);
00720 $yes = (strcmp($firstpart,$firstip)==0);
00721 } else {
00722
00723 $IPparts = explode('.',$test);
00724 $yes = 1;
00725 foreach ($IPparts as $index => $val) {
00726 $val = trim($val);
00727 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
00728 $yes=0;
00729 }
00730 }
00731 }
00732 if ($yes) return true;
00733 }
00734 }
00735 return false;
00736 }
00737
00738
00739
00740
00741
00742
00743
00744
00745 public static function cmpIPv6($baseIP, $list) {
00746 $success = false;
00747 $baseIP = self::normalizeIPv6($baseIP);
00748
00749 $values = self::trimExplode(',',$list,1);
00750 foreach ($values as $test) {
00751 list($test,$mask) = explode('/',$test);
00752 if (self::validIPv6($test)) {
00753 $test = self::normalizeIPv6($test);
00754 if (intval($mask)) {
00755 switch ($mask) {
00756 case '48':
00757 $testBin = substr(self::IPv6Hex2Bin($test), 0, 48);
00758 $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 48);
00759 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00760 break;
00761 case '64':
00762 $testBin = substr(self::IPv6Hex2Bin($test), 0, 64);
00763 $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 64);
00764 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00765 break;
00766 default:
00767 $success = false;
00768 }
00769 } else {
00770 if (self::validIPv6($test)) {
00771 $testBin = self::IPv6Hex2Bin($test);
00772 $baseIPBin = self::IPv6Hex2Bin($baseIP);
00773 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00774 }
00775 }
00776 }
00777 if ($success) return true;
00778 }
00779 return false;
00780 }
00781
00782
00783
00784
00785
00786
00787
00788 public static function IPv6Hex2Bin ($hex) {
00789 $bin = '';
00790 $hex = str_replace(':', '', $hex);
00791 for ($i=0; $i<strlen($hex); $i=$i+2) {
00792 $bin.= chr(hexdec(substr($hex, $i, 2)));
00793 }
00794 return $bin;
00795 }
00796
00797
00798
00799
00800
00801
00802
00803 public static function normalizeIPv6($address) {
00804 $normalizedAddress = '';
00805 $stageOneAddress = '';
00806
00807 $chunks = explode('::', $address);
00808 if (count($chunks)==2) {
00809 $chunksLeft = explode(':', $chunks[0]);
00810 $chunksRight = explode(':', $chunks[1]);
00811 $left = count($chunksLeft);
00812 $right = count($chunksRight);
00813
00814
00815 if ($left==1 && strlen($chunksLeft[0])==0) $left=0;
00816
00817 $hiddenBlocks = 8 - ($left + $right);
00818 $hiddenPart = '';
00819 while ($h<$hiddenBlocks) {
00820 $hiddenPart .= '0000:';
00821 $h++;
00822 }
00823
00824 if ($left == 0) {
00825 $stageOneAddress = $hiddenPart . $chunks[1];
00826 } else {
00827 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
00828 }
00829 } else $stageOneAddress = $address;
00830
00831
00832 $blocks = explode(':', $stageOneAddress);
00833 $divCounter = 0;
00834 foreach ($blocks as $block) {
00835 $tmpBlock = '';
00836 $i = 0;
00837 $hiddenZeros = 4 - strlen($block);
00838 while ($i < $hiddenZeros) {
00839 $tmpBlock .= '0';
00840 $i++;
00841 }
00842 $normalizedAddress .= $tmpBlock . $block;
00843 if ($divCounter < 7) {
00844 $normalizedAddress .= ':';
00845 $divCounter++;
00846 }
00847 }
00848 return $normalizedAddress;
00849 }
00850
00851
00852
00853
00854
00855
00856
00857
00858
00859 public static function validIP($ip) {
00860 return (filter_var($ip, FILTER_VALIDATE_IP) !== false);
00861 }
00862
00863
00864
00865
00866
00867
00868
00869
00870
00871 public static function validIPv4($ip) {
00872 return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false);
00873 }
00874
00875
00876
00877
00878
00879
00880
00881
00882
00883 public static function validIPv6($ip) {
00884 return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false);
00885 }
00886
00887
00888
00889
00890
00891
00892
00893
00894 public static function cmpFQDN($baseIP, $list) {
00895 if (count(explode('.',$baseIP))==4) {
00896 $resolvedHostName = explode('.', gethostbyaddr($baseIP));
00897 $values = self::trimExplode(',',$list,1);
00898
00899 foreach($values as $test) {
00900 $hostNameParts = explode('.',$test);
00901 $yes = 1;
00902
00903 foreach($hostNameParts as $index => $val) {
00904 $val = trim($val);
00905 if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
00906 $yes=0;
00907 }
00908 }
00909 if ($yes) return true;
00910 }
00911 }
00912 return false;
00913 }
00914
00915
00916
00917
00918
00919
00920
00921
00922 public static function isOnCurrentHost($url) {
00923 return (stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0);
00924 }
00925
00926
00927
00928
00929
00930
00931
00932
00933
00934
00935 public static function inList($list, $item) {
00936 return (strpos(','.$list.',', ','.$item.',')!==false ? true : false);
00937 }
00938
00939
00940
00941
00942
00943
00944
00945
00946
00947 public static function rmFromList($element,$list) {
00948 $items = explode(',',$list);
00949 foreach ($items as $k => $v) {
00950 if ($v==$element) {
00951 unset($items[$k]);
00952 }
00953 }
00954 return implode(',',$items);
00955 }
00956
00957
00958
00959
00960
00961
00962
00963
00964
00965 public static function expandList($list) {
00966 $items = explode(',',$list);
00967 $list = array();
00968 foreach ($items as $item) {
00969 $range = explode('-',$item);
00970 if (isset($range[1])) {
00971 $runAwayBrake = 1000;
00972 for ($n=$range[0]; $n<=$range[1]; $n++) {
00973 $list[] = $n;
00974
00975 $runAwayBrake--;
00976 if ($runAwayBrake<=0) break;
00977 }
00978 } else {
00979 $list[] = $item;
00980 }
00981 }
00982 return implode(',',$list);
00983 }
00984
00985
00986
00987
00988
00989
00990
00991
00992
00993
00994
00995 public static function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
00996
00997 $theInt = intval($theInt);
00998 if ($zeroValue && !$theInt) {$theInt=$zeroValue;}
00999 if ($theInt<$min){$theInt=$min;}
01000 if ($theInt>$max){$theInt=$max;}
01001 return $theInt;
01002 }
01003
01004
01005
01006
01007
01008
01009
01010
01011 public static function intval_positive($theInt) {
01012 $theInt = intval($theInt);
01013 if ($theInt<0){$theInt=0;}
01014 return $theInt;
01015 }
01016
01017
01018
01019
01020
01021
01022
01023
01024 public static function int_from_ver($verNumberStr) {
01025 $verParts = explode('.',$verNumberStr);
01026 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));
01027 }
01028
01029
01030
01031
01032
01033
01034
01035
01036
01037 public static function compat_version($verNumberStr) {
01038 global $TYPO3_CONF_VARS;
01039 $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ? $TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch;
01040
01041 if (self::int_from_ver($currVersionStr) < self::int_from_ver($verNumberStr)) {
01042 return FALSE;
01043 } else {
01044 return TRUE;
01045 }
01046 }
01047
01048
01049
01050
01051
01052
01053
01054
01055 public static function md5int($str) {
01056 return hexdec(substr(md5($str),0,7));
01057 }
01058
01059
01060
01061
01062
01063
01064
01065
01066
01067
01068 public static function shortMD5($input, $len=10) {
01069 return substr(md5($input),0,$len);
01070 }
01071
01072
01073
01074
01075
01076
01077
01078 public static function hmac($input) {
01079 $hashAlgorithm = 'sha1';
01080 $hashBlocksize = 64;
01081 $hmac = '';
01082
01083 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
01084 $hmac = hash_hmac($hashAlgorithm, $input, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
01085 } else {
01086
01087 $opad = str_repeat(chr(0x5C), $hashBlocksize);
01088
01089 $ipad = str_repeat(chr(0x36), $hashBlocksize);
01090 if (strlen($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) > $hashBlocksize) {
01091
01092 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])), $hashBlocksize, chr(0x00));
01093 } else {
01094
01095 $key = str_pad($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], $hashBlocksize, chr(0x00));
01096 }
01097 $hmac = call_user_func($hashAlgorithm, ($key^$opad) . pack('H*', call_user_func($hashAlgorithm, ($key^$ipad) . $input)));
01098 }
01099 return $hmac;
01100 }
01101
01102
01103
01104
01105
01106
01107
01108
01109
01110
01111 public static function uniqueList($in_list, $secondParameter=NULL) {
01112 if (is_array($in_list)) {
01113 throw new InvalidArgumentException(
01114 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
01115 1270853885
01116 );
01117 }
01118 if (isset($secondParameter)) {
01119 throw new InvalidArgumentException(
01120 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!',
01121 1270853886
01122 );
01123 }
01124
01125 return implode(',',array_unique(self::trimExplode(',',$in_list,1)));
01126 }
01127
01128
01129
01130
01131
01132
01133
01134
01135 public static function split_fileref($fileref) {
01136 $reg = array();
01137 if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
01138 $info['path'] = $reg[1];
01139 $info['file'] = $reg[2];
01140 } else {
01141 $info['path'] = '';
01142 $info['file'] = $fileref;
01143 }
01144
01145 $reg = '';
01146 if (!is_dir($fileref) && preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
01147 $info['filebody'] = $reg[1];
01148 $info['fileext'] = strtolower($reg[2]);
01149 $info['realFileext'] = $reg[2];
01150 } else {
01151 $info['filebody'] = $info['file'];
01152 $info['fileext'] = '';
01153 }
01154 reset($info);
01155 return $info;
01156 }
01157
01158
01159
01160
01161
01162
01163
01164
01165
01166
01167
01168
01169
01170
01171
01172
01173
01174 public static function dirname($path) {
01175 $p = self::revExplode('/',$path,2);
01176 return count($p)==2 ? $p[0] : '';
01177 }
01178
01179
01180
01181
01182
01183
01184
01185
01186
01187
01188
01189
01190 public static function modifyHTMLColor($color,$R,$G,$B) {
01191
01192 $nR = self::intInRange(hexdec(substr($color,1,2))+$R,0,255);
01193 $nG = self::intInRange(hexdec(substr($color,3,2))+$G,0,255);
01194 $nB = self::intInRange(hexdec(substr($color,5,2))+$B,0,255);
01195 return '#'.
01196 substr('0'.dechex($nR),-2).
01197 substr('0'.dechex($nG),-2).
01198 substr('0'.dechex($nB),-2);
01199 }
01200
01201
01202
01203
01204
01205
01206
01207
01208
01209
01210 public static function modifyHTMLColorAll($color,$all) {
01211 return self::modifyHTMLColor($color,$all,$all,$all);
01212 }
01213
01214
01215
01216
01217
01218
01219
01220
01221 public static function rm_endcomma($string) {
01222 return rtrim($string, ',');
01223 }
01224
01225
01226
01227
01228
01229
01230
01231
01232
01233
01234 public static function danish_strtoupper($string) {
01235 self::logDeprecatedFunction();
01236
01237 $value = strtoupper($string);
01238 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
01239 }
01240
01241
01242
01243
01244
01245
01246
01247
01248
01249
01250
01251 public static function convUmlauts($str) {
01252 self::logDeprecatedFunction();
01253
01254 $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' );
01255 $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
01256 return preg_replace($pat,$repl,$str);
01257 }
01258
01259
01260
01261
01262
01263
01264
01265
01266 public static function testInt($var) {
01267 return !strcmp($var,intval($var));
01268 }
01269
01270
01271
01272
01273
01274
01275
01276
01277
01278 public static function isFirstPartOfStr($str,$partStr) {
01279
01280 $psLen = strlen($partStr);
01281 if ($psLen) {
01282 return substr($str,0,$psLen)==(string)$partStr;
01283 } else return false;
01284 }
01285
01286
01287
01288
01289
01290
01291
01292
01293
01294 public static function formatSize($sizeInBytes,$labels='') {
01295
01296
01297 if (strlen($labels) == 0) {
01298 $labels = ' | K| M| G';
01299 } else {
01300 $labels = str_replace('"','',$labels);
01301 }
01302 $labelArr = explode('|',$labels);
01303
01304
01305 if ($sizeInBytes>900) {
01306 if ($sizeInBytes>900000000) {
01307 $val = $sizeInBytes/(1024*1024*1024);
01308 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
01309 }
01310 elseif ($sizeInBytes>900000) {
01311 $val = $sizeInBytes/(1024*1024);
01312 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
01313 } else {
01314 $val = $sizeInBytes/(1024);
01315 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
01316 }
01317 } else {
01318 return $sizeInBytes.$labelArr[0];
01319 }
01320 }
01321
01322
01323
01324
01325
01326
01327
01328
01329 public static function convertMicrotime($microtime) {
01330 $parts = explode(' ',$microtime);
01331 return round(($parts[0]+$parts[1])*1000);
01332 }
01333
01334
01335
01336
01337
01338
01339
01340
01341
01342
01343 public static function splitCalc($string,$operators) {
01344 $res = Array();
01345 $sign='+';
01346 while($string) {
01347 $valueLen=strcspn($string,$operators);
01348 $value=substr($string,0,$valueLen);
01349 $res[] = Array($sign,trim($value));
01350 $sign=substr($string,$valueLen,1);
01351 $string=substr($string,$valueLen+1);
01352 }
01353 reset($res);
01354 return $res;
01355 }
01356
01357
01358
01359
01360
01361
01362
01363
01364
01365 public static function calcPriority($string) {
01366 $string=preg_replace('/[[:space:]]*/','',$string);
01367 $string='+'.$string;
01368 $qm='\*\/\+-^%';
01369 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
01370
01371 $reg = array();
01372 preg_match_all('/'.$regex.'/',$string,$reg);
01373
01374 reset($reg[2]);
01375 $number=0;
01376 $Msign='+';
01377 $err='';
01378 $buffer=doubleval(current($reg[2]));
01379 next($reg[2]);
01380
01381 while(list($k,$v)=each($reg[2])) {
01382 $v=doubleval($v);
01383 $sign = $reg[1][$k];
01384 if ($sign=='+' || $sign=='-') {
01385 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01386 $Msign = $sign;
01387 $buffer=$v;
01388 } else {
01389 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
01390 if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
01391 if ($sign=='*') {$buffer*=$v;}
01392 if ($sign=='^') {$buffer=pow($buffer,$v);}
01393 }
01394 }
01395 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01396 return $err ? 'ERROR: '.$err : $number;
01397 }
01398
01399
01400
01401
01402
01403
01404
01405
01406
01407 public static function calcParenthesis($string) {
01408 $securC=100;
01409 do {
01410 $valueLenO=strcspn($string,'(');
01411 $valueLenC=strcspn($string,')');
01412 if ($valueLenC==strlen($string) || $valueLenC < $valueLenO) {
01413 $value = self::calcPriority(substr($string,0,$valueLenC));
01414 $string = $value.substr($string,$valueLenC+1);
01415 return $string;
01416 } else {
01417 $string = substr($string,0,$valueLenO).self::calcParenthesis(substr($string,$valueLenO+1));
01418 }
01419
01420 $securC--;
01421 if ($securC<=0) break;
01422 } while($valueLenO<strlen($string));
01423 return $string;
01424 }
01425
01426
01427
01428
01429
01430
01431
01432
01433 public static function htmlspecialchars_decode($value) {
01434 $value = str_replace('>','>',$value);
01435 $value = str_replace('<','<',$value);
01436 $value = str_replace('"','"',$value);
01437 $value = str_replace('&','&',$value);
01438 return $value;
01439 }
01440
01441
01442
01443
01444
01445
01446
01447
01448 public static function deHSCentities($str) {
01449 return preg_replace('/&([#[:alnum:]]*;)/','&\1',$str);
01450 }
01451
01452
01453
01454
01455
01456
01457
01458
01459
01460
01461 public static function slashJS($string,$extended=0,$char="'") {
01462 if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
01463 return str_replace ($char, "\\".$char, $string);
01464 }
01465
01466
01467
01468
01469
01470
01471
01472
01473
01474 public static function rawUrlEncodeJS($str) {
01475 return str_replace('%20',' ',rawurlencode($str));
01476 }
01477
01478
01479
01480
01481
01482
01483
01484
01485
01486 public static function rawUrlEncodeFP($str) {
01487 return str_replace('%2F','/',rawurlencode($str));
01488 }
01489
01490
01491
01492
01493
01494
01495
01496
01497 public static function validEmail($email) {
01498 return (filter_var($email, FILTER_VALIDATE_EMAIL) !== false);
01499 }
01500
01501
01502
01503
01504
01505
01506
01507
01508
01509
01510
01511
01512
01513 public static function isBrokenEmailEnvironment() {
01514 return TYPO3_OS == 'WIN' || (false !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
01515 }
01516
01517
01518
01519
01520
01521
01522
01523
01524 public static function normalizeMailAddress($address) {
01525 if (self::isBrokenEmailEnvironment() && false !== ($pos1 = strrpos($address, '<'))) {
01526 $pos2 = strpos($address, '>', $pos1);
01527 $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
01528 }
01529 return $address;
01530 }
01531
01532
01533
01534
01535
01536
01537
01538
01539
01540
01541 public static function formatForTextarea($content) {
01542 return LF.htmlspecialchars($content);
01543 }
01544
01545
01546
01547
01548
01549
01550
01551
01552
01553
01554 public static function strtoupper($str) {
01555 return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
01556 }
01557
01558
01559
01560
01561
01562
01563
01564
01565
01566
01567 public static function strtolower($str) {
01568 return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
01569 }
01570
01571
01572
01573
01574
01575
01576
01577
01578
01579 public static function generateRandomBytes($count) {
01580 $output = '';
01581 // /dev/urandom is available on many *nix systems and is considered
01582 // the best commonly available pseudo-random source.
01583 if (TYPO3_OS != 'WIN' && ($fh = @fopen('/dev/urandom', 'rb'))) {
01584 $output = fread($fh, $count);
01585 fclose($fh);
01586 }
01587
01588 // fallback if /dev/urandom is not available
01589 if (!isset($output{$count - 1})) {
01590 // We initialize with the somewhat random.
01591 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
01592 . microtime() . getmypid();
01593 while (!isset($output{$count - 1})) {
01594 $randomState = md5(microtime() . mt_rand() . $randomState);
01595 $output .= md5(mt_rand() . $randomState, true);
01596 }
01597 $output = substr($output, strlen($output) - $count, $count);
01598 }
01599 return $output;
01600 }
01601
01602
01603
01604
01605
01606
01607
01608
01609 public static function underscoredToUpperCamelCase($string) {
01610 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
01611 return $upperCamelCase;
01612 }
01613
01614
01615
01616
01617
01618
01619
01620
01621 public static function underscoredToLowerCamelCase($string) {
01622 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
01623 $lowerCamelCase = self::lcfirst($upperCamelCase);
01624 return $lowerCamelCase;
01625 }
01626
01627
01628
01629
01630
01631
01632
01633
01634 public static function camelCaseToLowerCaseUnderscored($string) {
01635 return self::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
01636 }
01637
01638
01639
01640
01641
01642
01643
01644
01645 public static function lcfirst($string) {
01646 return self::strtolower(substr($string, 0, 1)) . substr($string, 1);
01647 }
01648
01649
01650
01651
01652
01653
01654
01655 public static function isValidUrl($url) {
01656 return (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== false);
01657 }
01658
01659
01660
01661
01662
01663
01664
01665
01666
01667
01668 /*************************
01669 *
01670 * ARRAY FUNCTIONS
01671 *
01672 *************************/
01673
01674
01675
01676
01677
01678
01679
01680
01681
01682
01683
01684
01685
01686
01687
01688
01689
01690
01691
01692
01693
01694
01695
01696
01697 public static function inArray(array $in_array, $item) {
01698 foreach ($in_array as $val) {
01699 if (!is_array($val) && !strcmp($val, $item)) {
01700 return true;
01701 }
01702 }
01703 return false;
01704 }
01705
01706
01707
01708
01709
01710
01711
01712
01713
01714
01715
01716
01717
01718
01719 public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
01720 $explodedValues = self::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
01721 return array_map('intval', $explodedValues);
01722 }
01723
01724
01725
01726
01727
01728
01729
01730
01731
01732
01733
01734 public static function revExplode($delimiter, $string, $count=0) {
01735 $explodedValues = explode($delimiter, strrev($string), $count);
01736 $explodedValues = array_map('strrev', $explodedValues);
01737 return array_reverse($explodedValues);
01738 }
01739
01740
01741
01742
01743
01744
01745
01746
01747
01748
01749
01750
01751
01752
01753
01754
01755
01756 public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0) {
01757 $explodedValues = explode($delim, $string);
01758
01759 $result = array_map('trim', $explodedValues);
01760
01761 if ($removeEmptyValues) {
01762 $temp = array();
01763 foreach($result as $value) {
01764 if ($value !== '') {
01765 $temp[] = $value;
01766 }
01767 }
01768 $result = $temp;
01769 }
01770
01771 if ($limit != 0) {
01772 if ($limit < 0) {
01773 $result = array_slice($result, 0, $limit);
01774 } elseif (count($result) > $limit) {
01775 $lastElements = array_slice($result, $limit - 1);
01776 $result = array_slice($result, 0, $limit - 1);
01777 $result[] = implode($delim, $lastElements);
01778 }
01779 }
01780
01781 return $result;
01782 }
01783
01784
01785
01786
01787
01788
01789
01790
01791
01792
01793 public static function uniqueArray(array $valueArray) {
01794 self::logDeprecatedFunction();
01795
01796 return array_unique($valueArray);
01797 }
01798
01799
01800
01801
01802
01803
01804
01805
01806
01807 public static function removeArrayEntryByValue(array $array, $cmpValue) {
01808 foreach ($array as $k => $v) {
01809 if (is_array($v)) {
01810 $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
01811 } elseif (!strcmp($v, $cmpValue)) {
01812 unset($array[$k]);
01813 }
01814 }
01815 return $array;
01816 }
01817
01818
01819
01820
01821
01822
01823
01824
01825
01826
01827
01828
01829
01830
01831
01832
01833
01834
01835
01836
01837
01838
01839
01840
01841 public static function keepItemsInArray(array $array, $keepItems, $getValueFunc=null) {
01842 if ($array) {
01843 // Convert strings to arrays:
01844 if (is_string($keepItems)) {
01845 $keepItems = self::trimExplode(',', $keepItems);
01846 }
01847 // create_function() returns a string:
01848 if (!is_string($getValueFunc)) {
01849 $getValueFunc = null;
01850 }
01851 // Do the filtering:
01852 if (is_array($keepItems) && count($keepItems)) {
01853 foreach ($array as $key => $value) {
01854 // Get the value to compare by using the callback function:
01855 $keepValue = (isset($getValueFunc) ? $getValueFunc($value) : $value);
01856 if (!in_array($keepValue, $keepItems)) {
01857 unset($array[$key]);
01858 }
01859 }
01860 }
01861 }
01862 return $array;
01863 }
01864
01865
01866
01867
01868
01869
01870
01871
01872
01873
01874
01875
01876
01877 public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false) {
01878 foreach($theArray as $Akey => $AVal) {
01879 $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
01880 if (is_array($AVal)) {
01881 $str = self::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
01882 } else {
01883 if (!$skipBlank || strcmp($AVal,'')) {
01884 $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
01885 '='.rawurlencode($AVal);
01886 }
01887 }
01888 }
01889 return $str;
01890 }
01891
01892
01893
01894
01895
01896
01897
01898
01899
01900 public static function explodeUrl2Array($string,$multidim=FALSE) {
01901 $output = array();
01902 if ($multidim) {
01903 parse_str($string,$output);
01904 } else {
01905 $p = explode('&',$string);
01906 foreach($p as $v) {
01907 if (strlen($v)) {
01908 list($pK,$pV) = explode('=',$v,2);
01909 $output[rawurldecode($pK)] = rawurldecode($pV);
01910 }
01911 }
01912 }
01913 return $output;
01914 }
01915
01916
01917
01918
01919
01920
01921
01922
01923
01924
01925
01926 public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1) {
01927 $keys = self::trimExplode(',',$varList,1);
01928 $outArr = array();
01929 foreach($keys as $v) {
01930 if (isset($getArray[$v])) {
01931 $outArr[$v] = $getArray[$v];
01932 } elseif ($GPvarAlt) {
01933 $outArr[$v] = self::_GP($v);
01934 }
01935 }
01936 return $outArr;
01937 }
01938
01939
01940
01941
01942
01943
01944
01945
01946
01947
01948
01949 public static function addSlashesOnArray(array &$theArray) {
01950 foreach ($theArray as &$value) {
01951 if (is_array($value)) {
01952 self::addSlashesOnArray($value);
01953 } else {
01954 $value = addslashes($value);
01955 }
01956 unset($value);
01957 }
01958 reset($theArray);
01959 }
01960
01961
01962
01963
01964
01965
01966
01967
01968
01969
01970
01971 public static function stripSlashesOnArray(array &$theArray) {
01972 foreach ($theArray as &$value) {
01973 if (is_array($value)) {
01974 self::stripSlashesOnArray($value);
01975 } else {
01976 $value = stripslashes($value);
01977 }
01978 unset($value);
01979 }
01980 reset($theArray);
01981 }
01982
01983
01984
01985
01986
01987
01988
01989
01990
01991 public static function slashArray(array $arr,$cmd) {
01992 if ($cmd=='strip') self::stripSlashesOnArray($arr);
01993 if ($cmd=='add') self::addSlashesOnArray($arr);
01994 return $arr;
01995 }
01996
01997
01998
01999
02000
02001
02002 function remapArrayKeys(&$array, $mappingTable) {
02003 if (is_array($mappingTable)) {
02004 foreach ($mappingTable as $old => $new) {
02005 if ($new && isset($array[$old])) {
02006 $array[$new] = $array[$old];
02007 unset ($array[$old]);
02008 }
02009 }
02010 }
02011 }
02012
02013
02014
02015
02016
02017
02018
02019
02020
02021
02022
02023
02024
02025
02026
02027 public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) {
02028 foreach ($arr1 as $key => $val) {
02029 if(is_array($arr0[$key])) {
02030 if (is_array($arr1[$key])) {
02031 $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
02032 }
02033 } else {
02034 if ($notAddKeys) {
02035 if (isset($arr0[$key])) {
02036 if ($includeEmtpyValues || $val) {
02037 $arr0[$key] = $val;
02038 }
02039 }
02040 } else {
02041 if ($includeEmtpyValues || $val) {
02042 $arr0[$key] = $val;
02043 }
02044 }
02045 }
02046 }
02047 reset($arr0);
02048 return $arr0;
02049 }
02050
02051
02052
02053
02054
02055
02056
02057
02058
02059 public static function array_merge(array $arr1,array $arr2) {
02060 return $arr2+$arr1;
02061 }
02062
02063
02064
02065
02066
02067
02068
02069
02070
02071 public static function arrayDiffAssocRecursive(array $array1, array $array2) {
02072 $differenceArray = array();
02073 foreach ($array1 as $key => $value) {
02074 if (!array_key_exists($key, $array2)) {
02075 $differenceArray[$key] = $value;
02076 } elseif (is_array($value)) {
02077 if (is_array($array2[$key])) {
02078 $differenceArray[$key] = self::arrayDiffAssocRecursive($value, $array2[$key]);
02079 }
02080 }
02081 }
02082
02083 return $differenceArray;
02084 }
02085
02086
02087
02088
02089
02090
02091
02092
02093
02094
02095 public static function csvValues(array $row,$delim=',',$quote='"') {
02096 reset($row);
02097 $out=array();
02098 foreach ($row as $value) {
02099 $out[] = str_replace($quote, $quote.$quote, $value);
02100 }
02101 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
02102 return $str;
02103 }
02104
02105
02106
02107
02108
02109
02110
02111
02112
02113 public static function array2json(array $jsonArray) {
02114 self::logDeprecatedFunction();
02115
02116 return json_encode($jsonArray);
02117 }
02118
02119
02120
02121
02122
02123
02124
02125
02126 public static function removeDotsFromTS(array $ts) {
02127 $out = array();
02128 foreach ($ts as $key => $value) {
02129 if (is_array($value)) {
02130 $key = rtrim($key, '.');
02131 $out[$key] = self::removeDotsFromTS($value);
02132 } else {
02133 $out[$key] = $value;
02134 }
02135 }
02136 return $out;
02137 }
02138
02139
02140
02141
02142
02143
02144
02145
02146
02147
02148
02149
02150
02151
02152
02153
02154
02155
02156
02157
02158
02159
02160
02161
02162
02163
02164
02165
02166
02167
02168
02169 public static function get_tag_attributes($tag) {
02170 $components = self::split_tag_attributes($tag);
02171 $name = '';
02172 $valuemode = false;
02173 $attributes = array();
02174 foreach ($components as $key => $val) {
02175 if ($val != '=') {
02176 if ($valuemode) {
02177 if ($name) {
02178 $attributes[$name] = $val;
02179 $name = '';
02180 }
02181 } else {
02182 if ($key = strtolower(preg_replace('/[^a-zA-Z0-9]/','',$val))) {
02183 $attributes[$key] = '';
02184 $name = $key;
02185 }
02186 }
02187 $valuemode = false;
02188 } else {
02189 $valuemode = true;
02190 }
02191 }
02192 return $attributes;
02193 }
02194
02195
02196
02197
02198
02199
02200
02201
02202
02203 public static function split_tag_attributes($tag) {
02204 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/','',trim($tag)));
02205
02206 $tag_tmp = trim(rtrim($tag_tmp, '>'));
02207
02208 $value = array();
02209 while (strcmp($tag_tmp,'')) {
02210 $firstChar=substr($tag_tmp,0,1);
02211 if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
02212 $reg=explode($firstChar,$tag_tmp,3);
02213 $value[]=$reg[1];
02214 $tag_tmp=trim($reg[2]);
02215 } elseif (!strcmp($firstChar,'=')) {
02216 $value[] = '=';
02217 $tag_tmp = trim(substr($tag_tmp,1));
02218 } else {
02219
02220 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
02221 $value[] = trim($reg[0]);
02222 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
02223 }
02224 }
02225 reset($value);
02226 return $value;
02227 }
02228
02229
02230
02231
02232
02233
02234
02235
02236
02237
02238 public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
02239 if ($xhtmlSafe) {
02240 $newArr=array();
02241 foreach($arr as $p => $v) {
02242 if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
02243 }
02244 $arr = $newArr;
02245 }
02246 $list = array();
02247 foreach($arr as $p => $v) {
02248 if (strcmp($v,'') || $dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
02249 }
02250 return implode(' ',$list);
02251 }
02252
02253
02254
02255
02256
02257
02258
02259
02260
02261
02262
02263 public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
02264 self::logDeprecatedFunction();
02265
02266 return self::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
02267 }
02268
02269
02270
02271
02272
02273
02274
02275
02276
02277
02278
02279
02280 public static function wrapJS($string, $linebreak=TRUE) {
02281 if(trim($string)) {
02282
02283 $cr = $linebreak? LF : '';
02284
02285
02286 $string = preg_replace ('/^\n+/', '', $string);
02287
02288 $match = array();
02289 if(preg_match('/^(\t+)/',$string,$match)) {
02290 $string = str_replace($match[1],TAB, $string);
02291 }
02292 $string = $cr.'<script type="text/javascript">
02293
02294 '.$string.'
02295
02296 </script>'.$cr;
02297 }
02298 return trim($string);
02299 }
02300
02301
02302
02303
02304
02305
02306
02307
02308
02309
02310
02311 public static function xml2tree($string,$depth=999) {
02312 $parser = xml_parser_create();
02313 $vals = array();
02314 $index = array();
02315
02316 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
02317 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
02318 xml_parse_into_struct($parser, $string, $vals, $index);
02319
02320 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
02321 xml_parser_free($parser);
02322
02323 $stack = array( array() );
02324 $stacktop = 0;
02325 $startPoint=0;
02326
02327
02328 unset($tagi);
02329 foreach($vals as $key => $val) {
02330 $type = $val['type'];
02331
02332
02333 if ($type=='open' || $type=='complete') {
02334 $stack[$stacktop++] = $tagi;
02335
02336 if ($depth==$stacktop) {
02337 $startPoint=$key;
02338 }
02339
02340 $tagi = array('tag' => $val['tag']);
02341
02342 if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
02343 if(isset($val['value'])) $tagi['values'][] = $val['value'];
02344 }
02345
02346 if ($type=='complete' || $type=='close') {
02347 $oldtagi = $tagi;
02348 $tagi = $stack[--$stacktop];
02349 $oldtag = $oldtagi['tag'];
02350 unset($oldtagi['tag']);
02351
02352 if ($depth==($stacktop+1)) {
02353 if ($key-$startPoint > 0) {
02354 $partArray = array_slice(
02355 $vals,
02356 $startPoint+1,
02357 $key-$startPoint-1
02358 );
02359 #$oldtagi=array('XMLvalue'=>self::xmlRecompileFromStructValArray($partArray));
02360 $oldtagi['XMLvalue']=self::xmlRecompileFromStructValArray($partArray);
02361 } else {
02362 $oldtagi['XMLvalue']=$oldtagi['values'][0];
02363 }
02364 }
02365
02366 $tagi['ch'][$oldtag][] = $oldtagi;
02367 unset($oldtagi);
02368 }
02369
02370 if($type=='cdata') {
02371 $tagi['values'][] = $val['value'];
02372 }
02373 }
02374 return $tagi['ch'];
02375 }
02376
02377
02378
02379
02380
02381
02382
02383
02384
02385
02386
02387 public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') {
02388
02389
02390 if (!$charset) {
02391 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
02392 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
02393 } elseif (is_object($GLOBALS['LANG'])) {
02394 $charset = $GLOBALS['LANG']->charSet;
02395 } else {
02396 $charset = 'iso-8859-1';
02397 }
02398 }
02399
02400
02401 return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.LF.
02402 self::array2xml($array,'',0,$docTag,0, $options);
02403 }
02404
02405
02406
02407
02408
02409
02410
02411
02412
02413
02414
02415
02416
02417
02418
02419
02420
02421
02422
02423
02424
02425
02426
02427
02428 public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array()) {
02429
02430 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
02431 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
02432 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
02433 chr(30).chr(31);
02434
02435 $indentChar = $spaceInd ? ' ' : TAB;
02436 $indentN = $spaceInd>0 ? $spaceInd : 1;
02437 $nl = ($spaceInd >= 0 ? LF : '');
02438
02439
02440 $output='';
02441
02442
02443 foreach($array as $k=>$v) {
02444 $attr = '';
02445 $tagName = $k;
02446
02447
02448 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) {
02449 $attr.=' index="'.htmlspecialchars($tagName).'"';
02450 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
02451 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && self::testInt($tagName)) {
02452 $attr.=' index="'.htmlspecialchars($tagName).'"';
02453 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
02454 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) {
02455 $attr.=' index="'.htmlspecialchars($tagName).'"';
02456 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
02457 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) {
02458 $attr.=' index="'.htmlspecialchars($tagName).'"';
02459 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
02460 } elseif (!strcmp(intval($tagName),$tagName)) {
02461 if ($options['useNindex']) {
02462 $tagName = 'n'.$tagName;
02463 } else {
02464 $attr.=' index="'.$tagName.'"';
02465 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
02466 }
02467 } elseif($options['useIndexTagForAssoc']) {
02468 $attr.=' index="'.htmlspecialchars($tagName).'"';
02469 $tagName = $options['useIndexTagForAssoc'];
02470 }
02471
02472
02473 $tagName = substr(preg_replace('/[^[:alnum:]_-]/','',$tagName),0,100);
02474
02475
02476 if (is_array($v)) {
02477
02478
02479 if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
02480 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
02481 $clearStackPath = $subOptions['clearStackPath'];
02482 } else {
02483 $subOptions = $options;
02484 $clearStackPath = FALSE;
02485 }
02486
02487 $content = $nl .
02488 self::array2xml(
02489 $v,
02490 $NSprefix,
02491 $level+1,
02492 '',
02493 $spaceInd,
02494 $subOptions,
02495 array(
02496 'parentTagName' => $tagName,
02497 'grandParentTagName' => $stackData['parentTagName'],
02498 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
02499 )
02500 ).
02501 ($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '');
02502 if ((int)$options['disableTypeAttrib']!=2) {
02503 $attr.=' type="array"';
02504 }
02505 } else {
02506
02507
02508 $vLen = strlen($v);
02509 if ($vLen && strcspn($v,$binaryChars) != $vLen) {
02510
02511 $content = $nl.chunk_split(base64_encode($v));
02512 $attr.=' base64="1"';
02513 } else {
02514
02515 $content = htmlspecialchars($v);
02516 $dType = gettype($v);
02517 if ($dType == 'string') {
02518 if ($options['useCDATA'] && $content != $v) {
02519 $content = '<![CDATA[' . $v . ']]>';
02520 }
02521 } elseif (!$options['disableTypeAttrib']) {
02522 $attr.= ' type="'.$dType.'"';
02523 }
02524 }
02525 }
02526
02527
02528 $output.=($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
02529 }
02530
02531
02532 if (!$level) {
02533 $output =
02534 '<'.$docTag.'>'.$nl.
02535 $output.
02536 '</'.$docTag.'>';
02537 }
02538
02539 return $output;
02540 }
02541
02542
02543
02544
02545
02546
02547
02548
02549
02550
02551
02552
02553
02554
02555 public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
02556 static $firstLevelCache = array();
02557
02558 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
02559
02560
02561 if (!empty($firstLevelCache[$identifier])) {
02562 $array = $firstLevelCache[$identifier];
02563 } else {
02564
02565 $cacheContent = t3lib_pageSelect::getHash($identifier, 0);
02566 $array = unserialize($cacheContent);
02567
02568 if ($array === false) {
02569 $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
02570 t3lib_pageSelect::storeHash($identifier, serialize($array), 'ident_xml2array');
02571 }
02572
02573 $firstLevelCache[$identifier] = $array;
02574 }
02575 return $array;
02576 }
02577
02578
02579
02580
02581
02582
02583
02584
02585
02586
02587
02588
02589 protected function xml2arrayProcess($string,$NSprefix='',$reportDocTag=FALSE) {
02590 global $TYPO3_CONF_VARS;
02591
02592
02593 $parser = xml_parser_create();
02594 $vals = array();
02595 $index = array();
02596
02597 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
02598 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
02599
02600
02601 $match = array();
02602 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
02603 $theCharset = $match[1] ? $match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
02604 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
02605
02606 // Parse content:
02607 xml_parse_into_struct($parser, $string, $vals, $index);
02608
02609 // If error, return error message:
02610 if (xml_get_error_code($parser)) {
02611 return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
02612 }
02613 xml_parser_free($parser);
02614
02615 // Init vars:
02616 $stack = array(array());
02617 $stacktop = 0;
02618 $current = array();
02619 $tagName = '';
02620 $documentTag = '';
02621
02622 // Traverse the parsed XML structure:
02623 foreach($vals as $key => $val) {
02624
02625 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
02626 $tagName = $val['tag'];
02627 if (!$documentTag) $documentTag = $tagName;
02628
02629 // Test for name space:
02630 $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
02631
02632 // Test for numeric tag, encoded on the form "nXXX":
02633 $testNtag = substr($tagName,1); // Closing tag.
02634 $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
02635
02636 // Test for alternative index value:
02637 if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
02638
02639 // Setting tag-values, manage stack:
02640 switch($val['type']) {
02641 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
02642 $current[$tagName] = array(); // Setting blank place holder
02643 $stack[$stacktop++] = $current;
02644 $current = array();
02645 break;
02646 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
02647 $oldCurrent = $current;
02648 $current = $stack[--$stacktop];
02649 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
02650 $current[key($current)] = $oldCurrent;
02651 unset($oldCurrent);
02652 break;
02653 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
02654 if ($val['attributes']['base64']) {
02655 $current[$tagName] = base64_decode($val['value']);
02656 } else {
02657 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
02658
02659 // Cast type:
02660 switch((string)$val['attributes']['type']) {
02661 case 'integer':
02662 $current[$tagName] = (integer)$current[$tagName];
02663 break;
02664 case 'double':
02665 $current[$tagName] = (double)$current[$tagName];
02666 break;
02667 case 'boolean':
02668 $current[$tagName] = (bool)$current[$tagName];
02669 break;
02670 case 'array':
02671 $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...
02672 break;
02673 }
02674 }
02675 break;
02676 }
02677 }
02678
02679 if ($reportDocTag) {
02680 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
02681 }
02682
02683 // Finally return the content of the document tag.
02684 return $current[$tagName];
02685 }
02686
02687
02688
02689
02690
02691
02692
02693
02694 public static function xmlRecompileFromStructValArray(array $vals) {
02695 $XMLcontent='';
02696
02697 foreach($vals as $val) {
02698 $type = $val['type'];
02699
02700 // open tag:
02701 if ($type=='open' || $type=='complete') {
02702 $XMLcontent.='<'.$val['tag'];
02703 if(isset($val['attributes'])) {
02704 foreach($val['attributes'] as $k => $v) {
02705 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
02706 }
02707 }
02708 if ($type=='complete') {
02709 if(isset($val['value'])) {
02710 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
02711 } else $XMLcontent.='/>';
02712 } else $XMLcontent.='>';
02713
02714 if ($type=='open' && isset($val['value'])) {
02715 $XMLcontent.=htmlspecialchars($val['value']);
02716 }
02717 }
02718
02719 if ($type=='close') {
02720 $XMLcontent.='</'.$val['tag'].'>';
02721 }
02722
02723 if($type=='cdata') {
02724 $XMLcontent.=htmlspecialchars($val['value']);
02725 }
02726 }
02727
02728 return $XMLcontent;
02729 }
02730
02731
02732
02733
02734
02735
02736
02737
02738 public static function xmlGetHeaderAttribs($xmlData) {
02739 $match = array();
02740 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
02741 return self::get_tag_attributes($match[1]);
02742 }
02743 }
02744
02745
02746
02747
02748
02749
02750
02751
02752 public static function minifyJavaScript($script, &$error = '') {
02753 require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
02754 try {
02755 $error = '';
02756 $script = trim(JSMin::minify(str_replace(CR, '', $script)));
02757 }
02758 catch(JSMinException $e) {
02759 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
02760 self::devLog($error, 't3lib_div', 2,
02761 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
02762 }
02763 return $script;
02764 }
02765
02766
02767
02768
02769
02770
02771
02772
02773
02774
02775
02776
02777
02778
02779
02780
02781
02782
02783
02784
02785
02786
02787
02788
02789
02790 public static function getURL($url, $includeHeader = 0, $requestHeaders = false, &$report = NULL) {
02791 $content = false;
02792
02793 if (isset($report)) {
02794 $report['error'] = 0;
02795 $report['message'] = '';
02796 }
02797
02798
02799 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
02800 if (isset($report)) {
02801 $report['lib'] = 'cURL';
02802 }
02803
02804
02805 $ch = curl_init();
02806 if (!$ch) {
02807 if (isset($report)) {
02808 $report['error'] = -1;
02809 $report['message'] = 'Couldn\'t initialize cURL.';
02810 }
02811 return false;
02812 }
02813
02814 curl_setopt($ch, CURLOPT_URL, $url);
02815 curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
02816 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
02817 curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
02818 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
02819 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
02820 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout'])));
02821
02822
02823 $followLocation = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
02824
02825 if (is_array($requestHeaders)) {
02826 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
02827 }
02828
02829
02830 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
02831 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
02832
02833 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
02834 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
02835 }
02836 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
02837 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
02838 }
02839 }
02840 $content = curl_exec($ch);
02841 if (isset($report)) {
02842 if ($content===FALSE) {
02843 $report['error'] = curl_errno($ch);
02844 $report['message'] = curl_error($ch);
02845 } else {
02846 $curlInfo = curl_getinfo($ch);
02847
02848 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
02849 $report['error'] = -1;
02850 $report['message'] = 'Couldn\'t follow location redirect (either PHP configuration option safe_mode or open_basedir is in effect).';
02851 } elseif($includeHeader) {
02852
02853 $report['http_code'] = $curlInfo['http_code'];
02854 $report['content_type'] = $curlInfo['content_type'];
02855 }
02856 }
02857 }
02858 curl_close($ch);
02859
02860 } elseif ($includeHeader) {
02861 if (isset($report)) {
02862 $report['lib'] = 'socket';
02863 }
02864 $parsedURL = parse_url($url);
02865 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
02866 if (isset($report)) {
02867 $report['error'] = -1;
02868 $report['message'] = 'Reading headers is not allowed for this protocol.';
02869 }
02870 return false;
02871 }
02872 $port = intval($parsedURL['port']);
02873 if ($port < 1) {
02874 if ($parsedURL['scheme'] == 'http') {
02875 $port = ($port>0 ? $port : 80);
02876 $scheme = '';
02877 } else {
02878 $port = ($port>0 ? $port : 443);
02879 $scheme = 'ssl:
02880 }
02881 }
02882 $errno = 0;
02883
02884 $fp = @fsockopen($scheme.$parsedURL['host'], $port, $errno, $errstr, 2.0);
02885 if (!$fp || $errno > 0) {
02886 if (isset($report)) {
02887 $report['error'] = $errno ? $errno : -1;
02888 $report['message'] = $errno ? ($errstr ? $errstr : 'Socket error.') : 'Socket initialization error.';
02889 }
02890 return false;
02891 }
02892 $method = ($includeHeader == 2) ? 'HEAD' : 'GET';
02893 $msg = $method . ' ' . $parsedURL['path'] .
02894 ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
02895 ' HTTP/1.0' . CRLF . 'Host: ' .
02896 $parsedURL['host'] . "\r\nConnection: close\r\n";
02897 if (is_array($requestHeaders)) {
02898 $msg .= implode(CRLF, $requestHeaders) . CRLF;
02899 }
02900 $msg .= CRLF;
02901
02902 fputs($fp, $msg);
02903 while (!feof($fp)) {
02904 $line = fgets($fp, 2048);
02905 if (isset($report)) {
02906 if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
02907 $report['http_code'] = $status[1];
02908 }
02909 elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
02910 $report['content_type'] = $type[1];
02911 }
02912 }
02913 $content .= $line;
02914 if (!strlen(trim($line))) {
02915 break;
02916 }
02917 }
02918 if ($includeHeader != 2) {
02919 $content .= stream_get_contents($fp);
02920 }
02921 fclose($fp);
02922
02923 } elseif (is_array($requestHeaders)) {
02924 if (isset($report)) {
02925 $report['lib'] = 'file/context';
02926 }
02927 $parsedURL = parse_url($url);
02928 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
02929 if (isset($report)) {
02930 $report['error'] = -1;
02931 $report['message'] = 'Sending request headers is not allowed for this protocol.';
02932 }
02933 return false;
02934 }
02935 $ctx = stream_context_create(array(
02936 'http' => array(
02937 'header' => implode(CRLF, $requestHeaders)
02938 )
02939 )
02940 );
02941 $content = @file_get_contents($url, false, $ctx);
02942 if ($content === false && isset($report)) {
02943 $phpError = error_get_last();
02944 $report['error'] = $phpError['type'];
02945 $report['message'] = $phpError['message'];
02946 }
02947 } else {
02948 if (isset($report)) {
02949 $report['lib'] = 'file';
02950 }
02951 $content = @file_get_contents($url);
02952 if ($content === false && isset($report)) {
02953 if (function_exists('error_get_last')) {
02954 $phpError = error_get_last();
02955 $report['error'] = $phpError['type'];
02956 $report['message'] = $phpError['message'];
02957 } else {
02958 $report['error'] = -1;
02959 $report['message'] = 'Couldn\'t get URL.';
02960 }
02961 }
02962 }
02963
02964 return $content;
02965 }
02966
02967
02968
02969
02970
02971
02972
02973
02974
02975 public static function writeFile($file,$content) {
02976 if (!@is_file($file)) $changePermissions = true;
02977
02978 if ($fd = fopen($file,'wb')) {
02979 $res = fwrite($fd,$content);
02980 fclose($fd);
02981
02982 if ($res===false) return false;
02983
02984 if ($changePermissions) {
02985 self::fixPermissions($file);
02986 }
02987
02988 return true;
02989 }
02990
02991 return false;
02992 }
02993
02994
02995
02996
02997
02998
02999
03000
03001 public static function fixPermissions($path, $recursive = FALSE) {
03002 if (TYPO3_OS != 'WIN') {
03003 $result = FALSE;
03004 if (self::isAllowedAbsPath($path)) {
03005 if (@is_file($path)) {
03006
03007 $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
03008 } elseif (@is_dir($path)) {
03009 $path = preg_replace('|/$|', '', $path);
03010
03011 $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
03012 }
03013
03014
03015 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
03016
03017 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
03018 $result = $changeGroupResult ? $result : FALSE;
03019 }
03020
03021
03022 if ($recursive && @is_dir($path)) {
03023 $handle = opendir($path);
03024 while (($file = readdir($handle)) !== FALSE) {
03025 unset($recursionResult);
03026 if ($file !== '.' && $file !== '..') {
03027 if (@is_file($path . '/' . $file)) {
03028 $recursionResult = self::fixPermissions($path . '/' . $file);
03029 } elseif (@is_dir($path . '/' . $file)) {
03030 $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
03031 }
03032 if (isset($recursionResult) && !$recursionResult) {
03033 $result = FALSE;
03034 }
03035 }
03036 }
03037 closedir($handle);
03038 }
03039 }
03040 } else {
03041 $result = TRUE;
03042 }
03043 return $result;
03044 }
03045
03046
03047
03048
03049
03050
03051
03052
03053
03054 public static function writeFileToTypo3tempDir($filepath,$content) {
03055
03056
03057 $fI = pathinfo($filepath);
03058 $fI['dirname'].= '/';
03059
03060
03061 if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
03062 if (defined('PATH_site')) {
03063 $dirName = PATH_site.'typo3temp/';
03064 if (@is_dir($dirName)) {
03065 if (self::isFirstPartOfStr($fI['dirname'],$dirName)) {
03066
03067
03068 $subdir = substr($fI['dirname'],strlen($dirName));
03069 if ($subdir) {
03070 if (preg_match('/^[[:alnum:]_]+\/$/',$subdir) || preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/',$subdir)) {
03071 $dirName.= $subdir;
03072 if (!@is_dir($dirName)) {
03073 self::mkdir_deep(PATH_site.'typo3temp/', $subdir);
03074 }
03075 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
03076 }
03077
03078 if (@is_dir($dirName)) {
03079 if ($filepath == $dirName.$fI['basename']) {
03080 self::writeFile($filepath, $content);
03081 if (!@is_file($filepath)) return 'File not written to disk! Write permission error in filesystem?';
03082 } else return 'Calculated filelocation didn\'t match input $filepath!';
03083 } else return '"'.$dirName.'" is not a directory!';
03084 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
03085 } else return 'PATH_site + "typo3temp/" was not a directory!';
03086 } else return 'PATH_site constant was NOT defined!';
03087 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
03088 }
03089
03090
03091
03092
03093
03094
03095
03096
03097
03098 public static function mkdir($newFolder) {
03099 $newFolder = preg_replace('|/$|', '', $newFolder);
03100 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
03101 if ($result) {
03102 self::fixPermissions($newFolder);
03103 }
03104 return $result;
03105 }
03106
03107
03108
03109
03110
03111
03112
03113
03114 public static function mkdir_deep($destination,$deepDir) {
03115 $allParts = self::trimExplode('/',$deepDir,1);
03116 $root = '';
03117 foreach($allParts as $part) {
03118 $root.= $part.'/';
03119 if (!is_dir($destination.$root)) {
03120 self::mkdir($destination.$root);
03121 if (!@is_dir($destination.$root)) {
03122 return 'Error: The directory "'.$destination.$root.'" could not be created...';
03123 }
03124 }
03125 }
03126 }
03127
03128
03129
03130
03131
03132
03133
03134
03135 public static function rmdir($path,$removeNonEmpty=false) {
03136 $OK = false;
03137 $path = preg_replace('|/$|','',$path); // Remove trailing slash
03138
03139 if (file_exists($path)) {
03140 $OK = true;
03141
03142 if (is_dir($path)) {
03143 if ($removeNonEmpty==true && $handle = opendir($path)) {
03144 while ($OK && false !== ($file = readdir($handle))) {
03145 if ($file=='.' || $file=='..') continue;
03146 $OK = self::rmdir($path.'/'.$file,$removeNonEmpty);
03147 }
03148 closedir($handle);
03149 }
03150 if ($OK) { $OK = rmdir($path); }
03151
03152 } else { // If $dirname is a file, simply remove it
03153 $OK = unlink($path);
03154 }
03155
03156 clearstatcache();
03157 }
03158
03159 return $OK;
03160 }
03161
03162
03163
03164
03165
03166
03167
03168
03169
03170 public static function get_dirs($path) {
03171 if ($path) {
03172 if (is_dir($path)) {
03173 $dir = scandir($path);
03174 $dirs = array();
03175 foreach ($dir as $entry) {
03176 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
03177 $dirs[] = $entry;
03178 }
03179 }
03180 } else {
03181 $dirs = 'error';
03182 }
03183 }
03184 return $dirs;
03185 }
03186
03187
03188
03189
03190
03191
03192
03193
03194
03195
03196
03197
03198 public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='') {
03199
03200 // Initialize variabels:
03201 $filearray = array();
03202 $sortarray = array();
03203 $path = rtrim($path, '/');
03204
03205 // Find files+directories:
03206 if (@is_dir($path)) {
03207 $extensionList = strtolower($extensionList);
03208 $d = dir($path);
03209 if (is_object($d)) {
03210 while($entry=$d->read()) {
03211 if (@is_file($path.'/'.$entry)) {
03212 $fI = pathinfo($entry);
03213 $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)
03214 if ((!strlen($extensionList) || self::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry))) {
03215 $filearray[$key]=($prependPath?$path.'/':'').$entry;
03216 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
03217 elseif ($order) {$sortarray[$key]=$entry;}
03218 }
03219 }
03220 }
03221 $d->close();
03222 } else return 'error opening path: "'.$path.'"';
03223 }
03224
03225
03226 if ($order) {
03227 asort($sortarray);
03228 $newArr=array();
03229 foreach ($sortarray as $k => $v) {
03230 $newArr[$k]=$filearray[$k];
03231 }
03232 $filearray=$newArr;
03233 }
03234
03235
03236 reset($filearray);
03237 return $filearray;
03238 }
03239
03240
03241
03242
03243
03244
03245
03246
03247
03248
03249
03250
03251
03252 public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='') {
03253 if ($regDirs) $fileArr[] = $path;
03254 $fileArr = array_merge($fileArr, self::getFilesInDir($path,$extList,1,1,$excludePattern));
03255
03256 $dirs = self::get_dirs($path);
03257 if (is_array($dirs) && $recursivityLevels>0) {
03258 foreach ($dirs as $subdirs) {
03259 if ((string)$subdirs!='' && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$subdirs))) {
03260 $fileArr = self::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
03261 }
03262 }
03263 }
03264 return $fileArr;
03265 }
03266
03267
03268
03269
03270
03271
03272
03273
03274
03275 public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) {
03276 foreach ($fileArr as $k => &$absFileRef) {
03277 if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
03278 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
03279 } else {
03280 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
03281 }
03282 }
03283 return $fileArr;
03284 }
03285
03286
03287
03288
03289
03290
03291
03292
03293 public static function fixWindowsFilePath($theFile) {
03294 return str_replace('
03295 }
03296
03297
03298
03299
03300
03301
03302
03303
03304
03305 public static function resolveBackPath($pathStr) {
03306 $parts = explode('/',$pathStr);
03307 $output=array();
03308 $c = 0;
03309 foreach($parts as $pV) {
03310 if ($pV=='..') {
03311 if ($c) {
03312 array_pop($output);
03313 $c--;
03314 } else $output[]=$pV;
03315 } else {
03316 $c++;
03317 $output[]=$pV;
03318 }
03319 }
03320 return implode('/',$output);
03321 }
03322
03323
03324
03325
03326
03327
03328
03329
03330
03331
03332
03333 public static function locationHeaderUrl($path) {
03334 $uI = parse_url($path);
03335 if (substr($path,0,1)=='/') {
03336 $path = self::getIndpEnv('TYPO3_REQUEST_HOST').$path;
03337 } elseif (!$uI['scheme']) {
03338 $path = self::getIndpEnv('TYPO3_REQUEST_DIR').$path;
03339 }
03340 return $path;
03341 }
03342
03343
03344
03345
03346
03347
03348
03349
03350
03351
03352
03353 public static function getMaxUploadFileSize($localLimit = 0) {
03354
03355 $t3Limit = (intval($localLimit > 0 ? $localLimit : $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize']));
03356
03357 $t3Limit = $t3Limit * 1024;
03358
03359
03360 $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
03361
03362 $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
03363
03364
03365 $phpUploadLimit = ($phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit);
03366
03367
03368 return floor($phpUploadLimit < $t3Limit ? $phpUploadLimit : $t3Limit) / 1024;
03369 }
03370
03371
03372
03373
03374
03375
03376
03377 public static function getBytesFromSizeMeasurement($measurement) {
03378 if (stripos($measurement, 'G')) {
03379 $bytes = intval($measurement) * 1024 * 1024 * 1024;
03380 } else if (stripos($measurement, 'M')) {
03381 $bytes = intval($measurement) * 1024 * 1024;
03382 } else if (stripos($measurement, 'K')) {
03383 $bytes = intval($measurement) * 1024;
03384 } else {
03385 $bytes = intval($measurement);
03386 }
03387 return $bytes;
03388 }
03389
03390
03391
03392
03393
03394
03395
03396 public static function getMaximumPathLength() {
03397 $maximumPathLength = 0;
03398
03399 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
03400
03401 if (TYPO3_OS == 'WIN') {
03402
03403 $maximumPathLength = 255;
03404 } else {
03405 $maximumPathLength = 2048;
03406 }
03407 } else {
03408
03409 $maximumPathLength = PHP_MAXPATHLEN;
03410 }
03411
03412 return $maximumPathLength;
03413 }
03414
03415
03416
03417
03418
03419
03420
03421
03422
03423
03424
03425
03426
03427
03428
03429
03430
03431
03432
03433
03434 public static function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
03435 $lookupFile = explode('?', $file);
03436 $path = self::resolveBackPath(self::dirname(PATH_thisScript) .'/'. $lookupFile[0]);
03437
03438 if (TYPO3_MODE == 'FE') {
03439 $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
03440 if ($mode === 'embed') {
03441 $mode = TRUE;
03442 } else if ($mode === 'querystring') {
03443 $mode = FALSE;
03444 } else {
03445 $doNothing = TRUE;
03446 }
03447 } else {
03448 $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
03449 }
03450
03451 if (! file_exists($path) || $doNothing) {
03452
03453 $fullName = $file;
03454
03455 } else if (! $mode || $forceQueryString) {
03456
03457
03458 if ($lookupFile[1]) {
03459 $separator = '&';
03460 } else {
03461 $separator = '?';
03462 }
03463 $fullName = $file . $separator . filemtime($path);
03464
03465 } else {
03466
03467 $name = explode('.', $lookupFile[0]);
03468 $extension = array_pop($name);
03469
03470 array_push($name, filemtime($path), $extension);
03471 $fullName = implode('.', $name);
03472
03473 $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
03474 }
03475
03476 return $fullName;
03477 }
03478
03479
03480
03481
03482
03483
03484
03485
03486
03487
03488
03489
03490
03491
03492
03493
03494
03495
03496
03497
03498
03499
03500
03501 public static function debug_ordvalue($string,$characters=100) {
03502 if(strlen($string) < $characters) $characters = strlen($string);
03503 for ($i=0; $i<$characters; $i++) {
03504 $valuestring.=' '.ord(substr($string,$i,1));
03505 }
03506 return trim($valuestring);
03507 }
03508
03509
03510
03511
03512
03513
03514
03515
03516
03517
03518 public static function view_array($array_in) {
03519 if (is_array($array_in)) {
03520 $result='
03521 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
03522 if (count($array_in) == 0) {
03523 $result.= '<tr><td><font face="Verdana,Arial" size="1"><strong>EMPTY!</strong></font></td></tr>';
03524 } else {
03525 foreach ($array_in as $key => $val) {
03526 $result.= '<tr>
03527 <td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td>
03528 <td>';
03529 if (is_array($val)) {
03530 $result.=self::view_array($val);
03531 } elseif (is_object($val)) {
03532 $string = get_class($val);
03533 if (method_exists($val, '__toString')) {
03534 $string .= ': '.(string)$val;
03535 }
03536 $result .= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
03537 } else {
03538 if (gettype($val) == 'object') {
03539 $string = 'Unknown object';
03540 } else {
03541 $string = (string)$val;
03542 }
03543 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
03544 }
03545 $result.= '</td>
03546 </tr>';
03547 }
03548 }
03549 $result.= '</table>';
03550 } else {
03551 $result = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
03552 <tr>
03553 <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
03554 </tr>
03555 </table>';
03556 }
03557 return $result;
03558 }
03559
03560
03561
03562
03563
03564
03565
03566
03567
03568 public static function print_array($array_in) {
03569 echo self::view_array($array_in);
03570 }
03571
03572
03573
03574
03575
03576
03577
03578
03579
03580
03581
03582
03583
03584 public static function debug($var = '', $header = '', $group = 'Debug') {
03585
03586 if (ob_get_level()==0) {
03587 ob_start();
03588 }
03589 $debug = '';
03590
03591 if ($header) {
03592 $debug .= '
03593 <table class="typo3-debug" border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;">
03594 <tr>
03595 <td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">' .
03596 htmlspecialchars((string) $header) .
03597 '</td>
03598 </tr>
03599 <tr>
03600 <td>';
03601 }
03602
03603 if (is_array($var)) {
03604 $debug .= self::view_array($var);
03605 } elseif (is_object($var)) {
03606 $debug .= '<strong>|Object:<pre>';
03607 $debug .= print_r($var, TRUE);
03608 $debug .= '</pre>|</strong>';
03609 } elseif ((string) $var !== '') {
03610 $debug .= '<strong>|' . htmlspecialchars((string)$var) . '|</strong>';
03611 } else {
03612 $debug .= '<strong>| debug |</strong>';
03613 }
03614
03615 if ($header) {
03616 $debug .= '
03617 </td>
03618 </tr>
03619 </table>';
03620 }
03621
03622 if (TYPO3_MODE === 'BE') {
03623 $group = htmlspecialchars($group);
03624
03625 if ($header !== '') {
03626 $tabHeader = htmlspecialchars($header);
03627 } else {
03628 $tabHeader = 'Debug';
03629 }
03630
03631 if (is_object($var)) {
03632 $debug = str_replace(
03633 array('"', '/', '<', "\n", "\r"),
03634 array('\"', '\/', '<', '<br />', ''),
03635 $debug
03636 );
03637 } else {
03638 $debug = str_replace(
03639 array('"', '/', '<', "\n", "\r"),
03640 array('\"', '\/', '<', '', ''),
03641 $debug
03642 );
03643 }
03644
03645 $script = '
03646 (function debug() {
03647 var debugMessage = "' . $debug . '";
03648 var header = "' . $tabHeader . '";
03649 var group = "' . $group . '";
03650
03651 if (typeof Ext !== "object" && (top && typeof top.Ext !== "object")) {
03652 document.write(debugMessage);
03653 return;
03654 }
03655
03656 if (top && typeof Ext !== "object") {
03657 Ext = top.Ext;
03658 }
03659
03660 Ext.onReady(function() {
03661 var TYPO3ViewportInstance = null;
03662
03663 if (top && top.TYPO3 && typeof top.TYPO3.Backend === "object") {
03664 TYPO3ViewportInstance = top.TYPO3.Backend;
03665 } else if (typeof TYPO3 === "object" && typeof TYPO3.Backend === "object") {
03666 TYPO3ViewportInstance = TYPO3.Backend;
03667 }
03668
03669 if (TYPO3ViewportInstance !== null) {
03670 TYPO3ViewportInstance.DebugConsole.addTab(debugMessage, header, group);
03671 } else {
03672 document.write(debugMessage);
03673 }
03674 });
03675 })();
03676 ';
03677 echo self::wrapJS($script);
03678 } else {
03679 echo $debug;
03680 }
03681 }
03682
03683
03684
03685
03686
03687
03688 public static function debug_trail() {
03689 $trail = debug_backtrace();
03690 $trail = array_reverse($trail);
03691 array_pop($trail);
03692
03693 $path = array();
03694 foreach($trail as $dat) {
03695 $path[] = $dat['class'].$dat['type'].$dat['function'].'#'.$dat['line'];
03696 }
03697
03698 return implode('
03699 }
03700
03701
03702
03703
03704
03705
03706
03707
03708
03709 public static function debugRows($rows,$header='',$returnHTML=FALSE) {
03710 if (is_array($rows)) {
03711 reset($rows);
03712 $firstEl = current($rows);
03713 if (is_array($firstEl)) {
03714 $headerColumns = array_keys($firstEl);
03715 $tRows = array();
03716
03717
03718 $tRows[] = '<tr><td colspan="'.count($headerColumns).'" style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;"><strong>'.htmlspecialchars($header).'</strong></td></tr>';
03719 $tCells = array();
03720 foreach($headerColumns as $key) {
03721 $tCells[] = '
03722 <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
03723 }
03724 $tRows[] = '
03725 <tr>'.implode('',$tCells).'
03726 </tr>';
03727
03728
03729 foreach($rows as $singleRow) {
03730 $tCells = array();
03731 foreach($headerColumns as $key) {
03732 $tCells[] = '
03733 <td><font face="Verdana,Arial" size="1">'.(is_array($singleRow[$key]) ? self::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).'</font></td>';
03734 }
03735 $tRows[] = '
03736 <tr>'.implode('',$tCells).'
03737 </tr>';
03738 }
03739
03740 $table = '
03741 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
03742 </table>';
03743 if ($returnHTML) return $table; else echo $table;
03744 } else debug('Empty array of rows',$header);
03745 } else {
03746 debug('No array of rows',$header);
03747 }
03748 }
03749
03750
03751
03752
03753
03754
03755
03756
03757
03758
03759
03760
03761
03762
03763
03764
03765
03766
03767
03768
03769
03770
03771
03772
03773
03774
03775
03776
03777
03778
03779
03780
03781
03782
03783
03784
03785
03786
03787
03788
03789 public static function getThisUrl() {
03790 $p=parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT'));
03791 $dir=self::dirname($p['path']).'/';
03792 $url = str_replace('
03793 return $url;
03794 }
03795
03796
03797
03798
03799
03800
03801
03802
03803
03804
03805 public static function linkThisScript(array $getParams = array()) {
03806 $parts = self::getIndpEnv('SCRIPT_NAME');
03807 $params = self::_GET();
03808
03809 foreach ($getParams as $key => $value) {
03810 if ($value !== '') {
03811 $params[$key] = $value;
03812 } else {
03813 unset($params[$key]);
03814 }
03815 }
03816
03817 $pString = self::implodeArrayForUrl('', $params);
03818
03819 return $pString ? $parts . '?' . preg_replace('/^&/', '', $pString) : $parts;
03820 }
03821
03822
03823
03824
03825
03826
03827
03828
03829
03830
03831 public static function linkThisUrl($url,array $getParams=array()) {
03832 $parts = parse_url($url);
03833 $getP = array();
03834 if ($parts['query']) {
03835 parse_str($parts['query'],$getP);
03836 }
03837 $getP = self::array_merge_recursive_overrule($getP,$getParams);
03838 $uP = explode('?',$url);
03839
03840 $params = self::implodeArrayForUrl('',$getP);
03841 $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
03842
03843 return $outurl;
03844 }
03845
03846
03847
03848
03849
03850
03851
03852
03853
03854 public static function getIndpEnv($getEnvName) {
03855
03856
03857
03858
03859
03860
03861
03862
03863
03864
03865
03866
03867
03868
03869
03870
03871
03872
03873
03874
03875
03876
03877
03878
03879
03880
03881
03882
03883
03884
03885
03886
03887
03888
03889
03890
03891
03892
03893
03894
03895
03896
03897
03898
03899
03900
03901
03902
03903
03904
03905
03906
03907
03908
03909
03910
03911
03912
03913
03914
03915
03916
03917
03918 # if ($getEnvName=='HTTP_REFERER') return '';
03919
03920 $retVal = '';
03921
03922 switch ((string)$getEnvName) {
03923 case 'SCRIPT_NAME':
03924 $retVal = (PHP_SAPI=='cgi'||PHP_SAPI=='cgi-fcgi')&&($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) ? ($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) : ($_SERVER['ORIG_SCRIPT_NAME']?$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);
03925
03926 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
03927 if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
03928 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
03929 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
03930 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
03931 }
03932 }
03933 break;
03934 case 'SCRIPT_FILENAME':
03935 $retVal = str_replace('
03936 break;
03937 case 'REQUEST_URI':
03938
03939 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']) {
03940 list($v,$n) = explode('|',$GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
03941 $retVal = $GLOBALS[$v][$n];
03942 } elseif (!$_SERVER['REQUEST_URI']) {
03943 $retVal = '/'.ltrim(self::getIndpEnv('SCRIPT_NAME'), '/').
03944 ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
03945 } else {
03946 $retVal = $_SERVER['REQUEST_URI'];
03947 }
03948
03949 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
03950 if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
03951 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
03952 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
03953 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
03954 }
03955 }
03956 break;
03957 case 'PATH_INFO':
03958
03959
03960
03961
03962 if (PHP_SAPI!='cgi' && PHP_SAPI!='cgi-fcgi') {
03963 $retVal = $_SERVER['PATH_INFO'];
03964 }
03965 break;
03966 case 'TYPO3_REV_PROXY':
03967 $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
03968 break;
03969 case 'REMOTE_ADDR':
03970 $retVal = $_SERVER['REMOTE_ADDR'];
03971 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
03972 $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
03973
03974 if (count($ip)) {
03975 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
03976 case 'last':
03977 $ip = array_pop($ip);
03978 break;
03979 case 'first':
03980 $ip = array_shift($ip);
03981 break;
03982 case 'none':
03983 default:
03984 $ip = '';
03985 break;
03986 }
03987 }
03988 if (self::validIP($ip)) {
03989 $retVal = $ip;
03990 }
03991 }
03992 break;
03993 case 'HTTP_HOST':
03994 $retVal = $_SERVER['HTTP_HOST'];
03995 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
03996 $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
03997
03998 if (count($host)) {
03999 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
04000 case 'last':
04001 $host = array_pop($host);
04002 break;
04003 case 'first':
04004 $host = array_shift($host);
04005 break;
04006 case 'none':
04007 default:
04008 $host = '';
04009 break;
04010 }
04011 }
04012 if ($host) {
04013 $retVal = $host;
04014 }
04015 }
04016 break;
04017
04018 case 'HTTP_REFERER':
04019 case 'HTTP_USER_AGENT':
04020 case 'HTTP_ACCEPT_ENCODING':
04021 case 'HTTP_ACCEPT_LANGUAGE':
04022 case 'REMOTE_HOST':
04023 case 'QUERY_STRING':
04024 $retVal = $_SERVER[$getEnvName];
04025 break;
04026 case 'TYPO3_DOCUMENT_ROOT':
04027
04028
04029 $SFN = self::getIndpEnv('SCRIPT_FILENAME');
04030 $SN_A = explode('/',strrev(self::getIndpEnv('SCRIPT_NAME')));
04031 $SFN_A = explode('/',strrev($SFN));
04032 $acc = array();
04033 foreach ($SN_A as $kk => $vv) {
04034 if (!strcmp($SFN_A[$kk],$vv)) {
04035 $acc[] = $vv;
04036 } else break;
04037 }
04038 $commonEnd=strrev(implode('/',$acc));
04039 if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
04040 $retVal = $DR;
04041 break;
04042 case 'TYPO3_HOST_ONLY':
04043 $p = explode(':',self::getIndpEnv('HTTP_HOST'));
04044 $retVal = $p[0];
04045 break;
04046 case 'TYPO3_PORT':
04047 $p = explode(':',self::getIndpEnv('HTTP_HOST'));
04048 $retVal = $p[1];
04049 break;
04050 case 'TYPO3_REQUEST_HOST':
04051 $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https:
04052 self::getIndpEnv('HTTP_HOST');
04053 break;
04054 case 'TYPO3_REQUEST_URL':
04055 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('REQUEST_URI');
04056 break;
04057 case 'TYPO3_REQUEST_SCRIPT':
04058 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('SCRIPT_NAME');
04059 break;
04060 case 'TYPO3_REQUEST_DIR':
04061 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::dirname(self::getIndpEnv('SCRIPT_NAME')).'/';
04062 break;
04063 case 'TYPO3_SITE_URL':
04064 if (defined('PATH_thisScript') && defined('PATH_site')) {
04065 $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
04066 $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
04067 $siteUrl = substr($url,0,-strlen($lPath));
04068 if (substr($siteUrl,-1)!='/') $siteUrl.='/';
04069 $retVal = $siteUrl;
04070 }
04071 break;
04072 case 'TYPO3_SITE_PATH':
04073 $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
04074 break;
04075 case 'TYPO3_SITE_SCRIPT':
04076 $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'),strlen(self::getIndpEnv('TYPO3_SITE_URL')));
04077 break;
04078 case 'TYPO3_SSL':
04079 $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
04080 if ($proxySSL == '*') {
04081 $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
04082 }
04083 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {
04084 $retVal = true;
04085 } else {
04086 $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? true : false;
04087 }
04088 break;
04089 case '_ARRAY':
04090 $out = array();
04091
04092 $envTestVars = self::trimExplode(',','
04093 HTTP_HOST,
04094 TYPO3_HOST_ONLY,
04095 TYPO3_PORT,
04096 PATH_INFO,
04097 QUERY_STRING,
04098 REQUEST_URI,
04099 HTTP_REFERER,
04100 TYPO3_REQUEST_HOST,
04101 TYPO3_REQUEST_URL,
04102 TYPO3_REQUEST_SCRIPT,
04103 TYPO3_REQUEST_DIR,
04104 TYPO3_SITE_URL,
04105 TYPO3_SITE_SCRIPT,
04106 TYPO3_SSL,
04107 TYPO3_REV_PROXY,
04108 SCRIPT_NAME,
04109 TYPO3_DOCUMENT_ROOT,
04110 SCRIPT_FILENAME,
04111 REMOTE_ADDR,
04112 REMOTE_HOST,
04113 HTTP_USER_AGENT,
04114 HTTP_ACCEPT_LANGUAGE',1);
04115 foreach ($envTestVars as $v) {
04116 $out[$v]=self::getIndpEnv($v);
04117 }
04118 reset($out);
04119 $retVal = $out;
04120 break;
04121 }
04122 return $retVal;
04123 }
04124
04125
04126
04127
04128
04129
04130 public static function milliseconds() {
04131 return round(microtime(true) * 1000);
04132 }
04133
04134
04135
04136
04137
04138
04139
04140
04141 public static function clientInfo($useragent='') {
04142 if (!$useragent) $useragent=self::getIndpEnv('HTTP_USER_AGENT');
04143
04144 $bInfo=array();
04145
04146 if (strpos($useragent,'Konqueror') !== false) {
04147 $bInfo['BROWSER']= 'konqu';
04148 } elseif (strpos($useragent,'Opera') !== false) {
04149 $bInfo['BROWSER']= 'opera';
04150 } elseif (strpos($useragent, 'MSIE') !== false) {
04151 $bInfo['BROWSER']= 'msie';
04152 } elseif (strpos($useragent, 'Mozilla') !== false) {
04153 $bInfo['BROWSER']='net';
04154 } elseif (strpos($useragent, 'Flash') !== false) {
04155 $bInfo['BROWSER'] = 'flash';
04156 }
04157 if ($bInfo['BROWSER']) {
04158
04159 switch($bInfo['BROWSER']) {
04160 case 'net':
04161 $bInfo['VERSION']= doubleval(substr($useragent,8));
04162 if (strpos($useragent,'Netscape6/') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape6/'),10)); }
04163 if (strpos($useragent,'Netscape/6') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/6'),10)); }
04164 if (strpos($useragent,'Netscape/7') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/7'),9)); }
04165 break;
04166 case 'msie':
04167 $tmp = strstr($useragent,'MSIE');
04168 $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,4)));
04169 break;
04170 case 'opera':
04171 $tmp = strstr($useragent,'Opera');
04172 $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,5)));
04173 break;
04174 case 'konqu':
04175 $tmp = strstr($useragent,'Konqueror/');
04176 $bInfo['VERSION'] = doubleval(substr($tmp,10));
04177 break;
04178 }
04179
04180 if (strpos($useragent,'Win') !== false) {
04181 $bInfo['SYSTEM'] = 'win';
04182 } elseif (strpos($useragent,'Mac') !== false) {
04183 $bInfo['SYSTEM'] = 'mac';
04184 } elseif (strpos($useragent,'Linux') !== false || strpos($useragent,'X11') !== false || strpos($useragent,'SGI') !== false || strpos($useragent,' SunOS ') !== false || strpos($useragent,' HP-UX ') !== false) {
04185 $bInfo['SYSTEM'] = 'unix';
04186 }
04187 }
04188
04189 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net' && $bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
04190
04191 return $bInfo;
04192 }
04193
04194
04195
04196
04197
04198
04199
04200
04201 public static function getHostname($requestHost=TRUE) {
04202 $host = '';
04203
04204
04205 if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
04206 $host = self::getIndpEnv('HTTP_HOST');
04207 }
04208 if (!$host) {
04209
04210 $host = @php_uname('n');
04211
04212 if (strpos($host, ' ')) $host = '';
04213 }
04214
04215 if ($host && strpos($host, '.') === false) {
04216 $ip = gethostbyname($host);
04217
04218 if ($ip != $host) {
04219 $fqdn = gethostbyaddr($ip);
04220 if ($ip != $fqdn) $host = $fqdn;
04221 }
04222 }
04223 if (!$host) $host = 'localhost.localdomain';
04224
04225 return $host;
04226 }
04227
04228
04229
04230
04231
04232
04233
04234
04235
04236
04237
04238
04239
04240
04241
04242
04243
04244
04245
04246
04247
04248
04249
04250
04251
04252
04253
04254
04255
04256
04257
04258
04259
04260
04261
04262
04263
04264 public static function getFileAbsFileName($filename,$onlyRelative=TRUE,$relToTYPO3_mainDir=FALSE) {
04265 if (!strcmp($filename,'')) return '';
04266
04267 if ($relToTYPO3_mainDir) {
04268 if (!defined('PATH_typo3')) return '';
04269 $relPathPrefix = PATH_typo3;
04270 } else {
04271 $relPathPrefix = PATH_site;
04272 }
04273 if (substr($filename,0,4)=='EXT:') {
04274 list($extKey,$local) = explode('/',substr($filename,4),2);
04275 $filename='';
04276 if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
04277 $filename = t3lib_extMgm::extPath($extKey).$local;
04278 }
04279 } elseif (!self::isAbsPath($filename)) {
04280 $filename=$relPathPrefix.$filename;
04281 } elseif ($onlyRelative && !self::isFirstPartOfStr($filename,$relPathPrefix)) {
04282 $filename='';
04283 }
04284 if (strcmp($filename,'') && self::validPathStr($filename)) {
04285 return $filename;
04286 }
04287 }
04288
04289
04290
04291
04292
04293
04294
04295
04296
04297
04298
04299
04300 public static function validPathStr($theFile) {
04301 if (strpos($theFile, '
04302 return true;
04303 }
04304 }
04305
04306
04307
04308
04309
04310
04311
04312
04313 public static function isAbsPath($path) {
04314 return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' : substr($path,0,1)=='/';
04315 }
04316
04317
04318
04319
04320
04321
04322
04323
04324 public static function isAllowedAbsPath($path) {
04325 if (self::isAbsPath($path) &&
04326 self::validPathStr($path) &&
04327 ( self::isFirstPartOfStr($path,PATH_site)
04328 ||
04329 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
04330 )
04331 ) return true;
04332 }
04333
04334
04335
04336
04337
04338
04339
04340
04341 public static function verifyFilenameAgainstDenyPattern($filename) {
04342 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
04343 $result = preg_match('/'.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'].'/i',$filename);
04344 if ($result) return false;
04345 }
04346 return true;
04347 }
04348
04349
04350
04351
04352
04353
04354
04355
04356
04357
04358 public static function sanitizeLocalUrl($url = '') {
04359 $sanitizedUrl = '';
04360 $decodedUrl = rawurldecode($url);
04361
04362 if (!empty($url) && self::removeXSS($decodedUrl) === $decodedUrl) {
04363 $testAbsoluteUrl = self::resolveBackPath($decodedUrl);
04364 $testRelativeUrl = self::resolveBackPath(
04365 self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
04366 );
04367
04368
04369 if (self::isValidUrl($decodedUrl)) {
04370 if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) {
04371 $sanitizedUrl = $url;
04372 }
04373
04374 } elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) {
04375 $sanitizedUrl = $url;
04376
04377 } elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) === '/') {
04378 $sanitizedUrl = $url;
04379
04380 } elseif (strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) !== '/') {
04381 $sanitizedUrl = $url;
04382 }
04383 }
04384
04385 if (!empty($url) && empty($sanitizedUrl)) {
04386 self::sysLog('The URL "' . $url . '" is not considered to be local and was denied.', 'Core', self::SYSLOG_SEVERITY_NOTICE);
04387 }
04388
04389 return $sanitizedUrl;
04390 }
04391
04392
04393
04394
04395
04396
04397
04398
04399
04400
04401
04402 public static function upload_copy_move($source,$destination) {
04403 if (is_uploaded_file($source)) {
04404 $uploaded = TRUE;
04405
04406 $uploadedResult = move_uploaded_file($source, $destination);
04407 } else {
04408 $uploaded = FALSE;
04409 @copy($source,$destination);
04410 }
04411
04412 self::fixPermissions($destination);
04413
04414
04415 return $uploaded ? $uploadedResult : FALSE;
04416 }
04417
04418
04419
04420
04421
04422
04423
04424
04425
04426
04427
04428 public static function upload_to_tempfile($uploadedFileName) {
04429 if (is_uploaded_file($uploadedFileName)) {
04430 $tempFile = self::tempnam('upload_temp_');
04431 move_uploaded_file($uploadedFileName, $tempFile);
04432 return @is_file($tempFile) ? $tempFile : '';
04433 }
04434 }
04435
04436
04437
04438
04439
04440
04441
04442
04443
04444
04445
04446 public static function unlink_tempfile($uploadedTempFileName) {
04447 if ($uploadedTempFileName && self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName)) {
04448 if (unlink($uploadedTempFileName)) return TRUE;
04449 }
04450 }
04451
04452
04453
04454
04455
04456
04457
04458
04459
04460
04461
04462 public static function tempnam($filePrefix) {
04463 return tempnam(PATH_site.'typo3temp/',$filePrefix);
04464 }
04465
04466
04467
04468
04469
04470
04471
04472
04473
04474
04475 public static function stdAuthCode($uid_or_record,$fields='',$codeLength=8) {
04476
04477 if (is_array($uid_or_record)) {
04478 $recCopy_temp=array();
04479 if ($fields) {
04480 $fieldArr = self::trimExplode(',',$fields,1);
04481 foreach ($fieldArr as $k => $v) {
04482 $recCopy_temp[$k]=$uid_or_record[$v];
04483 }
04484 } else {
04485 $recCopy_temp=$uid_or_record;
04486 }
04487 $preKey = implode('|',$recCopy_temp);
04488 } else {
04489 $preKey = $uid_or_record;
04490 }
04491
04492 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
04493 $authCode = substr(md5($authCode),0,$codeLength);
04494 return $authCode;
04495 }
04496
04497
04498
04499
04500
04501
04502
04503
04504
04505 public static function cHashParams($addQueryParams) {
04506 $params = explode('&',substr($addQueryParams,1));
04507
04508
04509 $pA = array();
04510 foreach($params as $theP) {
04511 $pKV = explode('=', $theP);
04512 if (!self::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/',$pKV[0])) {
04513 $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
04514 }
04515 }
04516
04517 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
04518 $cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
04519 if (is_array($cHashParamsHook)) {
04520 $hookParameters = array(
04521 'addQueryParams' => &$addQueryParams,
04522 'params' => &$params,
04523 'pA' => &$pA,
04524 );
04525 $hookReference = null;
04526 foreach ($cHashParamsHook as $hookFunction) {
04527 self::callUserFunction($hookFunction, $hookParameters, $hookReference);
04528 }
04529 }
04530 }
04531
04532 $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
04533 ksort($pA);
04534
04535 return $pA;
04536 }
04537
04538
04539
04540
04541
04542
04543
04544
04545 public static function generateCHash($addQueryParams) {
04546 $cHashParams = self::cHashParams($addQueryParams);
04547 $cHash = self::calculateCHash($cHashParams);
04548 return $cHash;
04549 }
04550
04551
04552
04553
04554
04555
04556
04557 public static function calculateCHash($params) {
04558 $cHash = md5(serialize($params));
04559 return $cHash;
04560 }
04561
04562
04563
04564
04565
04566
04567
04568 public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
04569 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
04570 return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
04571 } else {
04572 return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
04573 }
04574 }
04575
04576
04577
04578
04579
04580
04581
04582
04583
04584
04585
04586 public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
04587
04588 $result = FALSE;
04589 $file = self::getFileAbsFileName($fileRef);
04590 if ($file) {
04591 $baseFile = preg_replace('/\.(php|xml)$/', '', $file);
04592
04593 if (@is_file($baseFile.'.xml')) {
04594 $LOCAL_LANG = self::readLLXMLfile($baseFile.'.xml', $langKey, $charset);
04595 } elseif (@is_file($baseFile.'.php')) {
04596 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] || $charset) {
04597 $LOCAL_LANG = self::readLLPHPfile($baseFile.'.php', $langKey, $charset);
04598 } else {
04599 include($baseFile.'.php');
04600 if (is_array($LOCAL_LANG)) {
04601 $LOCAL_LANG = array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]); }
04602 }
04603 } else {
04604 $errorMsg = 'File "' . $fileRef. '" not found!';
04605 if ($errorMode == 2) {
04606 throw new t3lib_exception($errorMsg);
04607 } elseif(!$errorMode) {
04608 self::sysLog($errorMsg, 'Core', self::SYSLOG_SEVERITY_ERROR);
04609 }
04610 $fileNotFound = TRUE;
04611 }
04612 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef])) {
04613 foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef] as $overrideFile) {
04614 $languageOverrideFileName = self::getFileAbsFileName($overrideFile);
04615 if (@is_file($languageOverrideFileName)) {
04616 $languageOverrideArray = self::readLLXMLfile($languageOverrideFileName, $langKey, $charset);
04617 $LOCAL_LANG = self::array_merge_recursive_overrule($LOCAL_LANG, $languageOverrideArray);
04618 }
04619 }
04620 }
04621 }
04622 if ($fileNotFound !== TRUE) {
04623 $result = is_array($LOCAL_LANG) ? $LOCAL_LANG : array();
04624 }
04625 return $result;
04626 }
04627
04628
04629
04630
04631
04632
04633
04634
04635
04636
04637 public static function readLLPHPfile($fileRef, $langKey, $charset='') {
04638
04639 if (is_object($GLOBALS['LANG'])) {
04640 $csConvObj = $GLOBALS['LANG']->csConvObj;
04641 } elseif (is_object($GLOBALS['TSFE'])) {
04642 $csConvObj = $GLOBALS['TSFE']->csConvObj;
04643 } else {
04644 $csConvObj = self::makeInstance('t3lib_cs');
04645 }
04646
04647 if (@is_file($fileRef) && $langKey) {
04648
04649
04650 $sourceCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
04651 if ($charset) {
04652 $targetCharset = $csConvObj->parse_charset($charset);
04653 } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
04654
04655 $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
04656 } else {
04657 $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
04658 }
04659
04660
04661 $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
04662 $cacheFileName = PATH_site.'typo3temp/llxml/'.
04663 substr(basename($fileRef),10,15).
04664 '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
04665
04666 if (!@is_file($cacheFileName)) {
04667
04668
04669 include($fileRef);
04670 if (!is_array($LOCAL_LANG)) {
04671 $fileName = substr($fileRef, strlen(PATH_site));
04672 throw new RuntimeException(
04673 'TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!',
04674 1270853900
04675 );
04676 }
04677
04678
04679
04680 if (is_array($LOCAL_LANG['default']) && $targetCharset != 'iso-8859-1') {
04681 foreach ($LOCAL_LANG['default'] as &$labelValue) {
04682 $labelValue = $csConvObj->conv($labelValue, 'iso-8859-1', $targetCharset);
04683 }
04684 }
04685
04686 if ($langKey!='default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset!=$targetCharset) {
04687 foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
04688 $labelValue = $csConvObj->conv($labelValue, $sourceCharset, $targetCharset);
04689 }
04690 }
04691
04692
04693 $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
04694 $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
04695 if ($res) {
04696 throw new RuntimeException(
04697 'TYPO3 Fatal Error: "' . $res,
04698 1270853901
04699 );
04700 }
04701 } else {
04702 // Get content from cache:
04703 $serContent = unserialize(self::getUrl($cacheFileName));
04704 $LOCAL_LANG = $serContent['LOCAL_LANG'];
04705 }
04706
04707 return $LOCAL_LANG;
04708 }
04709 }
04710
04711
04712
04713
04714
04715
04716
04717
04718
04719
04720 public static function readLLXMLfile($fileRef, $langKey, $charset='') {
04721
04722 if (is_object($GLOBALS['LANG'])) {
04723 $csConvObj = $GLOBALS['LANG']->csConvObj;
04724 } elseif (is_object($GLOBALS['TSFE'])) {
04725 $csConvObj = $GLOBALS['TSFE']->csConvObj;
04726 } else {
04727 $csConvObj = self::makeInstance('t3lib_cs');
04728 }
04729
04730 $LOCAL_LANG = NULL;
04731 if (@is_file($fileRef) && $langKey) {
04732
04733 // Set charset:
04734 if ($charset) {
04735 $targetCharset = $csConvObj->parse_charset($charset);
04736 } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
04737 // when forceCharset is set, we store ALL labels in this charset!!!
04738 $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
04739 } else {
04740 $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
04741 }
04742
04743 // Cache file name:
04744 $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
04745 $cacheFileName = PATH_site.'typo3temp/llxml/'.
04746 substr(basename($fileRef),10,15).
04747 '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
04748
04749 // Check if cache file exists...
04750 if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
04751
04752 // Read XML, parse it.
04753 $xmlString = self::getUrl($fileRef);
04754 $xmlContent = self::xml2array($xmlString);
04755 if (!is_array($xmlContent)) {
04756 $fileName = substr($fileRef, strlen(PATH_site));
04757 throw new RuntimeException(
04758 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
04759 1270853902
04760 );
04761 }
04762
04763 // Set default LOCAL_LANG array content:
04764 $LOCAL_LANG = array();
04765 $LOCAL_LANG['default'] = $xmlContent['data']['default'];
04766
04767 // converting the default language (English)
04768 // this needs to be done for a few accented loan words and extension names
04769 // NOTE: no conversion is done when in UTF-8 mode!
04770 if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
04771 foreach ($LOCAL_LANG['default'] as &$labelValue) {
04772 $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
04773 }
04774 unset($labelValue);
04775 }
04776
04777 // converting other languages to their "native" charsets
04778 // NOTE: no conversion is done when in UTF-8 mode!
04779 if ($langKey!='default') {
04780
04781 // If no entry is found for the language key, then force a value depending on meta-data setting. By default an automated filename will be used:
04782 $LOCAL_LANG[$langKey] = self::llXmlAutoFileName($fileRef, $langKey);
04783 $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
04784 if (!@is_file($localized_file) && isset($xmlContent['data'][$langKey])) {
04785 $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
04786 }
04787
04788 // Checking if charset should be converted.
04789 if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
04790 foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
04791 $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
04792 }
04793 }
04794 }
04795
04796 // Cache the content now:
04797 $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
04798 $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
04799 if ($res) {
04800 throw new RuntimeException(
04801 'TYPO3 Fatal Error: ' . $res,
04802 1270853903
04803 );
04804 }
04805 } else {
04806 // Get content from cache:
04807 $serContent = unserialize(self::getUrl($cacheFileName));
04808 $LOCAL_LANG = $serContent['LOCAL_LANG'];
04809 }
04810
04811 // Checking for EXTERNAL file for non-default language:
04812 if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
04813
04814 // Look for localized file:
04815 $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
04816 if ($localized_file && @is_file($localized_file)) {
04817
04818 // Cache file name:
04819 $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file)).'|version=2.3';
04820 $cacheFileName = PATH_site.'typo3temp/llxml/EXT_'.
04821 substr(basename($localized_file),10,15).
04822 '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
04823
04824 // Check if cache file exists...
04825 if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
04826
04827 // Read and parse XML content:
04828 $local_xmlString = self::getUrl($localized_file);
04829 $local_xmlContent = self::xml2array($local_xmlString);
04830 if (!is_array($local_xmlContent)) {
04831 $fileName = substr($localized_file, strlen(PATH_site));
04832 throw new RuntimeException(
04833 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
04834 1270853904
04835 );
04836 }
04837 $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
04838
04839 // Checking if charset should be converted.
04840 if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
04841 foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
04842 $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
04843 }
04844 }
04845
04846 // Cache the content now:
04847 $serContent = array('extlang'=>$langKey, 'origFile'=>$hashSource, 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
04848 $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
04849 if ($res) {
04850 throw new RuntimeException(
04851 'TYPO3 Fatal Error: ' . $res,
04852 1270853905
04853 );
04854 }
04855 } else {
04856 // Get content from cache:
04857 $serContent = unserialize(self::getUrl($cacheFileName));
04858 $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
04859 }
04860 } else {
04861 $LOCAL_LANG[$langKey] = array();
04862 }
04863 }
04864
04865 return $LOCAL_LANG;
04866 }
04867 }
04868
04869
04870
04871
04872
04873
04874
04875
04876 public static function llXmlAutoFileName($fileRef,$language) {
04877 // Analyse file reference:
04878 $location = 'typo3conf/l10n/'.$language.'/'; // Default location of translations
04879 if (self::isFirstPartOfStr($fileRef,PATH_typo3.'sysext/')) { // Is system:
04880 $validatedPrefix = PATH_typo3.'sysext/';
04881 #$location = 'EXT:csh_'.$language.'/'; // For system extensions translations are found in "csh_*" extensions (language packs)
04882 } elseif (self::isFirstPartOfStr($fileRef,PATH_typo3.'ext/')) { // Is global:
04883 $validatedPrefix = PATH_typo3.'ext/';
04884 } elseif (self::isFirstPartOfStr($fileRef,PATH_typo3conf.'ext/')) { // Is local:
04885 $validatedPrefix = PATH_typo3conf.'ext/';
04886 } else {
04887 $validatedPrefix = '';
04888 }
04889
04890 if ($validatedPrefix) {
04891
04892 // Divide file reference into extension key, directory (if any) and base name:
04893 list($file_extKey,$file_extPath) = explode('/',substr($fileRef,strlen($validatedPrefix)),2);
04894 $temp = self::revExplode('/',$file_extPath,2);
04895 if (count($temp)==1) array_unshift($temp,''); // Add empty first-entry if not there.
04896 list($file_extPath,$file_fileName) = $temp;
04897
04898 // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
04899 return $location.
04900 $file_extKey.'/'.
04901 ($file_extPath?$file_extPath.'/':'').
04902 $language.'.'.$file_fileName;
04903 } else {
04904 return NULL;
04905 }
04906 }
04907
04908
04909
04910
04911
04912
04913
04914
04915
04916
04917
04918
04919
04920
04921
04922
04923
04924
04925 public static function loadTCA($table) {
04926 global $TCA;
04927
04928 if (isset($TCA[$table])) {
04929 $tca = &$TCA[$table];
04930 if (!$tca['columns']) {
04931 $dcf = $tca['ctrl']['dynamicConfigFile'];
04932 if ($dcf) {
04933 if (!strcmp(substr($dcf,0,6),'T3LIB:')) {
04934 include(PATH_t3lib.'stddb/'.substr($dcf,6));
04935 } elseif (self::isAbsPath($dcf) && @is_file($dcf)) { // Absolute path...
04936 include($dcf);
04937 } else include(PATH_typo3conf.$dcf);
04938 }
04939 }
04940 }
04941 }
04942
04943
04944
04945
04946
04947
04948
04949
04950
04951
04952 public static function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
04953 if (!is_array ($dataStructArray)) return 'Data structure must be an array';
04954
04955 if (is_array($dataStructArray['sheets'])) {
04956 $singleSheet = FALSE;
04957 if (!isset($dataStructArray['sheets'][$sheet])) {
04958 $sheet='sDEF';
04959 }
04960 $dataStruct = $dataStructArray['sheets'][$sheet];
04961
04962 // If not an array, but still set, then regard it as a relative reference to a file:
04963 if ($dataStruct && !is_array($dataStruct)) {
04964 $file = self::getFileAbsFileName($dataStruct);
04965 if ($file && @is_file($file)) {
04966 $dataStruct = self::xml2array(self::getUrl($file));
04967 }
04968 }
04969 } else {
04970 $singleSheet = TRUE;
04971 $dataStruct = $dataStructArray;
04972 if (isset($dataStruct['meta'])) unset($dataStruct['meta']); // Meta data should not appear there.
04973 $sheet = 'sDEF'; // Default sheet
04974 }
04975 return array($dataStruct,$sheet,$singleSheet);
04976 }
04977
04978
04979
04980
04981
04982
04983
04984
04985 public static function resolveAllSheetsInDS(array $dataStructArray) {
04986 if (is_array($dataStructArray['sheets'])) {
04987 $out=array('sheets'=>array());
04988 foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
04989 list($ds,$aS) = self::resolveSheetDefInDS($dataStructArray,$sheetId);
04990 if ($sheetId==$aS) {
04991 $out['sheets'][$aS]=$ds;
04992 }
04993 }
04994 } else {
04995 list($ds) = self::resolveSheetDefInDS($dataStructArray);
04996 $out = array('sheets' => array('sDEF' => $ds));
04997 }
04998 return $out;
04999 }
05000
05001
05002
05003
05004
05005
05006
05007
05008
05009
05010
05011
05012