1
|
|
|
<?php |
2
|
|
|
namespace TYPO3\CMS\Core\Utility; |
3
|
|
|
|
4
|
|
|
/* |
5
|
|
|
* This file is part of the TYPO3 CMS project. |
6
|
|
|
* |
7
|
|
|
* It is free software; you can redistribute it and/or modify it under |
8
|
|
|
* the terms of the GNU General Public License, either version 2 |
9
|
|
|
* of the License, or any later version. |
10
|
|
|
* |
11
|
|
|
* For the full copyright and license information, please read the |
12
|
|
|
* LICENSE.txt file that was distributed with this source code. |
13
|
|
|
* |
14
|
|
|
* The TYPO3 project - inspiring people to share! |
15
|
|
|
*/ |
16
|
|
|
|
17
|
|
|
use GuzzleHttp\Exception\RequestException; |
18
|
|
|
use Psr\Log\LoggerAwareInterface; |
19
|
|
|
use Psr\Log\LoggerInterface; |
20
|
|
|
use TYPO3\CMS\Core\Core\ApplicationContext; |
21
|
|
|
use TYPO3\CMS\Core\Core\ClassLoadingInformation; |
22
|
|
|
use TYPO3\CMS\Core\Http\RequestFactory; |
23
|
|
|
use TYPO3\CMS\Core\Log\LogLevel; |
24
|
|
|
use TYPO3\CMS\Core\Log\LogManager; |
25
|
|
|
use TYPO3\CMS\Core\Service\OpcodeCacheService; |
26
|
|
|
use TYPO3\CMS\Core\SingletonInterface; |
27
|
|
|
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* The legendary "t3lib_div" class - Miscellaneous functions for general purpose. |
31
|
|
|
* Most of the functions do not relate specifically to TYPO3 |
32
|
|
|
* However a section of functions requires certain TYPO3 features available |
33
|
|
|
* See comments in the source. |
34
|
|
|
* You are encouraged to use this library in your own scripts! |
35
|
|
|
* |
36
|
|
|
* USE: |
37
|
|
|
* The class is intended to be used without creating an instance of it. |
38
|
|
|
* So: Don't instantiate - call functions with "\TYPO3\CMS\Core\Utility\GeneralUtility::" prefixed the function name. |
39
|
|
|
* So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()' |
40
|
|
|
*/ |
41
|
|
|
class GeneralUtility |
42
|
|
|
{ |
43
|
|
|
// Severity constants used by \TYPO3\CMS\Core\Utility\GeneralUtility::devLog() |
44
|
|
|
// @deprecated since TYPO3 CMS 9, will be removed in TYPO3 CMS 10. |
45
|
|
|
const SYSLOG_SEVERITY_INFO = 0; |
46
|
|
|
const SYSLOG_SEVERITY_NOTICE = 1; |
47
|
|
|
const SYSLOG_SEVERITY_WARNING = 2; |
48
|
|
|
const SYSLOG_SEVERITY_ERROR = 3; |
49
|
|
|
const SYSLOG_SEVERITY_FATAL = 4; |
50
|
|
|
|
51
|
|
|
const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*'; |
52
|
|
|
const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME'; |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* State of host header value security check |
56
|
|
|
* in order to avoid unnecessary multiple checks during one request |
57
|
|
|
* |
58
|
|
|
* @var bool |
59
|
|
|
*/ |
60
|
|
|
protected static $allowHostHeaderValue = false; |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Singleton instances returned by makeInstance, using the class names as |
64
|
|
|
* array keys |
65
|
|
|
* |
66
|
|
|
* @var array<\TYPO3\CMS\Core\SingletonInterface> |
67
|
|
|
*/ |
68
|
|
|
protected static $singletonInstances = []; |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Instances returned by makeInstance, using the class names as array keys |
72
|
|
|
* |
73
|
|
|
* @var array<array><object> |
74
|
|
|
*/ |
75
|
|
|
protected static $nonSingletonInstances = []; |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Cache for makeInstance with given class name and final class names to reduce number of self::getClassName() calls |
79
|
|
|
* |
80
|
|
|
* @var array Given class name => final class name |
81
|
|
|
*/ |
82
|
|
|
protected static $finalClassNameCache = []; |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* The application context |
86
|
|
|
* |
87
|
|
|
* @var \TYPO3\CMS\Core\Core\ApplicationContext |
88
|
|
|
*/ |
89
|
|
|
protected static $applicationContext = null; |
90
|
|
|
|
91
|
|
|
/** |
92
|
|
|
* IDNA string cache |
93
|
|
|
* |
94
|
|
|
* @var array<string> |
95
|
|
|
*/ |
96
|
|
|
protected static $idnaStringCache = []; |
97
|
|
|
|
98
|
|
|
/** |
99
|
|
|
* IDNA converter |
100
|
|
|
* |
101
|
|
|
* @var \Mso\IdnaConvert\IdnaConvert |
102
|
|
|
*/ |
103
|
|
|
protected static $idnaConverter = null; |
104
|
|
|
|
105
|
|
|
/** |
106
|
|
|
* A list of supported CGI server APIs |
107
|
|
|
* NOTICE: This is a duplicate of the SAME array in SystemEnvironmentBuilder |
108
|
|
|
* @var array |
109
|
|
|
*/ |
110
|
|
|
protected static $supportedCgiServerApis = [ |
111
|
|
|
'fpm-fcgi', |
112
|
|
|
'cgi', |
113
|
|
|
'isapi', |
114
|
|
|
'cgi-fcgi', |
115
|
|
|
'srv', // HHVM with fastcgi |
116
|
|
|
]; |
117
|
|
|
|
118
|
|
|
/** |
119
|
|
|
* @var array |
120
|
|
|
*/ |
121
|
|
|
protected static $indpEnvCache = []; |
122
|
|
|
|
123
|
|
|
/************************* |
124
|
|
|
* |
125
|
|
|
* GET/POST Variables |
126
|
|
|
* |
127
|
|
|
* Background: |
128
|
|
|
* Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration. |
129
|
|
|
* TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so. |
130
|
|
|
* But the clean solution is that quotes are never escaped and that is what the functions below offers. |
131
|
|
|
* Eventually TYPO3 should provide this in the global space as well. |
132
|
|
|
* In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below. |
133
|
|
|
* This functionality was previously needed to normalize between magic quotes logic, which was removed from PHP 5.4, |
134
|
|
|
* so these methods are still in use, but not tackle the slash problem anymore. |
135
|
|
|
* |
136
|
|
|
*************************/ |
137
|
|
|
/** |
138
|
|
|
* Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order) |
139
|
|
|
* To enhance security in your scripts, please consider using GeneralUtility::_GET or GeneralUtility::_POST if you already |
140
|
|
|
* know by which method your data is arriving to the scripts! |
141
|
|
|
* |
142
|
|
|
* @param string $var GET/POST var to return |
143
|
|
|
* @return mixed POST var named $var and if not set, the GET var of the same name. |
144
|
|
|
*/ |
145
|
|
|
public static function _GP($var) |
146
|
|
|
{ |
147
|
|
|
if (empty($var)) { |
148
|
|
|
return; |
149
|
|
|
} |
150
|
|
|
if (isset($_POST[$var])) { |
151
|
|
|
$value = $_POST[$var]; |
152
|
|
|
} elseif (isset($_GET[$var])) { |
153
|
|
|
$value = $_GET[$var]; |
154
|
|
|
} else { |
155
|
|
|
$value = null; |
156
|
|
|
} |
157
|
|
|
// This is there for backwards-compatibility, in order to avoid NULL |
158
|
|
|
if (isset($value) && !is_array($value)) { |
159
|
|
|
$value = (string)$value; |
160
|
|
|
} |
161
|
|
|
return $value; |
162
|
|
|
} |
163
|
|
|
|
164
|
|
|
/** |
165
|
|
|
* Returns the global arrays $_GET and $_POST merged with $_POST taking precedence. |
166
|
|
|
* |
167
|
|
|
* @param string $parameter Key (variable name) from GET or POST vars |
168
|
|
|
* @return array Returns the GET vars merged recursively onto the POST vars. |
169
|
|
|
*/ |
170
|
|
|
public static function _GPmerged($parameter) |
171
|
|
|
{ |
172
|
|
|
$postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : []; |
173
|
|
|
$getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : []; |
174
|
|
|
$mergedParameters = $getParameter; |
175
|
|
|
ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter); |
176
|
|
|
return $mergedParameters; |
177
|
|
|
} |
178
|
|
|
|
179
|
|
|
/** |
180
|
|
|
* Returns the global $_GET array (or value from) normalized to contain un-escaped values. |
181
|
|
|
* ALWAYS use this API function to acquire the GET variables! |
182
|
|
|
* This function was previously used to normalize between magic quotes logic, which was removed from PHP 5.5 |
183
|
|
|
* |
184
|
|
|
* @param string $var Optional pointer to value in GET array (basically name of GET var) |
185
|
|
|
* @return mixed If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself. In any case *slashes are stipped from the output!* |
186
|
|
|
* @see _POST(), _GP(), _GETset() |
187
|
|
|
*/ |
188
|
|
View Code Duplication |
public static function _GET($var = null) |
189
|
|
|
{ |
190
|
|
|
$value = $var === null ? $_GET : (empty($var) ? null : $_GET[$var]); |
191
|
|
|
// This is there for backwards-compatibility, in order to avoid NULL |
192
|
|
|
if (isset($value) && !is_array($value)) { |
193
|
|
|
$value = (string)$value; |
194
|
|
|
} |
195
|
|
|
return $value; |
196
|
|
|
} |
197
|
|
|
|
198
|
|
|
/** |
199
|
|
|
* Returns the global $_POST array (or value from) normalized to contain un-escaped values. |
200
|
|
|
* ALWAYS use this API function to acquire the $_POST variables! |
201
|
|
|
* |
202
|
|
|
* @param string $var Optional pointer to value in POST array (basically name of POST var) |
203
|
|
|
* @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself. In any case *slashes are stipped from the output!* |
204
|
|
|
* @see _GET(), _GP() |
205
|
|
|
*/ |
206
|
|
View Code Duplication |
public static function _POST($var = null) |
207
|
|
|
{ |
208
|
|
|
$value = $var === null ? $_POST : (empty($var) || !isset($_POST[$var]) ? null : $_POST[$var]); |
209
|
|
|
// This is there for backwards-compatibility, in order to avoid NULL |
210
|
|
|
if (isset($value) && !is_array($value)) { |
211
|
|
|
$value = (string)$value; |
212
|
|
|
} |
213
|
|
|
return $value; |
214
|
|
|
} |
215
|
|
|
|
216
|
|
|
/** |
217
|
|
|
* Writes input value to $_GET. |
218
|
|
|
* |
219
|
|
|
* @param mixed $inputGet |
220
|
|
|
* @param string $key |
221
|
|
|
*/ |
222
|
|
|
public static function _GETset($inputGet, $key = '') |
223
|
|
|
{ |
224
|
|
|
if ($key != '') { |
225
|
|
|
if (strpos($key, '|') !== false) { |
226
|
|
|
$pieces = explode('|', $key); |
227
|
|
|
$newGet = []; |
228
|
|
|
$pointer = &$newGet; |
229
|
|
|
foreach ($pieces as $piece) { |
230
|
|
|
$pointer = &$pointer[$piece]; |
231
|
|
|
} |
232
|
|
|
$pointer = $inputGet; |
233
|
|
|
$mergedGet = $_GET; |
234
|
|
|
ArrayUtility::mergeRecursiveWithOverrule($mergedGet, $newGet); |
235
|
|
|
$_GET = $mergedGet; |
236
|
|
|
$GLOBALS['HTTP_GET_VARS'] = $mergedGet; |
237
|
|
|
} else { |
238
|
|
|
$_GET[$key] = $inputGet; |
239
|
|
|
$GLOBALS['HTTP_GET_VARS'][$key] = $inputGet; |
240
|
|
|
} |
241
|
|
|
} elseif (is_array($inputGet)) { |
242
|
|
|
$_GET = $inputGet; |
243
|
|
|
$GLOBALS['HTTP_GET_VARS'] = $inputGet; |
244
|
|
|
} |
245
|
|
|
} |
246
|
|
|
|
247
|
|
|
/************************* |
248
|
|
|
* |
249
|
|
|
* STRING FUNCTIONS |
250
|
|
|
* |
251
|
|
|
*************************/ |
252
|
|
|
/** |
253
|
|
|
* Truncates a string with appended/prepended "..." and takes current character set into consideration. |
254
|
|
|
* |
255
|
|
|
* @param string $string String to truncate |
256
|
|
|
* @param int $chars Must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end. |
257
|
|
|
* @param string $appendString Appendix to the truncated string |
258
|
|
|
* @return string Cropped string |
259
|
|
|
*/ |
260
|
|
|
public static function fixed_lgd_cs($string, $chars, $appendString = '...') |
261
|
|
|
{ |
262
|
|
|
if ((int)$chars === 0 || mb_strlen($string, 'utf-8') <= abs($chars)) { |
263
|
|
|
return $string; |
264
|
|
|
} |
265
|
|
|
if ($chars > 0) { |
266
|
|
|
$string = mb_substr($string, 0, $chars, 'utf-8') . $appendString; |
267
|
|
|
} else { |
268
|
|
|
$string = $appendString . mb_substr($string, $chars, mb_strlen($string, 'utf-8'), 'utf-8'); |
269
|
|
|
} |
270
|
|
|
return $string; |
271
|
|
|
} |
272
|
|
|
|
273
|
|
|
/** |
274
|
|
|
* Match IP number with list of numbers with wildcard |
275
|
|
|
* Dispatcher method for switching into specialised IPv4 and IPv6 methods. |
276
|
|
|
* |
277
|
|
|
* @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR |
278
|
|
|
* @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE. |
279
|
|
|
* @return bool TRUE if an IP-mask from $list matches $baseIP |
280
|
|
|
*/ |
281
|
|
|
public static function cmpIP($baseIP, $list) |
282
|
|
|
{ |
283
|
|
|
$list = trim($list); |
284
|
|
|
if ($list === '') { |
285
|
|
|
return false; |
286
|
|
|
} |
287
|
|
|
if ($list === '*') { |
288
|
|
|
return true; |
289
|
|
|
} |
290
|
|
|
if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) { |
291
|
|
|
return self::cmpIPv6($baseIP, $list); |
292
|
|
|
} |
293
|
|
|
return self::cmpIPv4($baseIP, $list); |
294
|
|
|
} |
295
|
|
|
|
296
|
|
|
/** |
297
|
|
|
* Match IPv4 number with list of numbers with wildcard |
298
|
|
|
* |
299
|
|
|
* @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR |
300
|
|
|
* @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168), could also contain IPv6 addresses |
301
|
|
|
* @return bool TRUE if an IP-mask from $list matches $baseIP |
302
|
|
|
*/ |
303
|
|
|
public static function cmpIPv4($baseIP, $list) |
304
|
|
|
{ |
305
|
|
|
$IPpartsReq = explode('.', $baseIP); |
306
|
|
|
if (count($IPpartsReq) === 4) { |
307
|
|
|
$values = self::trimExplode(',', $list, true); |
308
|
|
|
foreach ($values as $test) { |
309
|
|
|
$testList = explode('/', $test); |
310
|
|
View Code Duplication |
if (count($testList) === 2) { |
311
|
|
|
list($test, $mask) = $testList; |
312
|
|
|
} else { |
313
|
|
|
$mask = false; |
314
|
|
|
} |
315
|
|
|
if ((int)$mask) { |
316
|
|
|
// "192.168.3.0/24" |
317
|
|
|
$lnet = ip2long($test); |
318
|
|
|
$lip = ip2long($baseIP); |
319
|
|
|
$binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT); |
320
|
|
|
$firstpart = substr($binnet, 0, $mask); |
|
|
|
|
321
|
|
|
$binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT); |
322
|
|
|
$firstip = substr($binip, 0, $mask); |
323
|
|
|
$yes = $firstpart === $firstip; |
324
|
|
|
} else { |
325
|
|
|
// "192.168.*.*" |
326
|
|
|
$IPparts = explode('.', $test); |
327
|
|
|
$yes = 1; |
328
|
|
|
foreach ($IPparts as $index => $val) { |
329
|
|
|
$val = trim($val); |
330
|
|
|
if ($val !== '*' && $IPpartsReq[$index] !== $val) { |
331
|
|
|
$yes = 0; |
332
|
|
|
} |
333
|
|
|
} |
334
|
|
|
} |
335
|
|
|
if ($yes) { |
336
|
|
|
return true; |
337
|
|
|
} |
338
|
|
|
} |
339
|
|
|
} |
340
|
|
|
return false; |
341
|
|
|
} |
342
|
|
|
|
343
|
|
|
/** |
344
|
|
|
* Match IPv6 address with a list of IPv6 prefixes |
345
|
|
|
* |
346
|
|
|
* @param string $baseIP Is the current remote IP address for instance |
347
|
|
|
* @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses |
348
|
|
|
* @return bool TRUE If an baseIP matches any prefix |
349
|
|
|
*/ |
350
|
|
|
public static function cmpIPv6($baseIP, $list) |
351
|
|
|
{ |
352
|
|
|
// Policy default: Deny connection |
353
|
|
|
$success = false; |
354
|
|
|
$baseIP = self::normalizeIPv6($baseIP); |
355
|
|
|
$values = self::trimExplode(',', $list, true); |
356
|
|
|
foreach ($values as $test) { |
357
|
|
|
$testList = explode('/', $test); |
358
|
|
View Code Duplication |
if (count($testList) === 2) { |
359
|
|
|
list($test, $mask) = $testList; |
360
|
|
|
} else { |
361
|
|
|
$mask = false; |
362
|
|
|
} |
363
|
|
|
if (self::validIPv6($test)) { |
364
|
|
|
$test = self::normalizeIPv6($test); |
365
|
|
|
$maskInt = (int)$mask ?: 128; |
366
|
|
|
// Special case; /0 is an allowed mask - equals a wildcard |
367
|
|
|
if ($mask === '0') { |
368
|
|
|
$success = true; |
369
|
|
|
} elseif ($maskInt == 128) { |
370
|
|
|
$success = $test === $baseIP; |
371
|
|
|
} else { |
372
|
|
|
$testBin = self::IPv6Hex2Bin($test); |
373
|
|
|
$baseIPBin = self::IPv6Hex2Bin($baseIP); |
374
|
|
|
$success = true; |
375
|
|
|
// Modulo is 0 if this is a 8-bit-boundary |
376
|
|
|
$maskIntModulo = $maskInt % 8; |
377
|
|
|
$numFullCharactersUntilBoundary = (int)($maskInt / 8); |
378
|
|
|
if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) { |
379
|
|
|
$success = false; |
380
|
|
|
} elseif ($maskIntModulo > 0) { |
381
|
|
|
// If not an 8-bit-boundary, check bits of last character |
382
|
|
|
$testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT); |
|
|
|
|
383
|
|
|
$baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT); |
384
|
|
|
if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) { |
385
|
|
|
$success = false; |
386
|
|
|
} |
387
|
|
|
} |
388
|
|
|
} |
389
|
|
|
} |
390
|
|
|
if ($success) { |
391
|
|
|
return true; |
392
|
|
|
} |
393
|
|
|
} |
394
|
|
|
return false; |
395
|
|
|
} |
396
|
|
|
|
397
|
|
|
/** |
398
|
|
|
* Transform a regular IPv6 address from hex-representation into binary |
399
|
|
|
* |
400
|
|
|
* @param string $hex IPv6 address in hex-presentation |
401
|
|
|
* @return string Binary representation (16 characters, 128 characters) |
402
|
|
|
* @see IPv6Bin2Hex() |
403
|
|
|
*/ |
404
|
|
|
public static function IPv6Hex2Bin($hex) |
405
|
|
|
{ |
406
|
|
|
return inet_pton($hex); |
407
|
|
|
} |
408
|
|
|
|
409
|
|
|
/** |
410
|
|
|
* Transform an IPv6 address from binary to hex-representation |
411
|
|
|
* |
412
|
|
|
* @param string $bin IPv6 address in hex-presentation |
413
|
|
|
* @return string Binary representation (16 characters, 128 characters) |
414
|
|
|
* @see IPv6Hex2Bin() |
415
|
|
|
*/ |
416
|
|
|
public static function IPv6Bin2Hex($bin) |
417
|
|
|
{ |
418
|
|
|
return inet_ntop($bin); |
419
|
|
|
} |
420
|
|
|
|
421
|
|
|
/** |
422
|
|
|
* Normalize an IPv6 address to full length |
423
|
|
|
* |
424
|
|
|
* @param string $address Given IPv6 address |
425
|
|
|
* @return string Normalized address |
426
|
|
|
* @see compressIPv6() |
427
|
|
|
*/ |
428
|
|
|
public static function normalizeIPv6($address) |
429
|
|
|
{ |
430
|
|
|
$normalizedAddress = ''; |
431
|
|
|
$stageOneAddress = ''; |
432
|
|
|
// According to RFC lowercase-representation is recommended |
433
|
|
|
$address = strtolower($address); |
434
|
|
|
// Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000) |
435
|
|
|
if (strlen($address) === 39) { |
436
|
|
|
// Already in full expanded form |
437
|
|
|
return $address; |
438
|
|
|
} |
439
|
|
|
// Count 2 if if address has hidden zero blocks |
440
|
|
|
$chunks = explode('::', $address); |
441
|
|
|
if (count($chunks) === 2) { |
442
|
|
|
$chunksLeft = explode(':', $chunks[0]); |
443
|
|
|
$chunksRight = explode(':', $chunks[1]); |
444
|
|
|
$left = count($chunksLeft); |
445
|
|
|
$right = count($chunksRight); |
446
|
|
|
// Special case: leading zero-only blocks count to 1, should be 0 |
447
|
|
|
if ($left === 1 && strlen($chunksLeft[0]) === 0) { |
448
|
|
|
$left = 0; |
449
|
|
|
} |
450
|
|
|
$hiddenBlocks = 8 - ($left + $right); |
451
|
|
|
$hiddenPart = ''; |
452
|
|
|
$h = 0; |
453
|
|
|
while ($h < $hiddenBlocks) { |
454
|
|
|
$hiddenPart .= '0000:'; |
455
|
|
|
$h++; |
456
|
|
|
} |
457
|
|
|
if ($left === 0) { |
458
|
|
|
$stageOneAddress = $hiddenPart . $chunks[1]; |
459
|
|
|
} else { |
460
|
|
|
$stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1]; |
461
|
|
|
} |
462
|
|
|
} else { |
463
|
|
|
$stageOneAddress = $address; |
464
|
|
|
} |
465
|
|
|
// Normalize the blocks: |
466
|
|
|
$blocks = explode(':', $stageOneAddress); |
467
|
|
|
$divCounter = 0; |
468
|
|
|
foreach ($blocks as $block) { |
469
|
|
|
$tmpBlock = ''; |
470
|
|
|
$i = 0; |
471
|
|
|
$hiddenZeros = 4 - strlen($block); |
472
|
|
|
while ($i < $hiddenZeros) { |
473
|
|
|
$tmpBlock .= '0'; |
474
|
|
|
$i++; |
475
|
|
|
} |
476
|
|
|
$normalizedAddress .= $tmpBlock . $block; |
477
|
|
|
if ($divCounter < 7) { |
478
|
|
|
$normalizedAddress .= ':'; |
479
|
|
|
$divCounter++; |
480
|
|
|
} |
481
|
|
|
} |
482
|
|
|
return $normalizedAddress; |
483
|
|
|
} |
484
|
|
|
|
485
|
|
|
/** |
486
|
|
|
* Compress an IPv6 address to the shortest notation |
487
|
|
|
* |
488
|
|
|
* @param string $address Given IPv6 address |
489
|
|
|
* @return string Compressed address |
490
|
|
|
* @see normalizeIPv6() |
491
|
|
|
*/ |
492
|
|
|
public static function compressIPv6($address) |
493
|
|
|
{ |
494
|
|
|
return inet_ntop(inet_pton($address)); |
495
|
|
|
} |
496
|
|
|
|
497
|
|
|
/** |
498
|
|
|
* Validate a given IP address. |
499
|
|
|
* |
500
|
|
|
* Possible format are IPv4 and IPv6. |
501
|
|
|
* |
502
|
|
|
* @param string $ip IP address to be tested |
503
|
|
|
* @return bool TRUE if $ip is either of IPv4 or IPv6 format. |
504
|
|
|
*/ |
505
|
|
|
public static function validIP($ip) |
506
|
|
|
{ |
507
|
|
|
return filter_var($ip, FILTER_VALIDATE_IP) !== false; |
508
|
|
|
} |
509
|
|
|
|
510
|
|
|
/** |
511
|
|
|
* Validate a given IP address to the IPv4 address format. |
512
|
|
|
* |
513
|
|
|
* Example for possible format: 10.0.45.99 |
514
|
|
|
* |
515
|
|
|
* @param string $ip IP address to be tested |
516
|
|
|
* @return bool TRUE if $ip is of IPv4 format. |
517
|
|
|
*/ |
518
|
|
|
public static function validIPv4($ip) |
519
|
|
|
{ |
520
|
|
|
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; |
521
|
|
|
} |
522
|
|
|
|
523
|
|
|
/** |
524
|
|
|
* Validate a given IP address to the IPv6 address format. |
525
|
|
|
* |
526
|
|
|
* Example for possible format: 43FB::BB3F:A0A0:0 | ::1 |
527
|
|
|
* |
528
|
|
|
* @param string $ip IP address to be tested |
529
|
|
|
* @return bool TRUE if $ip is of IPv6 format. |
530
|
|
|
*/ |
531
|
|
|
public static function validIPv6($ip) |
532
|
|
|
{ |
533
|
|
|
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; |
534
|
|
|
} |
535
|
|
|
|
536
|
|
|
/** |
537
|
|
|
* Match fully qualified domain name with list of strings with wildcard |
538
|
|
|
* |
539
|
|
|
* @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR) |
540
|
|
|
* @param string $list A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong) |
541
|
|
|
* @return bool TRUE if a domain name mask from $list matches $baseIP |
542
|
|
|
*/ |
543
|
|
|
public static function cmpFQDN($baseHost, $list) |
544
|
|
|
{ |
545
|
|
|
$baseHost = trim($baseHost); |
546
|
|
|
if (empty($baseHost)) { |
547
|
|
|
return false; |
548
|
|
|
} |
549
|
|
|
if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) { |
550
|
|
|
// Resolve hostname |
551
|
|
|
// Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set |
552
|
|
|
// the reverse-DNS for his IP (security when for example used with REMOTE_ADDR) |
553
|
|
|
$baseHostName = gethostbyaddr($baseHost); |
554
|
|
|
if ($baseHostName === $baseHost) { |
555
|
|
|
// Unable to resolve hostname |
556
|
|
|
return false; |
557
|
|
|
} |
558
|
|
|
} else { |
559
|
|
|
$baseHostName = $baseHost; |
560
|
|
|
} |
561
|
|
|
$baseHostNameParts = explode('.', $baseHostName); |
562
|
|
|
$values = self::trimExplode(',', $list, true); |
563
|
|
|
foreach ($values as $test) { |
564
|
|
|
$hostNameParts = explode('.', $test); |
565
|
|
|
// To match hostNameParts can only be shorter (in case of wildcards) or equal |
566
|
|
|
$hostNamePartsCount = count($hostNameParts); |
567
|
|
|
$baseHostNamePartsCount = count($baseHostNameParts); |
568
|
|
|
if ($hostNamePartsCount > $baseHostNamePartsCount) { |
569
|
|
|
continue; |
570
|
|
|
} |
571
|
|
|
$yes = true; |
572
|
|
|
foreach ($hostNameParts as $index => $val) { |
573
|
|
|
$val = trim($val); |
574
|
|
|
if ($val === '*') { |
575
|
|
|
// Wildcard valid for one or more hostname-parts |
576
|
|
|
$wildcardStart = $index + 1; |
577
|
|
|
// Wildcard as last/only part always matches, otherwise perform recursive checks |
578
|
|
|
if ($wildcardStart < $hostNamePartsCount) { |
579
|
|
|
$wildcardMatched = false; |
580
|
|
|
$tempHostName = implode('.', array_slice($hostNameParts, $index + 1)); |
581
|
|
|
while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) { |
582
|
|
|
$tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart)); |
583
|
|
|
$wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName); |
584
|
|
|
$wildcardStart++; |
585
|
|
|
} |
586
|
|
|
if ($wildcardMatched) { |
587
|
|
|
// Match found by recursive compare |
588
|
|
|
return true; |
589
|
|
|
} |
590
|
|
|
$yes = false; |
591
|
|
|
} |
592
|
|
|
} elseif ($baseHostNameParts[$index] !== $val) { |
593
|
|
|
// In case of no match |
594
|
|
|
$yes = false; |
595
|
|
|
} |
596
|
|
|
} |
597
|
|
|
if ($yes) { |
598
|
|
|
return true; |
599
|
|
|
} |
600
|
|
|
} |
601
|
|
|
return false; |
602
|
|
|
} |
603
|
|
|
|
604
|
|
|
/** |
605
|
|
|
* Checks if a given URL matches the host that currently handles this HTTP request. |
606
|
|
|
* Scheme, hostname and (optional) port of the given URL are compared. |
607
|
|
|
* |
608
|
|
|
* @param string $url URL to compare with the TYPO3 request host |
609
|
|
|
* @return bool Whether the URL matches the TYPO3 request host |
610
|
|
|
*/ |
611
|
|
|
public static function isOnCurrentHost($url) |
612
|
|
|
{ |
613
|
|
|
return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0; |
614
|
|
|
} |
615
|
|
|
|
616
|
|
|
/** |
617
|
|
|
* Check for item in list |
618
|
|
|
* Check if an item exists in a comma-separated list of items. |
619
|
|
|
* |
620
|
|
|
* @param string $list Comma-separated list of items (string) |
621
|
|
|
* @param string $item Item to check for |
622
|
|
|
* @return bool TRUE if $item is in $list |
623
|
|
|
*/ |
624
|
|
|
public static function inList($list, $item) |
625
|
|
|
{ |
626
|
|
|
return strpos(',' . $list . ',', ',' . $item . ',') !== false; |
627
|
|
|
} |
628
|
|
|
|
629
|
|
|
/** |
630
|
|
|
* Removes an item from a comma-separated list of items. |
631
|
|
|
* |
632
|
|
|
* If $element contains a comma, the behaviour of this method is undefined. |
633
|
|
|
* Empty elements in the list are preserved. |
634
|
|
|
* |
635
|
|
|
* @param string $element Element to remove |
636
|
|
|
* @param string $list Comma-separated list of items (string) |
637
|
|
|
* @return string New comma-separated list of items |
638
|
|
|
*/ |
639
|
|
|
public static function rmFromList($element, $list) |
640
|
|
|
{ |
641
|
|
|
$items = explode(',', $list); |
642
|
|
|
foreach ($items as $k => $v) { |
643
|
|
|
if ($v == $element) { |
644
|
|
|
unset($items[$k]); |
645
|
|
|
} |
646
|
|
|
} |
647
|
|
|
return implode(',', $items); |
648
|
|
|
} |
649
|
|
|
|
650
|
|
|
/** |
651
|
|
|
* Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7). |
652
|
|
|
* Ranges are limited to 1000 values per range. |
653
|
|
|
* |
654
|
|
|
* @param string $list Comma-separated list of integers with ranges (string) |
655
|
|
|
* @return string New comma-separated list of items |
656
|
|
|
*/ |
657
|
|
|
public static function expandList($list) |
658
|
|
|
{ |
659
|
|
|
$items = explode(',', $list); |
660
|
|
|
$list = []; |
661
|
|
|
foreach ($items as $item) { |
662
|
|
|
$range = explode('-', $item); |
663
|
|
|
if (isset($range[1])) { |
664
|
|
|
$runAwayBrake = 1000; |
665
|
|
|
for ($n = $range[0]; $n <= $range[1]; $n++) { |
666
|
|
|
$list[] = $n; |
667
|
|
|
$runAwayBrake--; |
668
|
|
|
if ($runAwayBrake <= 0) { |
669
|
|
|
break; |
670
|
|
|
} |
671
|
|
|
} |
672
|
|
|
} else { |
673
|
|
|
$list[] = $item; |
674
|
|
|
} |
675
|
|
|
} |
676
|
|
|
return implode(',', $list); |
677
|
|
|
} |
678
|
|
|
|
679
|
|
|
/** |
680
|
|
|
* Makes a positive integer hash out of the first 7 chars from the md5 hash of the input |
681
|
|
|
* |
682
|
|
|
* @param string $str String to md5-hash |
683
|
|
|
* @return int Returns 28bit integer-hash |
684
|
|
|
*/ |
685
|
|
|
public static function md5int($str) |
686
|
|
|
{ |
687
|
|
|
return hexdec(substr(md5($str), 0, 7)); |
|
|
|
|
688
|
|
|
} |
689
|
|
|
|
690
|
|
|
/** |
691
|
|
|
* Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently) |
692
|
|
|
* |
693
|
|
|
* @param string $input Input string to be md5-hashed |
694
|
|
|
* @param int $len The string-length of the output |
695
|
|
|
* @return string Substring of the resulting md5-hash, being $len chars long (from beginning) |
696
|
|
|
*/ |
697
|
|
|
public static function shortMD5($input, $len = 10) |
698
|
|
|
{ |
699
|
|
|
return substr(md5($input), 0, $len); |
700
|
|
|
} |
701
|
|
|
|
702
|
|
|
/** |
703
|
|
|
* Returns a proper HMAC on a given input string and secret TYPO3 encryption key. |
704
|
|
|
* |
705
|
|
|
* @param string $input Input string to create HMAC from |
706
|
|
|
* @param string $additionalSecret additionalSecret to prevent hmac being used in a different context |
707
|
|
|
* @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1) |
708
|
|
|
*/ |
709
|
|
|
public static function hmac($input, $additionalSecret = '') |
710
|
|
|
{ |
711
|
|
|
$hashAlgorithm = 'sha1'; |
712
|
|
|
$hashBlocksize = 64; |
713
|
|
|
$secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret; |
714
|
|
|
if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) { |
715
|
|
|
$hmac = hash_hmac($hashAlgorithm, $input, $secret); |
716
|
|
|
} else { |
717
|
|
|
// Outer padding |
718
|
|
|
$opad = str_repeat(chr(92), $hashBlocksize); |
719
|
|
|
// Inner padding |
720
|
|
|
$ipad = str_repeat(chr(54), $hashBlocksize); |
721
|
|
|
if (strlen($secret) > $hashBlocksize) { |
722
|
|
|
// Keys longer than block size are shorten |
723
|
|
|
$key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, chr(0)); |
724
|
|
|
} else { |
725
|
|
|
// Keys shorter than block size are zero-padded |
726
|
|
|
$key = str_pad($secret, $hashBlocksize, chr(0)); |
727
|
|
|
} |
728
|
|
|
$hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, (($key ^ $ipad) . $input)))); |
729
|
|
|
} |
730
|
|
|
return $hmac; |
731
|
|
|
} |
732
|
|
|
|
733
|
|
|
/** |
734
|
|
|
* Takes comma-separated lists and arrays and removes all duplicates |
735
|
|
|
* If a value in the list is trim(empty), the value is ignored. |
736
|
|
|
* |
737
|
|
|
* @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays. |
738
|
|
|
* @param mixed $secondParameter Dummy field, which if set will show a warning! |
739
|
|
|
* @return string Returns the list without any duplicates of values, space around values are trimmed |
740
|
|
|
*/ |
741
|
|
|
public static function uniqueList($in_list, $secondParameter = null) |
742
|
|
|
{ |
743
|
|
|
if (is_array($in_list)) { |
744
|
|
|
throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885); |
745
|
|
|
} |
746
|
|
|
if (isset($secondParameter)) { |
747
|
|
|
throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!', 1270853886); |
748
|
|
|
} |
749
|
|
|
return implode(',', array_unique(self::trimExplode(',', $in_list, true))); |
750
|
|
|
} |
751
|
|
|
|
752
|
|
|
/** |
753
|
|
|
* Splits a reference to a file in 5 parts |
754
|
|
|
* |
755
|
|
|
* @param string $fileNameWithPath File name with path to be analysed (must exist if open_basedir is set) |
756
|
|
|
* @return array Contains keys [path], [file], [filebody], [fileext], [realFileext] |
757
|
|
|
*/ |
758
|
|
|
public static function split_fileref($fileNameWithPath) |
759
|
|
|
{ |
760
|
|
|
$reg = []; |
761
|
|
|
if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) { |
762
|
|
|
$info['path'] = $reg[1]; |
|
|
|
|
763
|
|
|
$info['file'] = $reg[2]; |
764
|
|
|
} else { |
765
|
|
|
$info['path'] = ''; |
766
|
|
|
$info['file'] = $fileNameWithPath; |
767
|
|
|
} |
768
|
|
|
$reg = ''; |
769
|
|
|
// If open_basedir is set and the fileName was supplied without a path the is_dir check fails |
770
|
|
|
if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) { |
|
|
|
|
771
|
|
|
$info['filebody'] = $reg[1]; |
772
|
|
|
$info['fileext'] = strtolower($reg[2]); |
773
|
|
|
$info['realFileext'] = $reg[2]; |
774
|
|
|
} else { |
775
|
|
|
$info['filebody'] = $info['file']; |
776
|
|
|
$info['fileext'] = ''; |
777
|
|
|
} |
778
|
|
|
reset($info); |
779
|
|
|
return $info; |
780
|
|
|
} |
781
|
|
|
|
782
|
|
|
/** |
783
|
|
|
* Returns the directory part of a path without trailing slash |
784
|
|
|
* If there is no dir-part, then an empty string is returned. |
785
|
|
|
* Behaviour: |
786
|
|
|
* |
787
|
|
|
* '/dir1/dir2/script.php' => '/dir1/dir2' |
788
|
|
|
* '/dir1/' => '/dir1' |
789
|
|
|
* 'dir1/script.php' => 'dir1' |
790
|
|
|
* 'd/script.php' => 'd' |
791
|
|
|
* '/script.php' => '' |
792
|
|
|
* '' => '' |
793
|
|
|
* |
794
|
|
|
* @param string $path Directory name / path |
795
|
|
|
* @return string Processed input value. See function description. |
796
|
|
|
*/ |
797
|
|
|
public static function dirname($path) |
798
|
|
|
{ |
799
|
|
|
$p = self::revExplode('/', $path, 2); |
800
|
|
|
return count($p) === 2 ? $p[0] : ''; |
801
|
|
|
} |
802
|
|
|
|
803
|
|
|
/** |
804
|
|
|
* Returns TRUE if the first part of $str matches the string $partStr |
805
|
|
|
* |
806
|
|
|
* @param string $str Full string to check |
807
|
|
|
* @param string $partStr Reference string which must be found as the "first part" of the full string |
808
|
|
|
* @return bool TRUE if $partStr was found to be equal to the first part of $str |
809
|
|
|
*/ |
810
|
|
|
public static function isFirstPartOfStr($str, $partStr) |
811
|
|
|
{ |
812
|
|
|
return $partStr != '' && strpos((string)$str, (string)$partStr, 0) === 0; |
813
|
|
|
} |
814
|
|
|
|
815
|
|
|
/** |
816
|
|
|
* Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M) |
817
|
|
|
* |
818
|
|
|
* @param int $sizeInBytes Number of bytes to format. |
819
|
|
|
* @param string $labels Binary unit name "iec", decimal unit name "si" or labels for bytes, kilo, mega, giga, and so on separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G". Defaults to "iec". |
820
|
|
|
* @param int $base The unit base if not using a unit name. Defaults to 1024. |
821
|
|
|
* @return string Formatted representation of the byte number, for output. |
822
|
|
|
*/ |
823
|
|
|
public static function formatSize($sizeInBytes, $labels = '', $base = 0) |
824
|
|
|
{ |
825
|
|
|
$defaultFormats = [ |
826
|
|
|
'iec' => ['base' => 1024, 'labels' => [' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi']], |
827
|
|
|
'si' => ['base' => 1000, 'labels' => [' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']], |
828
|
|
|
]; |
829
|
|
|
// Set labels and base: |
830
|
|
|
if (empty($labels)) { |
831
|
|
|
$labels = 'iec'; |
832
|
|
|
} |
833
|
|
|
if (isset($defaultFormats[$labels])) { |
834
|
|
|
$base = $defaultFormats[$labels]['base']; |
835
|
|
|
$labelArr = $defaultFormats[$labels]['labels']; |
836
|
|
|
} else { |
837
|
|
|
$base = (int)$base; |
838
|
|
|
if ($base !== 1000 && $base !== 1024) { |
839
|
|
|
$base = 1024; |
840
|
|
|
} |
841
|
|
|
$labelArr = explode('|', str_replace('"', '', $labels)); |
842
|
|
|
} |
843
|
|
|
// @todo find out which locale is used for current BE user to cover the BE case as well |
844
|
|
|
$oldLocale = setlocale(LC_NUMERIC, 0); |
845
|
|
|
$newLocale = isset($GLOBALS['TSFE']) ? $GLOBALS['TSFE']->config['config']['locale_all'] : ''; |
846
|
|
|
if ($newLocale) { |
847
|
|
|
setlocale(LC_NUMERIC, $newLocale); |
848
|
|
|
} |
849
|
|
|
$localeInfo = localeconv(); |
850
|
|
|
if ($newLocale) { |
851
|
|
|
setlocale(LC_NUMERIC, $oldLocale); |
852
|
|
|
} |
853
|
|
|
$sizeInBytes = max($sizeInBytes, 0); |
854
|
|
|
$multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base)); |
855
|
|
|
$sizeInUnits = $sizeInBytes / pow($base, $multiplier); |
856
|
|
|
if ($sizeInUnits > ($base * .9)) { |
857
|
|
|
$multiplier++; |
858
|
|
|
} |
859
|
|
|
$multiplier = min($multiplier, count($labelArr) - 1); |
860
|
|
|
$sizeInUnits = $sizeInBytes / pow($base, $multiplier); |
861
|
|
|
return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier]; |
862
|
|
|
} |
863
|
|
|
|
864
|
|
|
/** |
865
|
|
|
* This splits a string by the chars in $operators (typical /+-*) and returns an array with them in |
866
|
|
|
* |
867
|
|
|
* @param string $string Input string, eg "123 + 456 / 789 - 4 |
868
|
|
|
* @param string $operators Operators to split by, typically "/+-* |
869
|
|
|
* @return array Array with operators and operands separated. |
870
|
|
|
* @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc(), \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset() |
871
|
|
|
*/ |
872
|
|
|
public static function splitCalc($string, $operators) |
873
|
|
|
{ |
874
|
|
|
$res = []; |
875
|
|
|
$sign = '+'; |
876
|
|
|
while ($string) { |
|
|
|
|
877
|
|
|
$valueLen = strcspn($string, $operators); |
878
|
|
|
$value = substr($string, 0, $valueLen); |
879
|
|
|
$res[] = [$sign, trim($value)]; |
|
|
|
|
880
|
|
|
$sign = substr($string, $valueLen, 1); |
881
|
|
|
$string = substr($string, $valueLen + 1); |
882
|
|
|
} |
883
|
|
|
reset($res); |
884
|
|
|
return $res; |
885
|
|
|
} |
886
|
|
|
|
887
|
|
|
/** |
888
|
|
|
* Checking syntax of input email address |
889
|
|
|
* |
890
|
|
|
* http://tools.ietf.org/html/rfc3696 |
891
|
|
|
* International characters are allowed in email. So the whole address needs |
892
|
|
|
* to be converted to punicode before passing it to filter_var(). We convert |
893
|
|
|
* the user- and domain part separately to increase the chance of hitting an |
894
|
|
|
* entry in self::$idnaStringCache. |
895
|
|
|
* |
896
|
|
|
* Also the @ sign may appear multiple times in an address. If not used as |
897
|
|
|
* a boundary marker between the user- and domain part, it must be escaped |
898
|
|
|
* with a backslash: \@. This mean we can not just explode on the @ sign and |
899
|
|
|
* expect to get just two parts. So we pop off the domain and then glue the |
900
|
|
|
* rest together again. |
901
|
|
|
* |
902
|
|
|
* @param string $email Input string to evaluate |
903
|
|
|
* @return bool Returns TRUE if the $email address (input string) is valid |
904
|
|
|
*/ |
905
|
|
|
public static function validEmail($email) |
906
|
|
|
{ |
907
|
|
|
// Early return in case input is not a string |
908
|
|
|
if (!is_string($email)) { |
909
|
|
|
return false; |
910
|
|
|
} |
911
|
|
|
$atPosition = strrpos($email, '@'); |
912
|
|
|
if (!$atPosition || $atPosition + 1 === strlen($email)) { |
|
|
|
|
913
|
|
|
// Return if no @ found or it is placed at the very beginning or end of the email |
914
|
|
|
return false; |
915
|
|
|
} |
916
|
|
|
$domain = substr($email, $atPosition + 1); |
917
|
|
|
$user = substr($email, 0, $atPosition); |
918
|
|
|
if (!preg_match('/^[a-z0-9.\\-]*$/i', $domain)) { |
|
|
|
|
919
|
|
|
try { |
920
|
|
|
$domain = self::idnaEncode($domain); |
|
|
|
|
921
|
|
|
} catch (\InvalidArgumentException $exception) { |
922
|
|
|
return false; |
923
|
|
|
} |
924
|
|
|
} |
925
|
|
|
return filter_var($user . '@' . $domain, FILTER_VALIDATE_EMAIL) !== false; |
|
|
|
|
926
|
|
|
} |
927
|
|
|
|
928
|
|
|
/** |
929
|
|
|
* Returns an ASCII string (punicode) representation of $value |
930
|
|
|
* |
931
|
|
|
* @param string $value |
932
|
|
|
* @return string An ASCII encoded (punicode) string |
933
|
|
|
*/ |
934
|
|
|
public static function idnaEncode($value) |
935
|
|
|
{ |
936
|
|
|
if (isset(self::$idnaStringCache[$value])) { |
937
|
|
|
return self::$idnaStringCache[$value]; |
938
|
|
|
} |
939
|
|
|
if (!self::$idnaConverter) { |
940
|
|
|
self::$idnaConverter = new \Mso\IdnaConvert\IdnaConvert(['idn_version' => 2008]); |
941
|
|
|
} |
942
|
|
|
self::$idnaStringCache[$value] = self::$idnaConverter->encode($value); |
943
|
|
|
return self::$idnaStringCache[$value]; |
944
|
|
|
} |
945
|
|
|
|
946
|
|
|
/** |
947
|
|
|
* Returns a given string with underscores as UpperCamelCase. |
948
|
|
|
* Example: Converts blog_example to BlogExample |
949
|
|
|
* |
950
|
|
|
* @param string $string String to be converted to camel case |
951
|
|
|
* @return string UpperCamelCasedWord |
952
|
|
|
*/ |
953
|
|
|
public static function underscoredToUpperCamelCase($string) |
954
|
|
|
{ |
955
|
|
|
return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string)))); |
956
|
|
|
} |
957
|
|
|
|
958
|
|
|
/** |
959
|
|
|
* Returns a given string with underscores as lowerCamelCase. |
960
|
|
|
* Example: Converts minimal_value to minimalValue |
961
|
|
|
* |
962
|
|
|
* @param string $string String to be converted to camel case |
963
|
|
|
* @return string lowerCamelCasedWord |
964
|
|
|
*/ |
965
|
|
|
public static function underscoredToLowerCamelCase($string) |
966
|
|
|
{ |
967
|
|
|
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string))))); |
968
|
|
|
} |
969
|
|
|
|
970
|
|
|
/** |
971
|
|
|
* Returns a given CamelCasedString as an lowercase string with underscores. |
972
|
|
|
* Example: Converts BlogExample to blog_example, and minimalValue to minimal_value |
973
|
|
|
* |
974
|
|
|
* @param string $string String to be converted to lowercase underscore |
975
|
|
|
* @return string lowercase_and_underscored_string |
976
|
|
|
*/ |
977
|
|
|
public static function camelCaseToLowerCaseUnderscored($string) |
978
|
|
|
{ |
979
|
|
|
$value = preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string); |
980
|
|
|
return mb_strtolower($value, 'utf-8'); |
981
|
|
|
} |
982
|
|
|
|
983
|
|
|
/** |
984
|
|
|
* Checks if a given string is a Uniform Resource Locator (URL). |
985
|
|
|
* |
986
|
|
|
* On seriously malformed URLs, parse_url may return FALSE and emit an |
987
|
|
|
* E_WARNING. |
988
|
|
|
* |
989
|
|
|
* filter_var() requires a scheme to be present. |
990
|
|
|
* |
991
|
|
|
* http://www.faqs.org/rfcs/rfc2396.html |
992
|
|
|
* Scheme names consist of a sequence of characters beginning with a |
993
|
|
|
* lower case letter and followed by any combination of lower case letters, |
994
|
|
|
* digits, plus ("+"), period ("."), or hyphen ("-"). For resiliency, |
995
|
|
|
* programs interpreting URI should treat upper case letters as equivalent to |
996
|
|
|
* lower case in scheme names (e.g., allow "HTTP" as well as "http"). |
997
|
|
|
* scheme = alpha *( alpha | digit | "+" | "-" | "." ) |
998
|
|
|
* |
999
|
|
|
* Convert the domain part to punicode if it does not look like a regular |
1000
|
|
|
* domain name. Only the domain part because RFC3986 specifies the the rest of |
1001
|
|
|
* the url may not contain special characters: |
1002
|
|
|
* http://tools.ietf.org/html/rfc3986#appendix-A |
1003
|
|
|
* |
1004
|
|
|
* @param string $url The URL to be validated |
1005
|
|
|
* @return bool Whether the given URL is valid |
1006
|
|
|
*/ |
1007
|
|
|
public static function isValidUrl($url) |
1008
|
|
|
{ |
1009
|
|
|
$parsedUrl = parse_url($url); |
1010
|
|
|
if (!$parsedUrl || !isset($parsedUrl['scheme'])) { |
|
|
|
|
1011
|
|
|
return false; |
1012
|
|
|
} |
1013
|
|
|
// HttpUtility::buildUrl() will always build urls with <scheme>:// |
1014
|
|
|
// our original $url might only contain <scheme>: (e.g. mail:) |
1015
|
|
|
// so we convert that to the double-slashed version to ensure |
1016
|
|
|
// our check against the $recomposedUrl is proper |
1017
|
|
|
if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) { |
1018
|
|
|
$url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url); |
1019
|
|
|
} |
1020
|
|
|
$recomposedUrl = HttpUtility::buildUrl($parsedUrl); |
1021
|
|
|
if ($recomposedUrl !== $url) { |
1022
|
|
|
// The parse_url() had to modify characters, so the URL is invalid |
1023
|
|
|
return false; |
1024
|
|
|
} |
1025
|
|
|
if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) { |
1026
|
|
|
try { |
1027
|
|
|
$parsedUrl['host'] = self::idnaEncode($parsedUrl['host']); |
1028
|
|
|
} catch (\InvalidArgumentException $exception) { |
1029
|
|
|
return false; |
1030
|
|
|
} |
1031
|
|
|
} |
1032
|
|
|
return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false; |
1033
|
|
|
} |
1034
|
|
|
|
1035
|
|
|
/************************* |
1036
|
|
|
* |
1037
|
|
|
* ARRAY FUNCTIONS |
1038
|
|
|
* |
1039
|
|
|
*************************/ |
1040
|
|
|
|
1041
|
|
|
/** |
1042
|
|
|
* Explodes a $string delimited by $delimiter and casts each item in the array to (int). |
1043
|
|
|
* Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values. |
1044
|
|
|
* |
1045
|
|
|
* @param string $delimiter Delimiter string to explode with |
1046
|
|
|
* @param string $string The string to explode |
1047
|
|
|
* @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output |
1048
|
|
|
* @param int $limit If positive, the result will contain a maximum of limit elements, |
1049
|
|
|
* @return array Exploded values, all converted to integers |
1050
|
|
|
*/ |
1051
|
|
|
public static function intExplode($delimiter, $string, $removeEmptyValues = false, $limit = 0) |
1052
|
|
|
{ |
1053
|
|
|
$result = explode($delimiter, $string); |
1054
|
|
|
foreach ($result as $key => &$value) { |
1055
|
|
|
if ($removeEmptyValues && ($value === '' || trim($value) === '')) { |
1056
|
|
|
unset($result[$key]); |
1057
|
|
|
} else { |
1058
|
|
|
$value = (int)$value; |
1059
|
|
|
} |
1060
|
|
|
} |
1061
|
|
|
unset($value); |
1062
|
|
|
if ($limit !== 0) { |
1063
|
|
|
if ($limit < 0) { |
1064
|
|
|
$result = array_slice($result, 0, $limit); |
1065
|
|
|
} elseif (count($result) > $limit) { |
1066
|
|
|
$lastElements = array_slice($result, $limit - 1); |
1067
|
|
|
$result = array_slice($result, 0, $limit - 1); |
1068
|
|
|
$result[] = implode($delimiter, $lastElements); |
1069
|
|
|
} |
1070
|
|
|
} |
1071
|
|
|
return $result; |
1072
|
|
|
} |
1073
|
|
|
|
1074
|
|
|
/** |
1075
|
|
|
* Reverse explode which explodes the string counting from behind. |
1076
|
|
|
* |
1077
|
|
|
* Note: The delimiter has to given in the reverse order as |
1078
|
|
|
* it is occurring within the string. |
1079
|
|
|
* |
1080
|
|
|
* GeneralUtility::revExplode('[]', '[my][words][here]', 2) |
1081
|
|
|
* ==> array('[my][words', 'here]') |
1082
|
|
|
* |
1083
|
|
|
* @param string $delimiter Delimiter string to explode with |
1084
|
|
|
* @param string $string The string to explode |
1085
|
|
|
* @param int $count Number of array entries |
1086
|
|
|
* @return array Exploded values |
1087
|
|
|
*/ |
1088
|
|
|
public static function revExplode($delimiter, $string, $count = 0) |
1089
|
|
|
{ |
1090
|
|
|
// 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first |
1091
|
|
|
if ($count === 2) { |
1092
|
|
|
$position = strrpos($string, strrev($delimiter)); |
1093
|
|
|
if ($position !== false) { |
1094
|
|
|
return [substr($string, 0, $position), substr($string, $position + strlen($delimiter))]; |
1095
|
|
|
} |
1096
|
|
|
return [$string]; |
1097
|
|
|
} |
1098
|
|
|
if ($count <= 1) { |
1099
|
|
|
return [$string]; |
1100
|
|
|
} |
1101
|
|
|
$explodedValues = explode($delimiter, strrev($string), $count); |
1102
|
|
|
$explodedValues = array_map('strrev', $explodedValues); |
1103
|
|
|
return array_reverse($explodedValues); |
1104
|
|
|
} |
1105
|
|
|
|
1106
|
|
|
/** |
1107
|
|
|
* Explodes a string and trims all values for whitespace in the end. |
1108
|
|
|
* If $onlyNonEmptyValues is set, then all blank ('') values are removed. |
1109
|
|
|
* |
1110
|
|
|
* @param string $delim Delimiter string to explode with |
1111
|
|
|
* @param string $string The string to explode |
1112
|
|
|
* @param bool $removeEmptyValues If set, all empty values will be removed in output |
1113
|
|
|
* @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with |
1114
|
|
|
* the last element containing the rest of string. If the limit parameter is negative, all components |
1115
|
|
|
* except the last -limit are returned. |
1116
|
|
|
* @return array Exploded values |
1117
|
|
|
*/ |
1118
|
|
|
public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0) |
1119
|
|
|
{ |
1120
|
|
|
$result = explode($delim, $string); |
1121
|
|
|
if ($removeEmptyValues) { |
1122
|
|
|
$temp = []; |
1123
|
|
|
foreach ($result as $value) { |
1124
|
|
|
if (trim($value) !== '') { |
1125
|
|
|
$temp[] = $value; |
1126
|
|
|
} |
1127
|
|
|
} |
1128
|
|
|
$result = $temp; |
1129
|
|
|
} |
1130
|
|
|
if ($limit > 0 && count($result) > $limit) { |
1131
|
|
|
$lastElements = array_splice($result, $limit - 1); |
1132
|
|
|
$result[] = implode($delim, $lastElements); |
1133
|
|
|
} elseif ($limit < 0) { |
1134
|
|
|
$result = array_slice($result, 0, $limit); |
1135
|
|
|
} |
1136
|
|
|
$result = array_map('trim', $result); |
1137
|
|
|
return $result; |
1138
|
|
|
} |
1139
|
|
|
|
1140
|
|
|
/** |
1141
|
|
|
* Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3) |
1142
|
|
|
* |
1143
|
|
|
* @param string $name Name prefix for entries. Set to blank if you wish none. |
1144
|
|
|
* @param array $theArray The (multidimensional) array to implode |
1145
|
|
|
* @param string $str (keep blank) |
1146
|
|
|
* @param bool $skipBlank If set, parameters which were blank strings would be removed. |
1147
|
|
|
* @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well. |
1148
|
|
|
* @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3 |
1149
|
|
|
* @see explodeUrl2Array() |
1150
|
|
|
*/ |
1151
|
|
|
public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false) |
1152
|
|
|
{ |
1153
|
|
|
foreach ($theArray as $Akey => $AVal) { |
1154
|
|
|
$thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey; |
1155
|
|
|
if (is_array($AVal)) { |
1156
|
|
|
$str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName); |
1157
|
|
|
} else { |
1158
|
|
|
if (!$skipBlank || (string)$AVal !== '') { |
1159
|
|
|
$str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal); |
1160
|
|
|
} |
1161
|
|
|
} |
1162
|
|
|
} |
1163
|
|
|
return $str; |
1164
|
|
|
} |
1165
|
|
|
|
1166
|
|
|
/** |
1167
|
|
|
* Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array |
1168
|
|
|
* |
1169
|
|
|
* @param string $string GETvars string |
1170
|
|
|
* @param bool $multidim If set, the string will be parsed into a multidimensional array if square brackets are used in variable names (using PHP function parse_str()) |
1171
|
|
|
* @return array Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it! |
1172
|
|
|
* @see implodeArrayForUrl() |
1173
|
|
|
*/ |
1174
|
|
|
public static function explodeUrl2Array($string, $multidim = false) |
1175
|
|
|
{ |
1176
|
|
|
$output = []; |
1177
|
|
|
if ($multidim) { |
1178
|
|
|
parse_str($string, $output); |
1179
|
|
|
} else { |
1180
|
|
|
$p = explode('&', $string); |
1181
|
|
|
foreach ($p as $v) { |
1182
|
|
|
if ($v !== '') { |
1183
|
|
|
list($pK, $pV) = explode('=', $v, 2); |
1184
|
|
|
$output[rawurldecode($pK)] = rawurldecode($pV); |
1185
|
|
|
} |
1186
|
|
|
} |
1187
|
|
|
} |
1188
|
|
|
return $output; |
1189
|
|
|
} |
1190
|
|
|
|
1191
|
|
|
/** |
1192
|
|
|
* Returns an array with selected keys from incoming data. |
1193
|
|
|
* (Better read source code if you want to find out...) |
1194
|
|
|
* |
1195
|
|
|
* @param string $varList List of variable/key names |
1196
|
|
|
* @param array $getArray Array from where to get values based on the keys in $varList |
1197
|
|
|
* @param bool $GPvarAlt If set, then \TYPO3\CMS\Core\Utility\GeneralUtility::_GP() is used to fetch the value if not found (isset) in the $getArray |
1198
|
|
|
* @return array Output array with selected variables. |
1199
|
|
|
*/ |
1200
|
|
|
public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = true) |
1201
|
|
|
{ |
1202
|
|
|
$keys = self::trimExplode(',', $varList, true); |
1203
|
|
|
$outArr = []; |
1204
|
|
|
foreach ($keys as $v) { |
1205
|
|
|
if (isset($getArray[$v])) { |
1206
|
|
|
$outArr[$v] = $getArray[$v]; |
1207
|
|
|
} elseif ($GPvarAlt) { |
1208
|
|
|
$outArr[$v] = self::_GP($v); |
1209
|
|
|
} |
1210
|
|
|
} |
1211
|
|
|
return $outArr; |
1212
|
|
|
} |
1213
|
|
|
|
1214
|
|
|
/** |
1215
|
|
|
* Removes dots "." from end of a key identifier of TypoScript styled array. |
1216
|
|
|
* array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value')) |
1217
|
|
|
* |
1218
|
|
|
* @param array $ts TypoScript configuration array |
1219
|
|
|
* @return array TypoScript configuration array without dots at the end of all keys |
1220
|
|
|
*/ |
1221
|
|
View Code Duplication |
public static function removeDotsFromTS(array $ts) |
1222
|
|
|
{ |
1223
|
|
|
$out = []; |
1224
|
|
|
foreach ($ts as $key => $value) { |
1225
|
|
|
if (is_array($value)) { |
1226
|
|
|
$key = rtrim($key, '.'); |
1227
|
|
|
$out[$key] = self::removeDotsFromTS($value); |
1228
|
|
|
} else { |
1229
|
|
|
$out[$key] = $value; |
1230
|
|
|
} |
1231
|
|
|
} |
1232
|
|
|
return $out; |
1233
|
|
|
} |
1234
|
|
|
|
1235
|
|
|
/************************* |
1236
|
|
|
* |
1237
|
|
|
* HTML/XML PROCESSING |
1238
|
|
|
* |
1239
|
|
|
*************************/ |
1240
|
|
|
/** |
1241
|
|
|
* Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z |
1242
|
|
|
* $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>') |
1243
|
|
|
* If an attribute is empty, then the value for the key is empty. You can check if it existed with isset() |
1244
|
|
|
* |
1245
|
|
|
* @param string $tag HTML-tag string (or attributes only) |
1246
|
|
|
* @return array Array with the attribute values. |
1247
|
|
|
*/ |
1248
|
|
|
public static function get_tag_attributes($tag) |
1249
|
|
|
{ |
1250
|
|
|
$components = self::split_tag_attributes($tag); |
1251
|
|
|
// Attribute name is stored here |
1252
|
|
|
$name = ''; |
1253
|
|
|
$valuemode = false; |
1254
|
|
|
$attributes = []; |
1255
|
|
|
foreach ($components as $key => $val) { |
1256
|
|
|
// Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value |
1257
|
|
|
if ($val !== '=') { |
1258
|
|
|
if ($valuemode) { |
1259
|
|
|
if ($name) { |
1260
|
|
|
$attributes[$name] = $val; |
1261
|
|
|
$name = ''; |
1262
|
|
|
} |
1263
|
|
|
} else { |
1264
|
|
|
if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val))) { |
1265
|
|
|
$attributes[$key] = ''; |
1266
|
|
|
$name = $key; |
1267
|
|
|
} |
1268
|
|
|
} |
1269
|
|
|
$valuemode = false; |
1270
|
|
|
} else { |
1271
|
|
|
$valuemode = true; |
1272
|
|
|
} |
1273
|
|
|
} |
1274
|
|
|
return $attributes; |
1275
|
|
|
} |
1276
|
|
|
|
1277
|
|
|
/** |
1278
|
|
|
* Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes |
1279
|
|
|
* Removes tag-name if found |
1280
|
|
|
* |
1281
|
|
|
* @param string $tag HTML-tag string (or attributes only) |
1282
|
|
|
* @return array Array with the attribute values. |
1283
|
|
|
*/ |
1284
|
|
|
public static function split_tag_attributes($tag) |
1285
|
|
|
{ |
1286
|
|
|
$tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag))); |
1287
|
|
|
// Removes any > in the end of the string |
1288
|
|
|
$tag_tmp = trim(rtrim($tag_tmp, '>')); |
1289
|
|
|
$value = []; |
1290
|
|
|
// Compared with empty string instead , 030102 |
1291
|
|
|
while ($tag_tmp !== '') { |
1292
|
|
|
$firstChar = $tag_tmp[0]; |
1293
|
|
|
if ($firstChar === '"' || $firstChar === '\'') { |
1294
|
|
|
$reg = explode($firstChar, $tag_tmp, 3); |
1295
|
|
|
$value[] = $reg[1]; |
1296
|
|
|
$tag_tmp = trim($reg[2]); |
1297
|
|
|
} elseif ($firstChar === '=') { |
1298
|
|
|
$value[] = '='; |
1299
|
|
|
// Removes = chars. |
1300
|
|
|
$tag_tmp = trim(substr($tag_tmp, 1)); |
|
|
|
|
1301
|
|
|
} else { |
1302
|
|
|
// There are '' around the value. We look for the next ' ' or '>' |
1303
|
|
|
$reg = preg_split('/[[:space:]=]/', $tag_tmp, 2); |
1304
|
|
|
$value[] = trim($reg[0]); |
1305
|
|
|
$tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]); |
|
|
|
|
1306
|
|
|
} |
1307
|
|
|
} |
1308
|
|
|
reset($value); |
1309
|
|
|
return $value; |
1310
|
|
|
} |
1311
|
|
|
|
1312
|
|
|
/** |
1313
|
|
|
* Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes) |
1314
|
|
|
* |
1315
|
|
|
* @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0 |
1316
|
|
|
* @param bool $xhtmlSafe If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch! |
1317
|
|
|
* @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values. |
1318
|
|
|
* @return string Imploded attributes, eg. 'bgcolor="red" border="0"' |
1319
|
|
|
*/ |
1320
|
|
|
public static function implodeAttributes(array $arr, $xhtmlSafe = false, $dontOmitBlankAttribs = false) |
1321
|
|
|
{ |
1322
|
|
|
if ($xhtmlSafe) { |
1323
|
|
|
$newArr = []; |
1324
|
|
|
foreach ($arr as $p => $v) { |
1325
|
|
|
if (!isset($newArr[strtolower($p)])) { |
1326
|
|
|
$newArr[strtolower($p)] = htmlspecialchars($v); |
1327
|
|
|
} |
1328
|
|
|
} |
1329
|
|
|
$arr = $newArr; |
1330
|
|
|
} |
1331
|
|
|
$list = []; |
1332
|
|
|
foreach ($arr as $p => $v) { |
1333
|
|
|
if ((string)$v !== '' || $dontOmitBlankAttribs) { |
1334
|
|
|
$list[] = $p . '="' . $v . '"'; |
1335
|
|
|
} |
1336
|
|
|
} |
1337
|
|
|
return implode(' ', $list); |
1338
|
|
|
} |
1339
|
|
|
|
1340
|
|
|
/** |
1341
|
|
|
* Wraps JavaScript code XHTML ready with <script>-tags |
1342
|
|
|
* Automatic re-indenting of the JS code is done by using the first line as indent reference. |
1343
|
|
|
* This is nice for indenting JS code with PHP code on the same level. |
1344
|
|
|
* |
1345
|
|
|
* @param string $string JavaScript code |
1346
|
|
|
* @return string The wrapped JS code, ready to put into a XHTML page |
1347
|
|
|
*/ |
1348
|
|
|
public static function wrapJS($string) |
1349
|
|
|
{ |
1350
|
|
|
if (trim($string)) { |
1351
|
|
|
// remove nl from the beginning |
1352
|
|
|
$string = ltrim($string, LF); |
1353
|
|
|
// re-ident to one tab using the first line as reference |
1354
|
|
|
$match = []; |
1355
|
|
|
if (preg_match('/^(\\t+)/', $string, $match)) { |
1356
|
|
|
$string = str_replace($match[1], TAB, $string); |
1357
|
|
|
} |
1358
|
|
|
return '<script type="text/javascript"> |
1359
|
|
|
/*<![CDATA[*/ |
1360
|
|
|
' . $string . ' |
1361
|
|
|
/*]]>*/ |
1362
|
|
|
</script>'; |
1363
|
|
|
} |
1364
|
|
|
return ''; |
1365
|
|
|
} |
1366
|
|
|
|
1367
|
|
|
/** |
1368
|
|
|
* Parses XML input into a PHP array with associative keys |
1369
|
|
|
* |
1370
|
|
|
* @param string $string XML data input |
1371
|
|
|
* @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML. |
1372
|
|
|
* @param array $parserOptions Options that will be passed to PHP's xml_parser_set_option() |
1373
|
|
|
* @return mixed The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned. |
1374
|
|
|
*/ |
1375
|
|
|
public static function xml2tree($string, $depth = 999, $parserOptions = []) |
1376
|
|
|
{ |
1377
|
|
|
// Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept |
1378
|
|
|
$previousValueOfEntityLoader = libxml_disable_entity_loader(true); |
1379
|
|
|
$parser = xml_parser_create(); |
1380
|
|
|
$vals = []; |
1381
|
|
|
$index = []; |
1382
|
|
|
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); |
1383
|
|
|
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0); |
1384
|
|
|
foreach ($parserOptions as $option => $value) { |
1385
|
|
|
xml_parser_set_option($parser, $option, $value); |
1386
|
|
|
} |
1387
|
|
|
xml_parse_into_struct($parser, $string, $vals, $index); |
1388
|
|
|
libxml_disable_entity_loader($previousValueOfEntityLoader); |
1389
|
|
View Code Duplication |
if (xml_get_error_code($parser)) { |
1390
|
|
|
return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser)); |
1391
|
|
|
} |
1392
|
|
|
xml_parser_free($parser); |
1393
|
|
|
$stack = [[]]; |
1394
|
|
|
$stacktop = 0; |
1395
|
|
|
$startPoint = 0; |
1396
|
|
|
$tagi = []; |
1397
|
|
|
foreach ($vals as $key => $val) { |
1398
|
|
|
$type = $val['type']; |
1399
|
|
|
// open tag: |
1400
|
|
|
if ($type === 'open' || $type === 'complete') { |
1401
|
|
|
$stack[$stacktop++] = $tagi; |
1402
|
|
|
if ($depth == $stacktop) { |
1403
|
|
|
$startPoint = $key; |
1404
|
|
|
} |
1405
|
|
|
$tagi = ['tag' => $val['tag']]; |
1406
|
|
|
if (isset($val['attributes'])) { |
1407
|
|
|
$tagi['attrs'] = $val['attributes']; |
1408
|
|
|
} |
1409
|
|
|
if (isset($val['value'])) { |
1410
|
|
|
$tagi['values'][] = $val['value']; |
1411
|
|
|
} |
1412
|
|
|
} |
1413
|
|
|
// finish tag: |
1414
|
|
|
if ($type === 'complete' || $type === 'close') { |
1415
|
|
|
$oldtagi = $tagi; |
1416
|
|
|
$tagi = $stack[--$stacktop]; |
1417
|
|
|
$oldtag = $oldtagi['tag']; |
1418
|
|
|
unset($oldtagi['tag']); |
1419
|
|
|
if ($depth == $stacktop + 1) { |
1420
|
|
|
if ($key - $startPoint > 0) { |
1421
|
|
|
$partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1); |
1422
|
|
|
$oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray); |
1423
|
|
|
} else { |
1424
|
|
|
$oldtagi['XMLvalue'] = $oldtagi['values'][0]; |
1425
|
|
|
} |
1426
|
|
|
} |
1427
|
|
|
$tagi['ch'][$oldtag][] = $oldtagi; |
1428
|
|
|
unset($oldtagi); |
1429
|
|
|
} |
1430
|
|
|
// cdata |
1431
|
|
|
if ($type === 'cdata') { |
1432
|
|
|
$tagi['values'][] = $val['value']; |
1433
|
|
|
} |
1434
|
|
|
} |
1435
|
|
|
return $tagi['ch']; |
1436
|
|
|
} |
1437
|
|
|
|
1438
|
|
|
/** |
1439
|
|
|
* Converts a PHP array into an XML string. |
1440
|
|
|
* The XML output is optimized for readability since associative keys are used as tag names. |
1441
|
|
|
* This also means that only alphanumeric characters are allowed in the tag names AND only keys NOT starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem. |
1442
|
|
|
* Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats) |
1443
|
|
|
* The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string |
1444
|
|
|
* The PHP variable type of the data IS preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set. |
1445
|
|
|
* The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances with 4.x versions. However, with PHP5 there seems to be the need to add an XML prologue a la <?xml version="1.0" encoding="[charset]" standalone="yes" ?> - otherwise UTF-8 is assumed! Unfortunately, many times the output from this function is used without adding that prologue meaning that non-ASCII characters will break the parsing!! This suchs of course! Effectively it means that the prologue should always be prepended setting the right characterset, alternatively the system should always run as utf-8! |
1446
|
|
|
* However using MSIE to read the XML output didn't always go well: One reason could be that the character encoding is not observed in the PHP data. The other reason may be if the tag-names are invalid in the eyes of MSIE. Also using the namespace feature will make MSIE break parsing. There might be more reasons... |
1447
|
|
|
* |
1448
|
|
|
* @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though. |
1449
|
|
|
* @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:" |
1450
|
|
|
* @param int $level Current recursion level. Don't change, stay at zero! |
1451
|
|
|
* @param string $docTag Alternative document tag. Default is "phparray". |
1452
|
|
|
* @param int $spaceInd If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single TAB is used |
1453
|
|
|
* @param array $options Options for the compilation. Key "useNindex" => 0/1 (boolean: whether to use "n0, n1, n2" for num. indexes); Key "useIndexTagForNum" => "[tag for numerical indexes]"; Key "useIndexTagForAssoc" => "[tag for associative indexes"; Key "parentTagMap" => array('parentTag' => 'thisLevelTag') |
1454
|
|
|
* @param array $stackData Stack data. Don't touch. |
1455
|
|
|
* @return string An XML string made from the input content in the array. |
1456
|
|
|
* @see xml2array() |
1457
|
|
|
*/ |
1458
|
|
|
public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = [], array $stackData = []) |
1459
|
|
|
{ |
1460
|
|
|
// The list of byte values which will trigger binary-safe storage. If any value has one of these char values in it, it will be encoded in base64 |
1461
|
|
|
$binaryChars = chr(0) . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) . chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) . chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) . chr(30) . chr(31); |
1462
|
|
|
// Set indenting mode: |
1463
|
|
|
$indentChar = $spaceInd ? ' ' : TAB; |
1464
|
|
|
$indentN = $spaceInd > 0 ? $spaceInd : 1; |
1465
|
|
|
$nl = $spaceInd >= 0 ? LF : ''; |
1466
|
|
|
// Init output variable: |
1467
|
|
|
$output = ''; |
1468
|
|
|
// Traverse the input array |
1469
|
|
|
foreach ($array as $k => $v) { |
1470
|
|
|
$attr = ''; |
1471
|
|
|
$tagName = $k; |
1472
|
|
|
// Construct the tag name. |
1473
|
|
|
// Use tag based on grand-parent + parent tag name |
1474
|
|
|
if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) { |
1475
|
|
|
$attr .= ' index="' . htmlspecialchars($tagName) . '"'; |
1476
|
|
|
$tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']]; |
1477
|
|
|
} elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) { |
1478
|
|
|
// Use tag based on parent tag name + if current tag is numeric |
1479
|
|
|
$attr .= ' index="' . htmlspecialchars($tagName) . '"'; |
1480
|
|
|
$tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']; |
1481
|
|
|
} elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) { |
1482
|
|
|
// Use tag based on parent tag name + current tag |
1483
|
|
|
$attr .= ' index="' . htmlspecialchars($tagName) . '"'; |
1484
|
|
|
$tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName]; |
1485
|
|
|
} elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) { |
1486
|
|
|
// Use tag based on parent tag name: |
1487
|
|
|
$attr .= ' index="' . htmlspecialchars($tagName) . '"'; |
1488
|
|
|
$tagName = (string)$options['parentTagMap'][$stackData['parentTagName']]; |
1489
|
|
|
} elseif (MathUtility::canBeInterpretedAsInteger($tagName)) { |
1490
|
|
|
// If integer...; |
1491
|
|
|
if ($options['useNindex']) { |
1492
|
|
|
// If numeric key, prefix "n" |
1493
|
|
|
$tagName = 'n' . $tagName; |
1494
|
|
|
} else { |
1495
|
|
|
// Use special tag for num. keys: |
1496
|
|
|
$attr .= ' index="' . $tagName . '"'; |
1497
|
|
|
$tagName = $options['useIndexTagForNum'] ?: 'numIndex'; |
1498
|
|
|
} |
1499
|
|
|
} elseif ($options['useIndexTagForAssoc']) { |
1500
|
|
|
// Use tag for all associative keys: |
1501
|
|
|
$attr .= ' index="' . htmlspecialchars($tagName) . '"'; |
1502
|
|
|
$tagName = $options['useIndexTagForAssoc']; |
1503
|
|
|
} |
1504
|
|
|
// The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either. |
1505
|
|
|
$tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100); |
1506
|
|
|
// If the value is an array then we will call this function recursively: |
1507
|
|
|
if (is_array($v)) { |
1508
|
|
|
// Sub elements: |
1509
|
|
|
if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) { |
|
|
|
|
1510
|
|
|
$subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName]; |
1511
|
|
|
$clearStackPath = $subOptions['clearStackPath']; |
1512
|
|
|
} else { |
1513
|
|
|
$subOptions = $options; |
1514
|
|
|
$clearStackPath = false; |
1515
|
|
|
} |
1516
|
|
|
if (empty($v)) { |
1517
|
|
|
$content = ''; |
1518
|
|
|
} else { |
1519
|
|
|
$content = $nl . self::array2xml($v, $NSprefix, ($level + 1), '', $spaceInd, $subOptions, [ |
1520
|
|
|
'parentTagName' => $tagName, |
1521
|
|
|
'grandParentTagName' => $stackData['parentTagName'], |
1522
|
|
|
'path' => ($clearStackPath ? '' : $stackData['path'] . '/' . $tagName) |
1523
|
|
|
]) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : ''); |
1524
|
|
|
} |
1525
|
|
|
// Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array |
1526
|
|
|
if ((int)$options['disableTypeAttrib'] != 2) { |
1527
|
|
|
$attr .= ' type="array"'; |
1528
|
|
|
} |
1529
|
|
|
} else { |
1530
|
|
|
// Just a value: |
1531
|
|
|
// Look for binary chars: |
1532
|
|
|
$vLen = strlen($v); |
1533
|
|
|
// Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string! |
1534
|
|
|
if ($vLen && strcspn($v, $binaryChars) != $vLen) { |
1535
|
|
|
// If the value contained binary chars then we base64-encode it an set an attribute to notify this situation: |
1536
|
|
|
$content = $nl . chunk_split(base64_encode($v)); |
1537
|
|
|
$attr .= ' base64="1"'; |
1538
|
|
|
} else { |
1539
|
|
|
// Otherwise, just htmlspecialchar the stuff: |
1540
|
|
|
$content = htmlspecialchars($v); |
1541
|
|
|
$dType = gettype($v); |
1542
|
|
|
if ($dType === 'string') { |
1543
|
|
|
if ($options['useCDATA'] && $content != $v) { |
1544
|
|
|
$content = '<![CDATA[' . $v . ']]>'; |
1545
|
|
|
} |
1546
|
|
|
} elseif (!$options['disableTypeAttrib']) { |
1547
|
|
|
$attr .= ' type="' . $dType . '"'; |
1548
|
|
|
} |
1549
|
|
|
} |
1550
|
|
|
} |
1551
|
|
|
if ((string)$tagName !== '') { |
1552
|
|
|
// Add the element to the output string: |
1553
|
|
|
$output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '') |
1554
|
|
|
. '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl; |
1555
|
|
|
} |
1556
|
|
|
} |
1557
|
|
|
// If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value: |
1558
|
|
|
if (!$level) { |
1559
|
|
|
$output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>'; |
1560
|
|
|
} |
1561
|
|
|
return $output; |
1562
|
|
|
} |
1563
|
|
|
|
1564
|
|
|
/** |
1565
|
|
|
* Converts an XML string to a PHP array. |
1566
|
|
|
* This is the reverse function of array2xml() |
1567
|
|
|
* This is a wrapper for xml2arrayProcess that adds a two-level cache |
1568
|
|
|
* |
1569
|
|
|
* @param string $string XML content to convert into an array |
1570
|
|
|
* @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:" |
1571
|
|
|
* @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array |
1572
|
|
|
* @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content. |
1573
|
|
|
* @see array2xml(),xml2arrayProcess() |
1574
|
|
|
*/ |
1575
|
|
|
public static function xml2array($string, $NSprefix = '', $reportDocTag = false) |
1576
|
|
|
{ |
1577
|
|
|
static $firstLevelCache = []; |
1578
|
|
|
$identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0')); |
1579
|
|
|
// Look up in first level cache |
1580
|
|
|
if (!empty($firstLevelCache[$identifier])) { |
1581
|
|
|
$array = $firstLevelCache[$identifier]; |
1582
|
|
|
} else { |
1583
|
|
|
$array = self::xml2arrayProcess(trim($string), $NSprefix, $reportDocTag); |
1584
|
|
|
// Store content in first level cache |
1585
|
|
|
$firstLevelCache[$identifier] = $array; |
1586
|
|
|
} |
1587
|
|
|
return $array; |
1588
|
|
|
} |
1589
|
|
|
|
1590
|
|
|
/** |
1591
|
|
|
* Converts an XML string to a PHP array. |
1592
|
|
|
* This is the reverse function of array2xml() |
1593
|
|
|
* |
1594
|
|
|
* @param string $string XML content to convert into an array |
1595
|
|
|
* @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:" |
1596
|
|
|
* @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array |
1597
|
|
|
* @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content. |
1598
|
|
|
* @see array2xml() |
1599
|
|
|
*/ |
1600
|
|
|
protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = false) |
1601
|
|
|
{ |
1602
|
|
|
// Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept |
1603
|
|
|
$previousValueOfEntityLoader = libxml_disable_entity_loader(true); |
1604
|
|
|
// Create parser: |
1605
|
|
|
$parser = xml_parser_create(); |
1606
|
|
|
$vals = []; |
1607
|
|
|
$index = []; |
1608
|
|
|
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); |
1609
|
|
|
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0); |
1610
|
|
|
// Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!! |
1611
|
|
|
$match = []; |
1612
|
|
|
preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match); |
|
|
|
|
1613
|
|
|
$theCharset = $match[1] ?: 'utf-8'; |
1614
|
|
|
// us-ascii / utf-8 / iso-8859-1 |
1615
|
|
|
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); |
1616
|
|
|
// Parse content: |
1617
|
|
|
xml_parse_into_struct($parser, $string, $vals, $index); |
1618
|
|
|
libxml_disable_entity_loader($previousValueOfEntityLoader); |
1619
|
|
|
// If error, return error message: |
1620
|
|
View Code Duplication |
if (xml_get_error_code($parser)) { |
1621
|
|
|
return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser)); |
1622
|
|
|
} |
1623
|
|
|
xml_parser_free($parser); |
1624
|
|
|
// Init vars: |
1625
|
|
|
$stack = [[]]; |
1626
|
|
|
$stacktop = 0; |
1627
|
|
|
$current = []; |
1628
|
|
|
$tagName = ''; |
1629
|
|
|
$documentTag = ''; |
1630
|
|
|
// Traverse the parsed XML structure: |
1631
|
|
|
foreach ($vals as $key => $val) { |
1632
|
|
|
// First, process the tag-name (which is used in both cases, whether "complete" or "close") |
1633
|
|
|
$tagName = $val['tag']; |
1634
|
|
|
if (!$documentTag) { |
1635
|
|
|
$documentTag = $tagName; |
1636
|
|
|
} |
1637
|
|
|
// Test for name space: |
1638
|
|
|
$tagName = $NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix ? substr($tagName, strlen($NSprefix)) : $tagName; |
1639
|
|
|
// Test for numeric tag, encoded on the form "nXXX": |
1640
|
|
|
$testNtag = substr($tagName, 1); |
|
|
|
|
1641
|
|
|
// Closing tag. |
1642
|
|
|
$tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName; |
1643
|
|
|
// Test for alternative index value: |
1644
|
|
|
if ((string)($val['attributes']['index'] ?? '') !== '') { |
1645
|
|
|
$tagName = $val['attributes']['index']; |
1646
|
|
|
} |
1647
|
|
|
// Setting tag-values, manage stack: |
1648
|
|
|
switch ($val['type']) { |
1649
|
|
View Code Duplication |
case 'open': |
1650
|
|
|
// If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array: |
1651
|
|
|
// Setting blank place holder |
1652
|
|
|
$current[$tagName] = []; |
1653
|
|
|
$stack[$stacktop++] = $current; |
1654
|
|
|
$current = []; |
1655
|
|
|
break; |
1656
|
|
View Code Duplication |
case 'close': |
1657
|
|
|
// If the tag is "close" then it is an array which is closing and we decrease the stack pointer. |
1658
|
|
|
$oldCurrent = $current; |
1659
|
|
|
$current = $stack[--$stacktop]; |
1660
|
|
|
// Going to the end of array to get placeholder key, key($current), and fill in array next: |
1661
|
|
|
end($current); |
1662
|
|
|
$current[key($current)] = $oldCurrent; |
1663
|
|
|
unset($oldCurrent); |
1664
|
|
|
break; |
1665
|
|
|
case 'complete': |
1666
|
|
|
// If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it. |
1667
|
|
|
if (!empty($val['attributes']['base64'])) { |
1668
|
|
|
$current[$tagName] = base64_decode($val['value']); |
1669
|
|
|
} else { |
1670
|
|
|
// Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!! |
1671
|
|
|
$current[$tagName] = (string)($val['value'] ?? ''); |
1672
|
|
|
// Cast type: |
1673
|
|
|
switch ((string)($val['attributes']['type'] ?? '')) { |
1674
|
|
|
case 'integer': |
1675
|
|
|
$current[$tagName] = (int)$current[$tagName]; |
1676
|
|
|
break; |
1677
|
|
|
case 'double': |
1678
|
|
|
$current[$tagName] = (double) $current[$tagName]; |
1679
|
|
|
break; |
1680
|
|
|
case 'boolean': |
1681
|
|
|
$current[$tagName] = (bool)$current[$tagName]; |
1682
|
|
|
break; |
1683
|
|
|
case 'NULL': |
1684
|
|
|
$current[$tagName] = null; |
1685
|
|
|
break; |
1686
|
|
|
case 'array': |
1687
|
|
|
// 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... |
1688
|
|
|
$current[$tagName] = []; |
1689
|
|
|
break; |
1690
|
|
|
} |
1691
|
|
|
} |
1692
|
|
|
break; |
1693
|
|
|
} |
1694
|
|
|
} |
1695
|
|
|
if ($reportDocTag) { |
1696
|
|
|
$current[$tagName]['_DOCUMENT_TAG'] = $documentTag; |
1697
|
|
|
} |
1698
|
|
|
// Finally return the content of the document tag. |
1699
|
|
|
return $current[$tagName]; |
1700
|
|
|
} |
1701
|
|
|
|
1702
|
|
|
/** |
1703
|
|
|
* This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again. |
1704
|
|
|
* |
1705
|
|
|
* @param array $vals An array of XML parts, see xml2tree |
1706
|
|
|
* @return string Re-compiled XML data. |
1707
|
|
|
*/ |
1708
|
|
|
public static function xmlRecompileFromStructValArray(array $vals) |
1709
|
|
|
{ |
1710
|
|
|
$XMLcontent = ''; |
1711
|
|
|
foreach ($vals as $val) { |
1712
|
|
|
$type = $val['type']; |
1713
|
|
|
// Open tag: |
1714
|
|
|
if ($type === 'open' || $type === 'complete') { |
1715
|
|
|
$XMLcontent .= '<' . $val['tag']; |
1716
|
|
|
if (isset($val['attributes'])) { |
1717
|
|
|
foreach ($val['attributes'] as $k => $v) { |
1718
|
|
|
$XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"'; |
1719
|
|
|
} |
1720
|
|
|
} |
1721
|
|
|
if ($type === 'complete') { |
1722
|
|
|
if (isset($val['value'])) { |
1723
|
|
|
$XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>'; |
1724
|
|
|
} else { |
1725
|
|
|
$XMLcontent .= '/>'; |
1726
|
|
|
} |
1727
|
|
|
} else { |
1728
|
|
|
$XMLcontent .= '>'; |
1729
|
|
|
} |
1730
|
|
|
if ($type === 'open' && isset($val['value'])) { |
1731
|
|
|
$XMLcontent .= htmlspecialchars($val['value']); |
1732
|
|
|
} |
1733
|
|
|
} |
1734
|
|
|
// Finish tag: |
1735
|
|
|
if ($type === 'close') { |
1736
|
|
|
$XMLcontent .= '</' . $val['tag'] . '>'; |
1737
|
|
|
} |
1738
|
|
|
// Cdata |
1739
|
|
|
if ($type === 'cdata') { |
1740
|
|
|
$XMLcontent .= htmlspecialchars($val['value']); |
1741
|
|
|
} |
1742
|
|
|
} |
1743
|
|
|
return $XMLcontent; |
1744
|
|
|
} |
1745
|
|
|
|
1746
|
|
|
/** |
1747
|
|
|
* Minifies JavaScript |
1748
|
|
|
* |
1749
|
|
|
* @param string $script Script to minify |
1750
|
|
|
* @param string $error Error message (if any) |
1751
|
|
|
* @return string Minified script or source string if error happened |
1752
|
|
|
*/ |
1753
|
|
|
public static function minifyJavaScript($script, &$error = '') |
1754
|
|
|
{ |
1755
|
|
|
$fakeThis = false; |
1756
|
|
|
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] ?? [] as $hookMethod) { |
1757
|
|
|
try { |
1758
|
|
|
$parameters = ['script' => $script]; |
1759
|
|
|
$script = static::callUserFunction($hookMethod, $parameters, $fakeThis); |
1760
|
|
|
} catch (\Exception $e) { |
1761
|
|
|
$errorMessage = 'Error minifying java script: ' . $e->getMessage(); |
1762
|
|
|
$error .= $errorMessage; |
1763
|
|
|
static::getLogger()->warning($errorMessage, [ |
1764
|
|
|
'JavaScript' => $script, |
1765
|
|
|
'hook' => $hookMethod, |
1766
|
|
|
'exception' => $e, |
1767
|
|
|
]); |
1768
|
|
|
} |
1769
|
|
|
} |
1770
|
|
|
return $script; |
1771
|
|
|
} |
1772
|
|
|
|
1773
|
|
|
/************************* |
1774
|
|
|
* |
1775
|
|
|
* FILES FUNCTIONS |
1776
|
|
|
* |
1777
|
|
|
*************************/ |
1778
|
|
|
/** |
1779
|
|
|
* Reads the file or url $url and returns the content |
1780
|
|
|
* If you are having trouble with proxies when reading URLs you can configure your way out of that with settings within $GLOBALS['TYPO3_CONF_VARS']['HTTP']. |
1781
|
|
|
* |
1782
|
|
|
* @param string $url File/URL to read |
1783
|
|
|
* @param int $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only |
1784
|
|
|
* @param array $requestHeaders HTTP headers to be used in the request |
1785
|
|
|
* @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type) |
1786
|
|
|
* @return mixed The content from the resource given as input. FALSE if an error has occurred. |
1787
|
|
|
*/ |
1788
|
|
|
public static function getUrl($url, $includeHeader = 0, $requestHeaders = null, &$report = null) |
1789
|
|
|
{ |
1790
|
|
|
if (isset($report)) { |
1791
|
|
|
$report['error'] = 0; |
1792
|
|
|
$report['message'] = ''; |
1793
|
|
|
} |
1794
|
|
|
// Looks like it's an external file, use Guzzle by default |
1795
|
|
|
if (preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) { |
1796
|
|
|
/** @var RequestFactory $requestFactory */ |
1797
|
|
|
$requestFactory = static::makeInstance(RequestFactory::class); |
1798
|
|
|
if (is_array($requestHeaders)) { |
1799
|
|
|
$configuration = ['headers' => $requestHeaders]; |
1800
|
|
|
} else { |
1801
|
|
|
$configuration = []; |
1802
|
|
|
} |
1803
|
|
|
|
1804
|
|
|
try { |
1805
|
|
|
if (isset($report)) { |
1806
|
|
|
$report['lib'] = 'GuzzleHttp'; |
1807
|
|
|
} |
1808
|
|
|
$response = $requestFactory->request($url, 'GET', $configuration); |
1809
|
|
|
} catch (RequestException $exception) { |
1810
|
|
|
if (isset($report)) { |
1811
|
|
|
$report['error'] = $exception->getCode(); |
1812
|
|
|
$report['message'] = $exception->getMessage(); |
1813
|
|
|
$report['exception'] = $exception; |
1814
|
|
|
} |
1815
|
|
|
return false; |
1816
|
|
|
} |
1817
|
|
|
|
1818
|
|
|
$content = ''; |
1819
|
|
|
|
1820
|
|
|
// Add the headers to the output |
1821
|
|
|
$includeHeader = (int)$includeHeader; |
1822
|
|
|
if ($includeHeader) { |
1823
|
|
|
$parsedURL = parse_url($url); |
1824
|
|
|
$method = $includeHeader === 2 ? 'HEAD' : 'GET'; |
1825
|
|
|
$content = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/') |
1826
|
|
|
. ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') . ' HTTP/1.0' . CRLF |
1827
|
|
|
. 'Host: ' . $parsedURL['host'] . CRLF |
1828
|
|
|
. 'Connection: close' . CRLF; |
1829
|
|
|
if (is_array($requestHeaders)) { |
1830
|
|
|
$content .= implode(CRLF, $requestHeaders) . CRLF; |
1831
|
|
|
} |
1832
|
|
|
foreach ($response->getHeaders() as $headerName => $headerValues) { |
1833
|
|
|
$content .= $headerName . ': ' . implode(', ', $headerValues) . CRLF; |
1834
|
|
|
} |
1835
|
|
|
// Headers are separated from the body with two CRLFs |
1836
|
|
|
$content .= CRLF; |
1837
|
|
|
} |
1838
|
|
|
// If not just headers are requested, add the body |
1839
|
|
|
if ($includeHeader !== 2) { |
1840
|
|
|
$content .= $response->getBody()->getContents(); |
1841
|
|
|
} |
1842
|
|
|
if (isset($report)) { |
1843
|
|
|
$report['lib'] = 'http'; |
1844
|
|
|
if ($response->getStatusCode() >= 300 && $response->getStatusCode() < 400) { |
1845
|
|
|
$report['http_code'] = $response->getStatusCode(); |
1846
|
|
|
$report['content_type'] = $response->getHeader('Content-Type'); |
1847
|
|
|
$report['error'] = $response->getStatusCode(); |
1848
|
|
|
$report['message'] = $response->getReasonPhrase(); |
1849
|
|
|
} elseif (!empty($content)) { |
1850
|
|
|
$report['error'] = $response->getStatusCode(); |
1851
|
|
|
$report['message'] = $response->getReasonPhrase(); |
1852
|
|
|
} elseif ($includeHeader) { |
1853
|
|
|
// Set only for $includeHeader to work exactly like PHP variant |
1854
|
|
|
$report['http_code'] = $response->getStatusCode(); |
1855
|
|
|
$report['content_type'] = $response->getHeader('Content-Type'); |
1856
|
|
|
} |
1857
|
|
|
} |
1858
|
|
|
} else { |
1859
|
|
|
if (isset($report)) { |
1860
|
|
|
$report['lib'] = 'file'; |
1861
|
|
|
} |
1862
|
|
|
$content = @file_get_contents($url); |
1863
|
|
|
if ($content === false && isset($report)) { |
1864
|
|
|
$report['error'] = -1; |
1865
|
|
|
$report['message'] = 'Couldn\'t get URL: ' . $url; |
1866
|
|
|
} |
1867
|
|
|
} |
1868
|
|
|
return $content; |
1869
|
|
|
} |
1870
|
|
|
|
1871
|
|
|
/** |
1872
|
|
|
* Writes $content to the file $file |
1873
|
|
|
* |
1874
|
|
|
* @param string $file Filepath to write to |
1875
|
|
|
* @param string $content Content to write |
1876
|
|
|
* @param bool $changePermissions If TRUE, permissions are forced to be set |
1877
|
|
|
* @return bool TRUE if the file was successfully opened and written to. |
1878
|
|
|
*/ |
1879
|
|
|
public static function writeFile($file, $content, $changePermissions = false) |
1880
|
|
|
{ |
1881
|
|
|
if (!@is_file($file)) { |
1882
|
|
|
$changePermissions = true; |
1883
|
|
|
} |
1884
|
|
|
if ($fd = fopen($file, 'wb')) { |
1885
|
|
|
$res = fwrite($fd, $content); |
1886
|
|
|
fclose($fd); |
1887
|
|
|
if ($res === false) { |
1888
|
|
|
return false; |
1889
|
|
|
} |
1890
|
|
|
// Change the permissions only if the file has just been created |
1891
|
|
|
if ($changePermissions) { |
1892
|
|
|
static::fixPermissions($file); |
1893
|
|
|
} |
1894
|
|
|
return true; |
1895
|
|
|
} |
1896
|
|
|
return false; |
1897
|
|
|
} |
1898
|
|
|
|
1899
|
|
|
/** |
1900
|
|
|
* Sets the file system mode and group ownership of a file or a folder. |
1901
|
|
|
* |
1902
|
|
|
* @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative |
1903
|
|
|
* @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder) |
1904
|
|
|
* @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS |
1905
|
|
|
*/ |
1906
|
|
|
public static function fixPermissions($path, $recursive = false) |
1907
|
|
|
{ |
1908
|
|
|
if (TYPO3_OS === 'WIN') { |
1909
|
|
|
return true; |
1910
|
|
|
} |
1911
|
|
|
$result = false; |
1912
|
|
|
// Make path absolute |
1913
|
|
|
if (!static::isAbsPath($path)) { |
1914
|
|
|
$path = static::getFileAbsFileName($path); |
1915
|
|
|
} |
1916
|
|
|
if (static::isAllowedAbsPath($path)) { |
1917
|
|
|
if (@is_file($path)) { |
1918
|
|
|
$targetPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask']) |
1919
|
|
|
? $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] |
1920
|
|
|
: '0644'; |
1921
|
|
|
} elseif (@is_dir($path)) { |
1922
|
|
|
$targetPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']) |
1923
|
|
|
? $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] |
1924
|
|
|
: '0755'; |
1925
|
|
|
} |
1926
|
|
|
if (!empty($targetPermissions)) { |
1927
|
|
|
// make sure it's always 4 digits |
1928
|
|
|
$targetPermissions = str_pad($targetPermissions, 4, 0, STR_PAD_LEFT); |
1929
|
|
|
$targetPermissions = octdec($targetPermissions); |
1930
|
|
|
// "@" is there because file is not necessarily OWNED by the user |
1931
|
|
|
$result = @chmod($path, $targetPermissions); |
|
|
|
|
1932
|
|
|
} |
1933
|
|
|
// Set createGroup if not empty |
1934
|
|
|
if ( |
1935
|
|
|
isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']) |
1936
|
|
|
&& $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] !== '' |
1937
|
|
|
) { |
1938
|
|
|
// "@" is there because file is not necessarily OWNED by the user |
1939
|
|
|
$changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']); |
1940
|
|
|
$result = $changeGroupResult ? $result : false; |
1941
|
|
|
} |
1942
|
|
|
// Call recursive if recursive flag if set and $path is directory |
1943
|
|
|
if ($recursive && @is_dir($path)) { |
1944
|
|
|
$handle = opendir($path); |
1945
|
|
|
if (is_resource($handle)) { |
1946
|
|
|
while (($file = readdir($handle)) !== false) { |
1947
|
|
|
$recursionResult = null; |
1948
|
|
|
if ($file !== '.' && $file !== '..') { |
1949
|
|
|
if (@is_file(($path . '/' . $file))) { |
1950
|
|
|
$recursionResult = static::fixPermissions($path . '/' . $file); |
1951
|
|
|
} elseif (@is_dir(($path . '/' . $file))) { |
1952
|
|
|
$recursionResult = static::fixPermissions($path . '/' . $file, true); |
1953
|
|
|
} |
1954
|
|
|
if (isset($recursionResult) && !$recursionResult) { |
1955
|
|
|
$result = false; |
1956
|
|
|
} |
1957
|
|
|
} |
1958
|
|
|
} |
1959
|
|
|
closedir($handle); |
1960
|
|
|
} |
1961
|
|
|
} |
1962
|
|
|
} |
1963
|
|
|
return $result; |
1964
|
|
|
} |
1965
|
|
|
|
1966
|
|
|
/** |
1967
|
|
|
* Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...) |
1968
|
|
|
* Accepts an additional subdirectory in the file path! |
1969
|
|
|
* |
1970
|
|
|
* @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/" |
1971
|
|
|
* @param string $content Content string to write |
1972
|
|
|
* @return string Returns NULL on success, otherwise an error string telling about the problem. |
1973
|
|
|
*/ |
1974
|
|
|
public static function writeFileToTypo3tempDir($filepath, $content) |
1975
|
|
|
{ |
1976
|
|
|
// Parse filepath into directory and basename: |
1977
|
|
|
$fI = pathinfo($filepath); |
1978
|
|
|
$fI['dirname'] .= '/'; |
1979
|
|
|
// Check parts: |
1980
|
|
|
if (!static::validPathStr($filepath) || !$fI['basename'] || strlen($fI['basename']) >= 60) { |
1981
|
|
|
return 'Input filepath "' . $filepath . '" was generally invalid!'; |
1982
|
|
|
} |
1983
|
|
|
// Setting main temporary directory name (standard) |
1984
|
|
|
$dirName = PATH_site . 'typo3temp/'; |
1985
|
|
|
if (!@is_dir($dirName)) { |
1986
|
|
|
return 'PATH_site + "typo3temp/" was not a directory!'; |
1987
|
|
|
} |
1988
|
|
|
if (!static::isFirstPartOfStr($fI['dirname'], $dirName)) { |
1989
|
|
|
return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"'; |
1990
|
|
|
} |
1991
|
|
|
// Checking if the "subdir" is found: |
1992
|
|
|
$subdir = substr($fI['dirname'], strlen($dirName)); |
1993
|
|
|
if ($subdir) { |
|
|
|
|
1994
|
|
|
if (preg_match('#^(?:[[:alnum:]_]+/)+$#', $subdir)) { |
1995
|
|
|
$dirName .= $subdir; |
1996
|
|
|
if (!@is_dir($dirName)) { |
1997
|
|
|
static::mkdir_deep(PATH_site . 'typo3temp/' . $subdir); |
1998
|
|
|
} |
1999
|
|
|
} else { |
2000
|
|
|
return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/+"'; |
2001
|
|
|
} |
2002
|
|
|
} |
2003
|
|
|
// Checking dir-name again (sub-dir might have been created): |
2004
|
|
|
if (@is_dir($dirName)) { |
2005
|
|
|
if ($filepath === $dirName . $fI['basename']) { |
2006
|
|
|
static::writeFile($filepath, $content); |
2007
|
|
|
if (!@is_file($filepath)) { |
2008
|
|
|
return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.'; |
2009
|
|
|
} |
2010
|
|
|
} else { |
2011
|
|
|
return 'Calculated file location didn\'t match input "' . $filepath . '".'; |
2012
|
|
|
} |
2013
|
|
|
} else { |
2014
|
|
|
return '"' . $dirName . '" is not a directory!'; |
2015
|
|
|
} |
2016
|
|
|
return null; |
2017
|
|
|
} |
2018
|
|
|
|
2019
|
|
|
/** |
2020
|
|
|
* Wrapper function for mkdir. |
2021
|
|
|
* Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] |
2022
|
|
|
* and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] |
2023
|
|
|
* |
2024
|
|
|
* @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally. |
2025
|
|
|
* @return bool TRUE if @mkdir went well! |
2026
|
|
|
*/ |
2027
|
|
|
public static function mkdir($newFolder) |
2028
|
|
|
{ |
2029
|
|
|
$result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'])); |
|
|
|
|
2030
|
|
|
if ($result) { |
2031
|
|
|
static::fixPermissions($newFolder); |
2032
|
|
|
} |
2033
|
|
|
return $result; |
2034
|
|
|
} |
2035
|
|
|
|
2036
|
|
|
/** |
2037
|
|
|
* Creates a directory - including parent directories if necessary and |
2038
|
|
|
* sets permissions on newly created directories. |
2039
|
|
|
* |
2040
|
|
|
* @param string $directory Target directory to create. Must a have trailing slash |
2041
|
|
|
* @param string $deepDirectory Directory to create. This second parameter |
2042
|
|
|
* @throws \InvalidArgumentException If $directory or $deepDirectory are not strings |
2043
|
|
|
* @throws \RuntimeException If directory could not be created |
2044
|
|
|
*/ |
2045
|
|
|
public static function mkdir_deep($directory, $deepDirectory = '') |
2046
|
|
|
{ |
2047
|
|
|
if (!is_string($directory)) { |
2048
|
|
|
throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955); |
2049
|
|
|
} |
2050
|
|
|
if (!is_string($deepDirectory)) { |
2051
|
|
|
throw new \InvalidArgumentException('The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.', 1303662956); |
2052
|
|
|
} |
2053
|
|
|
// Ensure there is only one slash |
2054
|
|
|
$fullPath = rtrim($directory, '/') . '/'; |
2055
|
|
|
if ($deepDirectory !== '') { |
2056
|
|
|
trigger_error('Second argument $deepDirectory of GeneralUtility::mkdir_deep() will be removed in TYPO3 v10.0, use a combined string as first argument instead.', E_USER_DEPRECATED); |
2057
|
|
|
$fullPath .= ltrim($deepDirectory, '/'); |
2058
|
|
|
} |
2059
|
|
|
if ($fullPath !== '/' && !is_dir($fullPath)) { |
2060
|
|
|
$firstCreatedPath = static::createDirectoryPath($fullPath); |
2061
|
|
|
if ($firstCreatedPath !== '') { |
2062
|
|
|
static::fixPermissions($firstCreatedPath, true); |
2063
|
|
|
} |
2064
|
|
|
} |
2065
|
|
|
} |
2066
|
|
|
|
2067
|
|
|
/** |
2068
|
|
|
* Creates directories for the specified paths if they do not exist. This |
2069
|
|
|
* functions sets proper permission mask but does not set proper user and |
2070
|
|
|
* group. |
2071
|
|
|
* |
2072
|
|
|
* @static |
2073
|
|
|
* @param string $fullDirectoryPath |
2074
|
|
|
* @return string Path to the the first created directory in the hierarchy |
2075
|
|
|
* @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep |
2076
|
|
|
* @throws \RuntimeException If directory could not be created |
2077
|
|
|
*/ |
2078
|
|
|
protected static function createDirectoryPath($fullDirectoryPath) |
2079
|
|
|
{ |
2080
|
|
|
$currentPath = $fullDirectoryPath; |
2081
|
|
|
$firstCreatedPath = ''; |
2082
|
|
|
$permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']); |
2083
|
|
|
if (!@is_dir($currentPath)) { |
2084
|
|
|
do { |
2085
|
|
|
$firstCreatedPath = $currentPath; |
2086
|
|
|
$separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR); |
|
|
|
|
2087
|
|
|
$currentPath = substr($currentPath, 0, $separatorPosition); |
|
|
|
|
2088
|
|
|
} while (!is_dir($currentPath) && $separatorPosition !== false); |
2089
|
|
|
$result = @mkdir($fullDirectoryPath, $permissionMask, true); |
|
|
|
|
2090
|
|
|
// Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir() |
2091
|
|
|
if (!$result && !@is_dir($fullDirectoryPath)) { |
2092
|
|
|
throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401); |
2093
|
|
|
} |
2094
|
|
|
} |
2095
|
|
|
return $firstCreatedPath; |
2096
|
|
|
} |
2097
|
|
|
|
2098
|
|
|
/** |
2099
|
|
|
* Wrapper function for rmdir, allowing recursive deletion of folders and files |
2100
|
|
|
* |
2101
|
|
|
* @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally. |
2102
|
|
|
* @param bool $removeNonEmpty Allow deletion of non-empty directories |
2103
|
|
|
* @return bool TRUE if @rmdir went well! |
2104
|
|
|
*/ |
2105
|
|
|
public static function rmdir($path, $removeNonEmpty = false) |
2106
|
|
|
{ |
2107
|
|
|
$OK = false; |
2108
|
|
|
// Remove trailing slash |
2109
|
|
|
$path = preg_replace('|/$|', '', $path); |
2110
|
|
|
if (file_exists($path)) { |
2111
|
|
|
$OK = true; |
2112
|
|
|
if (!is_link($path) && is_dir($path)) { |
2113
|
|
|
if ($removeNonEmpty == true && ($handle = @opendir($path))) { |
|
|
|
|
2114
|
|
|
while ($OK && false !== ($file = readdir($handle))) { |
2115
|
|
|
if ($file === '.' || $file === '..') { |
2116
|
|
|
continue; |
2117
|
|
|
} |
2118
|
|
|
$OK = static::rmdir($path . '/' . $file, $removeNonEmpty); |
2119
|
|
|
} |
2120
|
|
|
closedir($handle); |
2121
|
|
|
} |
2122
|
|
|
if ($OK) { |
2123
|
|
|
$OK = @rmdir($path); |
2124
|
|
|
} |
2125
|
|
|
} elseif (is_link($path) && is_dir($path) && TYPO3_OS === 'WIN') { |
2126
|
|
|
$OK = @rmdir($path); |
2127
|
|
|
} else { |
2128
|
|
|
// If $path is a file, simply remove it |
2129
|
|
|
$OK = @unlink($path); |
2130
|
|
|
} |
2131
|
|
|
clearstatcache(); |
2132
|
|
|
} elseif (is_link($path)) { |
2133
|
|
|
$OK = @unlink($path); |
2134
|
|
|
if (!$OK && TYPO3_OS === 'WIN') { |
2135
|
|
|
// Try to delete dead folder links on Windows systems |
2136
|
|
|
$OK = @rmdir($path); |
2137
|
|
|
} |
2138
|
|
|
clearstatcache(); |
2139
|
|
|
} |
2140
|
|
|
return $OK; |
2141
|
|
|
} |
2142
|
|
|
|
2143
|
|
|
/** |
2144
|
|
|
* Flushes a directory by first moving to a temporary resource, and then |
2145
|
|
|
* triggering the remove process. This way directories can be flushed faster |
2146
|
|
|
* to prevent race conditions on concurrent processes accessing the same directory. |
2147
|
|
|
* |
2148
|
|
|
* @param string $directory The directory to be renamed and flushed |
2149
|
|
|
* @param bool $keepOriginalDirectory Whether to only empty the directory and not remove it |
2150
|
|
|
* @param bool $flushOpcodeCache Also flush the opcode cache right after renaming the directory. |
2151
|
|
|
* @return bool Whether the action was successful |
2152
|
|
|
*/ |
2153
|
|
|
public static function flushDirectory($directory, $keepOriginalDirectory = false, $flushOpcodeCache = false) |
2154
|
|
|
{ |
2155
|
|
|
$result = false; |
2156
|
|
|
|
2157
|
|
|
if (is_dir($directory)) { |
2158
|
|
|
$temporaryDirectory = rtrim($directory, '/') . '.' . StringUtility::getUniqueId('remove') . '/'; |
2159
|
|
|
if (rename($directory, $temporaryDirectory)) { |
2160
|
|
|
if ($flushOpcodeCache) { |
2161
|
|
|
self::makeInstance(OpcodeCacheService::class)->clearAllActive($directory); |
2162
|
|
|
} |
2163
|
|
|
if ($keepOriginalDirectory) { |
2164
|
|
|
static::mkdir($directory); |
2165
|
|
|
} |
2166
|
|
|
clearstatcache(); |
2167
|
|
|
$result = static::rmdir($temporaryDirectory, true); |
2168
|
|
|
} |
2169
|
|
|
} |
2170
|
|
|
|
2171
|
|
|
return $result; |
2172
|
|
|
} |
2173
|
|
|
|
2174
|
|
|
/** |
2175
|
|
|
* Returns an array with the names of folders in a specific path |
2176
|
|
|
* Will return 'error' (string) if there were an error with reading directory content. |
2177
|
|
|
* |
2178
|
|
|
* @param string $path Path to list directories from |
2179
|
|
|
* @return array Returns an array with the directory entries as values. If no path, the return value is nothing. |
2180
|
|
|
*/ |
2181
|
|
|
public static function get_dirs($path) |
2182
|
|
|
{ |
2183
|
|
|
$dirs = null; |
2184
|
|
|
if ($path) { |
2185
|
|
|
if (is_dir($path)) { |
2186
|
|
|
$dir = scandir($path); |
2187
|
|
|
$dirs = []; |
2188
|
|
|
foreach ($dir as $entry) { |
2189
|
|
|
if (is_dir($path . '/' . $entry) && $entry !== '..' && $entry !== '.') { |
2190
|
|
|
$dirs[] = $entry; |
2191
|
|
|
} |
2192
|
|
|
} |
2193
|
|
|
} else { |
2194
|
|
|
$dirs = 'error'; |
2195
|
|
|
} |
2196
|
|
|
} |
2197
|
|
|
return $dirs; |
2198
|
|
|
} |
2199
|
|
|
|
2200
|
|
|
/** |
2201
|
|
|
* Finds all files in a given path and returns them as an array. Each |
2202
|
|
|
* array key is a md5 hash of the full path to the file. This is done because |
2203
|
|
|
* 'some' extensions like the import/export extension depend on this. |
2204
|
|
|
* |
2205
|
|
|
* @param string $path The path to retrieve the files from. |
2206
|
|
|
* @param string $extensionList A comma-separated list of file extensions. Only files of the specified types will be retrieved. When left blank, files of any type will be retrieved. |
2207
|
|
|
* @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned. |
2208
|
|
|
* @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time. |
2209
|
|
|
* @param string $excludePattern A regular expression pattern of file names to exclude. For example: 'clear.gif' or '(clear.gif|.htaccess)'. The pattern will be wrapped with: '/^' and '$/'. |
2210
|
|
|
* @return array|string Array of the files found, or an error message in case the path could not be opened. |
2211
|
|
|
*/ |
2212
|
|
|
public static function getFilesInDir($path, $extensionList = '', $prependPath = false, $order = '', $excludePattern = '') |
2213
|
|
|
{ |
2214
|
|
|
$excludePattern = (string)$excludePattern; |
2215
|
|
|
$path = rtrim($path, '/'); |
2216
|
|
|
if (!@is_dir($path)) { |
2217
|
|
|
return []; |
2218
|
|
|
} |
2219
|
|
|
|
2220
|
|
|
$rawFileList = scandir($path); |
2221
|
|
|
if ($rawFileList === false) { |
2222
|
|
|
return 'error opening path: "' . $path . '"'; |
2223
|
|
|
} |
2224
|
|
|
|
2225
|
|
|
$pathPrefix = $path . '/'; |
2226
|
|
|
$allowedFileExtensionArray = self::trimExplode(',', $extensionList); |
2227
|
|
|
$extensionList = ',' . str_replace(' ', '', $extensionList) . ','; |
2228
|
|
|
$files = []; |
2229
|
|
|
foreach ($rawFileList as $entry) { |
2230
|
|
|
$completePathToEntry = $pathPrefix . $entry; |
2231
|
|
|
if (!@is_file($completePathToEntry)) { |
2232
|
|
|
continue; |
2233
|
|
|
} |
2234
|
|
|
|
2235
|
|
|
foreach ($allowedFileExtensionArray as $allowedFileExtension) { |
2236
|
|
|
if ( |
2237
|
|
|
($extensionList === ',,' || stripos($extensionList, ',' . substr($entry, strlen($allowedFileExtension)*-1, strlen($allowedFileExtension)) . ',') !== false) |
|
|
|
|
2238
|
|
|
&& ($excludePattern === '' || !preg_match(('/^' . $excludePattern . '$/'), $entry)) |
2239
|
|
|
) { |
2240
|
|
|
if ($order !== 'mtime') { |
2241
|
|
|
$files[] = $entry; |
2242
|
|
|
} else { |
2243
|
|
|
// Store the value in the key so we can do a fast asort later. |
2244
|
|
|
$files[$entry] = filemtime($completePathToEntry); |
2245
|
|
|
} |
2246
|
|
|
} |
2247
|
|
|
} |
2248
|
|
|
} |
2249
|
|
|
|
2250
|
|
|
$valueName = 'value'; |
2251
|
|
|
if ($order === 'mtime') { |
2252
|
|
|
asort($files); |
2253
|
|
|
$valueName = 'key'; |
2254
|
|
|
} |
2255
|
|
|
|
2256
|
|
|
$valuePathPrefix = $prependPath ? $pathPrefix : ''; |
2257
|
|
|
$foundFiles = []; |
2258
|
|
|
foreach ($files as $key => $value) { |
2259
|
|
|
// Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension) |
2260
|
|
|
$foundFiles[md5($pathPrefix . ${$valueName})] = $valuePathPrefix . ${$valueName}; |
2261
|
|
|
} |
2262
|
|
|
|
2263
|
|
|
return $foundFiles; |
2264
|
|
|
} |
2265
|
|
|
|
2266
|
|
|
/** |
2267
|
|
|
* Recursively gather all files and folders of a path. |
2268
|
|
|
* |
2269
|
|
|
* @param array $fileArr Empty input array (will have files added to it) |
2270
|
|
|
* @param string $path The path to read recursively from (absolute) (include trailing slash!) |
2271
|
|
|
* @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected. |
2272
|
|
|
* @param bool $regDirs If set, directories are also included in output. |
2273
|
|
|
* @param int $recursivityLevels The number of levels to dig down... |
2274
|
|
|
* @param string $excludePattern regex pattern of files/directories to exclude |
2275
|
|
|
* @return array An array with the found files/directories. |
2276
|
|
|
*/ |
2277
|
|
|
public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = false, $recursivityLevels = 99, $excludePattern = '') |
2278
|
|
|
{ |
2279
|
|
|
if ($regDirs) { |
2280
|
|
|
$fileArr[md5($path)] = $path; |
2281
|
|
|
} |
2282
|
|
|
$fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern)); |
|
|
|
|
2283
|
|
|
$dirs = self::get_dirs($path); |
2284
|
|
|
if ($recursivityLevels > 0 && is_array($dirs)) { |
2285
|
|
|
foreach ($dirs as $subdirs) { |
2286
|
|
|
if ((string)$subdirs !== '' && ($excludePattern === '' || !preg_match(('/^' . $excludePattern . '$/'), $subdirs))) { |
2287
|
|
|
$fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern); |
2288
|
|
|
} |
2289
|
|
|
} |
2290
|
|
|
} |
2291
|
|
|
return $fileArr; |
2292
|
|
|
} |
2293
|
|
|
|
2294
|
|
|
/** |
2295
|
|
|
* Removes the absolute part of all files/folders in fileArr |
2296
|
|
|
* |
2297
|
|
|
* @param array $fileArr The file array to remove the prefix from |
2298
|
|
|
* @param string $prefixToRemove The prefix path to remove (if found as first part of string!) |
2299
|
|
|
* @return array The input $fileArr processed. |
2300
|
|
|
*/ |
2301
|
|
|
public static function removePrefixPathFromList(array $fileArr, $prefixToRemove) |
2302
|
|
|
{ |
2303
|
|
|
foreach ($fileArr as $k => &$absFileRef) { |
2304
|
|
|
if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) { |
2305
|
|
|
$absFileRef = substr($absFileRef, strlen($prefixToRemove)); |
2306
|
|
|
} else { |
2307
|
|
|
return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!'; |
2308
|
|
|
} |
2309
|
|
|
} |
2310
|
|
|
unset($absFileRef); |
2311
|
|
|
return $fileArr; |
2312
|
|
|
} |
2313
|
|
|
|
2314
|
|
|
/** |
2315
|
|
|
* Fixes a path for windows-backslashes and reduces double-slashes to single slashes |
2316
|
|
|
* |
2317
|
|
|
* @param string $theFile File path to process |
2318
|
|
|
* @return string |
2319
|
|
|
*/ |
2320
|
|
|
public static function fixWindowsFilePath($theFile) |
2321
|
|
|
{ |
2322
|
|
|
return str_replace(['\\', '//'], '/', $theFile); |
2323
|
|
|
} |
2324
|
|
|
|
2325
|
|
|
/** |
2326
|
|
|
* Resolves "../" sections in the input path string. |
2327
|
|
|
* For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/" |
2328
|
|
|
* |
2329
|
|
|
* @param string $pathStr File path in which "/../" is resolved |
2330
|
|
|
* @return string |
2331
|
|
|
*/ |
2332
|
|
|
public static function resolveBackPath($pathStr) |
2333
|
|
|
{ |
2334
|
|
|
if (strpos($pathStr, '..') === false) { |
2335
|
|
|
return $pathStr; |
2336
|
|
|
} |
2337
|
|
|
$parts = explode('/', $pathStr); |
2338
|
|
|
$output = []; |
2339
|
|
|
$c = 0; |
2340
|
|
|
foreach ($parts as $part) { |
2341
|
|
|
if ($part === '..') { |
2342
|
|
|
if ($c) { |
2343
|
|
|
array_pop($output); |
2344
|
|
|
--$c; |
2345
|
|
|
} else { |
2346
|
|
|
$output[] = $part; |
2347
|
|
|
} |
2348
|
|
|
} else { |
2349
|
|
|
++$c; |
2350
|
|
|
$output[] = $part; |
2351
|
|
|
} |
2352
|
|
|
} |
2353
|
|
|
return implode('/', $output); |
2354
|
|
|
} |
2355
|
|
|
|
2356
|
|
|
/** |
2357
|
|
|
* Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already. |
2358
|
|
|
* - If already having a scheme, nothing is prepended |
2359
|
|
|
* - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host) |
2360
|
|
|
* - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR) |
2361
|
|
|
* |
2362
|
|
|
* @param string $path URL / path to prepend full URL addressing to. |
2363
|
|
|
* @return string |
2364
|
|
|
*/ |
2365
|
|
|
public static function locationHeaderUrl($path) |
2366
|
|
|
{ |
2367
|
|
|
$uI = parse_url($path); |
2368
|
|
|
// relative to HOST |
2369
|
|
View Code Duplication |
if ($path[0] === '/') { |
2370
|
|
|
$path = self::getIndpEnv('TYPO3_REQUEST_HOST') . $path; |
2371
|
|
|
} elseif (!$uI['scheme']) { |
2372
|
|
|
// No scheme either |
2373
|
|
|
$path = self::getIndpEnv('TYPO3_REQUEST_DIR') . $path; |
2374
|
|
|
} |
2375
|
|
|
return $path; |
2376
|
|
|
} |
2377
|
|
|
|
2378
|
|
|
/** |
2379
|
|
|
* Returns the maximum upload size for a file that is allowed. Measured in KB. |
2380
|
|
|
* This might be handy to find out the real upload limit that is possible for this |
2381
|
|
|
* TYPO3 installation. |
2382
|
|
|
* |
2383
|
|
|
* @return int The maximum size of uploads that are allowed (measured in kilobytes) |
2384
|
|
|
*/ |
2385
|
|
|
public static function getMaxUploadFileSize() |
2386
|
|
|
{ |
2387
|
|
|
// Check for PHP restrictions of the maximum size of one of the $_FILES |
2388
|
|
|
$phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize')); |
2389
|
|
|
// Check for PHP restrictions of the maximum $_POST size |
2390
|
|
|
$phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size')); |
2391
|
|
|
// If the total amount of post data is smaller (!) than the upload_max_filesize directive, |
2392
|
|
|
// then this is the real limit in PHP |
2393
|
|
|
$phpUploadLimit = $phpPostLimit > 0 && $phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit; |
2394
|
|
|
return floor(($phpUploadLimit)) / 1024; |
2395
|
|
|
} |
2396
|
|
|
|
2397
|
|
|
/** |
2398
|
|
|
* Gets the bytes value from a measurement string like "100k". |
2399
|
|
|
* |
2400
|
|
|
* @param string $measurement The measurement (e.g. "100k") |
2401
|
|
|
* @return int The bytes value (e.g. 102400) |
2402
|
|
|
*/ |
2403
|
|
|
public static function getBytesFromSizeMeasurement($measurement) |
2404
|
|
|
{ |
2405
|
|
|
$bytes = (float)$measurement; |
2406
|
|
|
if (stripos($measurement, 'G')) { |
2407
|
|
|
$bytes *= 1024 * 1024 * 1024; |
2408
|
|
|
} elseif (stripos($measurement, 'M')) { |
2409
|
|
|
$bytes *= 1024 * 1024; |
2410
|
|
|
} elseif (stripos($measurement, 'K')) { |
2411
|
|
|
$bytes *= 1024; |
2412
|
|
|
} |
2413
|
|
|
return $bytes; |
2414
|
|
|
} |
2415
|
|
|
|
2416
|
|
|
/** |
2417
|
|
|
* Function for static version numbers on files, based on the filemtime |
2418
|
|
|
* |
2419
|
|
|
* This will make the filename automatically change when a file is |
2420
|
|
|
* changed, and by that re-cached by the browser. If the file does not |
2421
|
|
|
* exist physically the original file passed to the function is |
2422
|
|
|
* returned without the timestamp. |
2423
|
|
|
* |
2424
|
|
|
* Behaviour is influenced by the setting |
2425
|
|
|
* TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename] |
2426
|
|
|
* = TRUE (BE) / "embed" (FE) : modify filename |
2427
|
|
|
* = FALSE (BE) / "querystring" (FE) : add timestamp as parameter |
2428
|
|
|
* |
2429
|
|
|
* @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet) |
2430
|
|
|
* @return string Relative path with version filename including the timestamp |
2431
|
|
|
*/ |
2432
|
|
|
public static function createVersionNumberedFilename($file) |
2433
|
|
|
{ |
2434
|
|
|
$lookupFile = explode('?', $file); |
2435
|
|
|
$path = self::resolveBackPath(self::dirname(PATH_thisScript) . '/' . $lookupFile[0]); |
2436
|
|
|
|
2437
|
|
|
$doNothing = false; |
2438
|
|
|
if (TYPO3_MODE === 'FE') { |
2439
|
|
|
$mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']); |
2440
|
|
|
if ($mode === 'embed') { |
2441
|
|
|
$mode = true; |
2442
|
|
|
} else { |
2443
|
|
|
if ($mode === 'querystring') { |
2444
|
|
|
$mode = false; |
2445
|
|
|
} else { |
2446
|
|
|
$doNothing = true; |
2447
|
|
|
} |
2448
|
|
|
} |
2449
|
|
|
} else { |
2450
|
|
|
$mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']; |
2451
|
|
|
} |
2452
|
|
|
if ($doNothing || !file_exists($path)) { |
2453
|
|
|
// File not found, return filename unaltered |
2454
|
|
|
$fullName = $file; |
2455
|
|
|
} else { |
2456
|
|
|
if (!$mode) { |
2457
|
|
|
// If use of .htaccess rule is not configured, |
2458
|
|
|
// we use the default query-string method |
2459
|
|
|
if (!empty($lookupFile[1])) { |
2460
|
|
|
$separator = '&'; |
2461
|
|
|
} else { |
2462
|
|
|
$separator = '?'; |
2463
|
|
|
} |
2464
|
|
|
$fullName = $file . $separator . filemtime($path); |
|
|
|
|
2465
|
|
|
} else { |
2466
|
|
|
// Change the filename |
2467
|
|
|
$name = explode('.', $lookupFile[0]); |
2468
|
|
|
$extension = array_pop($name); |
2469
|
|
|
array_push($name, filemtime($path), $extension); |
2470
|
|
|
$fullName = implode('.', $name); |
2471
|
|
|
// Append potential query string |
2472
|
|
|
$fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : ''; |
2473
|
|
|
} |
2474
|
|
|
} |
2475
|
|
|
return $fullName; |
2476
|
|
|
} |
2477
|
|
|
|
2478
|
|
|
/************************* |
2479
|
|
|
* |
2480
|
|
|
* SYSTEM INFORMATION |
2481
|
|
|
* |
2482
|
|
|
*************************/ |
2483
|
|
|
|
2484
|
|
|
/** |
2485
|
|
|
* Returns the link-url to the current script. |
2486
|
|
|
* In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL. |
2487
|
|
|
* REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution) |
2488
|
|
|
* |
2489
|
|
|
* @param array $getParams Array of GET parameters to include |
2490
|
|
|
* @return string |
2491
|
|
|
*/ |
2492
|
|
|
public static function linkThisScript(array $getParams = []) |
2493
|
|
|
{ |
2494
|
|
|
$parts = self::getIndpEnv('SCRIPT_NAME'); |
2495
|
|
|
$params = self::_GET(); |
2496
|
|
|
foreach ($getParams as $key => $value) { |
2497
|
|
|
if ($value !== '') { |
2498
|
|
|
$params[$key] = $value; |
2499
|
|
|
} else { |
2500
|
|
|
unset($params[$key]); |
2501
|
|
|
} |
2502
|
|
|
} |
2503
|
|
|
$pString = self::implodeArrayForUrl('', $params); |
|
|
|
|
2504
|
|
|
return $pString ? $parts . '?' . ltrim($pString, '&') : $parts; |
2505
|
|
|
} |
2506
|
|
|
|
2507
|
|
|
/** |
2508
|
|
|
* Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again. |
2509
|
|
|
* So basically it adds the parameters in $getParams to an existing URL, $url |
2510
|
|
|
* |
2511
|
|
|
* @param string $url URL string |
2512
|
|
|
* @param array $getParams Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional. |
2513
|
|
|
* @return string Output URL with added getParams. |
2514
|
|
|
*/ |
2515
|
|
|
public static function linkThisUrl($url, array $getParams = []) |
2516
|
|
|
{ |
2517
|
|
|
$parts = parse_url($url); |
2518
|
|
|
$getP = []; |
2519
|
|
|
if ($parts['query']) { |
2520
|
|
|
parse_str($parts['query'], $getP); |
2521
|
|
|
} |
2522
|
|
|
ArrayUtility::mergeRecursiveWithOverrule($getP, $getParams); |
2523
|
|
|
$uP = explode('?', $url); |
2524
|
|
|
$params = self::implodeArrayForUrl('', $getP); |
2525
|
|
|
$outurl = $uP[0] . ($params ? '?' . substr($params, 1) : ''); |
|
|
|
|
2526
|
|
|
return $outurl; |
2527
|
|
|
} |
2528
|
|
|
|
2529
|
|
|
/** |
2530
|
|
|
* Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them. |
2531
|
|
|
* This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations. |
2532
|
|
|
* |
2533
|
|
|
* @param string $getEnvName Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY |
2534
|
|
|
* @return string Value based on the input key, independent of server/os environment. |
2535
|
|
|
* @throws \UnexpectedValueException |
2536
|
|
|
*/ |
2537
|
|
|
public static function getIndpEnv($getEnvName) |
2538
|
|
|
{ |
2539
|
|
|
if (isset(self::$indpEnvCache[$getEnvName])) { |
2540
|
|
|
return self::$indpEnvCache[$getEnvName]; |
2541
|
|
|
} |
2542
|
|
|
|
2543
|
|
|
/* |
2544
|
|
|
Conventions: |
2545
|
|
|
output from parse_url(): |
2546
|
|
|
URL: http://username:[email protected]:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1 |
2547
|
|
|
[scheme] => 'http' |
2548
|
|
|
[user] => 'username' |
2549
|
|
|
[pass] => 'password' |
2550
|
|
|
[host] => '192.168.1.4' |
2551
|
|
|
[port] => '8080' |
2552
|
|
|
[path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/' |
2553
|
|
|
[query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value' |
2554
|
|
|
[fragment] => 'link1'Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php' |
2555
|
|
|
[path_dir] = '/typo3/32/temp/phpcheck/' |
2556
|
|
|
[path_info] = '/arg1/arg2/arg3/' |
2557
|
|
|
[path] = [path_script/path_dir][path_info]Keys supported:URI______: |
2558
|
|
|
REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value |
2559
|
|
|
HTTP_HOST = [host][:[port]] = 192.168.1.4:8080 |
2560
|
|
|
SCRIPT_NAME = [path_script]++ = /typo3/32/temp/phpcheck/index.php // NOTICE THAT SCRIPT_NAME will return the php-script name ALSO. [path_script] may not do that (eg. '/somedir/' may result in SCRIPT_NAME '/somedir/index.php')! |
2561
|
|
|
PATH_INFO = [path_info] = /arg1/arg2/arg3/ |
2562
|
|
|
QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value |
2563
|
|
|
HTTP_REFERER = [scheme]://[host][:[port]][path] = http://192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value |
2564
|
|
|
(Notice: NO username/password + NO fragment)CLIENT____: |
2565
|
|
|
REMOTE_ADDR = (client IP) |
2566
|
|
|
REMOTE_HOST = (client host) |
2567
|
|
|
HTTP_USER_AGENT = (client user agent) |
2568
|
|
|
HTTP_ACCEPT_LANGUAGE = (client accept language)SERVER____: |
2569
|
|
|
SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'Special extras: |
2570
|
|
|
TYPO3_HOST_ONLY = [host] = 192.168.1.4 |
2571
|
|
|
TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value) |
2572
|
|
|
TYPO3_REQUEST_HOST = [scheme]://[host][:[port]] |
2573
|
|
|
TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different) |
2574
|
|
|
TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script] |
2575
|
|
|
TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir] |
2576
|
|
|
TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend |
2577
|
|
|
TYPO3_SITE_PATH = [path_dir] of the TYPO3 website frontend |
2578
|
|
|
TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website |
2579
|
|
|
TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically) |
2580
|
|
|
TYPO3_SSL = Returns TRUE if this session uses SSL/TLS (https) |
2581
|
|
|
TYPO3_PROXY = Returns TRUE if this session runs over a well known proxyNotice: [fragment] is apparently NEVER available to the script!Testing suggestions: |
2582
|
|
|
- Output all the values. |
2583
|
|
|
- In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen |
2584
|
|
|
- ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!) |
2585
|
|
|
*/ |
2586
|
|
|
$retVal = ''; |
2587
|
|
|
switch ((string)$getEnvName) { |
2588
|
|
|
case 'SCRIPT_NAME': |
2589
|
|
|
$retVal = self::isRunningOnCgiServerApi() |
2590
|
|
|
&& ($_SERVER['ORIG_PATH_INFO'] ?: $_SERVER['PATH_INFO']) |
2591
|
|
|
? ($_SERVER['ORIG_PATH_INFO'] ?: $_SERVER['PATH_INFO']) |
2592
|
|
|
: ($_SERVER['ORIG_SCRIPT_NAME'] ?: $_SERVER['SCRIPT_NAME']); |
2593
|
|
|
// Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix |
2594
|
|
View Code Duplication |
if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) { |
2595
|
|
|
if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) { |
2596
|
|
|
$retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal; |
2597
|
|
|
} elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) { |
2598
|
|
|
$retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal; |
2599
|
|
|
} |
2600
|
|
|
} |
2601
|
|
|
break; |
2602
|
|
|
case 'SCRIPT_FILENAME': |
2603
|
|
|
$retVal = PATH_thisScript; |
2604
|
|
|
break; |
2605
|
|
|
case 'REQUEST_URI': |
2606
|
|
|
// Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('REQUEST_URI')) |
2607
|
|
|
if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar'])) { |
2608
|
|
|
// This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL) |
2609
|
|
|
list($v, $n) = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']); |
2610
|
|
|
$retVal = $GLOBALS[$v][$n]; |
2611
|
|
|
} elseif (!$_SERVER['REQUEST_URI']) { |
2612
|
|
|
// This is for ISS/CGI which does not have the REQUEST_URI available. |
2613
|
|
|
$retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : ''); |
2614
|
|
|
} else { |
2615
|
|
|
$retVal = '/' . ltrim($_SERVER['REQUEST_URI'], '/'); |
2616
|
|
|
} |
2617
|
|
|
// Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix |
2618
|
|
View Code Duplication |
if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) { |
2619
|
|
|
if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) { |
2620
|
|
|
$retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal; |
2621
|
|
|
} elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) { |
2622
|
|
|
$retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal; |
2623
|
|
|
} |
2624
|
|
|
} |
2625
|
|
|
break; |
2626
|
|
|
case 'PATH_INFO': |
2627
|
|
|
// $_SERVER['PATH_INFO'] != $_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) |
2628
|
|
|
// are seen to set PATH_INFO equal to script_name |
2629
|
|
|
// Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense. |
2630
|
|
|
// IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, |
2631
|
|
|
// then 'PHP_SAPI=='cgi'' might be a better check. |
2632
|
|
|
// Right now strcmp($_SERVER['PATH_INFO'], GeneralUtility::getIndpEnv('SCRIPT_NAME')) will always |
2633
|
|
|
// return FALSE for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO |
2634
|
|
|
// because of PHP_SAPI=='cgi' (see above) |
2635
|
|
|
if (!self::isRunningOnCgiServerApi()) { |
2636
|
|
|
$retVal = $_SERVER['PATH_INFO']; |
2637
|
|
|
} |
2638
|
|
|
break; |
2639
|
|
|
case 'TYPO3_REV_PROXY': |
2640
|
|
|
$retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']); |
2641
|
|
|
break; |
2642
|
|
|
case 'REMOTE_ADDR': |
2643
|
|
|
$retVal = $_SERVER['REMOTE_ADDR']; |
2644
|
|
View Code Duplication |
if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) { |
2645
|
|
|
$ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); |
2646
|
|
|
// Choose which IP in list to use |
2647
|
|
|
if (!empty($ip)) { |
2648
|
|
|
switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) { |
2649
|
|
|
case 'last': |
2650
|
|
|
$ip = array_pop($ip); |
2651
|
|
|
break; |
2652
|
|
|
case 'first': |
2653
|
|
|
$ip = array_shift($ip); |
2654
|
|
|
break; |
2655
|
|
|
case 'none': |
2656
|
|
|
|
2657
|
|
|
default: |
2658
|
|
|
$ip = ''; |
2659
|
|
|
} |
2660
|
|
|
} |
2661
|
|
|
if (self::validIP($ip)) { |
2662
|
|
|
$retVal = $ip; |
2663
|
|
|
} |
2664
|
|
|
} |
2665
|
|
|
break; |
2666
|
|
|
case 'HTTP_HOST': |
2667
|
|
|
// if it is not set we're most likely on the cli |
2668
|
|
|
$retVal = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null; |
2669
|
|
View Code Duplication |
if (isset($_SERVER['REMOTE_ADDR']) && static::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) { |
2670
|
|
|
$host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']); |
2671
|
|
|
// Choose which host in list to use |
2672
|
|
|
if (!empty($host)) { |
2673
|
|
|
switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) { |
2674
|
|
|
case 'last': |
2675
|
|
|
$host = array_pop($host); |
2676
|
|
|
break; |
2677
|
|
|
case 'first': |
2678
|
|
|
$host = array_shift($host); |
2679
|
|
|
break; |
2680
|
|
|
case 'none': |
2681
|
|
|
|
2682
|
|
|
default: |
2683
|
|
|
$host = ''; |
2684
|
|
|
} |
2685
|
|
|
} |
2686
|
|
|
if ($host) { |
2687
|
|
|
$retVal = $host; |
2688
|
|
|
} |
2689
|
|
|
} |
2690
|
|
|
if (!static::isAllowedHostHeaderValue($retVal)) { |
2691
|
|
|
throw new \UnexpectedValueException( |
2692
|
|
|
'The current host header value does not match the configured trusted hosts pattern! Check the pattern defined in $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'trustedHostsPattern\'] and adapt it, if you want to allow the current host header \'' . $retVal . '\' for your installation.', |
2693
|
|
|
1396795884 |
2694
|
|
|
); |
2695
|
|
|
} |
2696
|
|
|
break; |
2697
|
|
|
case 'HTTP_REFERER': |
2698
|
|
|
|
2699
|
|
|
case 'HTTP_USER_AGENT': |
2700
|
|
|
|
2701
|
|
|
case 'HTTP_ACCEPT_ENCODING': |
2702
|
|
|
|
2703
|
|
|
case 'HTTP_ACCEPT_LANGUAGE': |
2704
|
|
|
|
2705
|
|
|
case 'REMOTE_HOST': |
2706
|
|
|
|
2707
|
|
|
case 'QUERY_STRING': |
2708
|
|
|
if (isset($_SERVER[$getEnvName])) { |
2709
|
|
|
$retVal = $_SERVER[$getEnvName]; |
2710
|
|
|
} |
2711
|
|
|
break; |
2712
|
|
|
case 'TYPO3_DOCUMENT_ROOT': |
2713
|
|
|
// Get the web root (it is not the root of the TYPO3 installation) |
2714
|
|
|
// The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME |
2715
|
|
|
// Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well. |
2716
|
|
|
// Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME. |
2717
|
|
|
$SFN = self::getIndpEnv('SCRIPT_FILENAME'); |
2718
|
|
|
$SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME'))); |
2719
|
|
|
$SFN_A = explode('/', strrev($SFN)); |
2720
|
|
|
$acc = []; |
2721
|
|
|
foreach ($SN_A as $kk => $vv) { |
2722
|
|
|
if ((string)$SFN_A[$kk] === (string)$vv) { |
2723
|
|
|
$acc[] = $vv; |
2724
|
|
|
} else { |
2725
|
|
|
break; |
2726
|
|
|
} |
2727
|
|
|
} |
2728
|
|
|
$commonEnd = strrev(implode('/', $acc)); |
2729
|
|
|
if ((string)$commonEnd !== '') { |
2730
|
|
|
$retVal = substr($SFN, 0, -(strlen($commonEnd) + 1)); |
2731
|
|
|
} |
2732
|
|
|
break; |
2733
|
|
|
case 'TYPO3_HOST_ONLY': |
2734
|
|
|
$httpHost = self::getIndpEnv('HTTP_HOST'); |
2735
|
|
|
$httpHostBracketPosition = strpos($httpHost, ']'); |
2736
|
|
|
$httpHostParts = explode(':', $httpHost); |
2737
|
|
|
$retVal = $httpHostBracketPosition !== false ? substr($httpHost, 0, $httpHostBracketPosition + 1) : array_shift($httpHostParts); |
2738
|
|
|
break; |
2739
|
|
|
case 'TYPO3_PORT': |
2740
|
|
|
$httpHost = self::getIndpEnv('HTTP_HOST'); |
2741
|
|
|
$httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY'); |
2742
|
|
|
$retVal = strlen($httpHost) > strlen($httpHostOnly) ? substr($httpHost, strlen($httpHostOnly) + 1) : ''; |
2743
|
|
|
break; |
2744
|
|
|
case 'TYPO3_REQUEST_HOST': |
2745
|
|
|
$retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') . self::getIndpEnv('HTTP_HOST'); |
2746
|
|
|
break; |
2747
|
|
|
case 'TYPO3_REQUEST_URL': |
2748
|
|
|
$retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI'); |
2749
|
|
|
break; |
2750
|
|
|
case 'TYPO3_REQUEST_SCRIPT': |
2751
|
|
|
$retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME'); |
2752
|
|
|
break; |
2753
|
|
|
case 'TYPO3_REQUEST_DIR': |
2754
|
|
|
$retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/'; |
2755
|
|
|
break; |
2756
|
|
|
case 'TYPO3_SITE_URL': |
2757
|
|
|
$url = self::getIndpEnv('TYPO3_REQUEST_DIR'); |
2758
|
|
|
// This can only be set by external entry scripts |
2759
|
|
|
if (defined('TYPO3_PATH_WEB')) { |
2760
|
|
|
$retVal = $url; |
2761
|
|
|
} elseif (defined('PATH_thisScript') && defined('PATH_site')) { |
2762
|
|
|
$lPath = PathUtility::stripPathSitePrefix(dirname(PATH_thisScript)) . '/'; |
2763
|
|
|
$siteUrl = substr($url, 0, -strlen($lPath)); |
2764
|
|
|
if (substr($siteUrl, -1) !== '/') { |
|
|
|
|
2765
|
|
|
$siteUrl .= '/'; |
2766
|
|
|
} |
2767
|
|
|
$retVal = $siteUrl; |
2768
|
|
|
} |
2769
|
|
|
break; |
2770
|
|
|
case 'TYPO3_SITE_PATH': |
2771
|
|
|
$retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST'))); |
2772
|
|
|
break; |
2773
|
|
|
case 'TYPO3_SITE_SCRIPT': |
2774
|
|
|
$retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL'))); |
2775
|
|
|
break; |
2776
|
|
|
case 'TYPO3_SSL': |
2777
|
|
|
$proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']); |
2778
|
|
|
if ($proxySSL === '*') { |
2779
|
|
|
$proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']; |
2780
|
|
|
} |
2781
|
|
|
if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) { |
2782
|
|
|
$retVal = true; |
2783
|
|
|
} else { |
2784
|
|
|
$retVal = $_SERVER['SSL_SESSION_ID'] || strtolower($_SERVER['HTTPS']) === 'on' || (string)$_SERVER['HTTPS'] === '1'; |
2785
|
|
|
} |
2786
|
|
|
break; |
2787
|
|
|
case '_ARRAY': |
2788
|
|
|
$out = []; |
2789
|
|
|
// Here, list ALL possible keys to this function for debug display. |
2790
|
|
|
$envTestVars = [ |
2791
|
|
|
'HTTP_HOST', |
2792
|
|
|
'TYPO3_HOST_ONLY', |
2793
|
|
|
'TYPO3_PORT', |
2794
|
|
|
'PATH_INFO', |
2795
|
|
|
'QUERY_STRING', |
2796
|
|
|
'REQUEST_URI', |
2797
|
|
|
'HTTP_REFERER', |
2798
|
|
|
'TYPO3_REQUEST_HOST', |
2799
|
|
|
'TYPO3_REQUEST_URL', |
2800
|
|
|
'TYPO3_REQUEST_SCRIPT', |
2801
|
|
|
'TYPO3_REQUEST_DIR', |
2802
|
|
|
'TYPO3_SITE_URL', |
2803
|
|
|
'TYPO3_SITE_SCRIPT', |
2804
|
|
|
'TYPO3_SSL', |
2805
|
|
|
'TYPO3_REV_PROXY', |
2806
|
|
|
'SCRIPT_NAME', |
2807
|
|
|
'TYPO3_DOCUMENT_ROOT', |
2808
|
|
|
'SCRIPT_FILENAME', |
2809
|
|
|
'REMOTE_ADDR', |
2810
|
|
|
'REMOTE_HOST', |
2811
|
|
|
'HTTP_USER_AGENT', |
2812
|
|
|
'HTTP_ACCEPT_LANGUAGE' |
2813
|
|
|
]; |
2814
|
|
|
foreach ($envTestVars as $v) { |
2815
|
|
|
$out[$v] = self::getIndpEnv($v); |
2816
|
|
|
} |
2817
|
|
|
reset($out); |
2818
|
|
|
$retVal = $out; |
2819
|
|
|
break; |
2820
|
|
|
} |
2821
|
|
|
self::$indpEnvCache[$getEnvName] = $retVal; |
2822
|
|
|
return $retVal; |
2823
|
|
|
} |
2824
|
|
|
|
2825
|
|
|
/** |
2826
|
|
|
* Checks if the provided host header value matches the trusted hosts pattern. |
2827
|
|
|
* If the pattern is not defined (which only can happen early in the bootstrap), deny any value. |
2828
|
|
|
* The result is saved, so the check needs to be executed only once. |
2829
|
|
|
* |
2830
|
|
|
* @param string $hostHeaderValue HTTP_HOST header value as sent during the request (may include port) |
2831
|
|
|
* @return bool |
2832
|
|
|
*/ |
2833
|
|
|
public static function isAllowedHostHeaderValue($hostHeaderValue) |
2834
|
|
|
{ |
2835
|
|
|
if (static::$allowHostHeaderValue === true) { |
2836
|
|
|
return true; |
2837
|
|
|
} |
2838
|
|
|
|
2839
|
|
|
if (static::isInternalRequestType()) { |
2840
|
|
|
return static::$allowHostHeaderValue = true; |
2841
|
|
|
} |
2842
|
|
|
|
2843
|
|
|
// Deny the value if trusted host patterns is empty, which means we are early in the bootstrap |
2844
|
|
|
if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'])) { |
2845
|
|
|
return false; |
2846
|
|
|
} |
2847
|
|
|
|
2848
|
|
|
if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL) { |
2849
|
|
|
static::$allowHostHeaderValue = true; |
2850
|
|
|
} else { |
2851
|
|
|
static::$allowHostHeaderValue = static::hostHeaderValueMatchesTrustedHostsPattern($hostHeaderValue); |
2852
|
|
|
} |
2853
|
|
|
|
2854
|
|
|
return static::$allowHostHeaderValue; |
2855
|
|
|
} |
2856
|
|
|
|
2857
|
|
|
/** |
2858
|
|
|
* Checks if the provided host header value matches the trusted hosts pattern without any preprocessing. |
2859
|
|
|
* |
2860
|
|
|
* @param string $hostHeaderValue |
2861
|
|
|
* @return bool |
2862
|
|
|
* @internal |
2863
|
|
|
*/ |
2864
|
|
|
public static function hostHeaderValueMatchesTrustedHostsPattern($hostHeaderValue) |
2865
|
|
|
{ |
2866
|
|
|
if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === self::ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME) { |
2867
|
|
|
// Allow values that equal the server name |
2868
|
|
|
// Note that this is only secure if name base virtual host are configured correctly in the webserver |
2869
|
|
|
$defaultPort = self::getIndpEnv('TYPO3_SSL') ? '443' : '80'; |
2870
|
|
|
$parsedHostValue = parse_url('http://' . $hostHeaderValue); |
2871
|
|
|
if (isset($parsedHostValue['port'])) { |
2872
|
|
|
$hostMatch = (strtolower($parsedHostValue['host']) === strtolower($_SERVER['SERVER_NAME']) && (string)$parsedHostValue['port'] === $_SERVER['SERVER_PORT']); |
2873
|
|
|
} else { |
2874
|
|
|
$hostMatch = (strtolower($hostHeaderValue) === strtolower($_SERVER['SERVER_NAME']) && $defaultPort === $_SERVER['SERVER_PORT']); |
2875
|
|
|
} |
2876
|
|
|
} else { |
2877
|
|
|
// In case name based virtual hosts are not possible, we allow setting a trusted host pattern |
2878
|
|
|
// See https://typo3.org/teams/security/security-bulletins/typo3-core/typo3-core-sa-2014-001/ for further details |
2879
|
|
|
$hostMatch = (bool)preg_match('/^' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] . '$/i', $hostHeaderValue); |
2880
|
|
|
} |
2881
|
|
|
|
2882
|
|
|
return $hostMatch; |
2883
|
|
|
} |
2884
|
|
|
|
2885
|
|
|
/** |
2886
|
|
|
* Allows internal requests to the install tool and from the command line. |
2887
|
|
|
* We accept this risk to have the install tool always available. |
2888
|
|
|
* Also CLI needs to be allowed as unfortunately AbstractUserAuthentication::getAuthInfoArray() |
2889
|
|
|
* accesses HTTP_HOST without reason on CLI |
2890
|
|
|
* Additionally, allows requests when no REQUESTTYPE is set, which can happen quite early in the |
2891
|
|
|
* Bootstrap. See Application.php in EXT:backend/Classes/Http/. |
2892
|
|
|
* |
2893
|
|
|
* @return bool |
2894
|
|
|
*/ |
2895
|
|
|
protected static function isInternalRequestType() |
2896
|
|
|
{ |
2897
|
|
|
return !defined('TYPO3_REQUESTTYPE') || (defined('TYPO3_REQUESTTYPE') && TYPO3_REQUESTTYPE & (TYPO3_REQUESTTYPE_INSTALL | TYPO3_REQUESTTYPE_CLI)); |
2898
|
|
|
} |
2899
|
|
|
|
2900
|
|
|
/** |
2901
|
|
|
* Gets the unixtime as milliseconds. |
2902
|
|
|
* |
2903
|
|
|
* @return int The unixtime as milliseconds |
2904
|
|
|
*/ |
2905
|
|
|
public static function milliseconds() |
2906
|
|
|
{ |
2907
|
|
|
return round(microtime(true) * 1000); |
2908
|
|
|
} |
2909
|
|
|
|
2910
|
|
|
/** |
2911
|
|
|
* Client Browser Information |
2912
|
|
|
* |
2913
|
|
|
* @param string $useragent Alternative User Agent string (if empty, \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('HTTP_USER_AGENT') is used) |
2914
|
|
|
* @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM |
2915
|
|
|
*/ |
2916
|
|
|
public static function clientInfo($useragent = '') |
2917
|
|
|
{ |
2918
|
|
|
if (!$useragent) { |
2919
|
|
|
$useragent = self::getIndpEnv('HTTP_USER_AGENT'); |
2920
|
|
|
} |
2921
|
|
|
$bInfo = []; |
2922
|
|
|
// Which browser? |
2923
|
|
|
if (strpos($useragent, 'Konqueror') !== false) { |
2924
|
|
|
$bInfo['BROWSER'] = 'konqu'; |
2925
|
|
|
} elseif (strpos($useragent, 'Opera') !== false) { |
2926
|
|
|
$bInfo['BROWSER'] = 'opera'; |
2927
|
|
|
} elseif (strpos($useragent, 'MSIE') !== false) { |
2928
|
|
|
$bInfo['BROWSER'] = 'msie'; |
2929
|
|
|
} elseif (strpos($useragent, 'Mozilla') !== false) { |
2930
|
|
|
$bInfo['BROWSER'] = 'net'; |
2931
|
|
|
} elseif (strpos($useragent, 'Flash') !== false) { |
2932
|
|
|
$bInfo['BROWSER'] = 'flash'; |
2933
|
|
|
} |
2934
|
|
|
if (isset($bInfo['BROWSER'])) { |
2935
|
|
|
// Browser version |
2936
|
|
|
switch ($bInfo['BROWSER']) { |
2937
|
|
|
case 'net': |
2938
|
|
|
$bInfo['VERSION'] = (float)substr($useragent, 8); |
2939
|
|
View Code Duplication |
if (strpos($useragent, 'Netscape6/') !== false) { |
2940
|
|
|
$bInfo['VERSION'] = (float)substr(strstr($useragent, 'Netscape6/'), 10); |
2941
|
|
|
} |
2942
|
|
|
// Will we ever know if this was a typo or intention...?! :-( |
2943
|
|
View Code Duplication |
if (strpos($useragent, 'Netscape/6') !== false) { |
2944
|
|
|
$bInfo['VERSION'] = (float)substr(strstr($useragent, 'Netscape/6'), 10); |
2945
|
|
|
} |
2946
|
|
View Code Duplication |
if (strpos($useragent, 'Netscape/7') !== false) { |
2947
|
|
|
$bInfo['VERSION'] = (float)substr(strstr($useragent, 'Netscape/7'), 9); |
2948
|
|
|
} |
2949
|
|
|
break; |
2950
|
|
View Code Duplication |
case 'msie': |
2951
|
|
|
$tmp = strstr($useragent, 'MSIE'); |
2952
|
|
|
$bInfo['VERSION'] = (float)preg_replace('/^[^0-9]*/', '', substr($tmp, 4)); |
2953
|
|
|
break; |
2954
|
|
View Code Duplication |
case 'opera': |
2955
|
|
|
$tmp = strstr($useragent, 'Opera'); |
2956
|
|
|
$bInfo['VERSION'] = (float)preg_replace('/^[^0-9]*/', '', substr($tmp, 5)); |
2957
|
|
|
break; |
2958
|
|
View Code Duplication |
case 'konqu': |
2959
|
|
|
$tmp = strstr($useragent, 'Konqueror/'); |
2960
|
|
|
$bInfo['VERSION'] = (float)substr($tmp, 10); |
2961
|
|
|
break; |
2962
|
|
|
} |
2963
|
|
|
// Client system |
2964
|
|
|
if (strpos($useragent, 'Win') !== false) { |
2965
|
|
|
$bInfo['SYSTEM'] = 'win'; |
2966
|
|
|
} elseif (strpos($useragent, 'Mac') !== false) { |
2967
|
|
|
$bInfo['SYSTEM'] = 'mac'; |
2968
|
|
|
} elseif (strpos($useragent, 'Linux') !== false || strpos($useragent, 'X11') !== false || strpos($useragent, 'SGI') !== false || strpos($useragent, ' SunOS ') !== false || strpos($useragent, ' HP-UX ') !== false) { |
2969
|
|
|
$bInfo['SYSTEM'] = 'unix'; |
2970
|
|
|
} |
2971
|
|
|
} |
2972
|
|
|
return $bInfo; |
2973
|
|
|
} |
2974
|
|
|
|
2975
|
|
|
/** |
2976
|
|
|
* Get the fully-qualified domain name of the host. |
2977
|
|
|
* |
2978
|
|
|
* @param bool $requestHost Use request host (when not in CLI mode). |
2979
|
|
|
* @return string The fully-qualified host name. |
2980
|
|
|
*/ |
2981
|
|
|
public static function getHostname($requestHost = true) |
2982
|
|
|
{ |
2983
|
|
|
$host = ''; |
2984
|
|
|
// If not called from the command-line, resolve on getIndpEnv() |
2985
|
|
|
if ($requestHost && !(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) { |
2986
|
|
|
$host = self::getIndpEnv('HTTP_HOST'); |
2987
|
|
|
} |
2988
|
|
|
if (!$host) { |
2989
|
|
|
// will fail for PHP 4.1 and 4.2 |
2990
|
|
|
$host = @php_uname('n'); |
2991
|
|
|
// 'n' is ignored in broken installations |
2992
|
|
|
if (strpos($host, ' ')) { |
2993
|
|
|
$host = ''; |
2994
|
|
|
} |
2995
|
|
|
} |
2996
|
|
|
// We have not found a FQDN yet |
2997
|
|
|
if ($host && strpos($host, '.') === false) { |
2998
|
|
|
$ip = gethostbyname($host); |
2999
|
|
|
// We got an IP address |
3000
|
|
|
if ($ip != $host) { |
3001
|
|
|
$fqdn = gethostbyaddr($ip); |
3002
|
|
|
if ($ip != $fqdn) { |
3003
|
|
|
$host = $fqdn; |
3004
|
|
|
} |
3005
|
|
|
} |
3006
|
|
|
} |
3007
|
|
|
if (!$host) { |
3008
|
|
|
$host = 'localhost.localdomain'; |
3009
|
|
|
} |
3010
|
|
|
return $host; |
3011
|
|
|
} |
3012
|
|
|
|
3013
|
|
|
/************************* |
3014
|
|
|
* |
3015
|
|
|
* TYPO3 SPECIFIC FUNCTIONS |
3016
|
|
|
* |
3017
|
|
|
*************************/ |
3018
|
|
|
/** |
3019
|
|
|
* Returns the absolute filename of a relative reference, resolves the "EXT:" prefix |
3020
|
|
|
* (way of referring to files inside extensions) and checks that the file is inside |
3021
|
|
|
* the PATH_site of the TYPO3 installation and implies a check with |
3022
|
|
|
* \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr(). |
3023
|
|
|
* |
3024
|
|
|
* @param string $filename The input filename/filepath to evaluate |
3025
|
|
|
* @return string Returns the absolute filename of $filename if valid, otherwise blank string. |
3026
|
|
|
*/ |
3027
|
|
|
public static function getFileAbsFileName($filename) |
3028
|
|
|
{ |
3029
|
|
|
if ((string)$filename === '') { |
3030
|
|
|
return ''; |
3031
|
|
|
} |
3032
|
|
|
// Extension |
3033
|
|
|
if (strpos($filename, 'EXT:') === 0) { |
3034
|
|
|
list($extKey, $local) = explode('/', substr($filename, 4), 2); |
|
|
|
|
3035
|
|
|
$filename = ''; |
3036
|
|
|
if ((string)$extKey !== '' && ExtensionManagementUtility::isLoaded($extKey) && (string)$local !== '') { |
3037
|
|
|
$filename = ExtensionManagementUtility::extPath($extKey) . $local; |
3038
|
|
|
} |
3039
|
|
|
} elseif (!static::isAbsPath($filename)) { |
3040
|
|
|
// is relative. Prepended with PATH_site |
3041
|
|
|
$filename = PATH_site . $filename; |
3042
|
|
|
} elseif (!static::isFirstPartOfStr($filename, PATH_site)) { |
3043
|
|
|
// absolute, but set to blank if not allowed |
3044
|
|
|
$filename = ''; |
3045
|
|
|
} |
3046
|
|
|
if ((string)$filename !== '' && static::validPathStr($filename)) { |
3047
|
|
|
// checks backpath. |
3048
|
|
|
return $filename; |
3049
|
|
|
} |
3050
|
|
|
return ''; |
3051
|
|
|
} |
3052
|
|
|
|
3053
|
|
|
/** |
3054
|
|
|
* Checks for malicious file paths. |
3055
|
|
|
* |
3056
|
|
|
* Returns TRUE if no '//', '..', '\' or control characters are found in the $theFile. |
3057
|
|
|
* This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes. |
3058
|
|
|
* So it's compatible with the UNIX style path strings valid for TYPO3 internally. |
3059
|
|
|
* |
3060
|
|
|
* @param string $theFile File path to evaluate |
3061
|
|
|
* @return bool TRUE, $theFile is allowed path string, FALSE otherwise |
3062
|
|
|
* @see http://php.net/manual/en/security.filesystem.nullbytes.php |
3063
|
|
|
*/ |
3064
|
|
|
public static function validPathStr($theFile) |
3065
|
|
|
{ |
3066
|
|
|
return strpos($theFile, '//') === false && strpos($theFile, '\\') === false |
3067
|
|
|
&& preg_match('#(?:^\\.\\.|/\\.\\./|[[:cntrl:]])#u', $theFile) === 0; |
3068
|
|
|
} |
3069
|
|
|
|
3070
|
|
|
/** |
3071
|
|
|
* Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns TRUE if so. |
3072
|
|
|
* |
3073
|
|
|
* @param string $path File path to evaluate |
3074
|
|
|
* @return bool |
3075
|
|
|
*/ |
3076
|
|
|
public static function isAbsPath($path) |
3077
|
|
|
{ |
3078
|
|
|
return $path[0] === '/' || TYPO3_OS === 'WIN' && (strpos($path, ':/') === 1 || strpos($path, ':\\') === 1); |
3079
|
|
|
} |
3080
|
|
|
|
3081
|
|
|
/** |
3082
|
|
|
* Returns TRUE if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath |
3083
|
|
|
* |
3084
|
|
|
* @param string $path File path to evaluate |
3085
|
|
|
* @return bool |
3086
|
|
|
*/ |
3087
|
|
|
public static function isAllowedAbsPath($path) |
3088
|
|
|
{ |
3089
|
|
|
$lockRootPath = $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']; |
3090
|
|
|
return static::isAbsPath($path) && static::validPathStr($path) |
3091
|
|
|
&& (static::isFirstPartOfStr($path, PATH_site) |
3092
|
|
|
|| $lockRootPath && static::isFirstPartOfStr($path, $lockRootPath)); |
3093
|
|
|
} |
3094
|
|
|
|
3095
|
|
|
/** |
3096
|
|
|
* Verifies the input filename against the 'fileDenyPattern'. Returns TRUE if OK. |
3097
|
|
|
* |
3098
|
|
|
* Filenames are not allowed to contain control characters. Therefore we |
3099
|
|
|
* always filter on [[:cntrl:]]. |
3100
|
|
|
* |
3101
|
|
|
* @param string $filename File path to evaluate |
3102
|
|
|
* @return bool |
3103
|
|
|
*/ |
3104
|
|
|
public static function verifyFilenameAgainstDenyPattern($filename) |
3105
|
|
|
{ |
3106
|
|
|
$pattern = '/[[:cntrl:]]/'; |
3107
|
|
|
if ((string)$filename !== '' && (string)$GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] !== '') { |
3108
|
|
|
$pattern = '/(?:[[:cntrl:]]|' . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] . ')/i'; |
3109
|
|
|
} |
3110
|
|
|
return !preg_match($pattern, $filename); |
3111
|
|
|
} |
3112
|
|
|
|
3113
|
|
|
/** |
3114
|
|
|
* Low level utility function to copy directories and content recursive |
3115
|
|
|
* |
3116
|
|
|
* @param string $source Path to source directory, relative to document root or absolute |
3117
|
|
|
* @param string $destination Path to destination directory, relative to document root or absolute |
3118
|
|
|
*/ |
3119
|
|
|
public static function copyDirectory($source, $destination) |
3120
|
|
|
{ |
3121
|
|
|
if (strpos($source, PATH_site) === false) { |
3122
|
|
|
$source = PATH_site . $source; |
3123
|
|
|
} |
3124
|
|
|
if (strpos($destination, PATH_site) === false) { |
3125
|
|
|
$destination = PATH_site . $destination; |
3126
|
|
|
} |
3127
|
|
|
if (static::isAllowedAbsPath($source) && static::isAllowedAbsPath($destination)) { |
3128
|
|
|
$iterator = new \RecursiveIteratorIterator( |
3129
|
|
|
new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), |
3130
|
|
|
\RecursiveIteratorIterator::SELF_FIRST |
3131
|
|
|
); |
3132
|
|
|
foreach ($iterator as $item) { |
3133
|
|
|
$target = $destination . '/' . $iterator->getSubPathName(); |
|
|
|
|
3134
|
|
|
if ($item->isDir()) { |
3135
|
|
|
static::mkdir($target); |
3136
|
|
|
} else { |
3137
|
|
|
static::upload_copy_move($item, $target); |
3138
|
|
|
} |
3139
|
|
|
} |
3140
|
|
|
} |
3141
|
|
|
} |
3142
|
|
|
|
3143
|
|
|
/** |
3144
|
|
|
* Checks if a given string is a valid frame URL to be loaded in the |
3145
|
|
|
* backend. |
3146
|
|
|
* |
3147
|
|
|
* If the given url is empty or considered to be harmless, it is returned |
3148
|
|
|
* as is, else the event is logged and an empty string is returned. |
3149
|
|
|
* |
3150
|
|
|
* @param string $url potential URL to check |
3151
|
|
|
* @return string $url or empty string |
3152
|
|
|
*/ |
3153
|
|
|
public static function sanitizeLocalUrl($url = '') |
3154
|
|
|
{ |
3155
|
|
|
$sanitizedUrl = ''; |
3156
|
|
|
if (!empty($url)) { |
3157
|
|
|
$decodedUrl = rawurldecode($url); |
3158
|
|
|
$parsedUrl = parse_url($decodedUrl); |
3159
|
|
|
$testAbsoluteUrl = self::resolveBackPath($decodedUrl); |
3160
|
|
|
$testRelativeUrl = self::resolveBackPath(self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl); |
3161
|
|
|
// Pass if URL is on the current host: |
3162
|
|
|
if (self::isValidUrl($decodedUrl)) { |
3163
|
|
|
if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) { |
3164
|
|
|
$sanitizedUrl = $url; |
3165
|
|
|
} |
3166
|
|
|
} elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) { |
3167
|
|
|
$sanitizedUrl = $url; |
3168
|
|
|
} elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && $decodedUrl[0] === '/') { |
3169
|
|
|
$sanitizedUrl = $url; |
3170
|
|
|
} elseif (empty($parsedUrl['scheme']) && strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 |
3171
|
|
|
&& $decodedUrl[0] !== '/' && strpbrk($decodedUrl, '*:|"<>') === false && strpos($decodedUrl, '\\\\') === false |
3172
|
|
|
) { |
3173
|
|
|
$sanitizedUrl = $url; |
3174
|
|
|
} |
3175
|
|
|
} |
3176
|
|
|
if (!empty($url) && empty($sanitizedUrl)) { |
3177
|
|
|
static::getLogger()->notice('The URL "' . $url . '" is not considered to be local and was denied.'); |
3178
|
|
|
} |
3179
|
|
|
return $sanitizedUrl; |
3180
|
|
|
} |
3181
|
|
|
|
3182
|
|
|
/** |
3183
|
|
|
* Moves $source file to $destination if uploaded, otherwise try to make a copy |
3184
|
|
|
* |
3185
|
|
|
* @param string $source Source file, absolute path |
3186
|
|
|
* @param string $destination Destination file, absolute path |
3187
|
|
|
* @return bool Returns TRUE if the file was moved. |
3188
|
|
|
* @see upload_to_tempfile() |
3189
|
|
|
*/ |
3190
|
|
|
public static function upload_copy_move($source, $destination) |
3191
|
|
|
{ |
3192
|
|
|
$result = false; |
3193
|
|
|
if (is_uploaded_file($source)) { |
3194
|
|
|
// Return the value of move_uploaded_file, and if FALSE the temporary $source is still |
3195
|
|
|
// around so the user can use unlink to delete it: |
3196
|
|
|
$result = move_uploaded_file($source, $destination); |
3197
|
|
|
} else { |
3198
|
|
|
@copy($source, $destination); |
|
|
|
|
3199
|
|
|
} |
3200
|
|
|
// Change the permissions of the file |
3201
|
|
|
self::fixPermissions($destination); |
3202
|
|
|
// If here the file is copied and the temporary $source is still around, |
3203
|
|
|
// so when returning FALSE the user can try unlink to delete the $source |
3204
|
|
|
return $result; |
3205
|
|
|
} |
3206
|
|
|
|
3207
|
|
|
/** |
3208
|
|
|
* Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it. |
3209
|
|
|
* Use this function to move uploaded files to where you can work on them. |
3210
|
|
|
* REMEMBER to use \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"! |
3211
|
|
|
* |
3212
|
|
|
* @param string $uploadedFileName The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name'] |
3213
|
|
|
* @return string If a new file was successfully created, return its filename, otherwise blank string. |
3214
|
|
|
* @see unlink_tempfile(), upload_copy_move() |
3215
|
|
|
*/ |
3216
|
|
|
public static function upload_to_tempfile($uploadedFileName) |
3217
|
|
|
{ |
3218
|
|
|
if (is_uploaded_file($uploadedFileName)) { |
3219
|
|
|
$tempFile = self::tempnam('upload_temp_'); |
3220
|
|
|
move_uploaded_file($uploadedFileName, $tempFile); |
3221
|
|
|
return @is_file($tempFile) ? $tempFile : ''; |
3222
|
|
|
} |
3223
|
|
|
} |
3224
|
|
|
|
3225
|
|
|
/** |
3226
|
|
|
* Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input. |
3227
|
|
|
* The function will check that the file exists, is in PATH_site."typo3temp/" and does not contain back-spaces ("../") so it should be pretty safe. |
3228
|
|
|
* Use this after upload_to_tempfile() or tempnam() from this class! |
3229
|
|
|
* |
3230
|
|
|
* @param string $uploadedTempFileName Filepath for a file in PATH_site."typo3temp/". Must be absolute. |
3231
|
|
|
* @return bool Returns TRUE if the file was unlink()'ed |
3232
|
|
|
* @see upload_to_tempfile(), tempnam() |
3233
|
|
|
*/ |
3234
|
|
|
public static function unlink_tempfile($uploadedTempFileName) |
3235
|
|
|
{ |
3236
|
|
|
if ($uploadedTempFileName) { |
3237
|
|
|
$uploadedTempFileName = self::fixWindowsFilePath($uploadedTempFileName); |
3238
|
|
|
if ( |
3239
|
|
|
self::validPathStr($uploadedTempFileName) |
3240
|
|
|
&& self::isFirstPartOfStr($uploadedTempFileName, PATH_site . 'typo3temp/') |
3241
|
|
|
&& @is_file($uploadedTempFileName) |
3242
|
|
|
) { |
3243
|
|
|
if (unlink($uploadedTempFileName)) { |
3244
|
|
|
return true; |
3245
|
|
|
} |
3246
|
|
|
} |
3247
|
|
|
} |
3248
|
|
|
} |
3249
|
|
|
|
3250
|
|
|
/** |
3251
|
|
|
* Create temporary filename (Create file with unique file name) |
3252
|
|
|
* This function should be used for getting temporary file names - will make your applications safe for open_basedir = on |
3253
|
|
|
* REMEMBER to delete the temporary files after use! This is done by \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile() |
3254
|
|
|
* |
3255
|
|
|
* @param string $filePrefix Prefix for temporary file |
3256
|
|
|
* @param string $fileSuffix Suffix for temporary file, for example a special file extension |
3257
|
|
|
* @return string result from PHP function tempnam() with PATH_site . 'typo3temp/' set for temp path. |
3258
|
|
|
* @see unlink_tempfile(), upload_to_tempfile() |
3259
|
|
|
*/ |
3260
|
|
|
public static function tempnam($filePrefix, $fileSuffix = '') |
3261
|
|
|
{ |
3262
|
|
|
$temporaryPath = PATH_site . 'typo3temp/var/transient/'; |
3263
|
|
|
if (!is_dir($temporaryPath)) { |
3264
|
|
|
self::mkdir_deep($temporaryPath); |
3265
|
|
|
} |
3266
|
|
|
if ($fileSuffix === '') { |
3267
|
|
|
$tempFileName = $temporaryPath . basename(tempnam($temporaryPath, $filePrefix)); |
|
|
|
|
3268
|
|
|
} else { |
3269
|
|
|
do { |
3270
|
|
|
$tempFileName = $temporaryPath . $filePrefix . mt_rand(1, PHP_INT_MAX) . $fileSuffix; |
3271
|
|
|
} while (file_exists($tempFileName)); |
3272
|
|
|
touch($tempFileName); |
3273
|
|
|
clearstatcache(null, $tempFileName); |
3274
|
|
|
} |
3275
|
|
|
return $tempFileName; |
3276
|
|
|
} |
3277
|
|
|
|
3278
|
|
|
/** |
3279
|
|
|
* Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations) |
3280
|
|
|
* |
3281
|
|
|
* @param mixed $uid_or_record Uid (int) or record (array) |
3282
|
|
|
* @param string $fields List of fields from the record if that is given. |
3283
|
|
|
* @param int $codeLength Length of returned authentication code. |
3284
|
|
|
* @return string MD5 hash of 8 chars. |
3285
|
|
|
*/ |
3286
|
|
|
public static function stdAuthCode($uid_or_record, $fields = '', $codeLength = 8) |
3287
|
|
|
{ |
3288
|
|
|
if (is_array($uid_or_record)) { |
3289
|
|
|
$recCopy_temp = []; |
3290
|
|
|
if ($fields) { |
3291
|
|
|
$fieldArr = self::trimExplode(',', $fields, true); |
3292
|
|
|
foreach ($fieldArr as $k => $v) { |
3293
|
|
|
$recCopy_temp[$k] = $uid_or_record[$v]; |
3294
|
|
|
} |
3295
|
|
|
} else { |
3296
|
|
|
$recCopy_temp = $uid_or_record; |
3297
|
|
|
} |
3298
|
|
|
$preKey = implode('|', $recCopy_temp); |
3299
|
|
|
} else { |
3300
|
|
|
$preKey = $uid_or_record; |
3301
|
|
|
} |
3302
|
|
|
$authCode = $preKey . '||' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']; |
3303
|
|
|
$authCode = substr(md5($authCode), 0, $codeLength); |
3304
|
|
|
return $authCode; |
3305
|
|
|
} |
3306
|
|
|
|
3307
|
|
|
/** |
3308
|
|
|
* Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not. |
3309
|
|
|
* |
3310
|
|
|
* @param int $l18n_cfg_fieldValue Value from "l18n_cfg" field of a page record |
3311
|
|
|
* @return bool TRUE if the page should be hidden |
3312
|
|
|
*/ |
3313
|
|
|
public static function hideIfNotTranslated($l18n_cfg_fieldValue) |
3314
|
|
|
{ |
3315
|
|
|
return $GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault'] xor ($l18n_cfg_fieldValue & 2); |
3316
|
|
|
} |
3317
|
|
|
|
3318
|
|
|
/** |
3319
|
|
|
* Returns true if the "l18n_cfg" field value is not set to hide |
3320
|
|
|
* pages in the default language |
3321
|
|
|
* |
3322
|
|
|
* @param int $localizationConfiguration |
3323
|
|
|
* @return bool |
3324
|
|
|
*/ |
3325
|
|
|
public static function hideIfDefaultLanguage($localizationConfiguration) |
3326
|
|
|
{ |
3327
|
|
|
return (bool)($localizationConfiguration & 1); |
3328
|
|
|
} |
3329
|
|
|
|
3330
|
|
|
/** |
3331
|
|
|
* Returns auto-filename for locallang localizations |
3332
|
|
|
* |
3333
|
|
|
* @param string $fileRef Absolute file reference to locallang file |
3334
|
|
|
* @param string $language Language key |
3335
|
|
|
* @param bool $sameLocation If TRUE, then locallang localization file name will be returned with same directory as $fileRef |
3336
|
|
|
* @return string Returns the filename reference for the language unless error occurred in which case it will be NULL |
3337
|
|
|
* @deprecated in TYPO3 v9.0, will be removed in TYPO3 v10.0, as the functionality has been moved into AbstractXmlParser. |
3338
|
|
|
*/ |
3339
|
|
|
public static function llXmlAutoFileName($fileRef, $language, $sameLocation = false) |
3340
|
|
|
{ |
3341
|
|
|
trigger_error('This method will be removed in TYPO3 v10.0, the functionality has been moved into AbstractXmlParser', E_USER_DEPRECATED); |
3342
|
|
|
// If $fileRef is already prefixed with "[language key]" then we should return it as is |
3343
|
|
|
$fileName = basename($fileRef); |
3344
|
|
|
if (self::isFirstPartOfStr($fileName, $language . '.')) { |
3345
|
|
|
return $fileRef; |
3346
|
|
|
} |
3347
|
|
|
|
3348
|
|
|
if ($sameLocation) { |
3349
|
|
|
return str_replace($fileName, $language . '.' . $fileName, $fileRef); |
3350
|
|
|
} |
3351
|
|
|
|
3352
|
|
|
// Analyse file reference: |
3353
|
|
|
// Is system: |
3354
|
|
View Code Duplication |
if (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'sysext/')) { |
3355
|
|
|
$validatedPrefix = PATH_typo3 . 'sysext/'; |
3356
|
|
|
} elseif (self::isFirstPartOfStr($fileRef, PATH_typo3 . 'ext/')) { |
3357
|
|
|
// Is global: |
3358
|
|
|
$validatedPrefix = PATH_typo3 . 'ext/'; |
3359
|
|
|
} elseif (self::isFirstPartOfStr($fileRef, PATH_typo3conf . 'ext/')) { |
3360
|
|
|
// Is local: |
3361
|
|
|
$validatedPrefix = PATH_typo3conf . 'ext/'; |
3362
|
|
|
} else { |
3363
|
|
|
$validatedPrefix = ''; |
3364
|
|
|
} |
3365
|
|
View Code Duplication |
if ($validatedPrefix) { |
3366
|
|
|
// Divide file reference into extension key, directory (if any) and base name: |
3367
|
|
|
list($file_extKey, $file_extPath) = explode('/', substr($fileRef, strlen($validatedPrefix)), 2); |
|
|
|
|
3368
|
|
|
$temp = self::revExplode('/', $file_extPath, 2); |
3369
|
|
|
if (count($temp) === 1) { |
3370
|
|
|
array_unshift($temp, ''); |
3371
|
|
|
} |
3372
|
|
|
// Add empty first-entry if not there. |
3373
|
|
|
list($file_extPath, $file_fileName) = $temp; |
3374
|
|
|
// The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it. |
3375
|
|
|
$location = 'typo3conf/l10n/' . $language . '/' . $file_extKey . '/' . ($file_extPath ? $file_extPath . '/' : ''); |
3376
|
|
|
return $location . $language . '.' . $file_fileName; |
3377
|
|
|
} |
3378
|
|
|
return null; |
3379
|
|
|
} |
3380
|
|
|
|
3381
|
|
|
/** |
3382
|
|
|
* Calls a user-defined function/method in class |
3383
|
|
|
* Such a function/method should look like this: "function proc(&$params, &$ref) {...}" |
3384
|
|
|
* |
3385
|
|
|
* @param string $funcName Function/Method reference or Closure. |
3386
|
|
|
* @param mixed $params Parameters to be pass along (typically an array) (REFERENCE!) |
3387
|
|
|
* @param mixed $ref Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!) |
3388
|
|
|
* @return mixed Content from method/function call |
3389
|
|
|
* @throws \InvalidArgumentException |
3390
|
|
|
*/ |
3391
|
|
|
public static function callUserFunction($funcName, &$params, &$ref) |
3392
|
|
|
{ |
3393
|
|
|
// Check if we're using a closure and invoke it directly. |
3394
|
|
|
if (is_object($funcName) && is_a($funcName, 'Closure')) { |
3395
|
|
|
return call_user_func_array($funcName, [&$params, &$ref]); |
3396
|
|
|
} |
3397
|
|
|
$funcName = trim($funcName); |
3398
|
|
|
$parts = explode('->', $funcName); |
3399
|
|
|
// Call function or method |
3400
|
|
|
if (count($parts) === 2) { |
3401
|
|
|
// It's a class/method |
3402
|
|
|
// Check if class/method exists: |
3403
|
|
|
if (class_exists($parts[0])) { |
3404
|
|
|
// Create object |
3405
|
|
|
$classObj = self::makeInstance($parts[0]); |
3406
|
|
|
if (method_exists($classObj, $parts[1])) { |
3407
|
|
|
// Call method: |
3408
|
|
|
$content = call_user_func_array([&$classObj, $parts[1]], [&$params, &$ref]); |
3409
|
|
|
} else { |
3410
|
|
|
$errorMsg = 'No method name \'' . $parts[1] . '\' in class ' . $parts[0]; |
3411
|
|
|
throw new \InvalidArgumentException($errorMsg, 1294585865); |
3412
|
|
|
} |
3413
|
|
|
} else { |
3414
|
|
|
$errorMsg = 'No class named ' . $parts[0]; |
3415
|
|
|
throw new \InvalidArgumentException($errorMsg, 1294585866); |
3416
|
|
|
} |
3417
|
|
|
} elseif (function_exists($funcName)) { |
3418
|
|
|
// It's a function |
3419
|
|
|
$content = call_user_func_array($funcName, [&$params, &$ref]); |
3420
|
|
|
} else { |
3421
|
|
|
$errorMsg = 'No function named: ' . $funcName; |
3422
|
|
|
throw new \InvalidArgumentException($errorMsg, 1294585867); |
3423
|
|
|
} |
3424
|
|
|
return $content; |
3425
|
|
|
} |
3426
|
|
|
|
3427
|
|
|
/** |
3428
|
|
|
* This method should be avoided, as it will be deprecated completely in TYPO3 v9, and will be removed in TYPO3 v10. |
3429
|
|
|
* Instead use makeInstance() directly. |
3430
|
|
|
* |
3431
|
|
|
* Creates and returns reference to a user defined object. |
3432
|
|
|
* This function can return an object reference if you like. |
3433
|
|
|
* |
3434
|
|
|
* @param string $className Class name |
3435
|
|
|
* @return object The instance of the class asked for. Instance is created with GeneralUtility::makeInstance |
3436
|
|
|
* @see callUserFunction() |
3437
|
|
|
* @deprecated |
3438
|
|
|
*/ |
3439
|
|
|
public static function getUserObj($className) |
3440
|
|
|
{ |
3441
|
|
|
trigger_error('This method will be removed in TYPO3 v10.0, use GeneralUtility::makeInstance() directly instead', E_USER_DEPRECATED); |
3442
|
|
|
// Check if class exists: |
3443
|
|
|
if (class_exists($className)) { |
3444
|
|
|
return self::makeInstance($className); |
3445
|
|
|
} |
3446
|
|
|
} |
3447
|
|
|
|
3448
|
|
|
/** |
3449
|
|
|
* Creates an instance of a class taking into account the class-extensions |
3450
|
|
|
* API of TYPO3. USE THIS method instead of the PHP "new" keyword. |
3451
|
|
|
* Eg. "$obj = new myclass;" should be "$obj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance("myclass")" instead! |
3452
|
|
|
* |
3453
|
|
|
* You can also pass arguments for a constructor: |
3454
|
|
|
* \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\myClass::class, $arg1, $arg2, ..., $argN) |
3455
|
|
|
* |
3456
|
|
|
* You may want to use \TYPO3\CMS\Extbase\Object\ObjectManager::get() if you |
3457
|
|
|
* want TYPO3 to take care about injecting dependencies of the class to be |
3458
|
|
|
* created. Therefore create an instance of ObjectManager via |
3459
|
|
|
* GeneralUtility::makeInstance() first and call its get() method to get |
3460
|
|
|
* the instance of a specific class. |
3461
|
|
|
* |
3462
|
|
|
* @param string $className name of the class to instantiate, must not be empty and not start with a backslash |
3463
|
|
|
* @param array<int, mixed> $constructorArguments Arguments for the constructor |
3464
|
|
|
* @return object the created instance |
3465
|
|
|
* @throws \InvalidArgumentException if $className is empty or starts with a backslash |
3466
|
|
|
*/ |
3467
|
|
|
public static function makeInstance($className, ...$constructorArguments) |
3468
|
|
|
{ |
3469
|
|
|
if (!is_string($className) || empty($className)) { |
3470
|
|
|
throw new \InvalidArgumentException('$className must be a non empty string.', 1288965219); |
3471
|
|
|
} |
3472
|
|
|
// Never instantiate with a beginning backslash, otherwise things like singletons won't work. |
3473
|
|
|
if ($className[0] === '\\') { |
3474
|
|
|
throw new \InvalidArgumentException( |
3475
|
|
|
'$className "' . $className . '" must not start with a backslash.', |
3476
|
|
|
1420281366 |
3477
|
|
|
); |
3478
|
|
|
} |
3479
|
|
|
if (isset(static::$finalClassNameCache[$className])) { |
3480
|
|
|
$finalClassName = static::$finalClassNameCache[$className]; |
3481
|
|
|
} else { |
3482
|
|
|
$finalClassName = self::getClassName($className); |
3483
|
|
|
static::$finalClassNameCache[$className] = $finalClassName; |
3484
|
|
|
} |
3485
|
|
|
// Return singleton instance if it is already registered |
3486
|
|
|
if (isset(self::$singletonInstances[$finalClassName])) { |
3487
|
|
|
return self::$singletonInstances[$finalClassName]; |
3488
|
|
|
} |
3489
|
|
|
// Return instance if it has been injected by addInstance() |
3490
|
|
|
if ( |
3491
|
|
|
isset(self::$nonSingletonInstances[$finalClassName]) |
3492
|
|
|
&& !empty(self::$nonSingletonInstances[$finalClassName]) |
3493
|
|
|
) { |
3494
|
|
|
return array_shift(self::$nonSingletonInstances[$finalClassName]); |
3495
|
|
|
} |
3496
|
|
|
// Create new instance and call constructor with parameters |
3497
|
|
|
$instance = new $finalClassName(...$constructorArguments); |
3498
|
|
|
// Register new singleton instance |
3499
|
|
|
if ($instance instanceof SingletonInterface) { |
3500
|
|
|
self::$singletonInstances[$finalClassName] = $instance; |
3501
|
|
|
} |
3502
|
|
|
if ($instance instanceof LoggerAwareInterface) { |
3503
|
|
|
$instance->setLogger(static::makeInstance(LogManager::class)->getLogger($className)); |
3504
|
|
|
} |
3505
|
|
|
return $instance; |
3506
|
|
|
} |
3507
|
|
|
|
3508
|
|
|
/** |
3509
|
|
|
* Returns the class name for a new instance, taking into account |
3510
|
|
|
* registered implementations for this class |
3511
|
|
|
* |
3512
|
|
|
* @param string $className Base class name to evaluate |
3513
|
|
|
* @return string Final class name to instantiate with "new [classname] |
3514
|
|
|
*/ |
3515
|
|
|
protected static function getClassName($className) |
3516
|
|
|
{ |
3517
|
|
|
if (class_exists($className)) { |
3518
|
|
|
while (static::classHasImplementation($className)) { |
3519
|
|
|
$className = static::getImplementationForClass($className); |
3520
|
|
|
} |
3521
|
|
|
} |
3522
|
|
|
return ClassLoadingInformation::getClassNameForAlias($className); |
3523
|
|
|
} |
3524
|
|
|
|
3525
|
|
|
/** |
3526
|
|
|
* Returns the configured implementation of the class |
3527
|
|
|
* |
3528
|
|
|
* @param string $className |
3529
|
|
|
* @return string |
3530
|
|
|
*/ |
3531
|
|
|
protected static function getImplementationForClass($className) |
3532
|
|
|
{ |
3533
|
|
|
return $GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][$className]['className']; |
3534
|
|
|
} |
3535
|
|
|
|
3536
|
|
|
/** |
3537
|
|
|
* Checks if a class has a configured implementation |
3538
|
|
|
* |
3539
|
|
|
* @param string $className |
3540
|
|
|
* @return bool |
3541
|
|
|
*/ |
3542
|
|
|
protected static function classHasImplementation($className) |
3543
|
|
|
{ |
3544
|
|
|
return !empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][$className]['className']); |
3545
|
|
|
} |
3546
|
|
|
|
3547
|
|
|
/** |
3548
|
|
|
* Sets the instance of a singleton class to be returned by makeInstance. |
3549
|
|
|
* |
3550
|
|
|
* If this function is called multiple times for the same $className, |
3551
|
|
|
* makeInstance will return the last set instance. |
3552
|
|
|
* |
3553
|
|
|
* Warning: |
3554
|
|
|
* This is NOT a public API method and must not be used in own extensions! |
3555
|
|
|
* This methods exists mostly for unit tests to inject a mock of a singleton class. |
3556
|
|
|
* If you use this, make sure to always combine this with getSingletonInstances() |
3557
|
|
|
* and resetSingletonInstances() in setUp() and tearDown() of the test class. |
3558
|
|
|
* |
3559
|
|
|
* @see makeInstance |
3560
|
|
|
* @param string $className |
3561
|
|
|
* @param \TYPO3\CMS\Core\SingletonInterface $instance |
3562
|
|
|
* @internal |
3563
|
|
|
*/ |
3564
|
|
|
public static function setSingletonInstance($className, SingletonInterface $instance) |
3565
|
|
|
{ |
3566
|
|
|
self::checkInstanceClassName($className, $instance); |
3567
|
|
|
self::$singletonInstances[$className] = $instance; |
3568
|
|
|
} |
3569
|
|
|
|
3570
|
|
|
/** |
3571
|
|
|
* Removes the instance of a singleton class to be returned by makeInstance. |
3572
|
|
|
* |
3573
|
|
|
* Warning: |
3574
|
|
|
* This is NOT a public API method and must not be used in own extensions! |
3575
|
|
|
* This methods exists mostly for unit tests to inject a mock of a singleton class. |
3576
|
|
|
* If you use this, make sure to always combine this with getSingletonInstances() |
3577
|
|
|
* and resetSingletonInstances() in setUp() and tearDown() of the test class. |
3578
|
|
|
* |
3579
|
|
|
* @see makeInstance |
3580
|
|
|
* @throws \InvalidArgumentException |
3581
|
|
|
* @param string $className |
3582
|
|
|
* @param \TYPO3\CMS\Core\SingletonInterface $instance |
3583
|
|
|
* @internal |
3584
|
|
|
*/ |
3585
|
|
|
public static function removeSingletonInstance($className, SingletonInterface $instance) |
3586
|
|
|
{ |
3587
|
|
|
self::checkInstanceClassName($className, $instance); |
3588
|
|
|
if (!isset(self::$singletonInstances[$className])) { |
3589
|
|
|
throw new \InvalidArgumentException('No Instance registered for ' . $className . '.', 1394099179); |
3590
|
|
|
} |
3591
|
|
|
if ($instance !== self::$singletonInstances[$className]) { |
3592
|
|
|
throw new \InvalidArgumentException('The instance you are trying to remove has not been registered before.', 1394099256); |
3593
|
|
|
} |
3594
|
|
|
unset(self::$singletonInstances[$className]); |
3595
|
|
|
} |
3596
|
|
|
|
3597
|
|
|
/** |
3598
|
|
|
* Set a group of singleton instances. Similar to setSingletonInstance(), |
3599
|
|
|
* but multiple instances can be set. |
3600
|
|
|
* |
3601
|
|
|
* Warning: |
3602
|
|
|
* This is NOT a public API method and must not be used in own extensions! |
3603
|
|
|
* This method is usually only used in tests to restore the list of singletons in |
3604
|
|
|
* tearDown(), that was backed up with getSingletonInstances() in setUp() and |
3605
|
|
|
* manipulated in tests with setSingletonInstance() |
3606
|
|
|
* |
3607
|
|
|
* @internal |
3608
|
|
|
* @param array $newSingletonInstances $className => $object |
3609
|
|
|
*/ |
3610
|
|
|
public static function resetSingletonInstances(array $newSingletonInstances) |
3611
|
|
|
{ |
3612
|
|
|
static::$singletonInstances = []; |
3613
|
|
|
foreach ($newSingletonInstances as $className => $instance) { |
3614
|
|
|
static::setSingletonInstance($className, $instance); |
3615
|
|
|
} |
3616
|
|
|
} |
3617
|
|
|
|
3618
|
|
|
/** |
3619
|
|
|
* Get all currently registered singletons |
3620
|
|
|
* |
3621
|
|
|
* Warning: |
3622
|
|
|
* This is NOT a public API method and must not be used in own extensions! |
3623
|
|
|
* This method is usually only used in tests in setUp() to fetch the list of |
3624
|
|
|
* currently registered singletons, if this list is manipulated with |
3625
|
|
|
* setSingletonInstance() in tests. |
3626
|
|
|
* |
3627
|
|
|
* @internal |
3628
|
|
|
* @return array $className => $object |
3629
|
|
|
*/ |
3630
|
|
|
public static function getSingletonInstances() |
3631
|
|
|
{ |
3632
|
|
|
return static::$singletonInstances; |
3633
|
|
|
} |
3634
|
|
|
|
3635
|
|
|
/** |
3636
|
|
|
* Sets the instance of a non-singleton class to be returned by makeInstance. |
3637
|
|
|
* |
3638
|
|
|
* If this function is called multiple times for the same $className, |
3639
|
|
|
* makeInstance will return the instances in the order in which they have |
3640
|
|
|
* been added (FIFO). |
3641
|
|
|
* |
3642
|
|
|
* Warning: This is a helper method for unit tests. Do not call this directly in production code! |
3643
|
|
|
* |
3644
|
|
|
* @see makeInstance |
3645
|
|
|
* @throws \InvalidArgumentException if class extends \TYPO3\CMS\Core\SingletonInterface |
3646
|
|
|
* @param string $className |
3647
|
|
|
* @param object $instance |
3648
|
|
|
*/ |
3649
|
|
|
public static function addInstance($className, $instance) |
3650
|
|
|
{ |
3651
|
|
|
self::checkInstanceClassName($className, $instance); |
3652
|
|
|
if ($instance instanceof SingletonInterface) { |
3653
|
|
|
throw new \InvalidArgumentException('$instance must not be an instance of TYPO3\\CMS\\Core\\SingletonInterface. ' . 'For setting singletons, please use setSingletonInstance.', 1288969325); |
3654
|
|
|
} |
3655
|
|
|
if (!isset(self::$nonSingletonInstances[$className])) { |
3656
|
|
|
self::$nonSingletonInstances[$className] = []; |
3657
|
|
|
} |
3658
|
|
|
self::$nonSingletonInstances[$className][] = $instance; |
3659
|
|
|
} |
3660
|
|
|
|
3661
|
|
|
/** |
3662
|
|
|
* Checks that $className is non-empty and that $instance is an instance of |
3663
|
|
|
* $className. |
3664
|
|
|
* |
3665
|
|
|
* @throws \InvalidArgumentException if $className is empty or if $instance is no instance of $className |
3666
|
|
|
* @param string $className a class name |
3667
|
|
|
* @param object $instance an object |
3668
|
|
|
*/ |
3669
|
|
|
protected static function checkInstanceClassName($className, $instance) |
3670
|
|
|
{ |
3671
|
|
|
if ($className === '') { |
3672
|
|
|
throw new \InvalidArgumentException('$className must not be empty.', 1288967479); |
3673
|
|
|
} |
3674
|
|
|
if (!$instance instanceof $className) { |
3675
|
|
|
throw new \InvalidArgumentException('$instance must be an instance of ' . $className . ', but actually is an instance of ' . get_class($instance) . '.', 1288967686); |
3676
|
|
|
} |
3677
|
|
|
} |
3678
|
|
|
|
3679
|
|
|
/** |
3680
|
|
|
* Purge all instances returned by makeInstance. |
3681
|
|
|
* |
3682
|
|
|
* This function is most useful when called from tearDown in a test case |
3683
|
|
|
* to drop any instances that have been created by the tests. |
3684
|
|
|
* |
3685
|
|
|
* Warning: This is a helper method for unit tests. Do not call this directly in production code! |
3686
|
|
|
* |
3687
|
|
|
* @see makeInstance |
3688
|
|
|
*/ |
3689
|
|
|
public static function purgeInstances() |
3690
|
|
|
{ |
3691
|
|
|
self::$singletonInstances = []; |
3692
|
|
|
self::$nonSingletonInstances = []; |
3693
|
|
|
} |
3694
|
|
|
|
3695
|
|
|
/** |
3696
|
|
|
* Flush internal runtime caches |
3697
|
|
|
* |
3698
|
|
|
* Used in unit tests only. |
3699
|
|
|
* |
3700
|
|
|
* @internal |
3701
|
|
|
*/ |
3702
|
|
|
public static function flushInternalRuntimeCaches() |
3703
|
|
|
{ |
3704
|
|
|
self::$indpEnvCache = []; |
3705
|
|
|
self::$idnaStringCache = []; |
3706
|
|
|
} |
3707
|
|
|
|
3708
|
|
|
/** |
3709
|
|
|
* Find the best service and check if it works. |
3710
|
|
|
* Returns object of the service class. |
3711
|
|
|
* |
3712
|
|
|
* @param string $serviceType Type of service (service key). |
3713
|
|
|
* @param string $serviceSubType Sub type like file extensions or similar. Defined by the service. |
3714
|
|
|
* @param mixed $excludeServiceKeys List of service keys which should be excluded in the search for a service. Array or comma list. |
3715
|
|
|
* @return object|string[] The service object or an array with error infos. |
3716
|
|
|
*/ |
3717
|
|
|
public static function makeInstanceService($serviceType, $serviceSubType = '', $excludeServiceKeys = []) |
3718
|
|
|
{ |
3719
|
|
|
$error = false; |
3720
|
|
|
if (!is_array($excludeServiceKeys)) { |
3721
|
|
|
$excludeServiceKeys = self::trimExplode(',', $excludeServiceKeys, true); |
3722
|
|
|
} |
3723
|
|
|
$requestInfo = [ |
3724
|
|
|
'requestedServiceType' => $serviceType, |
3725
|
|
|
'requestedServiceSubType' => $serviceSubType, |
3726
|
|
|
'requestedExcludeServiceKeys' => $excludeServiceKeys |
3727
|
|
|
]; |
3728
|
|
|
while ($info = ExtensionManagementUtility::findService($serviceType, $serviceSubType, $excludeServiceKeys)) { |
3729
|
|
|
// provide information about requested service to service object |
3730
|
|
|
$info = array_merge($info, $requestInfo); |
3731
|
|
|
// Check persistent object and if found, call directly and exit. |
3732
|
|
|
if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) { |
3733
|
|
|
// update request info in persistent object |
3734
|
|
|
$GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->info = $info; |
3735
|
|
|
// reset service and return object |
3736
|
|
|
$GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->reset(); |
3737
|
|
|
return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]; |
3738
|
|
|
} |
3739
|
|
|
$obj = self::makeInstance($info['className']); |
3740
|
|
|
if (is_object($obj)) { |
3741
|
|
|
if (!@is_callable([$obj, 'init'])) { |
3742
|
|
|
// use silent logging??? I don't think so. |
3743
|
|
|
die('Broken service:' . DebugUtility::viewArray($info)); |
|
|
|
|
3744
|
|
|
} |
3745
|
|
|
$obj->info = $info; |
3746
|
|
|
// service available? |
3747
|
|
|
if ($obj->init()) { |
3748
|
|
|
// create persistent object |
3749
|
|
|
$GLOBALS['T3_VAR']['makeInstanceService'][$info['className']] = $obj; |
3750
|
|
|
return $obj; |
3751
|
|
|
} |
3752
|
|
|
$error = $obj->getLastErrorArray(); |
3753
|
|
|
unset($obj); |
3754
|
|
|
} |
3755
|
|
|
|
3756
|
|
|
// deactivate the service |
3757
|
|
|
ExtensionManagementUtility::deactivateService($info['serviceType'], $info['serviceKey']); |
3758
|
|
|
} |
3759
|
|
|
return $error; |
3760
|
|
|
} |
3761
|
|
|
|
3762
|
|
|
/** |
3763
|
|
|
* Initialize the system log. |
3764
|
|
|
* |
3765
|
|
|
* @see sysLog() |
3766
|
|
|
* @deprecated since TYPO3 v9, will be removed in TYPO3 v10 |
3767
|
|
|
*/ |
3768
|
|
|
public static function initSysLog() |
3769
|
|
|
{ |
3770
|
|
|
// Init custom logging |
3771
|
|
|
$params = ['initLog' => true]; |
3772
|
|
|
$fakeThis = false; |
3773
|
|
|
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] ?? [] as $hookMethod) { |
3774
|
|
|
self::callUserFunction($hookMethod, $params, $fakeThis); |
3775
|
|
|
} |
3776
|
|
|
$GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] = MathUtility::forceIntegerInRange($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'], 0, 4); |
3777
|
|
|
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = true; |
3778
|
|
|
} |
3779
|
|
|
|
3780
|
|
|
/** |
3781
|
|
|
* Logs message to custom "systemLog" handlers and logging API |
3782
|
|
|
* |
3783
|
|
|
* This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors. |
3784
|
|
|
* If you want to implement the sysLog in your applications, simply add lines like: |
3785
|
|
|
* \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog('[write message in English here]', 'extension_key', 'severity'); |
3786
|
|
|
* |
3787
|
|
|
* @param string $msg Message (in English). |
3788
|
|
|
* @param string $extKey Extension key (from which extension you are calling the log) or "Core" |
3789
|
|
|
* @param int $severity \TYPO3\CMS\Core\Utility\GeneralUtility::SYSLOG_SEVERITY_* constant |
3790
|
|
|
* @deprecated |
3791
|
|
|
*/ |
3792
|
|
|
public static function sysLog($msg, $extKey, $severity = 0) |
3793
|
|
|
{ |
3794
|
|
|
trigger_error('Method sysLog() is deprecated since v9 and will be removed with v10', E_USER_DEPRECATED); |
3795
|
|
|
|
3796
|
|
|
$severity = MathUtility::forceIntegerInRange($severity, 0, 4); |
3797
|
|
|
// Is message worth logging? |
3798
|
|
|
if ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] > $severity) { |
3799
|
|
|
return; |
3800
|
|
|
} |
3801
|
|
|
// Initialize logging |
3802
|
|
|
if (!$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) { |
3803
|
|
|
self::initSysLog(); |
|
|
|
|
3804
|
|
|
} |
3805
|
|
|
// Do custom logging; avoid calling debug_backtrace if there are no custom loggers. |
3806
|
|
View Code Duplication |
if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) { |
3807
|
|
|
$params = ['msg' => $msg, 'extKey' => $extKey, 'backTrace' => debug_backtrace(), 'severity' => $severity]; |
3808
|
|
|
$fakeThis = false; |
3809
|
|
|
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) { |
3810
|
|
|
self::callUserFunction($hookMethod, $params, $fakeThis); |
3811
|
|
|
} |
3812
|
|
|
} |
3813
|
|
|
// TYPO3 logging enabled? |
3814
|
|
|
if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog']) { |
3815
|
|
|
return; |
3816
|
|
|
} |
3817
|
|
|
|
3818
|
|
|
static::getLogger()->log(LogLevel::INFO - $severity, $msg, ['extension' => $extKey]); |
3819
|
|
|
} |
3820
|
|
|
|
3821
|
|
|
/** |
3822
|
|
|
* Logs message to the development log. |
3823
|
|
|
* This should be implemented around the source code, both frontend and backend, logging everything from the flow through an application, messages, results from comparisons to fatal errors. |
3824
|
|
|
* The result is meant to make sense to developers during development or debugging of a site. |
3825
|
|
|
* The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like. |
3826
|
|
|
* If you want to implement the devLog in your applications, simply add a line like: |
3827
|
|
|
* \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[write message in english here]', 'extension key'); |
3828
|
|
|
* |
3829
|
|
|
* @param string $msg Message (in english). |
3830
|
|
|
* @param string $extKey Extension key (from which extension you are calling the log) |
3831
|
|
|
* @param int $severity Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message |
3832
|
|
|
* @param mixed $dataVar Additional data you want to pass to the logger. |
3833
|
|
|
* @deprecated |
3834
|
|
|
*/ |
3835
|
|
|
public static function devLog($msg, $extKey, $severity = 0, $dataVar = false) |
3836
|
|
|
{ |
3837
|
|
|
trigger_error('Method devLog() is deprecated since v9 and will be removed with v10', E_USER_DEPRECATED); |
3838
|
|
View Code Duplication |
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) { |
3839
|
|
|
$params = ['msg' => $msg, 'extKey' => $extKey, 'severity' => $severity, 'dataVar' => $dataVar]; |
3840
|
|
|
$fakeThis = false; |
3841
|
|
|
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) { |
3842
|
|
|
self::callUserFunction($hookMethod, $params, $fakeThis); |
3843
|
|
|
} |
3844
|
|
|
} |
3845
|
|
|
} |
3846
|
|
|
|
3847
|
|
|
/** |
3848
|
|
|
* Writes a message to the deprecation log. |
3849
|
|
|
* |
3850
|
|
|
* @param string $msg Message (in English). |
3851
|
|
|
* @deprecated |
3852
|
|
|
*/ |
3853
|
|
|
public static function deprecationLog($msg) |
3854
|
|
|
{ |
3855
|
|
|
static::writeDeprecationLogFileEntry(__METHOD__ . ' is deprecated since TYPO3 v9.0, will be removed in TYPO3 v10.0, use "trigger_error("Given reason", E_USER_DEPRECATED);" to log deprecations.'); |
|
|
|
|
3856
|
|
|
trigger_error($msg, E_USER_DEPRECATED); |
3857
|
|
|
} |
3858
|
|
|
|
3859
|
|
|
/** |
3860
|
|
|
* Logs the usage of a deprecated fluid ViewHelper argument. |
3861
|
|
|
* The log message will be generated automatically and contains the template path. |
3862
|
|
|
* With the third argument of this method it is possible to append some text to the log message. |
3863
|
|
|
* |
3864
|
|
|
* example usage: |
3865
|
|
|
* if ($htmlEscape !== null) { |
3866
|
|
|
* GeneralUtility::logDeprecatedViewHelperAttribute( |
3867
|
|
|
* 'htmlEscape', |
3868
|
|
|
* $renderingContext, |
3869
|
|
|
* 'Please wrap the view helper in <f:format.raw> if you want to disable HTML escaping, which is enabled by default now.' |
3870
|
|
|
* ); |
3871
|
|
|
* } |
3872
|
|
|
* |
3873
|
|
|
* The example above will create this deprecation log message: |
3874
|
|
|
* 15-02-17 23:12: [typo3/sysext/backend/Resources/Private/Templates/ToolbarItems/HelpToolbarItemDropDown.html] |
3875
|
|
|
* The property "htmlEscape" has been deprecated. |
3876
|
|
|
* Please wrap the view helper in <f:format.raw> if you want to disable HTML escaping, |
3877
|
|
|
* which is enabled by default now. |
3878
|
|
|
* |
3879
|
|
|
* @param string $property |
3880
|
|
|
* @param RenderingContextInterface $renderingContext |
3881
|
|
|
* @param string $additionalMessage |
3882
|
|
|
* @deprecated |
3883
|
|
|
*/ |
3884
|
|
|
public static function logDeprecatedViewHelperAttribute(string $property, RenderingContextInterface $renderingContext, string $additionalMessage = '') |
3885
|
|
|
{ |
3886
|
|
|
static::writeDeprecationLogFileEntry(__METHOD__ . ' is deprecated since TYPO3 v9.0, will be removed in TYPO3 v10.0'); |
|
|
|
|
3887
|
|
|
$template = $renderingContext->getTemplatePaths()->resolveTemplateFileForControllerAndActionAndFormat( |
3888
|
|
|
$renderingContext->getControllerName(), |
3889
|
|
|
$renderingContext->getControllerAction() |
3890
|
|
|
); |
3891
|
|
|
$template = str_replace(PATH_site, '', $template); |
3892
|
|
|
$message = []; |
3893
|
|
|
$message[] = '[' . $template . ']'; |
3894
|
|
|
$message[] = 'The property "' . $property . '" has been marked as deprecated.'; |
3895
|
|
|
$message[] = $additionalMessage; |
3896
|
|
|
$message[] = 'Please check also your partial and layout files of this template'; |
3897
|
|
|
trigger_error(implode(' ', $message), E_USER_DEPRECATED); |
3898
|
|
|
} |
3899
|
|
|
|
3900
|
|
|
/** |
3901
|
|
|
* Gets the absolute path to the deprecation log file. |
3902
|
|
|
* |
3903
|
|
|
* @return string Absolute path to the deprecation log file |
3904
|
|
|
* @deprecated |
3905
|
|
|
*/ |
3906
|
|
|
public static function getDeprecationLogFileName() |
3907
|
|
|
{ |
3908
|
|
|
static::writeDeprecationLogFileEntry(__METHOD__ . ' is deprecated since TYPO3 v9.0, will be removed in TYPO3 v10.0'); |
|
|
|
|
3909
|
|
|
return PATH_typo3conf . 'deprecation_' . self::shortMD5((PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) . '.log'; |
3910
|
|
|
} |
3911
|
|
|
|
3912
|
|
|
/** |
3913
|
|
|
* Logs a call to a deprecated function. |
3914
|
|
|
* The log message will be taken from the annotation. |
3915
|
|
|
* @deprecated |
3916
|
|
|
*/ |
3917
|
|
|
public static function logDeprecatedFunction() |
3918
|
|
|
{ |
3919
|
|
|
static::writeDeprecationLogFileEntry(__METHOD__ . ' is deprecated since TYPO3 v9.0, will be removed in TYPO3 v10.0'); |
|
|
|
|
3920
|
|
|
$trail = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
3921
|
|
|
if ($trail[1]['type']) { |
3922
|
|
|
$function = new \ReflectionMethod($trail[1]['class'], $trail[1]['function']); |
3923
|
|
|
} else { |
3924
|
|
|
$function = new \ReflectionFunction($trail[1]['function']); |
3925
|
|
|
} |
3926
|
|
|
$msg = ''; |
3927
|
|
|
if (preg_match('/@deprecated\\s+(.*)/', $function->getDocComment(), $match)) { |
3928
|
|
|
$msg = $match[1]; |
3929
|
|
|
} |
3930
|
|
|
// Write a longer message to the deprecation log: <function> <annotion> - <trace> (<source>) |
3931
|
|
|
$logMsg = $trail[1]['class'] . $trail[1]['type'] . $trail[1]['function']; |
3932
|
|
|
$logMsg .= '() - ' . $msg . ' - ' . DebugUtility::debugTrail(); |
3933
|
|
|
$logMsg .= ' (' . PathUtility::stripPathSitePrefix($function->getFileName()) . '#' . $function->getStartLine() . ')'; |
3934
|
|
|
trigger_error($logMsg, E_USER_DEPRECATED); |
3935
|
|
|
} |
3936
|
|
|
|
3937
|
|
|
/** |
3938
|
|
|
* Converts a one dimensional array to a one line string which can be used for logging or debugging output |
3939
|
|
|
* Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;" |
3940
|
|
|
* |
3941
|
|
|
* @param array $arr Data array which should be outputted |
3942
|
|
|
* @param mixed $valueList List of keys which should be listed in the output string. Pass a comma list or an array. An empty list outputs the whole array. |
3943
|
|
|
* @param int $valueLength Long string values are shortened to this length. Default: 20 |
3944
|
|
|
* @return string Output string with key names and their value as string |
3945
|
|
|
*/ |
3946
|
|
|
public static function arrayToLogString(array $arr, $valueList = [], $valueLength = 20) |
3947
|
|
|
{ |
3948
|
|
|
$str = ''; |
3949
|
|
|
if (!is_array($valueList)) { |
3950
|
|
|
$valueList = self::trimExplode(',', $valueList, true); |
3951
|
|
|
} |
3952
|
|
|
$valListCnt = count($valueList); |
3953
|
|
|
foreach ($arr as $key => $value) { |
3954
|
|
|
if (!$valListCnt || in_array($key, $valueList)) { |
3955
|
|
|
$str .= (string)$key . trim(': ' . self::fixed_lgd_cs(str_replace(LF, '|', (string)$value), $valueLength)) . '; '; |
3956
|
|
|
} |
3957
|
|
|
} |
3958
|
|
|
return $str; |
3959
|
|
|
} |
3960
|
|
|
|
3961
|
|
|
/** |
3962
|
|
|
* Explode a string (normally a list of filenames) with whitespaces by considering quotes in that string. |
3963
|
|
|
* |
3964
|
|
|
* @param string $parameters The whole parameters string |
3965
|
|
|
* @param bool $unQuote If set, the elements of the resulting array are unquoted. |
3966
|
|
|
* @return array Exploded parameters |
3967
|
|
|
*/ |
3968
|
|
|
public static function unQuoteFilenames($parameters, $unQuote = false) |
3969
|
|
|
{ |
3970
|
|
|
$paramsArr = explode(' ', trim($parameters)); |
3971
|
|
|
// Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position. |
3972
|
|
|
$quoteActive = -1; |
3973
|
|
|
foreach ($paramsArr as $k => $v) { |
3974
|
|
|
if ($quoteActive > -1) { |
3975
|
|
|
$paramsArr[$quoteActive] .= ' ' . $v; |
3976
|
|
|
unset($paramsArr[$k]); |
3977
|
|
|
if (substr($v, -1) === $paramsArr[$quoteActive][0]) { |
3978
|
|
|
$quoteActive = -1; |
3979
|
|
|
} |
3980
|
|
|
} elseif (!trim($v)) { |
3981
|
|
|
// Remove empty elements |
3982
|
|
|
unset($paramsArr[$k]); |
3983
|
|
|
} elseif (preg_match('/^(["\'])/', $v) && substr($v, -1) !== $v[0]) { |
3984
|
|
|
$quoteActive = $k; |
3985
|
|
|
} |
3986
|
|
|
} |
3987
|
|
|
if ($unQuote) { |
3988
|
|
|
foreach ($paramsArr as $key => &$val) { |
3989
|
|
|
$val = preg_replace('/(?:^"|"$)/', '', $val); |
3990
|
|
|
$val = preg_replace('/(?:^\'|\'$)/', '', $val); |
3991
|
|
|
} |
3992
|
|
|
unset($val); |
3993
|
|
|
} |
3994
|
|
|
// Return reindexed array |
3995
|
|
|
return array_values($paramsArr); |
3996
|
|
|
} |
3997
|
|
|
|
3998
|
|
|
/** |
3999
|
|
|
* Quotes a string for usage as JS parameter. |
4000
|
|
|
* |
4001
|
|
|
* @param string $value the string to encode, may be empty |
4002
|
|
|
* @return string the encoded value already quoted (with single quotes), |
4003
|
|
|
*/ |
4004
|
|
|
public static function quoteJSvalue($value) |
4005
|
|
|
{ |
4006
|
|
|
return strtr( |
|
|
|
|
4007
|
|
|
json_encode((string)$value, JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_TAG), |
4008
|
|
|
[ |
|
|
|
|
4009
|
|
|
'"' => '\'', |
4010
|
|
|
'\\\\' => '\\u005C', |
4011
|
|
|
' ' => '\\u0020', |
4012
|
|
|
'!' => '\\u0021', |
4013
|
|
|
'\\t' => '\\u0009', |
4014
|
|
|
'\\n' => '\\u000A', |
4015
|
|
|
'\\r' => '\\u000D' |
4016
|
|
|
] |
4017
|
|
|
); |
4018
|
|
|
} |
4019
|
|
|
|
4020
|
|
|
/** |
4021
|
|
|
* Set the ApplicationContext |
4022
|
|
|
* |
4023
|
|
|
* This function is used by the Bootstrap to hand over the application context. It must not be used anywhere else, |
4024
|
|
|
* because the context shall never be changed on runtime! |
4025
|
|
|
* |
4026
|
|
|
* @param \TYPO3\CMS\Core\Core\ApplicationContext $applicationContext |
4027
|
|
|
* @throws \RuntimeException if applicationContext is overridden |
4028
|
|
|
* @internal This is not a public API method, do not use in own extensions |
4029
|
|
|
*/ |
4030
|
|
|
public static function presetApplicationContext(ApplicationContext $applicationContext) |
4031
|
|
|
{ |
4032
|
|
|
if (is_null(static::$applicationContext)) { |
4033
|
|
|
static::$applicationContext = $applicationContext; |
4034
|
|
|
} else { |
4035
|
|
|
throw new \RuntimeException('Trying to override applicationContext which has already been defined!', 1376084316); |
4036
|
|
|
} |
4037
|
|
|
} |
4038
|
|
|
|
4039
|
|
|
/** |
4040
|
|
|
* Get the ApplicationContext |
4041
|
|
|
* |
4042
|
|
|
* @return \TYPO3\CMS\Core\Core\ApplicationContext |
4043
|
|
|
*/ |
4044
|
|
|
public static function getApplicationContext() |
4045
|
|
|
{ |
4046
|
|
|
return static::$applicationContext; |
4047
|
|
|
} |
4048
|
|
|
|
4049
|
|
|
/** |
4050
|
|
|
* Check if the current request is running on a CGI server API |
4051
|
|
|
* @return bool |
4052
|
|
|
*/ |
4053
|
|
|
public static function isRunningOnCgiServerApi() |
4054
|
|
|
{ |
4055
|
|
|
return in_array(PHP_SAPI, self::$supportedCgiServerApis, true); |
4056
|
|
|
} |
4057
|
|
|
|
4058
|
|
|
/** |
4059
|
|
|
* @return LoggerInterface |
4060
|
|
|
*/ |
4061
|
|
|
protected static function getLogger() |
4062
|
|
|
{ |
4063
|
|
|
return static::makeInstance(LogManager::class)->getLogger(__CLASS__); |
4064
|
|
|
} |
4065
|
|
|
|
4066
|
|
|
/** |
4067
|
|
|
* @param string $msg |
4068
|
|
|
* @deprecated |
4069
|
|
|
*/ |
4070
|
|
|
private static function writeDeprecationLogFileEntry($msg) |
4071
|
|
|
{ |
4072
|
|
|
$date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': '); |
4073
|
|
|
// Write a longer message to the deprecation log |
4074
|
|
|
$destination = PATH_typo3conf . 'deprecation_' . self::shortMD5(PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) . '.log'; |
4075
|
|
|
$file = @fopen($destination, 'a'); |
4076
|
|
|
if ($file) { |
4077
|
|
|
@fwrite($file, $date . $msg . LF); |
|
|
|
|
4078
|
|
|
@fclose($file); |
|
|
|
|
4079
|
|
|
self::fixPermissions($destination); |
4080
|
|
|
} |
4081
|
|
|
} |
4082
|
|
|
} |
4083
|
|
|
|