Debian Codegraph @

includes/GlobalFunctions.php

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