Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
52.41% |
326 / 622 |
|
18.92% |
14 / 74 |
CRAP | n/a |
0 / 0 |
|
wfLoadExtension | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
wfLoadExtensions | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
wfLoadSkin | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
wfLoadSkins | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
wfArrayDiff2 | |
82.61% |
19 / 23 |
|
0.00% |
0 / 1 |
9.43 | |||
wfMergeErrorArrays | |
0.00% |
0 / 10 |
|
0.00% |
0 / 1 |
20 | |||
wfArrayInsertAfter | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
6 | |||
wfObjectToArray | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
42 | |||
wfRandom | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
wfRandomString | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
wfUrlencode | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
5 | |||
wfArrayToCgi | |
95.24% |
20 / 21 |
|
0.00% |
0 / 1 |
12 | |||
wfCgiToArray | |
96.00% |
24 / 25 |
|
0.00% |
0 / 1 |
10 | |||
wfAppendQuery | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
6 | |||
wfGetUrlUtils | |
0.00% |
0 / 13 |
|
0.00% |
0 / 1 |
20 | |||
wfExpandUrl | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
wfGetServerUrl | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
wfAssembleUrl | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
wfUrlProtocols | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
wfUrlProtocolsWithoutProtRel | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
wfParseUrl | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
wfExpandIRI | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
wfMatchesDomainList | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
wfDebug | |
75.00% |
6 / 8 |
|
0.00% |
0 / 1 |
5.39 | |||
wfIsDebugRawPage | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
30 | |||
wfDebugLog | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
6 | |||
wfLogDBError | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
wfDeprecated | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
12 | |||
wfDeprecatedMsg | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
6 | |||
wfWarn | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
wfLogWarning | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
wfMessage | |
83.33% |
5 / 6 |
|
0.00% |
0 / 1 |
3.04 | |||
wfMessageFallback | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
wfMsgReplaceArgs | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
30 | |||
wfHostname | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
12 | |||
wfDebugBacktrace | |
0.00% |
0 / 10 |
|
0.00% |
0 / 1 |
30 | |||
wfBacktrace | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
20 | |||
wfGetCaller | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
2.06 | |||
wfGetAllCallers | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
12 | |||
wfFormatStackFrame | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
20 | |||
wfClientAcceptsGzip | |
93.33% |
14 / 15 |
|
0.00% |
0 / 1 |
8.02 | |||
wfEscapeWikiText | |
90.00% |
45 / 50 |
|
0.00% |
0 / 1 |
10.10 | |||
wfSetVar | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
12 | |||
wfSetBit | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
12 | |||
wfVarDump | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
20 | |||
wfHttpError | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
6 | |||
wfResetOutputBuffers | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
90 | |||
wfTimestamp | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
2.06 | |||
wfTimestampOrNull | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
wfTimestampNow | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
wfTempDir | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
wfMkdirParents | |
75.00% |
9 / 12 |
|
0.00% |
0 / 1 |
7.77 | |||
wfRecursiveRemoveDir | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
42 | |||
wfPercent | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
3 | |||
wfIniGetBool | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
wfStringToBool | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 | |||
wfEscapeShellArg | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
wfShellExec | |
71.43% |
15 / 21 |
|
0.00% |
0 / 1 |
5.58 | |||
wfShellExecWithStderr | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
wfShellWikiCmd | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
wfMerge | |
90.91% |
40 / 44 |
|
0.00% |
0 / 1 |
8.05 | |||
wfBaseName | |
71.43% |
5 / 7 |
|
0.00% |
0 / 1 |
3.21 | |||
wfRelativePath | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
42 | |||
wfGetDB | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
6 | |||
wfScript | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
12 | |||
wfBoolToStr | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
6 | |||
wfGetNull | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
6 | |||
wfStripIllegalFilenameChars | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
6 | |||
wfMemoryLimit | |
0.00% |
0 / 13 |
|
0.00% |
0 / 1 |
20 | |||
wfTransactionalTimeLimit | |
0.00% |
0 / 10 |
|
0.00% |
0 / 1 |
30 | |||
wfShorthandToInteger | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
8 | |||
wfIsInfinity | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
wfThumbIsStandard | |
95.24% |
40 / 42 |
|
0.00% |
0 / 1 |
13 | |||
wfArrayPlus2d | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 |
1 | <?php |
2 | /** |
3 | * Global functions used everywhere. |
4 | * |
5 | * This program is free software; you can redistribute it and/or modify |
6 | * it under the terms of the GNU General Public License as published by |
7 | * the Free Software Foundation; either version 2 of the License, or |
8 | * (at your option) any later version. |
9 | * |
10 | * This program is distributed in the hope that it will be useful, |
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13 | * GNU General Public License for more details. |
14 | * |
15 | * You should have received a copy of the GNU General Public License along |
16 | * with this program; if not, write to the Free Software Foundation, Inc., |
17 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
18 | * http://www.gnu.org/copyleft/gpl.html |
19 | * |
20 | * @file |
21 | */ |
22 | |
23 | use MediaWiki\Debug\MWDebug; |
24 | use MediaWiki\HookContainer\HookRunner; |
25 | use MediaWiki\Logger\LoggerFactory; |
26 | use MediaWiki\MediaWikiServices; |
27 | use MediaWiki\Message\Message; |
28 | use MediaWiki\ProcOpenError; |
29 | use MediaWiki\Registration\ExtensionRegistry; |
30 | use MediaWiki\Request\WebRequest; |
31 | use MediaWiki\Shell\Shell; |
32 | use MediaWiki\Title\Title; |
33 | use MediaWiki\Utils\MWTimestamp; |
34 | use MediaWiki\Utils\UrlUtils; |
35 | use Wikimedia\AtEase\AtEase; |
36 | use Wikimedia\FileBackend\FileBackend; |
37 | use Wikimedia\FileBackend\FSFile\TempFSFile; |
38 | use Wikimedia\Message\MessageParam; |
39 | use Wikimedia\Message\MessageSpecifier; |
40 | use Wikimedia\ParamValidator\TypeDef\ExpiryDef; |
41 | use Wikimedia\RequestTimeout\RequestTimeout; |
42 | |
43 | /** |
44 | * Load an extension |
45 | * |
46 | * This queues an extension to be loaded through |
47 | * the ExtensionRegistry system. |
48 | * |
49 | * @param string $ext Name of the extension to load |
50 | * @param string|null $path Absolute path of where to find the extension.json file |
51 | * @since 1.25 |
52 | */ |
53 | function wfLoadExtension( $ext, $path = null ) { |
54 | if ( !$path ) { |
55 | global $wgExtensionDirectory; |
56 | $path = "$wgExtensionDirectory/$ext/extension.json"; |
57 | } |
58 | ExtensionRegistry::getInstance()->queue( $path ); |
59 | } |
60 | |
61 | /** |
62 | * Load multiple extensions at once |
63 | * |
64 | * Same as wfLoadExtension, but more efficient if you |
65 | * are loading multiple extensions. |
66 | * |
67 | * If you want to specify custom paths, you should interact with |
68 | * ExtensionRegistry directly. |
69 | * |
70 | * @see wfLoadExtension |
71 | * @param string[] $exts Array of extension names to load |
72 | * @since 1.25 |
73 | */ |
74 | function wfLoadExtensions( array $exts ) { |
75 | global $wgExtensionDirectory; |
76 | $registry = ExtensionRegistry::getInstance(); |
77 | foreach ( $exts as $ext ) { |
78 | $registry->queue( "$wgExtensionDirectory/$ext/extension.json" ); |
79 | } |
80 | } |
81 | |
82 | /** |
83 | * Load a skin |
84 | * |
85 | * @see wfLoadExtension |
86 | * @param string $skin Name of the extension to load |
87 | * @param string|null $path Absolute path of where to find the skin.json file |
88 | * @since 1.25 |
89 | */ |
90 | function wfLoadSkin( $skin, $path = null ) { |
91 | if ( !$path ) { |
92 | global $wgStyleDirectory; |
93 | $path = "$wgStyleDirectory/$skin/skin.json"; |
94 | } |
95 | ExtensionRegistry::getInstance()->queue( $path ); |
96 | } |
97 | |
98 | /** |
99 | * Load multiple skins at once |
100 | * |
101 | * @see wfLoadExtensions |
102 | * @param string[] $skins Array of extension names to load |
103 | * @since 1.25 |
104 | */ |
105 | function wfLoadSkins( array $skins ) { |
106 | global $wgStyleDirectory; |
107 | $registry = ExtensionRegistry::getInstance(); |
108 | foreach ( $skins as $skin ) { |
109 | $registry->queue( "$wgStyleDirectory/$skin/skin.json" ); |
110 | } |
111 | } |
112 | |
113 | /** |
114 | * Like array_diff( $arr1, $arr2 ) except that it works with two-dimensional arrays. |
115 | * @deprecated since 1.43 Use StatusValue::merge() instead |
116 | * @param string[]|array[] $arr1 |
117 | * @param string[]|array[] $arr2 |
118 | * @return array |
119 | */ |
120 | function wfArrayDiff2( $arr1, $arr2 ) { |
121 | wfDeprecated( __FUNCTION__, '1.43' ); |
122 | /** |
123 | * @param string|array $a |
124 | * @param string|array $b |
125 | */ |
126 | $comparator = static function ( $a, $b ): int { |
127 | if ( is_string( $a ) && is_string( $b ) ) { |
128 | return strcmp( $a, $b ); |
129 | } |
130 | if ( !is_array( $a ) && !is_array( $b ) ) { |
131 | throw new InvalidArgumentException( |
132 | 'This function assumes that array elements are all strings or all arrays' |
133 | ); |
134 | } |
135 | if ( count( $a ) !== count( $b ) ) { |
136 | return count( $a ) <=> count( $b ); |
137 | } else { |
138 | reset( $a ); |
139 | reset( $b ); |
140 | while ( key( $a ) !== null && key( $b ) !== null ) { |
141 | $valueA = current( $a ); |
142 | $valueB = current( $b ); |
143 | $cmp = strcmp( $valueA, $valueB ); |
144 | if ( $cmp !== 0 ) { |
145 | return $cmp; |
146 | } |
147 | next( $a ); |
148 | next( $b ); |
149 | } |
150 | return 0; |
151 | } |
152 | }; |
153 | return array_udiff( $arr1, $arr2, $comparator ); |
154 | } |
155 | |
156 | /** |
157 | * Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal |
158 | * e.g. |
159 | * wfMergeErrorArrays( |
160 | * [ [ 'x' ] ], |
161 | * [ [ 'x', '2' ] ], |
162 | * [ [ 'x' ] ], |
163 | * [ [ 'y' ] ] |
164 | * ); |
165 | * returns: |
166 | * [ |
167 | * [ 'x', '2' ], |
168 | * [ 'x' ], |
169 | * [ 'y' ] |
170 | * ] |
171 | * |
172 | * @deprecated since 1.43 Use StatusValue::merge() instead |
173 | * @param array[] ...$args |
174 | * @return array |
175 | */ |
176 | function wfMergeErrorArrays( ...$args ) { |
177 | wfDeprecated( __FUNCTION__, '1.43' ); |
178 | $out = []; |
179 | foreach ( $args as $errors ) { |
180 | foreach ( $errors as $params ) { |
181 | $originalParams = $params; |
182 | if ( $params[0] instanceof MessageSpecifier ) { |
183 | $params = [ $params[0]->getKey(), ...$params[0]->getParams() ]; |
184 | } |
185 | # @todo FIXME: Sometimes get nested arrays for $params, |
186 | # which leads to E_NOTICEs |
187 | $spec = implode( "\t", $params ); |
188 | $out[$spec] = $originalParams; |
189 | } |
190 | } |
191 | return array_values( $out ); |
192 | } |
193 | |
194 | /** |
195 | * Insert an array into another array after the specified key. If the key is |
196 | * not present in the input array, it is returned without modification. |
197 | * |
198 | * @param array $array |
199 | * @param array $insert The array to insert. |
200 | * @param mixed $after The key to insert after. |
201 | * @return array |
202 | */ |
203 | function wfArrayInsertAfter( array $array, array $insert, $after ) { |
204 | // Find the offset of the element to insert after. |
205 | $keys = array_keys( $array ); |
206 | $offsetByKey = array_flip( $keys ); |
207 | |
208 | if ( !\array_key_exists( $after, $offsetByKey ) ) { |
209 | return $array; |
210 | } |
211 | $offset = $offsetByKey[$after]; |
212 | |
213 | // Insert at the specified offset |
214 | $before = array_slice( $array, 0, $offset + 1, true ); |
215 | $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true ); |
216 | |
217 | $output = $before + $insert + $after; |
218 | |
219 | return $output; |
220 | } |
221 | |
222 | /** |
223 | * Recursively converts the parameter (an object) to an array with the same data |
224 | * |
225 | * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam |
226 | * @param object|array $objOrArray |
227 | * @param bool $recursive |
228 | * @return array |
229 | */ |
230 | function wfObjectToArray( $objOrArray, $recursive = true ) { |
231 | $array = []; |
232 | if ( is_object( $objOrArray ) ) { |
233 | $objOrArray = get_object_vars( $objOrArray ); |
234 | } |
235 | foreach ( $objOrArray as $key => $value ) { |
236 | if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) { |
237 | $value = wfObjectToArray( $value ); |
238 | } |
239 | |
240 | $array[$key] = $value; |
241 | } |
242 | |
243 | return $array; |
244 | } |
245 | |
246 | /** |
247 | * Get a random decimal value in the domain of [0, 1), in a way |
248 | * not likely to give duplicate values for any realistic |
249 | * number of articles. |
250 | * |
251 | * @note This is designed for use in relation to Special:RandomPage |
252 | * and the page_random database field. |
253 | * |
254 | * @return string |
255 | */ |
256 | function wfRandom() { |
257 | // The maximum random value is "only" 2^31-1, so get two random |
258 | // values to reduce the chance of dupes |
259 | $max = mt_getrandmax() + 1; |
260 | $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' ); |
261 | return $rand; |
262 | } |
263 | |
264 | /** |
265 | * Get a random string containing a number of pseudo-random hex characters. |
266 | * |
267 | * @note This is not secure, if you are trying to generate some sort |
268 | * of token please use MWCryptRand instead. |
269 | * |
270 | * @param int $length The length of the string to generate |
271 | * @return string |
272 | * @since 1.20 |
273 | */ |
274 | function wfRandomString( $length = 32 ) { |
275 | $str = ''; |
276 | for ( $n = 0; $n < $length; $n += 7 ) { |
277 | $str .= sprintf( '%07x', mt_rand() & 0xfffffff ); |
278 | } |
279 | return substr( $str, 0, $length ); |
280 | } |
281 | |
282 | /** |
283 | * We want some things to be included as literal characters in our title URLs |
284 | * for prettiness, which urlencode encodes by default. According to RFC 1738, |
285 | * all of the following should be safe: |
286 | * |
287 | * ;:@&=$-_.+!*'(), |
288 | * |
289 | * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved |
290 | * character which should not be encoded. More importantly, google chrome |
291 | * always converts %7E back to ~, and converting it in this function can |
292 | * cause a redirect loop (T105265). |
293 | * |
294 | * But + is not safe because it's used to indicate a space; &= are only safe in |
295 | * paths and not in queries (and we don't distinguish here); ' seems kind of |
296 | * scary; and urlencode() doesn't touch -_. to begin with. Plus, although / |
297 | * is reserved, we don't care. So the list we unescape is: |
298 | * |
299 | * ;:@$!*(),/~ |
300 | * |
301 | * However, IIS7 redirects fail when the url contains a colon (see T24709), |
302 | * so no fancy : for IIS7. |
303 | * |
304 | * %2F in the page titles seems to fatally break for some reason. |
305 | * |
306 | * @param string $s |
307 | * @return string |
308 | */ |
309 | function wfUrlencode( $s ) { |
310 | static $needle; |
311 | |
312 | if ( $s === null ) { |
313 | // Reset $needle for testing. |
314 | $needle = null; |
315 | return ''; |
316 | } |
317 | |
318 | if ( $needle === null ) { |
319 | $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ]; |
320 | if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || |
321 | !str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) |
322 | ) { |
323 | $needle[] = '%3A'; |
324 | } |
325 | } |
326 | |
327 | $s = urlencode( $s ); |
328 | $s = str_ireplace( |
329 | $needle, |
330 | [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ], |
331 | $s |
332 | ); |
333 | |
334 | return $s; |
335 | } |
336 | |
337 | /** |
338 | * This function takes one or two arrays as input, and returns a CGI-style string, e.g. |
339 | * "days=7&limit=100". Options in the first array override options in the second. |
340 | * Options set to null or false will not be output. |
341 | * |
342 | * @param array $array1 ( String|Array ) |
343 | * @param array|null $array2 ( String|Array ) |
344 | * @param string $prefix |
345 | * @return string |
346 | */ |
347 | function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) { |
348 | if ( $array2 !== null ) { |
349 | $array1 += $array2; |
350 | } |
351 | |
352 | $cgi = ''; |
353 | foreach ( $array1 as $key => $value ) { |
354 | if ( $value !== null && $value !== false ) { |
355 | if ( $cgi != '' ) { |
356 | $cgi .= '&'; |
357 | } |
358 | if ( $prefix !== '' ) { |
359 | $key = $prefix . "[$key]"; |
360 | } |
361 | if ( is_array( $value ) ) { |
362 | $firstTime = true; |
363 | foreach ( $value as $k => $v ) { |
364 | $cgi .= $firstTime ? '' : '&'; |
365 | if ( is_array( $v ) ) { |
366 | $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" ); |
367 | } else { |
368 | $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v ); |
369 | } |
370 | $firstTime = false; |
371 | } |
372 | } else { |
373 | if ( is_object( $value ) ) { |
374 | $value = $value->__toString(); |
375 | } |
376 | $cgi .= urlencode( $key ) . '=' . urlencode( $value ); |
377 | } |
378 | } |
379 | } |
380 | return $cgi; |
381 | } |
382 | |
383 | /** |
384 | * This is the logical opposite of wfArrayToCgi(): it accepts a query string as |
385 | * its argument and returns the same string in array form. This allows compatibility |
386 | * with legacy functions that accept raw query strings instead of nice |
387 | * arrays. Of course, keys and values are urldecode()d. |
388 | * |
389 | * @param string $query Query string |
390 | * @return string[] Array version of input |
391 | */ |
392 | function wfCgiToArray( $query ) { |
393 | if ( isset( $query[0] ) && $query[0] == '?' ) { |
394 | $query = substr( $query, 1 ); |
395 | } |
396 | $bits = explode( '&', $query ); |
397 | $ret = []; |
398 | foreach ( $bits as $bit ) { |
399 | if ( $bit === '' ) { |
400 | continue; |
401 | } |
402 | if ( strpos( $bit, '=' ) === false ) { |
403 | // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does) |
404 | $key = $bit; |
405 | $value = ''; |
406 | } else { |
407 | [ $key, $value ] = explode( '=', $bit ); |
408 | } |
409 | $key = urldecode( $key ); |
410 | $value = urldecode( $value ); |
411 | if ( strpos( $key, '[' ) !== false ) { |
412 | $keys = array_reverse( explode( '[', $key ) ); |
413 | $key = array_pop( $keys ); |
414 | $temp = $value; |
415 | foreach ( $keys as $k ) { |
416 | $k = substr( $k, 0, -1 ); |
417 | $temp = [ $k => $temp ]; |
418 | } |
419 | if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) { |
420 | $ret[$key] = array_merge( $ret[$key], $temp ); |
421 | } else { |
422 | $ret[$key] = $temp; |
423 | } |
424 | } else { |
425 | $ret[$key] = $value; |
426 | } |
427 | } |
428 | return $ret; |
429 | } |
430 | |
431 | /** |
432 | * Append a query string to an existing URL, which may or may not already |
433 | * have query string parameters already. If so, they will be combined. |
434 | * |
435 | * @param string $url |
436 | * @param string|array $query String or associative array |
437 | * @return string |
438 | */ |
439 | function wfAppendQuery( $url, $query ) { |
440 | if ( is_array( $query ) ) { |
441 | $query = wfArrayToCgi( $query ); |
442 | } |
443 | if ( $query != '' ) { |
444 | // Remove the fragment, if there is one |
445 | $fragment = false; |
446 | $hashPos = strpos( $url, '#' ); |
447 | if ( $hashPos !== false ) { |
448 | $fragment = substr( $url, $hashPos ); |
449 | $url = substr( $url, 0, $hashPos ); |
450 | } |
451 | |
452 | // Add parameter |
453 | if ( strpos( $url, '?' ) === false ) { |
454 | $url .= '?'; |
455 | } else { |
456 | $url .= '&'; |
457 | } |
458 | $url .= $query; |
459 | |
460 | // Put the fragment back |
461 | if ( $fragment !== false ) { |
462 | $url .= $fragment; |
463 | } |
464 | } |
465 | return $url; |
466 | } |
467 | |
468 | /** |
469 | * @deprecated since 1.43; get a UrlUtils from services, or construct your own |
470 | * @internal |
471 | * @return UrlUtils from services if initialized, otherwise make one from globals |
472 | */ |
473 | function wfGetUrlUtils(): UrlUtils { |
474 | global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest, $wgHttpsPort, |
475 | $wgUrlProtocols; |
476 | |
477 | if ( MediaWikiServices::hasInstance() ) { |
478 | $services = MediaWikiServices::getInstance(); |
479 | if ( $services->hasService( 'UrlUtils' ) ) { |
480 | return $services->getUrlUtils(); |
481 | } |
482 | } |
483 | |
484 | return new UrlUtils( [ |
485 | // UrlUtils throws if the relevant $wg(|Canonical|Internal) variable is null, but the old |
486 | // implementations implicitly converted it to an empty string (presumably by mistake). |
487 | // Preserve the old behavior for compatibility. |
488 | UrlUtils::SERVER => $wgServer ?? '', |
489 | UrlUtils::CANONICAL_SERVER => $wgCanonicalServer ?? '', |
490 | UrlUtils::INTERNAL_SERVER => $wgInternalServer ?? '', |
491 | UrlUtils::FALLBACK_PROTOCOL => $wgRequest ? $wgRequest->getProtocol() |
492 | : WebRequest::detectProtocol(), |
493 | UrlUtils::HTTPS_PORT => $wgHttpsPort, |
494 | UrlUtils::VALID_PROTOCOLS => $wgUrlProtocols, |
495 | ] ); |
496 | } |
497 | |
498 | /** |
499 | * Expand a potentially local URL to a fully-qualified URL using $wgServer |
500 | * (or one of its alternatives). |
501 | * |
502 | * The meaning of the PROTO_* constants is as follows: |
503 | * PROTO_HTTP: Output a URL starting with http:// |
504 | * PROTO_HTTPS: Output a URL starting with https:// |
505 | * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL) |
506 | * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending |
507 | * on which protocol was used for the current incoming request |
508 | * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer. |
509 | * For protocol-relative URLs, use the protocol of $wgCanonicalServer |
510 | * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer |
511 | * |
512 | * If $url specifies a protocol, or $url is domain-relative and $wgServer |
513 | * specifies a protocol, PROTO_HTTP, PROTO_HTTPS, PROTO_RELATIVE and |
514 | * PROTO_CURRENT do not change that. |
515 | * |
516 | * Parent references (/../) in the path are resolved (as in UrlUtils::removeDotSegments()). |
517 | * |
518 | * @deprecated since 1.39, use UrlUtils::expand() |
519 | * @param string $url An URL; can be absolute (e.g. http://example.com/foo/bar), |
520 | * protocol-relative (//example.com/foo/bar) or domain-relative (/foo/bar). |
521 | * @param string|int|null $defaultProto One of the PROTO_* constants, as described above. |
522 | * @return string|false Fully-qualified URL, current-path-relative URL or false if |
523 | * no valid URL can be constructed |
524 | */ |
525 | function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) { |
526 | return wfGetUrlUtils()->expand( (string)$url, $defaultProto ) ?? false; |
527 | } |
528 | |
529 | /** |
530 | * Get the wiki's "server", i.e. the protocol and host part of the URL, with a |
531 | * protocol specified using a PROTO_* constant as in wfExpandUrl() |
532 | * |
533 | * @deprecated since 1.39, use UrlUtils::getServer(); hard-deprecated since 1.43 |
534 | * @since 1.32 |
535 | * @param string|int|null $proto One of the PROTO_* constants. |
536 | * @return string The URL |
537 | */ |
538 | function wfGetServerUrl( $proto ) { |
539 | wfDeprecated( __FUNCTION__, '1.39' ); |
540 | |
541 | return wfGetUrlUtils()->getServer( $proto ) ?? ''; |
542 | } |
543 | |
544 | /** |
545 | * This function will reassemble a URL parsed with wfParseURL. This is useful |
546 | * if you need to edit part of a URL and put it back together. |
547 | * |
548 | * This is the basic structure used (brackets contain keys for $urlParts): |
549 | * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment] |
550 | * |
551 | * @deprecated since 1.39, use UrlUtils::assemble() |
552 | * @since 1.19 |
553 | * @param array $urlParts URL parts, as output from wfParseUrl |
554 | * @return string URL assembled from its component parts |
555 | */ |
556 | function wfAssembleUrl( $urlParts ) { |
557 | return UrlUtils::assemble( (array)$urlParts ); |
558 | } |
559 | |
560 | /** |
561 | * Returns a partial regular expression of recognized URL protocols, e.g. "http:\/\/|https:\/\/" |
562 | * |
563 | * @deprecated since 1.39, use UrlUtils::validProtocols(); hard-deprecated since 1.43 |
564 | * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list. |
565 | * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead |
566 | * @return string |
567 | */ |
568 | function wfUrlProtocols( $includeProtocolRelative = true ) { |
569 | wfDeprecated( __FUNCTION__, '1.39' ); |
570 | |
571 | return $includeProtocolRelative ? wfGetUrlUtils()->validProtocols() : |
572 | wfGetUrlUtils()->validAbsoluteProtocols(); |
573 | } |
574 | |
575 | /** |
576 | * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if |
577 | * you need a regex that matches all URL protocols but does not match protocol- |
578 | * relative URLs |
579 | * @deprecated since 1.39, use UrlUtils::validAbsoluteProtocols() |
580 | * @return string |
581 | */ |
582 | function wfUrlProtocolsWithoutProtRel() { |
583 | return wfGetUrlUtils()->validAbsoluteProtocols(); |
584 | } |
585 | |
586 | /** |
587 | * parse_url() work-alike, but non-broken. Differences: |
588 | * |
589 | * 1) Handles protocols that don't use :// (e.g., mailto: and news:, as well as |
590 | * protocol-relative URLs) correctly. |
591 | * 2) Adds a "delimiter" element to the array (see (2)). |
592 | * 3) Verifies that the protocol is on the $wgUrlProtocols allowed list. |
593 | * 4) Rejects some invalid URLs that parse_url doesn't, e.g. the empty string or URLs starting with |
594 | * a line feed character. |
595 | * |
596 | * @deprecated since 1.39, use UrlUtils::parse() |
597 | * @param string $url A URL to parse |
598 | * @return string[]|false Bits of the URL in an associative array, or false on failure. |
599 | * Possible fields: |
600 | * - scheme: URI scheme (protocol), e.g. 'http', 'mailto'. Lowercase, always present, but can |
601 | * be an empty string for protocol-relative URLs. |
602 | * - delimiter: either '://', ':' or '//'. Always present. |
603 | * - host: domain name / IP. Always present, but could be an empty string, e.g. for file: URLs. |
604 | * - port: port number. Will be missing when port is not explicitly specified. |
605 | * - user: user name, e.g. for HTTP Basic auth URLs such as http://user:pass@example.com/ |
606 | * Missing when there is no username. |
607 | * - pass: password, same as above. |
608 | * - path: path including the leading /. Will be missing when empty (e.g. 'http://example.com') |
609 | * - query: query string (as a string; see wfCgiToArray() for parsing it), can be missing. |
610 | * - fragment: the part after #, can be missing. |
611 | */ |
612 | function wfParseUrl( $url ) { |
613 | return wfGetUrlUtils()->parse( (string)$url ) ?? false; |
614 | } |
615 | |
616 | /** |
617 | * Take a URL, make sure it's expanded to fully qualified, and replace any |
618 | * encoded non-ASCII Unicode characters with their UTF-8 original forms |
619 | * for more compact display and legibility for local audiences. |
620 | * |
621 | * @deprecated since 1.39, use UrlUtils::expandIRI(); hard-deprecated since 1.43 |
622 | * @param string $url |
623 | * @return string |
624 | */ |
625 | function wfExpandIRI( $url ) { |
626 | wfDeprecated( __FUNCTION__, '1.39' ); |
627 | |
628 | return wfGetUrlUtils()->expandIRI( (string)$url ) ?? ''; |
629 | } |
630 | |
631 | /** |
632 | * Check whether a given URL has a domain that occurs in a given set of domains |
633 | * |
634 | * @deprecated since 1.39, use UrlUtils::expandIRI() |
635 | * @param string $url |
636 | * @param array $domains Array of domains (strings) |
637 | * @return bool True if the host part of $url ends in one of the strings in $domains |
638 | */ |
639 | function wfMatchesDomainList( $url, $domains ) { |
640 | return wfGetUrlUtils()->matchesDomainList( (string)$url, (array)$domains ); |
641 | } |
642 | |
643 | /** |
644 | * Sends a line to the debug log if enabled or, optionally, to a comment in output. |
645 | * In normal operation this is a NOP. |
646 | * |
647 | * Controlling globals: |
648 | * $wgDebugLogFile - points to the log file |
649 | * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output. |
650 | * $wgDebugComments - if on, some debug items may appear in comments in the HTML output. |
651 | * |
652 | * @since 1.25 support for additional context data |
653 | * |
654 | * @param string $text |
655 | * @param string|bool $dest Destination of the message: |
656 | * - 'all': both to the log and HTML (debug toolbar or HTML comments) |
657 | * - 'private': excluded from HTML output |
658 | * For backward compatibility, it can also take a boolean: |
659 | * - true: same as 'all' |
660 | * - false: same as 'private' |
661 | * @param array $context Additional logging context data |
662 | */ |
663 | function wfDebug( $text, $dest = 'all', array $context = [] ) { |
664 | global $wgDebugRawPage, $wgDebugLogPrefix; |
665 | |
666 | if ( !$wgDebugRawPage && wfIsDebugRawPage() ) { |
667 | return; |
668 | } |
669 | |
670 | $text = trim( $text ); |
671 | |
672 | if ( $wgDebugLogPrefix !== '' ) { |
673 | $context['prefix'] = $wgDebugLogPrefix; |
674 | } |
675 | $context['private'] = ( $dest === false || $dest === 'private' ); |
676 | |
677 | $logger = LoggerFactory::getInstance( 'wfDebug' ); |
678 | $logger->debug( $text, $context ); |
679 | } |
680 | |
681 | /** |
682 | * Returns true if debug logging should be suppressed if $wgDebugRawPage = false |
683 | * @return bool |
684 | */ |
685 | function wfIsDebugRawPage() { |
686 | static $cache; |
687 | if ( $cache !== null ) { |
688 | return $cache; |
689 | } |
690 | // Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet |
691 | // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals |
692 | if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' ) |
693 | || MW_ENTRY_POINT === 'load' |
694 | ) { |
695 | $cache = true; |
696 | } else { |
697 | $cache = false; |
698 | } |
699 | return $cache; |
700 | } |
701 | |
702 | /** |
703 | * Send a line to a supplementary debug log file, if configured, or main debug |
704 | * log if not. |
705 | * |
706 | * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to |
707 | * a string filename or an associative array mapping 'destination' to the |
708 | * desired filename. The associative array may also contain a 'sample' key |
709 | * with an integer value, specifying a sampling factor. Sampled log events |
710 | * will be emitted with a 1 in N random chance. |
711 | * |
712 | * @since 1.23 support for sampling log messages via $wgDebugLogGroups. |
713 | * @since 1.25 support for additional context data |
714 | * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi |
715 | * |
716 | * @param string $logGroup |
717 | * @param string $text |
718 | * @param string|bool $dest Destination of the message: |
719 | * - 'all': both to the log and HTML (debug toolbar or HTML comments) |
720 | * - 'private': only to the specific log if set in $wgDebugLogGroups and |
721 | * discarded otherwise |
722 | * For backward compatibility, it can also take a boolean: |
723 | * - true: same as 'all' |
724 | * - false: same as 'private' |
725 | * @param array $context Additional logging context data |
726 | */ |
727 | function wfDebugLog( |
728 | $logGroup, $text, $dest = 'all', array $context = [] |
729 | ) { |
730 | $text = trim( $text ); |
731 | |
732 | $logger = LoggerFactory::getInstance( $logGroup ); |
733 | $context['private'] = ( $dest === false || $dest === 'private' ); |
734 | $logger->info( $text, $context ); |
735 | } |
736 | |
737 | /** |
738 | * Log for database errors |
739 | * |
740 | * @since 1.25 support for additional context data |
741 | * |
742 | * @param string $text Database error message. |
743 | * @param array $context Additional logging context data |
744 | */ |
745 | function wfLogDBError( $text, array $context = [] ) { |
746 | $logger = LoggerFactory::getInstance( 'wfLogDBError' ); |
747 | $logger->error( trim( $text ), $context ); |
748 | } |
749 | |
750 | /** |
751 | * Logs a warning that a deprecated feature was used. |
752 | * |
753 | * To write a custom deprecation message, use wfDeprecatedMsg() instead. |
754 | * |
755 | * @param string $function Feature that is deprecated. |
756 | * @param string|false $version Version of MediaWiki that the feature |
757 | * was deprecated in (Added in 1.19). |
758 | * @param string|bool $component Component to which the feature belongs. |
759 | * If false, it is assumed the function is in MediaWiki core (Added in 1.19). |
760 | * @param int $callerOffset How far up the call stack is the original |
761 | * caller. 2 = function that called the function that called |
762 | * wfDeprecated (Added in 1.20). |
763 | * @throws InvalidArgumentException If the MediaWiki version |
764 | * number specified by $version is neither a string nor false. |
765 | */ |
766 | function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) { |
767 | if ( !is_string( $version ) && $version !== false ) { |
768 | throw new InvalidArgumentException( |
769 | "MediaWiki version must either be a string or false. " . |
770 | "Example valid version: '1.33'" |
771 | ); |
772 | } |
773 | |
774 | MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 ); |
775 | } |
776 | |
777 | /** |
778 | * Log a deprecation warning with arbitrary message text. A caller |
779 | * description will be appended. If the message has already been sent for |
780 | * this caller, it won't be sent again. |
781 | * |
782 | * Although there are component and version parameters, they are not |
783 | * automatically appended to the message. The message text should include |
784 | * information about when the thing was deprecated. The component and version |
785 | * are just used to implement $wgDeprecationReleaseLimit. |
786 | * |
787 | * @since 1.35 |
788 | * @param string $msg The message |
789 | * @param string|false $version Version of MediaWiki that the function |
790 | * was deprecated in. |
791 | * @param string|bool $component Component to which the function belongs. |
792 | * If false, it is assumed the function is in MediaWiki core. |
793 | * @param int|false $callerOffset How far up the call stack is the original |
794 | * caller. 2 = function that called the function that called us. If false, |
795 | * the caller description will not be appended. |
796 | */ |
797 | function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) { |
798 | MWDebug::deprecatedMsg( $msg, $version, $component, |
799 | $callerOffset === false ? false : $callerOffset + 1 ); |
800 | } |
801 | |
802 | /** |
803 | * Send a warning either to the debug log or in a PHP error depending on |
804 | * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead. |
805 | * |
806 | * @param string $msg Message to send |
807 | * @param int $callerOffset Number of items to go back in the backtrace to |
808 | * find the correct caller (1 = function calling wfWarn, ...) |
809 | * @param int $level PHP error level; defaults to E_USER_NOTICE; |
810 | * only used when $wgDevelopmentWarnings is true |
811 | */ |
812 | function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) { |
813 | MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' ); |
814 | } |
815 | |
816 | /** |
817 | * Send a warning as a PHP error and the debug log. This is intended for logging |
818 | * warnings in production. For logging development warnings, use WfWarn instead. |
819 | * |
820 | * @param string $msg Message to send |
821 | * @param int $callerOffset Number of items to go back in the backtrace to |
822 | * find the correct caller (1 = function calling wfLogWarning, ...) |
823 | * @param int $level PHP error level; defaults to E_USER_WARNING |
824 | */ |
825 | function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) { |
826 | MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' ); |
827 | } |
828 | |
829 | /** |
830 | * This is the function for getting translated interface messages. |
831 | * |
832 | * @see Message class for documentation how to use them. |
833 | * @see https://www.mediawiki.org/wiki/Manual:Messages_API |
834 | * |
835 | * This function replaces all old wfMsg* functions. |
836 | * |
837 | * When the MessageSpecifier object is an instance of Message, a clone of the object is returned. |
838 | * This is unlike the `new Message( … )` constructor, which returns a new object constructed from |
839 | * scratch with the same key. This difference is mostly relevant when the passed object is an |
840 | * instance of a subclass like RawMessage or ApiMessage. |
841 | * |
842 | * @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier |
843 | * @param MessageParam|MessageSpecifier|string|int|float|list<MessageParam|MessageSpecifier|string|int|float> ...$params |
844 | * See Message::params() |
845 | * @return Message |
846 | * |
847 | * @since 1.17 |
848 | * |
849 | * @see Message::__construct |
850 | */ |
851 | function wfMessage( $key, ...$params ) { |
852 | if ( is_array( $key ) ) { |
853 | // Fallback keys are not allowed in message specifiers |
854 | $message = wfMessageFallback( ...$key ); |
855 | } else { |
856 | $message = Message::newFromSpecifier( $key ); |
857 | } |
858 | |
859 | // We call Message::params() to reduce code duplication |
860 | if ( $params ) { |
861 | $message->params( ...$params ); |
862 | } |
863 | |
864 | return $message; |
865 | } |
866 | |
867 | /** |
868 | * This function accepts multiple message keys and returns a message instance |
869 | * for the first message which is non-empty. If all messages are empty then an |
870 | * instance of the last message key is returned. |
871 | * |
872 | * @param string ...$keys Message keys |
873 | * @return Message |
874 | * |
875 | * @since 1.18 |
876 | * |
877 | * @see Message::newFallbackSequence |
878 | */ |
879 | function wfMessageFallback( ...$keys ) { |
880 | return Message::newFallbackSequence( ...$keys ); |
881 | } |
882 | |
883 | /** |
884 | * Replace message parameter keys on the given formatted output. |
885 | * |
886 | * @param string $message |
887 | * @param array $args |
888 | * @return string |
889 | * @internal |
890 | */ |
891 | function wfMsgReplaceArgs( $message, $args ) { |
892 | # Fix windows line-endings |
893 | # Some messages are split with explode("\n", $msg) |
894 | $message = str_replace( "\r", '', $message ); |
895 | |
896 | // Replace arguments |
897 | if ( is_array( $args ) && $args ) { |
898 | if ( is_array( $args[0] ) ) { |
899 | $args = array_values( $args[0] ); |
900 | } |
901 | $replacementKeys = []; |
902 | foreach ( $args as $n => $param ) { |
903 | $replacementKeys['$' . ( $n + 1 )] = $param; |
904 | } |
905 | $message = strtr( $message, $replacementKeys ); |
906 | } |
907 | |
908 | return $message; |
909 | } |
910 | |
911 | /** |
912 | * Get host name of the current machine, for use in error reporting. |
913 | * |
914 | * This helps to know which machine in a data center generated the |
915 | * current page. |
916 | * |
917 | * @return string |
918 | */ |
919 | function wfHostname() { |
920 | // Hostname overriding |
921 | global $wgOverrideHostname; |
922 | if ( $wgOverrideHostname !== false ) { |
923 | return $wgOverrideHostname; |
924 | } |
925 | |
926 | return php_uname( 'n' ) ?: 'unknown'; |
927 | } |
928 | |
929 | /** |
930 | * Safety wrapper for debug_backtrace(). |
931 | * |
932 | * Will return an empty array if debug_backtrace is disabled, otherwise |
933 | * the output from debug_backtrace() (trimmed). |
934 | * |
935 | * @param int $limit This parameter can be used to limit the number of stack frames returned |
936 | * |
937 | * @return array Array of backtrace information |
938 | */ |
939 | function wfDebugBacktrace( $limit = 0 ) { |
940 | static $disabled = null; |
941 | |
942 | if ( $disabled === null ) { |
943 | $disabled = !function_exists( 'debug_backtrace' ); |
944 | if ( $disabled ) { |
945 | wfDebug( "debug_backtrace() is disabled" ); |
946 | } |
947 | } |
948 | if ( $disabled ) { |
949 | return []; |
950 | } |
951 | |
952 | if ( $limit ) { |
953 | return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 ); |
954 | } else { |
955 | return array_slice( debug_backtrace(), 1 ); |
956 | } |
957 | } |
958 | |
959 | /** |
960 | * Get a debug backtrace as a string |
961 | * |
962 | * @param bool|null $raw If true, the return value is plain text. If false, HTML. |
963 | * Defaults to true if MW_ENTRY_POINT is 'cli', otherwise false. |
964 | * @return string |
965 | * @since 1.25 Supports $raw parameter. |
966 | */ |
967 | function wfBacktrace( $raw = null ) { |
968 | $raw ??= MW_ENTRY_POINT === 'cli'; |
969 | if ( $raw ) { |
970 | $frameFormat = "%s line %s calls %s()\n"; |
971 | $traceFormat = "%s"; |
972 | } else { |
973 | $frameFormat = "<li>%s line %s calls %s()</li>\n"; |
974 | $traceFormat = "<ul>\n%s</ul>\n"; |
975 | } |
976 | |
977 | $frames = array_map( static function ( $frame ) use ( $frameFormat ) { |
978 | $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-'; |
979 | $line = $frame['line'] ?? '-'; |
980 | $call = $frame['function']; |
981 | if ( !empty( $frame['class'] ) ) { |
982 | $call = $frame['class'] . $frame['type'] . $call; |
983 | } |
984 | return sprintf( $frameFormat, $file, $line, $call ); |
985 | }, wfDebugBacktrace() ); |
986 | |
987 | return sprintf( $traceFormat, implode( '', $frames ) ); |
988 | } |
989 | |
990 | /** |
991 | * Get the name of the function which called this function |
992 | * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__) |
993 | * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller() |
994 | * wfGetCaller( 3 ) is the parent of that. |
995 | * |
996 | * The format will be the same as for {@see wfFormatStackFrame()}. |
997 | * @param int $level |
998 | * @return string function name or 'unknown' |
999 | */ |
1000 | function wfGetCaller( $level = 2 ) { |
1001 | $backtrace = wfDebugBacktrace( $level + 1 ); |
1002 | if ( isset( $backtrace[$level] ) ) { |
1003 | return wfFormatStackFrame( $backtrace[$level] ); |
1004 | } else { |
1005 | return 'unknown'; |
1006 | } |
1007 | } |
1008 | |
1009 | /** |
1010 | * Return a string consisting of callers in the stack. Useful sometimes |
1011 | * for profiling specific points. |
1012 | * |
1013 | * @param int|false $limit The maximum depth of the stack frame to return, or false for the entire stack. |
1014 | * @return string |
1015 | */ |
1016 | function wfGetAllCallers( $limit = 3 ) { |
1017 | $trace = array_reverse( wfDebugBacktrace() ); |
1018 | if ( !$limit || $limit > count( $trace ) - 1 ) { |
1019 | $limit = count( $trace ) - 1; |
1020 | } |
1021 | $trace = array_slice( $trace, -$limit - 1, $limit ); |
1022 | return implode( '/', array_map( 'wfFormatStackFrame', $trace ) ); |
1023 | } |
1024 | |
1025 | /** |
1026 | * Return a string representation of frame |
1027 | * |
1028 | * Typically, the returned value will be in one of these formats: |
1029 | * - method |
1030 | * - Fully\Qualified\method |
1031 | * - Fully\Qualified\Class->method |
1032 | * - Fully\Qualified\Class::method |
1033 | * |
1034 | * @param array $frame |
1035 | * @return string |
1036 | */ |
1037 | function wfFormatStackFrame( $frame ) { |
1038 | if ( !isset( $frame['function'] ) ) { |
1039 | return 'NO_FUNCTION_GIVEN'; |
1040 | } |
1041 | return isset( $frame['class'] ) && isset( $frame['type'] ) ? |
1042 | $frame['class'] . $frame['type'] . $frame['function'] : |
1043 | $frame['function']; |
1044 | } |
1045 | |
1046 | /** |
1047 | * Whether the client accept gzip encoding |
1048 | * |
1049 | * Uses the Accept-Encoding header to check if the client supports gzip encoding. |
1050 | * Use this when considering to send a gzip-encoded response to the client. |
1051 | * |
1052 | * @param bool $force Forces another check even if we already have a cached result. |
1053 | * @return bool |
1054 | */ |
1055 | function wfClientAcceptsGzip( $force = false ) { |
1056 | static $result = null; |
1057 | if ( $result === null || $force ) { |
1058 | $result = false; |
1059 | if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) { |
1060 | # @todo FIXME: We may want to disallow some broken browsers |
1061 | $m = []; |
1062 | if ( preg_match( |
1063 | '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/', |
1064 | $_SERVER['HTTP_ACCEPT_ENCODING'], |
1065 | $m |
1066 | ) |
1067 | ) { |
1068 | if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) { |
1069 | return $result; |
1070 | } |
1071 | wfDebug( "wfClientAcceptsGzip: client accepts gzip." ); |
1072 | $result = true; |
1073 | } |
1074 | } |
1075 | } |
1076 | return $result; |
1077 | } |
1078 | |
1079 | /** |
1080 | * Escapes the given text so that it may be output using addWikiText() |
1081 | * without any linking, formatting, etc. making its way through. This |
1082 | * is achieved by substituting certain characters with HTML entities. |
1083 | * As required by the callers, "<nowiki>" is not used. |
1084 | * |
1085 | * @param string|null|false $input Text to be escaped |
1086 | * @param-taint $input escapes_html |
1087 | * @return string |
1088 | */ |
1089 | function wfEscapeWikiText( $input ): string { |
1090 | global $wgEnableMagicLinks; |
1091 | static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null; |
1092 | if ( $repl === null || defined( 'MW_PARSER_TEST' ) || defined( 'MW_PHPUNIT_TEST' ) ) { |
1093 | // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache |
1094 | // in those situations |
1095 | $repl = [ |
1096 | '"' => '"', '&' => '&', "'" => ''', '<' => '<', |
1097 | '=' => '=', '>' => '>', '[' => '[', ']' => ']', |
1098 | '{' => '{', '|' => '|', '}' => '}', |
1099 | ';' => ';', // a token inside language converter brackets |
1100 | '!!' => '!!', // a token inside table context |
1101 | "\n!" => "\n!", "\r!" => "\r!", // a token inside table context |
1102 | "\n#" => "\n#", "\r#" => "\r#", |
1103 | "\n*" => "\n*", "\r*" => "\r*", |
1104 | "\n:" => "\n:", "\r:" => "\r:", |
1105 | "\n " => "\n ", "\r " => "\r ", |
1106 | "\n\n" => "\n ", "\r\n" => " \n", |
1107 | "\n\r" => "\n ", "\r\r" => "\r ", |
1108 | "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n" |
1109 | "\n----" => "\n----", "\r----" => "\r----", |
1110 | '__' => '__', '://' => '://', |
1111 | '~~~' => '~~~', // protect from PST, just to be safe(r) |
1112 | ]; |
1113 | |
1114 | $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) ); |
1115 | // We have to catch everything "\s" matches in PCRE |
1116 | foreach ( $magicLinks as $magic ) { |
1117 | $repl["$magic "] = "$magic "; |
1118 | $repl["$magic\t"] = "$magic	"; |
1119 | $repl["$magic\r"] = "$magic "; |
1120 | $repl["$magic\n"] = "$magic "; |
1121 | $repl["$magic\f"] = "$magic"; |
1122 | } |
1123 | // Additionally escape the following characters at the beginning of the |
1124 | // string, in case they merge to form tokens when spliced into a |
1125 | // string. Tokens like -{ {{ [[ {| etc are already escaped because |
1126 | // the second character is escaped above, but the following tokens |
1127 | // are handled here: |+ |- __FOO__ ~~~ |
1128 | $repl3 = [ |
1129 | '+' => '+', '-' => '-', '_' => '_', '~' => '~', |
1130 | ]; |
1131 | // Similarly, protect the following characters at the end of the |
1132 | // string, which could turn form the start of `__FOO__` or `~~~~` |
1133 | // A trailing newline could also form the unintended start of a |
1134 | // paragraph break if it is glued to a newline in the following |
1135 | // context. |
1136 | $repl4 = [ |
1137 | '_' => '_', '~' => '~', |
1138 | "\n" => " ", "\r" => " ", |
1139 | "\t" => "	", // "\n\t\n" is treated like "\n\n" |
1140 | ]; |
1141 | |
1142 | // And handle protocols that don't use "://" |
1143 | global $wgUrlProtocols; |
1144 | $repl2 = []; |
1145 | foreach ( $wgUrlProtocols as $prot ) { |
1146 | if ( substr( $prot, -1 ) === ':' ) { |
1147 | $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' ); |
1148 | } |
1149 | } |
1150 | $repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/'; |
1151 | } |
1152 | // Tell phan that $repl2, $repl3 and $repl4 will also be non-null here |
1153 | '@phan-var string $repl2'; |
1154 | '@phan-var string $repl3'; |
1155 | '@phan-var string $repl4'; |
1156 | // This will also stringify input in case it's not a string |
1157 | $text = substr( strtr( "\n$input", $repl ), 1 ); |
1158 | if ( $text === '' ) { |
1159 | return $text; |
1160 | } |
1161 | $first = strtr( $text[0], $repl3 ); // protect first character |
1162 | if ( strlen( $text ) > 1 ) { |
1163 | $text = $first . substr( $text, 1, -1 ) . |
1164 | strtr( substr( $text, -1 ), $repl4 ); // protect last character |
1165 | } else { |
1166 | // special case for single-character strings |
1167 | $text = strtr( $first, $repl4 ); // protect last character |
1168 | } |
1169 | $text = preg_replace( $repl2, '$1:', $text ); |
1170 | return $text; |
1171 | } |
1172 | |
1173 | /** |
1174 | * Sets dest to source and returns the original value of dest |
1175 | * If source is NULL, it just returns the value, it doesn't set the variable |
1176 | * If force is true, it will set the value even if source is NULL |
1177 | * |
1178 | * @param mixed &$dest |
1179 | * @param mixed $source |
1180 | * @param bool $force |
1181 | * @return mixed |
1182 | */ |
1183 | function wfSetVar( &$dest, $source, $force = false ) { |
1184 | $temp = $dest; |
1185 | if ( $source !== null || $force ) { |
1186 | $dest = $source; |
1187 | } |
1188 | return $temp; |
1189 | } |
1190 | |
1191 | /** |
1192 | * As for wfSetVar except setting a bit |
1193 | * |
1194 | * @param int &$dest |
1195 | * @param int $bit |
1196 | * @param bool $state |
1197 | * |
1198 | * @return bool |
1199 | */ |
1200 | function wfSetBit( &$dest, $bit, $state = true ) { |
1201 | $temp = (bool)( $dest & $bit ); |
1202 | if ( $state !== null ) { |
1203 | if ( $state ) { |
1204 | $dest |= $bit; |
1205 | } else { |
1206 | $dest &= ~$bit; |
1207 | } |
1208 | } |
1209 | return $temp; |
1210 | } |
1211 | |
1212 | /** |
1213 | * A wrapper around the PHP function var_export(). |
1214 | * Either print it or add it to the regular output ($wgOut). |
1215 | * |
1216 | * @param mixed $var A PHP variable to dump. |
1217 | */ |
1218 | function wfVarDump( $var ) { |
1219 | global $wgOut; |
1220 | $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" ); |
1221 | if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) { |
1222 | print $s; |
1223 | } else { |
1224 | $wgOut->addHTML( $s ); |
1225 | } |
1226 | } |
1227 | |
1228 | /** |
1229 | * Provide a simple HTTP error. |
1230 | * |
1231 | * @param int|string $code |
1232 | * @param string $label |
1233 | * @param string $desc |
1234 | */ |
1235 | function wfHttpError( $code, $label, $desc ) { |
1236 | global $wgOut; |
1237 | HttpStatus::header( $code ); |
1238 | if ( $wgOut ) { |
1239 | $wgOut->disable(); |
1240 | $wgOut->sendCacheControl(); |
1241 | } |
1242 | |
1243 | \MediaWiki\Request\HeaderCallback::warnIfHeadersSent(); |
1244 | header( 'Content-type: text/html; charset=utf-8' ); |
1245 | ob_start(); |
1246 | print '<!DOCTYPE html>' . |
1247 | '<html><head><title>' . |
1248 | htmlspecialchars( $label ) . |
1249 | '</title></head><body><h1>' . |
1250 | htmlspecialchars( $label ) . |
1251 | '</h1><p>' . |
1252 | nl2br( htmlspecialchars( $desc ) ) . |
1253 | "</p></body></html>\n"; |
1254 | header( 'Content-Length: ' . ob_get_length() ); |
1255 | ob_end_flush(); |
1256 | } |
1257 | |
1258 | /** |
1259 | * Clear away any user-level output buffers, discarding contents. |
1260 | * |
1261 | * Suitable for 'starting afresh', for instance when streaming |
1262 | * relatively large amounts of data without buffering, or wanting to |
1263 | * output image files without ob_gzhandler's compression. |
1264 | * |
1265 | * The optional $resetGzipEncoding parameter controls suppression of |
1266 | * the Content-Encoding header sent by ob_gzhandler; by default it |
1267 | * is left. This should be used for HTTP 304 responses, where you need to |
1268 | * preserve the Content-Encoding header of the real result, but |
1269 | * also need to suppress the output of ob_gzhandler to keep to spec |
1270 | * and avoid breaking Firefox in rare cases where the headers and |
1271 | * body are broken over two packets. |
1272 | * |
1273 | * Note that some PHP configuration options may add output buffer |
1274 | * layers which cannot be removed; these are left in place. |
1275 | * |
1276 | * @param bool $resetGzipEncoding |
1277 | */ |
1278 | function wfResetOutputBuffers( $resetGzipEncoding = true ) { |
1279 | // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition |
1280 | while ( $status = ob_get_status() ) { |
1281 | if ( isset( $status['flags'] ) ) { |
1282 | $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE; |
1283 | $deleteable = ( $status['flags'] & $flags ) === $flags; |
1284 | } elseif ( isset( $status['del'] ) ) { |
1285 | $deleteable = $status['del']; |
1286 | } else { |
1287 | // Guess that any PHP-internal setting can't be removed. |
1288 | $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */ |
1289 | } |
1290 | if ( !$deleteable ) { |
1291 | // Give up, and hope the result doesn't break |
1292 | // output behavior. |
1293 | break; |
1294 | } |
1295 | if ( $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' ) { |
1296 | // Unit testing barrier to prevent this function from breaking PHPUnit. |
1297 | break; |
1298 | } |
1299 | if ( !ob_end_clean() ) { |
1300 | // Could not remove output buffer handler; abort now |
1301 | // to avoid getting in some kind of infinite loop. |
1302 | break; |
1303 | } |
1304 | if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) { |
1305 | // Reset the 'Content-Encoding' field set by this handler |
1306 | // so we can start fresh. |
1307 | header_remove( 'Content-Encoding' ); |
1308 | break; |
1309 | } |
1310 | } |
1311 | } |
1312 | |
1313 | /** |
1314 | * Get a timestamp string in one of various formats |
1315 | * |
1316 | * @param mixed $outputtype Output format, one of the TS_* constants. Defaults to |
1317 | * Unix timestamp. |
1318 | * @param mixed $ts A timestamp in any supported format. The |
1319 | * function will autodetect which format is supplied and act accordingly. Use 0 or |
1320 | * omit to use current time |
1321 | * @return string|false The date in the specified format, or false on error. |
1322 | */ |
1323 | function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) { |
1324 | $ret = MWTimestamp::convert( $outputtype, $ts ); |
1325 | if ( $ret === false ) { |
1326 | wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts" ); |
1327 | } |
1328 | return $ret; |
1329 | } |
1330 | |
1331 | /** |
1332 | * Return a formatted timestamp, or null if input is null. |
1333 | * For dealing with nullable timestamp columns in the database. |
1334 | * |
1335 | * @param mixed $outputtype |
1336 | * @param mixed|null $ts |
1337 | * @return string|false|null Null if called with null, otherwise the result of wfTimestamp() |
1338 | */ |
1339 | function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) { |
1340 | if ( $ts === null ) { |
1341 | return null; |
1342 | } else { |
1343 | return wfTimestamp( $outputtype, $ts ); |
1344 | } |
1345 | } |
1346 | |
1347 | /** |
1348 | * Convenience function; returns MediaWiki timestamp for the present time. |
1349 | * |
1350 | * @return string TS_MW timestamp |
1351 | */ |
1352 | function wfTimestampNow() { |
1353 | return MWTimestamp::now( TS_MW ); |
1354 | } |
1355 | |
1356 | /** |
1357 | * Tries to get the system directory for temporary files. First |
1358 | * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP |
1359 | * environment variables are then checked in sequence, then |
1360 | * sys_get_temp_dir(), then upload_tmp_dir from php.ini. |
1361 | * |
1362 | * NOTE: When possible, use instead the tmpfile() function to create |
1363 | * temporary files to avoid race conditions on file creation, etc. |
1364 | * |
1365 | * @return string |
1366 | */ |
1367 | function wfTempDir() { |
1368 | global $wgTmpDirectory; |
1369 | |
1370 | if ( $wgTmpDirectory !== false ) { |
1371 | return $wgTmpDirectory; |
1372 | } |
1373 | |
1374 | return TempFSFile::getUsableTempDirectory(); |
1375 | } |
1376 | |
1377 | /** |
1378 | * Make directory, and make all parent directories if they don't exist |
1379 | * |
1380 | * @param string $dir Full path to directory to create. Callers should make sure this is not a storage path. |
1381 | * @param int|null $mode Chmod value to use, default is $wgDirectoryMode |
1382 | * @param string|null $caller Optional caller param for debugging. |
1383 | * @return bool |
1384 | */ |
1385 | function wfMkdirParents( $dir, $mode = null, $caller = null ) { |
1386 | global $wgDirectoryMode; |
1387 | |
1388 | if ( FileBackend::isStoragePath( $dir ) ) { |
1389 | throw new LogicException( __FUNCTION__ . " given storage path '$dir'." ); |
1390 | } |
1391 | if ( $caller !== null ) { |
1392 | wfDebug( "$caller: called wfMkdirParents($dir)" ); |
1393 | } |
1394 | if ( strval( $dir ) === '' ) { |
1395 | return true; |
1396 | } |
1397 | |
1398 | $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir ); |
1399 | $mode ??= $wgDirectoryMode; |
1400 | |
1401 | // Turn off the normal warning, we're doing our own below |
1402 | // PHP doesn't include the path in its warning message, so we add our own to aid in diagnosis. |
1403 | // |
1404 | // Repeat existence check if creation failed so that we silently recover in case of |
1405 | // a race condition where another request created it since the first check. |
1406 | // |
1407 | // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged |
1408 | $ok = is_dir( $dir ) || @mkdir( $dir, $mode, true ) || is_dir( $dir ); |
1409 | if ( !$ok ) { |
1410 | trigger_error( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ), E_USER_WARNING ); |
1411 | } |
1412 | |
1413 | return $ok; |
1414 | } |
1415 | |
1416 | /** |
1417 | * Remove a directory and all its content. |
1418 | * Does not hide error. |
1419 | * @param string $dir |
1420 | */ |
1421 | function wfRecursiveRemoveDir( $dir ) { |
1422 | // taken from https://www.php.net/manual/en/function.rmdir.php#98622 |
1423 | if ( is_dir( $dir ) ) { |
1424 | $objects = scandir( $dir ); |
1425 | foreach ( $objects as $object ) { |
1426 | if ( $object != "." && $object != ".." ) { |
1427 | if ( filetype( $dir . '/' . $object ) == "dir" ) { |
1428 | wfRecursiveRemoveDir( $dir . '/' . $object ); |
1429 | } else { |
1430 | unlink( $dir . '/' . $object ); |
1431 | } |
1432 | } |
1433 | } |
1434 | rmdir( $dir ); |
1435 | } |
1436 | } |
1437 | |
1438 | /** |
1439 | * @param float|int $nr The number to format |
1440 | * @param int $acc The number of digits after the decimal point, default 2 |
1441 | * @param bool $round Whether or not to round the value, default true |
1442 | * @return string |
1443 | */ |
1444 | function wfPercent( $nr, int $acc = 2, bool $round = true ) { |
1445 | $accForFormat = $acc >= 0 ? $acc : 0; |
1446 | $ret = sprintf( "%.{$accForFormat}f", $nr ); |
1447 | return $round ? round( (float)$ret, $acc ) . '%' : "$ret%"; |
1448 | } |
1449 | |
1450 | /** |
1451 | * Safety wrapper around ini_get() for boolean settings. |
1452 | * The values returned from ini_get() are pre-normalized for settings |
1453 | * set via php.ini or php_flag/php_admin_flag... but *not* |
1454 | * for those set via php_value/php_admin_value. |
1455 | * |
1456 | * It's fairly common for people to use php_value instead of php_flag, |
1457 | * which can leave you with an 'off' setting giving a false positive |
1458 | * for code that just takes the ini_get() return value as a boolean. |
1459 | * |
1460 | * To make things extra interesting, setting via php_value accepts |
1461 | * "true" and "yes" as true, but php.ini and php_flag consider them false. :) |
1462 | * Unrecognized values go false... again opposite PHP's own coercion |
1463 | * from string to bool. |
1464 | * |
1465 | * Luckily, 'properly' set settings will always come back as '0' or '1', |
1466 | * so we only have to worry about them and the 'improper' settings. |
1467 | * |
1468 | * I frickin' hate PHP... :P |
1469 | * |
1470 | * @param string $setting |
1471 | * @return bool |
1472 | */ |
1473 | function wfIniGetBool( $setting ) { |
1474 | return wfStringToBool( ini_get( $setting ) ); |
1475 | } |
1476 | |
1477 | /** |
1478 | * Convert string value to boolean, when the following are interpreted as true: |
1479 | * - on |
1480 | * - true |
1481 | * - yes |
1482 | * - Any number, except 0 |
1483 | * All other strings are interpreted as false. |
1484 | * |
1485 | * @param string $val |
1486 | * @return bool |
1487 | * @since 1.31 |
1488 | */ |
1489 | function wfStringToBool( $val ) { |
1490 | $val = strtolower( $val ); |
1491 | // 'on' and 'true' can't have whitespace around them, but '1' can. |
1492 | return $val == 'on' |
1493 | || $val == 'true' |
1494 | || $val == 'yes' |
1495 | || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function |
1496 | } |
1497 | |
1498 | /** |
1499 | * Locale-independent version of escapeshellarg() |
1500 | * |
1501 | * Originally, this fixed the incorrect use of single quotes on Windows |
1502 | * (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in |
1503 | * PHP 5.2.6+ (https://bugs.php.net/bug.php?id=54391). The second bug is still |
1504 | * open as of 2021. |
1505 | * |
1506 | * @param string|string[] ...$args strings to escape and glue together, |
1507 | * or a single array of strings parameter |
1508 | * @return string |
1509 | * @deprecated since 1.30 use MediaWiki\Shell\Shell::escape() |
1510 | */ |
1511 | function wfEscapeShellArg( ...$args ) { |
1512 | return Shell::escape( ...$args ); |
1513 | } |
1514 | |
1515 | /** |
1516 | * Execute a shell command, with time and memory limits mirrored from the PHP |
1517 | * configuration if supported. |
1518 | * |
1519 | * @param string|string[] $cmd If string, a properly shell-escaped command line, |
1520 | * or an array of unescaped arguments, in which case each value will be escaped |
1521 | * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'" |
1522 | * @param null|mixed &$retval Optional, will receive the program's exit code. |
1523 | * (non-zero is usually failure). If there is an error from |
1524 | * read, select, or proc_open(), this will be set to -1. |
1525 | * @param array $environ Optional environment variables which should be |
1526 | * added to the executed command environment. |
1527 | * @param array $limits Optional array with limits(filesize, memory, time, walltime) |
1528 | * this overwrites the global wgMaxShell* limits. |
1529 | * @param array $options Array of options: |
1530 | * - duplicateStderr: Set this to true to duplicate stderr to stdout, |
1531 | * including errors from limit.sh |
1532 | * - profileMethod: By default this function will profile based on the calling |
1533 | * method. Set this to a string for an alternative method to profile from |
1534 | * @phan-param array{duplicateStderr?:bool,profileMethod?:string} $options |
1535 | * |
1536 | * @return string Collected stdout as a string |
1537 | * @deprecated since 1.30 use class MediaWiki\Shell\Shell |
1538 | */ |
1539 | function wfShellExec( $cmd, &$retval = null, $environ = [], |
1540 | $limits = [], $options = [] |
1541 | ) { |
1542 | if ( Shell::isDisabled() ) { |
1543 | $retval = 1; |
1544 | // Backwards compatibility be upon us... |
1545 | return 'Unable to run external programs, proc_open() is disabled.'; |
1546 | } |
1547 | |
1548 | if ( is_array( $cmd ) ) { |
1549 | $cmd = Shell::escape( $cmd ); |
1550 | } |
1551 | |
1552 | $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr']; |
1553 | $profileMethod = $options['profileMethod'] ?? wfGetCaller(); |
1554 | |
1555 | try { |
1556 | $result = Shell::command( [] ) |
1557 | ->unsafeParams( (array)$cmd ) |
1558 | ->environment( $environ ) |
1559 | ->limits( $limits ) |
1560 | ->includeStderr( $includeStderr ) |
1561 | ->profileMethod( $profileMethod ) |
1562 | // For b/c |
1563 | ->restrict( Shell::RESTRICT_NONE ) |
1564 | ->execute(); |
1565 | } catch ( ProcOpenError $ex ) { |
1566 | $retval = -1; |
1567 | return ''; |
1568 | } |
1569 | |
1570 | $retval = $result->getExitCode(); |
1571 | |
1572 | return $result->getStdout(); |
1573 | } |
1574 | |
1575 | /** |
1576 | * Execute a shell command, returning both stdout and stderr. Convenience |
1577 | * function, as all the arguments to wfShellExec can become unwieldy. |
1578 | * |
1579 | * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded. |
1580 | * @param string|string[] $cmd If string, a properly shell-escaped command line, |
1581 | * or an array of unescaped arguments, in which case each value will be escaped |
1582 | * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'" |
1583 | * @param null|mixed &$retval Optional, will receive the program's exit code. |
1584 | * (non-zero is usually failure) |
1585 | * @param array $environ Optional environment variables which should be |
1586 | * added to the executed command environment. |
1587 | * @param array $limits Optional array with limits(filesize, memory, time, walltime) |
1588 | * this overwrites the global wgMaxShell* limits. |
1589 | * @return string Collected stdout and stderr as a string |
1590 | * @deprecated since 1.30 use class MediaWiki\Shell\Shell |
1591 | */ |
1592 | function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) { |
1593 | return wfShellExec( $cmd, $retval, $environ, $limits, |
1594 | [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] ); |
1595 | } |
1596 | |
1597 | /** |
1598 | * Generate a shell-escaped command line string to run a MediaWiki cli script. |
1599 | * Note that $parameters should be a flat array and an option with an argument |
1600 | * should consist of two consecutive items in the array (do not use "--option value"). |
1601 | * |
1602 | * @deprecated since 1.31, use Shell::makeScriptCommand() |
1603 | * |
1604 | * @param string $script MediaWiki cli script path |
1605 | * @param array $parameters Arguments and options to the script |
1606 | * @param array $options Associative array of options: |
1607 | * 'php': The path to the php executable |
1608 | * 'wrapper': Path to a PHP wrapper to handle the maintenance script |
1609 | * @phan-param array{php?:string,wrapper?:string} $options |
1610 | * @return string |
1611 | */ |
1612 | function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) { |
1613 | global $wgPhpCli; |
1614 | // Give site config file a chance to run the script in a wrapper. |
1615 | // The caller may likely want to call wfBasename() on $script. |
1616 | ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) ) |
1617 | ->onWfShellWikiCmd( $script, $parameters, $options ); |
1618 | $cmd = [ $options['php'] ?? $wgPhpCli ]; |
1619 | if ( isset( $options['wrapper'] ) ) { |
1620 | $cmd[] = $options['wrapper']; |
1621 | } |
1622 | $cmd[] = $script; |
1623 | // Escape each parameter for shell |
1624 | return Shell::escape( array_merge( $cmd, $parameters ) ); |
1625 | } |
1626 | |
1627 | /** |
1628 | * wfMerge attempts to merge differences between three texts. |
1629 | * |
1630 | * @param string $old Common base revision |
1631 | * @param string $mine The edit we wish to store but which potentially conflicts with another edit |
1632 | * which happened since we started editing. |
1633 | * @param string $yours The most recent stored revision of the article. Note that "mine" and "yours" |
1634 | * might have another meaning depending on the specific use case. |
1635 | * @param string|null &$simplisticMergeAttempt Automatically merged text, with overlapping edits |
1636 | * falling back to "my" text. |
1637 | * @param string|null &$mergeLeftovers Optional out parameter containing an "ed" script with the |
1638 | * remaining bits of "your" text that could not be merged into $simplisticMergeAttempt. |
1639 | * The "ed" file format is documented here: |
1640 | * https://www.gnu.org/software/diffutils/manual/html_node/Detailed-ed.html |
1641 | * @return bool true for a clean merge and false for failure or a conflict. |
1642 | */ |
1643 | function wfMerge( |
1644 | string $old, |
1645 | string $mine, |
1646 | string $yours, |
1647 | ?string &$simplisticMergeAttempt, |
1648 | ?string &$mergeLeftovers = null |
1649 | ): bool { |
1650 | global $wgDiff3; |
1651 | |
1652 | # This check may also protect against code injection in |
1653 | # case of broken installations. |
1654 | AtEase::suppressWarnings(); |
1655 | $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 ); |
1656 | AtEase::restoreWarnings(); |
1657 | |
1658 | if ( !$haveDiff3 ) { |
1659 | wfDebug( "diff3 not found" ); |
1660 | return false; |
1661 | } |
1662 | |
1663 | # Make temporary files |
1664 | $td = wfTempDir(); |
1665 | $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' ); |
1666 | $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' ); |
1667 | $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' ); |
1668 | |
1669 | # NOTE: diff3 issues a warning to stderr if any of the files does not end with |
1670 | # a newline character. To avoid this, we normalize the trailing whitespace before |
1671 | # creating the diff. |
1672 | |
1673 | fwrite( $oldtextFile, rtrim( $old ) . "\n" ); |
1674 | fclose( $oldtextFile ); |
1675 | fwrite( $mytextFile, rtrim( $mine ) . "\n" ); |
1676 | fclose( $mytextFile ); |
1677 | fwrite( $yourtextFile, rtrim( $yours ) . "\n" ); |
1678 | fclose( $yourtextFile ); |
1679 | |
1680 | # Check for a conflict |
1681 | $cmd = Shell::escape( $wgDiff3, '--text', '--overlap-only', $mytextName, |
1682 | $oldtextName, $yourtextName ); |
1683 | $handle = popen( $cmd, 'r' ); |
1684 | |
1685 | $mergeLeftovers = ''; |
1686 | do { |
1687 | $data = fread( $handle, 8192 ); |
1688 | if ( strlen( $data ) == 0 ) { |
1689 | break; |
1690 | } |
1691 | $mergeLeftovers .= $data; |
1692 | } while ( true ); |
1693 | pclose( $handle ); |
1694 | |
1695 | $conflict = $mergeLeftovers !== ''; |
1696 | |
1697 | # Merge differences automatically where possible, preferring "my" text for conflicts. |
1698 | $cmd = Shell::escape( $wgDiff3, '--text', '--ed', '--merge', $mytextName, |
1699 | $oldtextName, $yourtextName ); |
1700 | $handle = popen( $cmd, 'r' ); |
1701 | $simplisticMergeAttempt = ''; |
1702 | do { |
1703 | $data = fread( $handle, 8192 ); |
1704 | if ( strlen( $data ) == 0 ) { |
1705 | break; |
1706 | } |
1707 | $simplisticMergeAttempt .= $data; |
1708 | } while ( true ); |
1709 | pclose( $handle ); |
1710 | unlink( $mytextName ); |
1711 | unlink( $oldtextName ); |
1712 | unlink( $yourtextName ); |
1713 | |
1714 | if ( $simplisticMergeAttempt === '' && $old !== '' && !$conflict ) { |
1715 | wfDebug( "Unexpected null result from diff3. Command: $cmd" ); |
1716 | $conflict = true; |
1717 | } |
1718 | return !$conflict; |
1719 | } |
1720 | |
1721 | /** |
1722 | * Return the final portion of a pathname. |
1723 | * Reimplemented because PHP5's "basename()" is buggy with multibyte text. |
1724 | * https://bugs.php.net/bug.php?id=33898 |
1725 | * |
1726 | * PHP's basename() only considers '\' a pathchar on Windows and Netware. |
1727 | * We'll consider it so always, as we don't want '\s' in our Unix paths either. |
1728 | * |
1729 | * @param string $path |
1730 | * @param string $suffix String to remove if present |
1731 | * @return string |
1732 | */ |
1733 | function wfBaseName( $path, $suffix = '' ) { |
1734 | if ( $suffix == '' ) { |
1735 | $encSuffix = ''; |
1736 | } else { |
1737 | $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?'; |
1738 | } |
1739 | |
1740 | $matches = []; |
1741 | if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) { |
1742 | return $matches[1]; |
1743 | } else { |
1744 | return ''; |
1745 | } |
1746 | } |
1747 | |
1748 | /** |
1749 | * Generate a relative path name to the given file. |
1750 | * May explode on non-matching case-insensitive paths, |
1751 | * funky symlinks, etc. |
1752 | * |
1753 | * @param string $path Absolute destination path including target filename |
1754 | * @param string $from Absolute source path, directory only |
1755 | * @return string |
1756 | */ |
1757 | function wfRelativePath( $path, $from ) { |
1758 | // Normalize mixed input on Windows... |
1759 | $path = str_replace( '/', DIRECTORY_SEPARATOR, $path ); |
1760 | $from = str_replace( '/', DIRECTORY_SEPARATOR, $from ); |
1761 | |
1762 | // Trim trailing slashes -- fix for drive root |
1763 | $path = rtrim( $path, DIRECTORY_SEPARATOR ); |
1764 | $from = rtrim( $from, DIRECTORY_SEPARATOR ); |
1765 | |
1766 | $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) ); |
1767 | $against = explode( DIRECTORY_SEPARATOR, $from ); |
1768 | |
1769 | if ( $pieces[0] !== $against[0] ) { |
1770 | // Non-matching Windows drive letters? |
1771 | // Return a full path. |
1772 | return $path; |
1773 | } |
1774 | |
1775 | // Trim off common prefix |
1776 | while ( count( $pieces ) && count( $against ) |
1777 | && $pieces[0] == $against[0] ) { |
1778 | array_shift( $pieces ); |
1779 | array_shift( $against ); |
1780 | } |
1781 | |
1782 | // relative dots to bump us to the parent |
1783 | while ( count( $against ) ) { |
1784 | array_unshift( $pieces, '..' ); |
1785 | array_shift( $against ); |
1786 | } |
1787 | |
1788 | $pieces[] = wfBaseName( $path ); |
1789 | |
1790 | return implode( DIRECTORY_SEPARATOR, $pieces ); |
1791 | } |
1792 | |
1793 | /** |
1794 | * Get a Database object. |
1795 | * |
1796 | * @param int $db Index of the connection to get. May be DB_PRIMARY for the |
1797 | * primary (for write queries), DB_REPLICA for potentially lagged read |
1798 | * queries, or an integer >= 0 for a particular server. |
1799 | * |
1800 | * @param string|string[] $groups Query groups. An array of group names that this query |
1801 | * belongs to. May contain a single string if the query is only |
1802 | * in one group. |
1803 | * |
1804 | * @param string|false $wiki The wiki ID, or false for the current wiki |
1805 | * |
1806 | * Note: multiple calls to wfGetDB(DB_REPLICA) during the course of one request |
1807 | * will always return the same object, unless the underlying connection or load |
1808 | * balancer is manually destroyed. |
1809 | * |
1810 | * Note 2: use $this->getDB() in maintenance scripts that may be invoked by |
1811 | * updater to ensure that a proper database is being updated. |
1812 | * |
1813 | * Note 3: When replacing calls to this with calls to methods on an injected |
1814 | * LoadBalancer, LoadBalancer::getConnection is more commonly needed than |
1815 | * LoadBalancer::getMaintenanceConnectionRef, which is needed for more advanced |
1816 | * administrative tasks. See the IMaintainableDatabase and IDatabase interfaces |
1817 | * for details. |
1818 | * |
1819 | * @deprecated since 1.39, emitting warnings since 1.42; instead, you can use: |
1820 | * $services = MediaWikiServices::getInstance(); |
1821 | * $dbr = $services->getConnectionProvider()->getReplicaDatabase(); |
1822 | * $dbw = $services->getConnectionProvider()->getPrimaryDatabase(); |
1823 | * |
1824 | * … or, in rare circumstances, you may need to use: |
1825 | * |
1826 | * $services->getDBLoadBalancer()->getConnection() / getMaintenanceConnectionRef() |
1827 | * |
1828 | * @return \Wikimedia\Rdbms\DBConnRef |
1829 | */ |
1830 | function wfGetDB( $db, $groups = [], $wiki = false ) { |
1831 | wfDeprecated( __FUNCTION__, '1.39' ); |
1832 | |
1833 | if ( $wiki === false ) { |
1834 | return MediaWikiServices::getInstance() |
1835 | ->getDBLoadBalancer() |
1836 | ->getMaintenanceConnectionRef( $db, $groups, $wiki ); |
1837 | } else { |
1838 | return MediaWikiServices::getInstance() |
1839 | ->getDBLoadBalancerFactory() |
1840 | ->getMainLB( $wiki ) |
1841 | ->getMaintenanceConnectionRef( $db, $groups, $wiki ); |
1842 | } |
1843 | } |
1844 | |
1845 | /** |
1846 | * Get the URL path to a MediaWiki entry point. |
1847 | * |
1848 | * This is a wrapper to respect $wgScript and $wgLoadScript overrides. |
1849 | * |
1850 | * @see MW_ENTRY_POINT |
1851 | * @param string $script Name of entrypoint, without `.php` extension. |
1852 | * @return string |
1853 | */ |
1854 | function wfScript( $script = 'index' ) { |
1855 | global $wgScriptPath, $wgScript, $wgLoadScript; |
1856 | if ( $script === 'index' ) { |
1857 | return $wgScript; |
1858 | } elseif ( $script === 'load' ) { |
1859 | return $wgLoadScript; |
1860 | } else { |
1861 | return "{$wgScriptPath}/{$script}.php"; |
1862 | } |
1863 | } |
1864 | |
1865 | /** |
1866 | * Convenience function converts boolean values into "true" |
1867 | * or "false" (string) values |
1868 | * |
1869 | * @param bool $value |
1870 | * @return string |
1871 | */ |
1872 | function wfBoolToStr( $value ) { |
1873 | return $value ? 'true' : 'false'; |
1874 | } |
1875 | |
1876 | /** |
1877 | * Get a platform-independent path to the null file, e.g. /dev/null |
1878 | * |
1879 | * @return string |
1880 | */ |
1881 | function wfGetNull() { |
1882 | return wfIsWindows() ? 'NUL' : '/dev/null'; |
1883 | } |
1884 | |
1885 | /** |
1886 | * Replace all invalid characters with '-'. |
1887 | * Additional characters can be defined in $wgIllegalFileChars (see T22489). |
1888 | * By default, $wgIllegalFileChars includes ':', '/', '\'. |
1889 | * |
1890 | * @param string $name Filename to process |
1891 | * @return string |
1892 | */ |
1893 | function wfStripIllegalFilenameChars( $name ) { |
1894 | global $wgIllegalFileChars; |
1895 | $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : ''; |
1896 | $name = preg_replace( |
1897 | "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/", |
1898 | '-', |
1899 | $name |
1900 | ); |
1901 | // $wgIllegalFileChars may not include '/' and '\', so we still need to do this |
1902 | $name = wfBaseName( $name ); |
1903 | return $name; |
1904 | } |
1905 | |
1906 | /** |
1907 | * Raise PHP's memory limit (if needed). |
1908 | * |
1909 | * @internal For use by Setup.php |
1910 | * @param int $newLimit |
1911 | */ |
1912 | function wfMemoryLimit( $newLimit ) { |
1913 | $oldLimit = wfShorthandToInteger( ini_get( 'memory_limit' ) ); |
1914 | // If the INI config is already unlimited, there is nothing larger |
1915 | if ( $oldLimit != -1 ) { |
1916 | $newLimit = wfShorthandToInteger( (string)$newLimit ); |
1917 | if ( $newLimit == -1 ) { |
1918 | wfDebug( "Removing PHP's memory limit" ); |
1919 | AtEase::suppressWarnings(); |
1920 | ini_set( 'memory_limit', $newLimit ); |
1921 | AtEase::restoreWarnings(); |
1922 | } elseif ( $newLimit > $oldLimit ) { |
1923 | wfDebug( "Raising PHP's memory limit to $newLimit bytes" ); |
1924 | AtEase::suppressWarnings(); |
1925 | ini_set( 'memory_limit', $newLimit ); |
1926 | AtEase::restoreWarnings(); |
1927 | } |
1928 | } |
1929 | } |
1930 | |
1931 | /** |
1932 | * Raise the request time limit to $wgTransactionalTimeLimit |
1933 | * |
1934 | * @return int Prior time limit |
1935 | * @since 1.26 |
1936 | */ |
1937 | function wfTransactionalTimeLimit() { |
1938 | global $wgTransactionalTimeLimit; |
1939 | |
1940 | $timeout = RequestTimeout::singleton(); |
1941 | $timeLimit = $timeout->getWallTimeLimit(); |
1942 | if ( $timeLimit !== INF ) { |
1943 | // RequestTimeout library is active |
1944 | if ( $wgTransactionalTimeLimit > $timeLimit ) { |
1945 | $timeout->setWallTimeLimit( $wgTransactionalTimeLimit ); |
1946 | } |
1947 | } else { |
1948 | // Fallback case, likely $wgRequestTimeLimit === null |
1949 | $timeLimit = (int)ini_get( 'max_execution_time' ); |
1950 | // Note that CLI scripts use 0 |
1951 | if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) { |
1952 | $timeout->setWallTimeLimit( $wgTransactionalTimeLimit ); |
1953 | } |
1954 | } |
1955 | ignore_user_abort( true ); // ignore client disconnects |
1956 | |
1957 | return $timeLimit; |
1958 | } |
1959 | |
1960 | /** |
1961 | * Converts shorthand byte notation to integer form |
1962 | * |
1963 | * @param null|string $string |
1964 | * @param int $default Returned if $string is empty |
1965 | * @return int |
1966 | */ |
1967 | function wfShorthandToInteger( ?string $string = '', int $default = -1 ): int { |
1968 | $string = trim( $string ?? '' ); |
1969 | if ( $string === '' ) { |
1970 | return $default; |
1971 | } |
1972 | $last = $string[strlen( $string ) - 1]; |
1973 | $val = intval( $string ); |
1974 | switch ( $last ) { |
1975 | case 'g': |
1976 | case 'G': |
1977 | $val *= 1024; |
1978 | // break intentionally missing |
1979 | case 'm': |
1980 | case 'M': |
1981 | $val *= 1024; |
1982 | // break intentionally missing |
1983 | case 'k': |
1984 | case 'K': |
1985 | $val *= 1024; |
1986 | } |
1987 | |
1988 | return $val; |
1989 | } |
1990 | |
1991 | /** |
1992 | * Determine input string is represents as infinity |
1993 | * |
1994 | * @param string $str The string to determine |
1995 | * @return bool |
1996 | * @since 1.25 |
1997 | */ |
1998 | function wfIsInfinity( $str ) { |
1999 | // The INFINITY_VALS are hardcoded elsewhere in MediaWiki (e.g. mediawiki.special.block.js). |
2000 | return in_array( $str, ExpiryDef::INFINITY_VALS ); |
2001 | } |
2002 | |
2003 | /** |
2004 | * Returns true if these thumbnail parameters match one that MediaWiki |
2005 | * requests from file description pages and/or parser output. |
2006 | * |
2007 | * $params is considered non-standard if they involve a non-standard |
2008 | * width or any non-default parameters aside from width and page number. |
2009 | * The number of possible files with standard parameters is far less than |
2010 | * that of all combinations; rate-limiting for them can thus be more generous. |
2011 | * |
2012 | * @param File $file |
2013 | * @param array $params |
2014 | * @return bool |
2015 | * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25 |
2016 | */ |
2017 | function wfThumbIsStandard( File $file, array $params ) { |
2018 | global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages; |
2019 | |
2020 | $multipliers = [ 1 ]; |
2021 | if ( $wgResponsiveImages ) { |
2022 | // These available sizes are hardcoded currently elsewhere in MediaWiki. |
2023 | // @see Linker::processResponsiveImages |
2024 | $multipliers[] = 1.5; |
2025 | $multipliers[] = 2; |
2026 | } |
2027 | |
2028 | $handler = $file->getHandler(); |
2029 | if ( !$handler || !isset( $params['width'] ) ) { |
2030 | return false; |
2031 | } |
2032 | |
2033 | $basicParams = []; |
2034 | if ( isset( $params['page'] ) ) { |
2035 | $basicParams['page'] = $params['page']; |
2036 | } |
2037 | |
2038 | $thumbLimits = []; |
2039 | $imageLimits = []; |
2040 | // Expand limits to account for multipliers |
2041 | foreach ( $multipliers as $multiplier ) { |
2042 | $thumbLimits = array_merge( $thumbLimits, array_map( |
2043 | static function ( $width ) use ( $multiplier ) { |
2044 | return round( $width * $multiplier ); |
2045 | }, $wgThumbLimits ) |
2046 | ); |
2047 | $imageLimits = array_merge( $imageLimits, array_map( |
2048 | static function ( $pair ) use ( $multiplier ) { |
2049 | return [ |
2050 | round( $pair[0] * $multiplier ), |
2051 | round( $pair[1] * $multiplier ), |
2052 | ]; |
2053 | }, $wgImageLimits ) |
2054 | ); |
2055 | } |
2056 | |
2057 | // Check if the width matches one of $wgThumbLimits |
2058 | if ( in_array( $params['width'], $thumbLimits ) ) { |
2059 | $normalParams = $basicParams + [ 'width' => $params['width'] ]; |
2060 | // Append any default values to the map (e.g. "lossy", "lossless", ...) |
2061 | $handler->normaliseParams( $file, $normalParams ); |
2062 | } else { |
2063 | // If not, then check if the width matches one of $wgImageLimits |
2064 | $match = false; |
2065 | foreach ( $imageLimits as $pair ) { |
2066 | $normalParams = $basicParams + [ 'width' => $pair[0], 'height' => $pair[1] ]; |
2067 | // Decide whether the thumbnail should be scaled on width or height. |
2068 | // Also append any default values to the map (e.g. "lossy", "lossless", ...) |
2069 | $handler->normaliseParams( $file, $normalParams ); |
2070 | // Check if this standard thumbnail size maps to the given width |
2071 | if ( $normalParams['width'] == $params['width'] ) { |
2072 | $match = true; |
2073 | break; |
2074 | } |
2075 | } |
2076 | if ( !$match ) { |
2077 | return false; // not standard for description pages |
2078 | } |
2079 | } |
2080 | |
2081 | // Check that the given values for non-page, non-width, params are just defaults |
2082 | foreach ( $params as $key => $value ) { |
2083 | if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) { |
2084 | return false; |
2085 | } |
2086 | } |
2087 | |
2088 | return true; |
2089 | } |
2090 | |
2091 | /** |
2092 | * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray). |
2093 | * |
2094 | * Values that exist in both values will be combined with += (all values of the array |
2095 | * of $newValues will be added to the values of the array of $baseArray, while values, |
2096 | * that exists in both, the value of $baseArray will be used). |
2097 | * |
2098 | * @param array $baseArray The array where you want to add the values of $newValues to |
2099 | * @param array $newValues An array with new values |
2100 | * @return array The combined array |
2101 | * @since 1.26 |
2102 | */ |
2103 | function wfArrayPlus2d( array $baseArray, array $newValues ) { |
2104 | // First merge items that are in both arrays |
2105 | foreach ( $baseArray as $name => &$groupVal ) { |
2106 | if ( isset( $newValues[$name] ) ) { |
2107 | $groupVal += $newValues[$name]; |
2108 | } |
2109 | } |
2110 | // Now add items that didn't exist yet |
2111 | $baseArray += $newValues; |
2112 | |
2113 | return $baseArray; |
2114 | } |