3 * Global functions used everywhere.
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.
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.
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
23 if ( !defined( 'MEDIAWIKI' ) ) {
24 die( "This file is part of MediaWiki, it is not a valid entry point" );
27 use Liuggio\StatsdClient\Sender\SocketSender
;
28 use MediaWiki\Logger\LoggerFactory
;
29 use MediaWiki\Session\SessionManager
;
30 use MediaWiki\MediaWikiServices
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Rdbms\DBReplicationWaitError
;
34 // Hide compatibility functions from Doxygen
37 * Compatibility functions
39 * We support PHP 5.5.9 and up.
40 * Re-implementations of newer functions or functions in non-standard
41 * PHP extensions may be included here.
44 // hash_equals function only exists in PHP >= 5.6.0
45 // https://secure.php.net/hash_equals
46 if ( !function_exists( 'hash_equals' ) ) {
48 * Check whether a user-provided string is equal to a fixed-length secret string
49 * without revealing bytes of the secret string through timing differences.
51 * The usual way to compare strings (PHP's === operator or the underlying memcmp()
52 * function in C) is to compare corresponding bytes and stop at the first difference,
53 * which would take longer for a partial match than for a complete mismatch. This
54 * is not secure when one of the strings (e.g. an HMAC or token) must remain secret
55 * and the other may come from an attacker. Statistical analysis of timing measurements
56 * over many requests may allow the attacker to guess the string's bytes one at a time
57 * (and check his guesses) even if the timing differences are extremely small.
59 * When making such a security-sensitive comparison, it is essential that the sequence
60 * in which instructions are executed and memory locations are accessed not depend on
61 * the secret string's value. HOWEVER, for simplicity, we do not attempt to minimize
62 * the inevitable leakage of the string's length. That is generally known anyway as
63 * a chararacteristic of the hash function used to compute the secret value.
65 * Longer explanation: http://www.emerose.com/timing-attacks-explained
68 * @param string $known_string Fixed-length secret string to compare against
69 * @param string $user_string User-provided string
70 * @return bool True if the strings are the same, false otherwise
72 function hash_equals( $known_string, $user_string ) {
73 // Strict type checking as in PHP's native implementation
74 if ( !is_string( $known_string ) ) {
75 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
76 gettype( $known_string ) . ' given', E_USER_WARNING
);
81 if ( !is_string( $user_string ) ) {
82 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
83 gettype( $user_string ) . ' given', E_USER_WARNING
);
88 $known_string_len = strlen( $known_string );
89 if ( $known_string_len !== strlen( $user_string ) ) {
94 for ( $i = 0; $i < $known_string_len; $i++
) {
95 $result |
= ord( $known_string[$i] ) ^
ord( $user_string[$i] );
98 return ( $result === 0 );
106 * This queues an extension to be loaded through
107 * the ExtensionRegistry system.
109 * @param string $ext Name of the extension to load
110 * @param string|null $path Absolute path of where to find the extension.json file
113 function wfLoadExtension( $ext, $path = null ) {
115 global $wgExtensionDirectory;
116 $path = "$wgExtensionDirectory/$ext/extension.json";
118 ExtensionRegistry
::getInstance()->queue( $path );
122 * Load multiple extensions at once
124 * Same as wfLoadExtension, but more efficient if you
125 * are loading multiple extensions.
127 * If you want to specify custom paths, you should interact with
128 * ExtensionRegistry directly.
130 * @see wfLoadExtension
131 * @param string[] $exts Array of extension names to load
134 function wfLoadExtensions( array $exts ) {
135 global $wgExtensionDirectory;
136 $registry = ExtensionRegistry
::getInstance();
137 foreach ( $exts as $ext ) {
138 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
145 * @see wfLoadExtension
146 * @param string $skin Name of the extension to load
147 * @param string|null $path Absolute path of where to find the skin.json file
150 function wfLoadSkin( $skin, $path = null ) {
152 global $wgStyleDirectory;
153 $path = "$wgStyleDirectory/$skin/skin.json";
155 ExtensionRegistry
::getInstance()->queue( $path );
159 * Load multiple skins at once
161 * @see wfLoadExtensions
162 * @param string[] $skins Array of extension names to load
165 function wfLoadSkins( array $skins ) {
166 global $wgStyleDirectory;
167 $registry = ExtensionRegistry
::getInstance();
168 foreach ( $skins as $skin ) {
169 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
174 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
179 function wfArrayDiff2( $a, $b ) {
180 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
184 * @param array|string $a
185 * @param array|string $b
188 function wfArrayDiff2_cmp( $a, $b ) {
189 if ( is_string( $a ) && is_string( $b ) ) {
190 return strcmp( $a, $b );
191 } elseif ( count( $a ) !== count( $b ) ) {
192 return count( $a ) < count( $b ) ?
-1 : 1;
196 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
197 $cmp = strcmp( $valueA, $valueB );
207 * Like array_filter with ARRAY_FILTER_USE_BOTH, but works pre-5.6.
210 * @param callable $callback Will be called with the array value and key (in that order) and
211 * should return a bool which will determine whether the array element is kept.
214 function wfArrayFilter( array $arr, callable
$callback ) {
215 if ( defined( 'ARRAY_FILTER_USE_BOTH' ) ) {
216 return array_filter( $arr, $callback, ARRAY_FILTER_USE_BOTH
);
218 $filteredKeys = array_filter( array_keys( $arr ), function ( $key ) use ( $arr, $callback ) {
219 return call_user_func( $callback, $arr[$key], $key );
221 return array_intersect_key( $arr, array_fill_keys( $filteredKeys, true ) );
225 * Like array_filter with ARRAY_FILTER_USE_KEY, but works pre-5.6.
228 * @param callable $callback Will be called with the array key and should return a bool which
229 * will determine whether the array element is kept.
232 function wfArrayFilterByKey( array $arr, callable
$callback ) {
233 return wfArrayFilter( $arr, function ( $val, $key ) use ( $callback ) {
234 return call_user_func( $callback, $key );
239 * Appends to second array if $value differs from that in $default
241 * @param string|int $key
242 * @param mixed $value
243 * @param mixed $default
244 * @param array $changed Array to alter
245 * @throws MWException
247 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
248 if ( is_null( $changed ) ) {
249 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
251 if ( $default[$key] !== $value ) {
252 $changed[$key] = $value;
257 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
259 * wfMergeErrorArrays(
272 * @param array $array1,...
275 function wfMergeErrorArrays( /*...*/ ) {
276 $args = func_get_args();
278 foreach ( $args as $errors ) {
279 foreach ( $errors as $params ) {
280 $originalParams = $params;
281 if ( $params[0] instanceof MessageSpecifier
) {
283 $params = array_merge( [ $msg->getKey() ], $msg->getParams() );
285 # @todo FIXME: Sometimes get nested arrays for $params,
286 # which leads to E_NOTICEs
287 $spec = implode( "\t", $params );
288 $out[$spec] = $originalParams;
291 return array_values( $out );
295 * Insert array into another array after the specified *KEY*
297 * @param array $array The array.
298 * @param array $insert The array to insert.
299 * @param mixed $after The key to insert after
302 function wfArrayInsertAfter( array $array, array $insert, $after ) {
303 // Find the offset of the element to insert after.
304 $keys = array_keys( $array );
305 $offsetByKey = array_flip( $keys );
307 $offset = $offsetByKey[$after];
309 // Insert at the specified offset
310 $before = array_slice( $array, 0, $offset +
1, true );
311 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
313 $output = $before +
$insert +
$after;
319 * Recursively converts the parameter (an object) to an array with the same data
321 * @param object|array $objOrArray
322 * @param bool $recursive
325 function wfObjectToArray( $objOrArray, $recursive = true ) {
327 if ( is_object( $objOrArray ) ) {
328 $objOrArray = get_object_vars( $objOrArray );
330 foreach ( $objOrArray as $key => $value ) {
331 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
332 $value = wfObjectToArray( $value );
335 $array[$key] = $value;
342 * Get a random decimal value between 0 and 1, in a way
343 * not likely to give duplicate values for any realistic
344 * number of articles.
346 * @note This is designed for use in relation to Special:RandomPage
347 * and the page_random database field.
351 function wfRandom() {
352 // The maximum random value is "only" 2^31-1, so get two random
353 // values to reduce the chance of dupes
354 $max = mt_getrandmax() +
1;
355 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
360 * Get a random string containing a number of pseudo-random hex characters.
362 * @note This is not secure, if you are trying to generate some sort
363 * of token please use MWCryptRand instead.
365 * @param int $length The length of the string to generate
369 function wfRandomString( $length = 32 ) {
371 for ( $n = 0; $n < $length; $n +
= 7 ) {
372 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
374 return substr( $str, 0, $length );
378 * We want some things to be included as literal characters in our title URLs
379 * for prettiness, which urlencode encodes by default. According to RFC 1738,
380 * all of the following should be safe:
384 * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved
385 * character which should not be encoded. More importantly, google chrome
386 * always converts %7E back to ~, and converting it in this function can
387 * cause a redirect loop (T105265).
389 * But + is not safe because it's used to indicate a space; &= are only safe in
390 * paths and not in queries (and we don't distinguish here); ' seems kind of
391 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
392 * is reserved, we don't care. So the list we unescape is:
396 * However, IIS7 redirects fail when the url contains a colon (see T24709),
397 * so no fancy : for IIS7.
399 * %2F in the page titles seems to fatally break for some reason.
404 function wfUrlencode( $s ) {
407 if ( is_null( $s ) ) {
412 if ( is_null( $needle ) ) {
413 $needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
414 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
415 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
421 $s = urlencode( $s );
424 [ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
432 * This function takes one or two arrays as input, and returns a CGI-style string, e.g.
433 * "days=7&limit=100". Options in the first array override options in the second.
434 * Options set to null or false will not be output.
436 * @param array $array1 ( String|Array )
437 * @param array|null $array2 ( String|Array )
438 * @param string $prefix
441 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
442 if ( !is_null( $array2 ) ) {
443 $array1 = $array1 +
$array2;
447 foreach ( $array1 as $key => $value ) {
448 if ( !is_null( $value ) && $value !== false ) {
452 if ( $prefix !== '' ) {
453 $key = $prefix . "[$key]";
455 if ( is_array( $value ) ) {
457 foreach ( $value as $k => $v ) {
458 $cgi .= $firstTime ?
'' : '&';
459 if ( is_array( $v ) ) {
460 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
462 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
467 if ( is_object( $value ) ) {
468 $value = $value->__toString();
470 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
478 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
479 * its argument and returns the same string in array form. This allows compatibility
480 * with legacy functions that accept raw query strings instead of nice
481 * arrays. Of course, keys and values are urldecode()d.
483 * @param string $query Query string
484 * @return string[] Array version of input
486 function wfCgiToArray( $query ) {
487 if ( isset( $query[0] ) && $query[0] == '?' ) {
488 $query = substr( $query, 1 );
490 $bits = explode( '&', $query );
492 foreach ( $bits as $bit ) {
496 if ( strpos( $bit, '=' ) === false ) {
497 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
501 list( $key, $value ) = explode( '=', $bit );
503 $key = urldecode( $key );
504 $value = urldecode( $value );
505 if ( strpos( $key, '[' ) !== false ) {
506 $keys = array_reverse( explode( '[', $key ) );
507 $key = array_pop( $keys );
509 foreach ( $keys as $k ) {
510 $k = substr( $k, 0, -1 );
511 $temp = [ $k => $temp ];
513 if ( isset( $ret[$key] ) ) {
514 $ret[$key] = array_merge( $ret[$key], $temp );
526 * Append a query string to an existing URL, which may or may not already
527 * have query string parameters already. If so, they will be combined.
530 * @param string|string[] $query String or associative array
533 function wfAppendQuery( $url, $query ) {
534 if ( is_array( $query ) ) {
535 $query = wfArrayToCgi( $query );
537 if ( $query != '' ) {
538 // Remove the fragment, if there is one
540 $hashPos = strpos( $url, '#' );
541 if ( $hashPos !== false ) {
542 $fragment = substr( $url, $hashPos );
543 $url = substr( $url, 0, $hashPos );
547 if ( false === strpos( $url, '?' ) ) {
554 // Put the fragment back
555 if ( $fragment !== false ) {
563 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
566 * The meaning of the PROTO_* constants is as follows:
567 * PROTO_HTTP: Output a URL starting with http://
568 * PROTO_HTTPS: Output a URL starting with https://
569 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
570 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
571 * on which protocol was used for the current incoming request
572 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
573 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
574 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
576 * @todo this won't work with current-path-relative URLs
577 * like "subdir/foo.html", etc.
579 * @param string $url Either fully-qualified or a local path + query
580 * @param string $defaultProto One of the PROTO_* constants. Determines the
581 * protocol to use if $url or $wgServer is protocol-relative
582 * @return string|false Fully-qualified URL, current-path-relative URL or false if
583 * no valid URL can be constructed
585 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
586 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
588 if ( $defaultProto === PROTO_CANONICAL
) {
589 $serverUrl = $wgCanonicalServer;
590 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
591 // Make $wgInternalServer fall back to $wgServer if not set
592 $serverUrl = $wgInternalServer;
594 $serverUrl = $wgServer;
595 if ( $defaultProto === PROTO_CURRENT
) {
596 $defaultProto = $wgRequest->getProtocol() . '://';
600 // Analyze $serverUrl to obtain its protocol
601 $bits = wfParseUrl( $serverUrl );
602 $serverHasProto = $bits && $bits['scheme'] != '';
604 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
605 if ( $serverHasProto ) {
606 $defaultProto = $bits['scheme'] . '://';
608 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
609 // This really isn't supposed to happen. Fall back to HTTP in this
611 $defaultProto = PROTO_HTTP
;
615 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
617 if ( substr( $url, 0, 2 ) == '//' ) {
618 $url = $defaultProtoWithoutSlashes . $url;
619 } elseif ( substr( $url, 0, 1 ) == '/' ) {
620 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
621 // otherwise leave it alone.
622 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
625 $bits = wfParseUrl( $url );
627 // ensure proper port for HTTPS arrives in URL
628 // https://phabricator.wikimedia.org/T67184
629 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
630 $bits['port'] = $wgHttpsPort;
633 if ( $bits && isset( $bits['path'] ) ) {
634 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
635 return wfAssembleUrl( $bits );
639 } elseif ( substr( $url, 0, 1 ) != '/' ) {
640 # URL is a relative path
641 return wfRemoveDotSegments( $url );
644 # Expanded URL is not valid.
649 * This function will reassemble a URL parsed with wfParseURL. This is useful
650 * if you need to edit part of a URL and put it back together.
652 * This is the basic structure used (brackets contain keys for $urlParts):
653 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
655 * @todo Need to integrate this into wfExpandUrl (see T34168)
658 * @param array $urlParts URL parts, as output from wfParseUrl
659 * @return string URL assembled from its component parts
661 function wfAssembleUrl( $urlParts ) {
664 if ( isset( $urlParts['delimiter'] ) ) {
665 if ( isset( $urlParts['scheme'] ) ) {
666 $result .= $urlParts['scheme'];
669 $result .= $urlParts['delimiter'];
672 if ( isset( $urlParts['host'] ) ) {
673 if ( isset( $urlParts['user'] ) ) {
674 $result .= $urlParts['user'];
675 if ( isset( $urlParts['pass'] ) ) {
676 $result .= ':' . $urlParts['pass'];
681 $result .= $urlParts['host'];
683 if ( isset( $urlParts['port'] ) ) {
684 $result .= ':' . $urlParts['port'];
688 if ( isset( $urlParts['path'] ) ) {
689 $result .= $urlParts['path'];
692 if ( isset( $urlParts['query'] ) ) {
693 $result .= '?' . $urlParts['query'];
696 if ( isset( $urlParts['fragment'] ) ) {
697 $result .= '#' . $urlParts['fragment'];
704 * Remove all dot-segments in the provided URL path. For example,
705 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
706 * RFC3986 section 5.2.4.
708 * @todo Need to integrate this into wfExpandUrl (see T34168)
710 * @param string $urlPath URL path, potentially containing dot-segments
711 * @return string URL path with all dot-segments removed
713 function wfRemoveDotSegments( $urlPath ) {
716 $inputLength = strlen( $urlPath );
718 while ( $inputOffset < $inputLength ) {
719 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
720 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
721 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
722 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
725 if ( $prefixLengthTwo == './' ) {
726 # Step A, remove leading "./"
728 } elseif ( $prefixLengthThree == '../' ) {
729 # Step A, remove leading "../"
731 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
732 # Step B, replace leading "/.$" with "/"
734 $urlPath[$inputOffset] = '/';
735 } elseif ( $prefixLengthThree == '/./' ) {
736 # Step B, replace leading "/./" with "/"
738 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
739 # Step C, replace leading "/..$" with "/" and
740 # remove last path component in output
742 $urlPath[$inputOffset] = '/';
744 } elseif ( $prefixLengthFour == '/../' ) {
745 # Step C, replace leading "/../" with "/" and
746 # remove last path component in output
749 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
750 # Step D, remove "^.$"
752 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
753 # Step D, remove "^..$"
756 # Step E, move leading path segment to output
757 if ( $prefixLengthOne == '/' ) {
758 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
760 $slashPos = strpos( $urlPath, '/', $inputOffset );
762 if ( $slashPos === false ) {
763 $output .= substr( $urlPath, $inputOffset );
764 $inputOffset = $inputLength;
766 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
767 $inputOffset +
= $slashPos - $inputOffset;
772 $slashPos = strrpos( $output, '/' );
773 if ( $slashPos === false ) {
776 $output = substr( $output, 0, $slashPos );
785 * Returns a regular expression of url protocols
787 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
788 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
791 function wfUrlProtocols( $includeProtocolRelative = true ) {
792 global $wgUrlProtocols;
794 // Cache return values separately based on $includeProtocolRelative
795 static $withProtRel = null, $withoutProtRel = null;
796 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
797 if ( !is_null( $cachedValue ) ) {
801 // Support old-style $wgUrlProtocols strings, for backwards compatibility
802 // with LocalSettings files from 1.5
803 if ( is_array( $wgUrlProtocols ) ) {
805 foreach ( $wgUrlProtocols as $protocol ) {
806 // Filter out '//' if !$includeProtocolRelative
807 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
808 $protocols[] = preg_quote( $protocol, '/' );
812 $retval = implode( '|', $protocols );
814 // Ignore $includeProtocolRelative in this case
815 // This case exists for pre-1.6 compatibility, and we can safely assume
816 // that '//' won't appear in a pre-1.6 config because protocol-relative
817 // URLs weren't supported until 1.18
818 $retval = $wgUrlProtocols;
821 // Cache return value
822 if ( $includeProtocolRelative ) {
823 $withProtRel = $retval;
825 $withoutProtRel = $retval;
831 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
832 * you need a regex that matches all URL protocols but does not match protocol-
836 function wfUrlProtocolsWithoutProtRel() {
837 return wfUrlProtocols( false );
841 * parse_url() work-alike, but non-broken. Differences:
843 * 1) Does not raise warnings on bad URLs (just returns false).
844 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
845 * protocol-relative URLs) correctly.
846 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
848 * @param string $url A URL to parse
849 * @return string[]|bool Bits of the URL in an associative array, per PHP docs, false on failure
851 function wfParseUrl( $url ) {
852 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
854 // Protocol-relative URLs are handled really badly by parse_url(). It's so
855 // bad that the easiest way to handle them is to just prepend 'http:' and
856 // strip the protocol out later.
857 $wasRelative = substr( $url, 0, 2 ) == '//';
858 if ( $wasRelative ) {
861 MediaWiki\
suppressWarnings();
862 $bits = parse_url( $url );
863 MediaWiki\restoreWarnings
();
864 // parse_url() returns an array without scheme for some invalid URLs, e.g.
865 // parse_url("%0Ahttp://example.com") == [ 'host' => '%0Ahttp', 'path' => 'example.com' ]
866 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
870 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
871 $bits['scheme'] = strtolower( $bits['scheme'] );
873 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
874 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
875 $bits['delimiter'] = '://';
876 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
877 $bits['delimiter'] = ':';
878 // parse_url detects for news: and mailto: the host part of an url as path
879 // We have to correct this wrong detection
880 if ( isset( $bits['path'] ) ) {
881 $bits['host'] = $bits['path'];
888 /* Provide an empty host for eg. file:/// urls (see T30627) */
889 if ( !isset( $bits['host'] ) ) {
893 if ( isset( $bits['path'] ) ) {
894 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
895 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
896 $bits['path'] = '/' . $bits['path'];
903 // If the URL was protocol-relative, fix scheme and delimiter
904 if ( $wasRelative ) {
905 $bits['scheme'] = '';
906 $bits['delimiter'] = '//';
912 * Take a URL, make sure it's expanded to fully qualified, and replace any
913 * encoded non-ASCII Unicode characters with their UTF-8 original forms
914 * for more compact display and legibility for local audiences.
916 * @todo handle punycode domains too
921 function wfExpandIRI( $url ) {
922 return preg_replace_callback(
923 '/((?:%[89A-F][0-9A-F])+)/i',
924 'wfExpandIRI_callback',
930 * Private callback for wfExpandIRI
931 * @param array $matches
934 function wfExpandIRI_callback( $matches ) {
935 return urldecode( $matches[1] );
939 * Make URL indexes, appropriate for the el_index field of externallinks.
944 function wfMakeUrlIndexes( $url ) {
945 $bits = wfParseUrl( $url );
947 // Reverse the labels in the hostname, convert to lower case
948 // For emails reverse domainpart only
949 if ( $bits['scheme'] == 'mailto' ) {
950 $mailparts = explode( '@', $bits['host'], 2 );
951 if ( count( $mailparts ) === 2 ) {
952 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
954 // No domain specified, don't mangle it
957 $reversedHost = $domainpart . '@' . $mailparts[0];
959 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
961 // Add an extra dot to the end
962 // Why? Is it in wrong place in mailto links?
963 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
964 $reversedHost .= '.';
966 // Reconstruct the pseudo-URL
967 $prot = $bits['scheme'];
968 $index = $prot . $bits['delimiter'] . $reversedHost;
969 // Leave out user and password. Add the port, path, query and fragment
970 if ( isset( $bits['port'] ) ) {
971 $index .= ':' . $bits['port'];
973 if ( isset( $bits['path'] ) ) {
974 $index .= $bits['path'];
978 if ( isset( $bits['query'] ) ) {
979 $index .= '?' . $bits['query'];
981 if ( isset( $bits['fragment'] ) ) {
982 $index .= '#' . $bits['fragment'];
986 return [ "http:$index", "https:$index" ];
993 * Check whether a given URL has a domain that occurs in a given set of domains
994 * @param string $url URL
995 * @param array $domains Array of domains (strings)
996 * @return bool True if the host part of $url ends in one of the strings in $domains
998 function wfMatchesDomainList( $url, $domains ) {
999 $bits = wfParseUrl( $url );
1000 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1001 $host = '.' . $bits['host'];
1002 foreach ( (array)$domains as $domain ) {
1003 $domain = '.' . $domain;
1004 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
1013 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
1014 * In normal operation this is a NOP.
1016 * Controlling globals:
1017 * $wgDebugLogFile - points to the log file
1018 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
1019 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
1021 * @since 1.25 support for additional context data
1023 * @param string $text
1024 * @param string|bool $dest Destination of the message:
1025 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1026 * - 'private': excluded from HTML output
1027 * For backward compatibility, it can also take a boolean:
1028 * - true: same as 'all'
1029 * - false: same as 'private'
1030 * @param array $context Additional logging context data
1032 function wfDebug( $text, $dest = 'all', array $context = [] ) {
1033 global $wgDebugRawPage, $wgDebugLogPrefix;
1034 global $wgDebugTimestamps, $wgRequestTime;
1036 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1040 $text = trim( $text );
1042 if ( $wgDebugTimestamps ) {
1043 $context['seconds_elapsed'] = sprintf(
1045 microtime( true ) - $wgRequestTime
1047 $context['memory_used'] = sprintf(
1049 ( memory_get_usage( true ) / ( 1024 * 1024 ) )
1053 if ( $wgDebugLogPrefix !== '' ) {
1054 $context['prefix'] = $wgDebugLogPrefix;
1056 $context['private'] = ( $dest === false ||
$dest === 'private' );
1058 $logger = LoggerFactory
::getInstance( 'wfDebug' );
1059 $logger->debug( $text, $context );
1063 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1066 function wfIsDebugRawPage() {
1068 if ( $cache !== null ) {
1071 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1072 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1074 isset( $_SERVER['SCRIPT_NAME'] )
1075 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1086 * Send a line giving PHP memory usage.
1088 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1090 function wfDebugMem( $exact = false ) {
1091 $mem = memory_get_usage();
1093 $mem = floor( $mem / 1024 ) . ' KiB';
1097 wfDebug( "Memory usage: $mem\n" );
1101 * Send a line to a supplementary debug log file, if configured, or main debug
1104 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
1105 * a string filename or an associative array mapping 'destination' to the
1106 * desired filename. The associative array may also contain a 'sample' key
1107 * with an integer value, specifying a sampling factor. Sampled log events
1108 * will be emitted with a 1 in N random chance.
1110 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1111 * @since 1.25 support for additional context data
1112 * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
1114 * @param string $logGroup
1115 * @param string $text
1116 * @param string|bool $dest Destination of the message:
1117 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1118 * - 'private': only to the specific log if set in $wgDebugLogGroups and
1119 * discarded otherwise
1120 * For backward compatibility, it can also take a boolean:
1121 * - true: same as 'all'
1122 * - false: same as 'private'
1123 * @param array $context Additional logging context data
1125 function wfDebugLog(
1126 $logGroup, $text, $dest = 'all', array $context = []
1128 $text = trim( $text );
1130 $logger = LoggerFactory
::getInstance( $logGroup );
1131 $context['private'] = ( $dest === false ||
$dest === 'private' );
1132 $logger->info( $text, $context );
1136 * Log for database errors
1138 * @since 1.25 support for additional context data
1140 * @param string $text Database error message.
1141 * @param array $context Additional logging context data
1143 function wfLogDBError( $text, array $context = [] ) {
1144 $logger = LoggerFactory
::getInstance( 'wfLogDBError' );
1145 $logger->error( trim( $text ), $context );
1149 * Throws a warning that $function is deprecated
1151 * @param string $function
1152 * @param string|bool $version Version of MediaWiki that the function
1153 * was deprecated in (Added in 1.19).
1154 * @param string|bool $component Added in 1.19.
1155 * @param int $callerOffset How far up the call stack is the original
1156 * caller. 2 = function that called the function that called
1157 * wfDeprecated (Added in 1.20)
1161 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1162 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1166 * Send a warning either to the debug log or in a PHP error depending on
1167 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1169 * @param string $msg Message to send
1170 * @param int $callerOffset Number of items to go back in the backtrace to
1171 * find the correct caller (1 = function calling wfWarn, ...)
1172 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1173 * only used when $wgDevelopmentWarnings is true
1175 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1176 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1180 * Send a warning as a PHP error and the debug log. This is intended for logging
1181 * warnings in production. For logging development warnings, use WfWarn instead.
1183 * @param string $msg Message to send
1184 * @param int $callerOffset Number of items to go back in the backtrace to
1185 * find the correct caller (1 = function calling wfLogWarning, ...)
1186 * @param int $level PHP error level; defaults to E_USER_WARNING
1188 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1189 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1193 * Log to a file without getting "file size exceeded" signals.
1195 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1196 * send lines to the specified port, prefixed by the specified prefix and a space.
1197 * @since 1.25 support for additional context data
1199 * @param string $text
1200 * @param string $file Filename
1201 * @param array $context Additional logging context data
1202 * @throws MWException
1203 * @deprecated since 1.25 Use \MediaWiki\Logger\LegacyLogger::emit or UDPTransport
1205 function wfErrorLog( $text, $file, array $context = [] ) {
1206 wfDeprecated( __METHOD__
, '1.25' );
1207 $logger = LoggerFactory
::getInstance( 'wfErrorLog' );
1208 $context['destination'] = $file;
1209 $logger->info( trim( $text ), $context );
1215 function wfLogProfilingData() {
1216 global $wgDebugLogGroups, $wgDebugRawPage;
1218 $context = RequestContext
::getMain();
1219 $request = $context->getRequest();
1221 $profiler = Profiler
::instance();
1222 $profiler->setContext( $context );
1223 $profiler->logData();
1225 $config = $context->getConfig();
1226 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1227 if ( $config->get( 'StatsdServer' ) && $stats->hasData() ) {
1229 $statsdServer = explode( ':', $config->get( 'StatsdServer' ) );
1230 $statsdHost = $statsdServer[0];
1231 $statsdPort = isset( $statsdServer[1] ) ?
$statsdServer[1] : 8125;
1232 $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1233 $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
1234 $statsdClient->setSamplingRates( $config->get( 'StatsdSamplingRates' ) );
1235 $statsdClient->send( $stats->getData() );
1236 } catch ( Exception
$ex ) {
1237 MWExceptionHandler
::logException( $ex );
1241 # Profiling must actually be enabled...
1242 if ( $profiler instanceof ProfilerStub
) {
1246 if ( isset( $wgDebugLogGroups['profileoutput'] )
1247 && $wgDebugLogGroups['profileoutput'] === false
1249 // Explicitly disabled
1252 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1256 $ctx = [ 'elapsed' => $request->getElapsedTime() ];
1257 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1258 $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
1260 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1261 $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP'];
1263 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1264 $ctx['from'] = $_SERVER['HTTP_FROM'];
1266 if ( isset( $ctx['forwarded_for'] ) ||
1267 isset( $ctx['client_ip'] ) ||
1268 isset( $ctx['from'] ) ) {
1269 $ctx['proxy'] = $_SERVER['REMOTE_ADDR'];
1272 // Don't load $wgUser at this late stage just for statistics purposes
1273 // @todo FIXME: We can detect some anons even if it is not loaded.
1274 // See User::getId()
1275 $user = $context->getUser();
1276 $ctx['anon'] = $user->isItemLoaded( 'id' ) && $user->isAnon();
1278 // Command line script uses a FauxRequest object which does not have
1279 // any knowledge about an URL and throw an exception instead.
1281 $ctx['url'] = urldecode( $request->getRequestURL() );
1282 } catch ( Exception
$ignored ) {
1286 $ctx['output'] = $profiler->getOutput();
1288 $log = LoggerFactory
::getInstance( 'profileoutput' );
1289 $log->info( "Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx );
1293 * Increment a statistics counter
1295 * @param string $key
1299 function wfIncrStats( $key, $count = 1 ) {
1300 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1301 $stats->updateCount( $key, $count );
1305 * Check whether the wiki is in read-only mode.
1309 function wfReadOnly() {
1310 return MediaWikiServices
::getInstance()->getReadOnlyMode()
1315 * Check if the site is in read-only mode and return the message if so
1317 * This checks wfConfiguredReadOnlyReason() and the main load balancer
1318 * for replica DB lag. This may result in DB connection being made.
1320 * @return string|bool String when in read-only mode; false otherwise
1322 function wfReadOnlyReason() {
1323 return MediaWikiServices
::getInstance()->getReadOnlyMode()
1328 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1330 * @return string|bool String when in read-only mode; false otherwise
1333 function wfConfiguredReadOnlyReason() {
1334 return MediaWikiServices
::getInstance()->getConfiguredReadOnlyMode()
1339 * Return a Language object from $langcode
1341 * @param Language|string|bool $langcode Either:
1342 * - a Language object
1343 * - code of the language to get the message for, if it is
1344 * a valid code create a language for that language, if
1345 * it is a string but not a valid code then make a basic
1347 * - a boolean: if it's false then use the global object for
1348 * the current user's language (as a fallback for the old parameter
1349 * functionality), or if it is true then use global object
1350 * for the wiki's content language.
1353 function wfGetLangObj( $langcode = false ) {
1354 # Identify which language to get or create a language object for.
1355 # Using is_object here due to Stub objects.
1356 if ( is_object( $langcode ) ) {
1357 # Great, we already have the object (hopefully)!
1361 global $wgContLang, $wgLanguageCode;
1362 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1363 # $langcode is the language code of the wikis content language object.
1364 # or it is a boolean and value is true
1369 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1370 # $langcode is the language code of user language object.
1371 # or it was a boolean and value is false
1375 $validCodes = array_keys( Language
::fetchLanguageNames() );
1376 if ( in_array( $langcode, $validCodes ) ) {
1377 # $langcode corresponds to a valid language.
1378 return Language
::factory( $langcode );
1381 # $langcode is a string, but not a valid language code; use content language.
1382 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1387 * This is the function for getting translated interface messages.
1389 * @see Message class for documentation how to use them.
1390 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1392 * This function replaces all old wfMsg* functions.
1394 * @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier
1395 * @param mixed $params,... Normal message parameters
1400 * @see Message::__construct
1402 function wfMessage( $key /*...*/ ) {
1403 $message = new Message( $key );
1405 // We call Message::params() to reduce code duplication
1406 $params = func_get_args();
1407 array_shift( $params );
1409 call_user_func_array( [ $message, 'params' ], $params );
1416 * This function accepts multiple message keys and returns a message instance
1417 * for the first message which is non-empty. If all messages are empty then an
1418 * instance of the first message key is returned.
1420 * @param string|string[] $keys,... Message keys
1425 * @see Message::newFallbackSequence
1427 function wfMessageFallback( /*...*/ ) {
1428 $args = func_get_args();
1429 return call_user_func_array( 'Message::newFallbackSequence', $args );
1433 * Replace message parameter keys on the given formatted output.
1435 * @param string $message
1436 * @param array $args
1440 function wfMsgReplaceArgs( $message, $args ) {
1441 # Fix windows line-endings
1442 # Some messages are split with explode("\n", $msg)
1443 $message = str_replace( "\r", '', $message );
1445 // Replace arguments
1446 if ( is_array( $args ) && $args ) {
1447 if ( is_array( $args[0] ) ) {
1448 $args = array_values( $args[0] );
1450 $replacementKeys = [];
1451 foreach ( $args as $n => $param ) {
1452 $replacementKeys['$' . ( $n +
1 )] = $param;
1454 $message = strtr( $message, $replacementKeys );
1461 * Fetch server name for use in error reporting etc.
1462 * Use real server name if available, so we know which machine
1463 * in a server farm generated the current page.
1467 function wfHostname() {
1469 if ( is_null( $host ) ) {
1470 # Hostname overriding
1471 global $wgOverrideHostname;
1472 if ( $wgOverrideHostname !== false ) {
1473 # Set static and skip any detection
1474 $host = $wgOverrideHostname;
1478 if ( function_exists( 'posix_uname' ) ) {
1479 // This function not present on Windows
1480 $uname = posix_uname();
1484 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1485 $host = $uname['nodename'];
1486 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1487 # Windows computer name
1488 $host = getenv( 'COMPUTERNAME' );
1490 # This may be a virtual server.
1491 $host = $_SERVER['SERVER_NAME'];
1498 * Returns a script tag that stores the amount of time it took MediaWiki to
1499 * handle the request in milliseconds as 'wgBackendResponseTime'.
1501 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1502 * hostname of the server handling the request.
1506 function wfReportTime() {
1507 global $wgRequestTime, $wgShowHostnames;
1509 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1510 $reportVars = [ 'wgBackendResponseTime' => $responseTime ];
1511 if ( $wgShowHostnames ) {
1512 $reportVars['wgHostname'] = wfHostname();
1514 return Skin
::makeVariablesScript( $reportVars );
1518 * Safety wrapper for debug_backtrace().
1520 * Will return an empty array if debug_backtrace is disabled, otherwise
1521 * the output from debug_backtrace() (trimmed).
1523 * @param int $limit This parameter can be used to limit the number of stack frames returned
1525 * @return array Array of backtrace information
1527 function wfDebugBacktrace( $limit = 0 ) {
1528 static $disabled = null;
1530 if ( is_null( $disabled ) ) {
1531 $disabled = !function_exists( 'debug_backtrace' );
1533 wfDebug( "debug_backtrace() is disabled\n" );
1541 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1543 return array_slice( debug_backtrace(), 1 );
1548 * Get a debug backtrace as a string
1550 * @param bool|null $raw If true, the return value is plain text. If false, HTML.
1551 * Defaults to $wgCommandLineMode if unset.
1553 * @since 1.25 Supports $raw parameter.
1555 function wfBacktrace( $raw = null ) {
1556 global $wgCommandLineMode;
1558 if ( $raw === null ) {
1559 $raw = $wgCommandLineMode;
1563 $frameFormat = "%s line %s calls %s()\n";
1564 $traceFormat = "%s";
1566 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1567 $traceFormat = "<ul>\n%s</ul>\n";
1570 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1571 $file = !empty( $frame['file'] ) ?
basename( $frame['file'] ) : '-';
1572 $line = isset( $frame['line'] ) ?
$frame['line'] : '-';
1573 $call = $frame['function'];
1574 if ( !empty( $frame['class'] ) ) {
1575 $call = $frame['class'] . $frame['type'] . $call;
1577 return sprintf( $frameFormat, $file, $line, $call );
1578 }, wfDebugBacktrace() );
1580 return sprintf( $traceFormat, implode( '', $frames ) );
1584 * Get the name of the function which called this function
1585 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1586 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1587 * wfGetCaller( 3 ) is the parent of that.
1592 function wfGetCaller( $level = 2 ) {
1593 $backtrace = wfDebugBacktrace( $level +
1 );
1594 if ( isset( $backtrace[$level] ) ) {
1595 return wfFormatStackFrame( $backtrace[$level] );
1602 * Return a string consisting of callers in the stack. Useful sometimes
1603 * for profiling specific points.
1605 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1608 function wfGetAllCallers( $limit = 3 ) {
1609 $trace = array_reverse( wfDebugBacktrace() );
1610 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1611 $limit = count( $trace ) - 1;
1613 $trace = array_slice( $trace, -$limit - 1, $limit );
1614 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1618 * Return a string representation of frame
1620 * @param array $frame
1623 function wfFormatStackFrame( $frame ) {
1624 if ( !isset( $frame['function'] ) ) {
1625 return 'NO_FUNCTION_GIVEN';
1627 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1628 $frame['class'] . $frame['type'] . $frame['function'] :
1632 /* Some generic result counters, pulled out of SearchEngine */
1637 * @param int $offset
1641 function wfShowingResults( $offset, $limit ) {
1642 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
1646 * Whether the client accept gzip encoding
1648 * Uses the Accept-Encoding header to check if the client supports gzip encoding.
1649 * Use this when considering to send a gzip-encoded response to the client.
1651 * @param bool $force Forces another check even if we already have a cached result.
1654 function wfClientAcceptsGzip( $force = false ) {
1655 static $result = null;
1656 if ( $result === null ||
$force ) {
1658 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1659 # @todo FIXME: We may want to blacklist some broken browsers
1662 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1663 $_SERVER['HTTP_ACCEPT_ENCODING'],
1667 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1671 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
1680 * Escapes the given text so that it may be output using addWikiText()
1681 * without any linking, formatting, etc. making its way through. This
1682 * is achieved by substituting certain characters with HTML entities.
1683 * As required by the callers, "<nowiki>" is not used.
1685 * @param string $text Text to be escaped
1688 function wfEscapeWikiText( $text ) {
1689 global $wgEnableMagicLinks;
1690 static $repl = null, $repl2 = null;
1691 if ( $repl === null ||
defined( 'MW_PARSER_TEST' ) ||
defined( 'MW_PHPUNIT_TEST' ) ) {
1692 // Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
1693 // in those situations
1695 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
1696 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
1697 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
1698 "\n#" => "\n#", "\r#" => "\r#",
1699 "\n*" => "\n*", "\r*" => "\r*",
1700 "\n:" => "\n:", "\r:" => "\r:",
1701 "\n " => "\n ", "\r " => "\r ",
1702 "\n\n" => "\n ", "\r\n" => " \n",
1703 "\n\r" => "\n ", "\r\r" => "\r ",
1704 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
1705 "\n----" => "\n----", "\r----" => "\r----",
1706 '__' => '__', '://' => '://',
1709 $magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
1710 // We have to catch everything "\s" matches in PCRE
1711 foreach ( $magicLinks as $magic ) {
1712 $repl["$magic "] = "$magic ";
1713 $repl["$magic\t"] = "$magic	";
1714 $repl["$magic\r"] = "$magic ";
1715 $repl["$magic\n"] = "$magic ";
1716 $repl["$magic\f"] = "$magic";
1719 // And handle protocols that don't use "://"
1720 global $wgUrlProtocols;
1722 foreach ( $wgUrlProtocols as $prot ) {
1723 if ( substr( $prot, -1 ) === ':' ) {
1724 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
1727 $repl2 = $repl2 ?
'/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
1729 $text = substr( strtr( "\n$text", $repl ), 1 );
1730 $text = preg_replace( $repl2, '$1:', $text );
1735 * Sets dest to source and returns the original value of dest
1736 * If source is NULL, it just returns the value, it doesn't set the variable
1737 * If force is true, it will set the value even if source is NULL
1739 * @param mixed $dest
1740 * @param mixed $source
1741 * @param bool $force
1744 function wfSetVar( &$dest, $source, $force = false ) {
1746 if ( !is_null( $source ) ||
$force ) {
1753 * As for wfSetVar except setting a bit
1757 * @param bool $state
1761 function wfSetBit( &$dest, $bit, $state = true ) {
1762 $temp = (bool)( $dest & $bit );
1763 if ( !is_null( $state ) ) {
1774 * A wrapper around the PHP function var_export().
1775 * Either print it or add it to the regular output ($wgOut).
1777 * @param mixed $var A PHP variable to dump.
1779 function wfVarDump( $var ) {
1781 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
1782 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
1785 $wgOut->addHTML( $s );
1790 * Provide a simple HTTP error.
1792 * @param int|string $code
1793 * @param string $label
1794 * @param string $desc
1796 function wfHttpError( $code, $label, $desc ) {
1798 HttpStatus
::header( $code );
1801 $wgOut->sendCacheControl();
1804 MediaWiki\HeaderCallback
::warnIfHeadersSent();
1805 header( 'Content-type: text/html; charset=utf-8' );
1806 print '<!DOCTYPE html>' .
1807 '<html><head><title>' .
1808 htmlspecialchars( $label ) .
1809 '</title></head><body><h1>' .
1810 htmlspecialchars( $label ) .
1812 nl2br( htmlspecialchars( $desc ) ) .
1813 "</p></body></html>\n";
1817 * Clear away any user-level output buffers, discarding contents.
1819 * Suitable for 'starting afresh', for instance when streaming
1820 * relatively large amounts of data without buffering, or wanting to
1821 * output image files without ob_gzhandler's compression.
1823 * The optional $resetGzipEncoding parameter controls suppression of
1824 * the Content-Encoding header sent by ob_gzhandler; by default it
1825 * is left. See comments for wfClearOutputBuffers() for why it would
1828 * Note that some PHP configuration options may add output buffer
1829 * layers which cannot be removed; these are left in place.
1831 * @param bool $resetGzipEncoding
1833 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
1834 if ( $resetGzipEncoding ) {
1835 // Suppress Content-Encoding and Content-Length
1836 // headers from 1.10+s wfOutputHandler
1837 global $wgDisableOutputCompression;
1838 $wgDisableOutputCompression = true;
1840 while ( $status = ob_get_status() ) {
1841 if ( isset( $status['flags'] ) ) {
1842 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE
;
1843 $deleteable = ( $status['flags'] & $flags ) === $flags;
1844 } elseif ( isset( $status['del'] ) ) {
1845 $deleteable = $status['del'];
1847 // Guess that any PHP-internal setting can't be removed.
1848 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
1850 if ( !$deleteable ) {
1851 // Give up, and hope the result doesn't break
1855 if ( $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ) {
1856 // Unit testing barrier to prevent this function from breaking PHPUnit.
1859 if ( !ob_end_clean() ) {
1860 // Could not remove output buffer handler; abort now
1861 // to avoid getting in some kind of infinite loop.
1864 if ( $resetGzipEncoding ) {
1865 if ( $status['name'] == 'ob_gzhandler' ) {
1866 // Reset the 'Content-Encoding' field set by this handler
1867 // so we can start fresh.
1868 header_remove( 'Content-Encoding' );
1876 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1878 * Clear away output buffers, but keep the Content-Encoding header
1879 * produced by ob_gzhandler, if any.
1881 * This should be used for HTTP 304 responses, where you need to
1882 * preserve the Content-Encoding header of the real result, but
1883 * also need to suppress the output of ob_gzhandler to keep to spec
1884 * and avoid breaking Firefox in rare cases where the headers and
1885 * body are broken over two packets.
1887 function wfClearOutputBuffers() {
1888 wfResetOutputBuffers( false );
1892 * Converts an Accept-* header into an array mapping string values to quality
1895 * @param string $accept
1896 * @param string $def Default
1897 * @return float[] Associative array of string => float pairs
1899 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1900 # No arg means accept anything (per HTTP spec)
1902 return [ $def => 1.0 ];
1907 $parts = explode( ',', $accept );
1909 foreach ( $parts as $part ) {
1910 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
1911 $values = explode( ';', trim( $part ) );
1913 if ( count( $values ) == 1 ) {
1914 $prefs[$values[0]] = 1.0;
1915 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
1916 $prefs[$values[0]] = floatval( $match[1] );
1924 * Checks if a given MIME type matches any of the keys in the given
1925 * array. Basic wildcards are accepted in the array keys.
1927 * Returns the matching MIME type (or wildcard) if a match, otherwise
1930 * @param string $type
1931 * @param array $avail
1935 function mimeTypeMatch( $type, $avail ) {
1936 if ( array_key_exists( $type, $avail ) ) {
1939 $mainType = explode( '/', $type )[0];
1940 if ( array_key_exists( "$mainType/*", $avail ) ) {
1941 return "$mainType/*";
1942 } elseif ( array_key_exists( '*/*', $avail ) ) {
1951 * Returns the 'best' match between a client's requested internet media types
1952 * and the server's list of available types. Each list should be an associative
1953 * array of type to preference (preference is a float between 0.0 and 1.0).
1954 * Wildcards in the types are acceptable.
1956 * @param array $cprefs Client's acceptable type list
1957 * @param array $sprefs Server's offered types
1960 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
1961 * XXX: generalize to negotiate other stuff
1963 function wfNegotiateType( $cprefs, $sprefs ) {
1966 foreach ( array_keys( $sprefs ) as $type ) {
1967 $subType = explode( '/', $type )[1];
1968 if ( $subType != '*' ) {
1969 $ckey = mimeTypeMatch( $type, $cprefs );
1971 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1976 foreach ( array_keys( $cprefs ) as $type ) {
1977 $subType = explode( '/', $type )[1];
1978 if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
1979 $skey = mimeTypeMatch( $type, $sprefs );
1981 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1989 foreach ( array_keys( $combine ) as $type ) {
1990 if ( $combine[$type] > $bestq ) {
1992 $bestq = $combine[$type];
2000 * Reference-counted warning suppression
2002 * @deprecated since 1.26, use MediaWiki\suppressWarnings() directly
2005 function wfSuppressWarnings( $end = false ) {
2006 MediaWiki\
suppressWarnings( $end );
2010 * @deprecated since 1.26, use MediaWiki\restoreWarnings() directly
2011 * Restore error level to previous value
2013 function wfRestoreWarnings() {
2014 MediaWiki\
suppressWarnings( true );
2018 * Get a timestamp string in one of various formats
2020 * @param mixed $outputtype A timestamp in one of the supported formats, the
2021 * function will autodetect which format is supplied and act accordingly.
2022 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2023 * @return string|bool String / false The same date in the format specified in $outputtype or false
2025 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2026 $ret = MWTimestamp
::convert( $outputtype, $ts );
2027 if ( $ret === false ) {
2028 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2034 * Return a formatted timestamp, or null if input is null.
2035 * For dealing with nullable timestamp columns in the database.
2037 * @param int $outputtype
2041 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2042 if ( is_null( $ts ) ) {
2045 return wfTimestamp( $outputtype, $ts );
2050 * Convenience function; returns MediaWiki timestamp for the present time.
2054 function wfTimestampNow() {
2056 return MWTimestamp
::now( TS_MW
);
2060 * Check if the operating system is Windows
2062 * @return bool True if it's Windows, false otherwise.
2064 function wfIsWindows() {
2065 static $isWindows = null;
2066 if ( $isWindows === null ) {
2067 $isWindows = strtoupper( substr( PHP_OS
, 0, 3 ) ) === 'WIN';
2073 * Check if we are running under HHVM
2077 function wfIsHHVM() {
2078 return defined( 'HHVM_VERSION' );
2082 * Tries to get the system directory for temporary files. First
2083 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2084 * environment variables are then checked in sequence, then
2085 * sys_get_temp_dir(), then upload_tmp_dir from php.ini.
2087 * NOTE: When possible, use instead the tmpfile() function to create
2088 * temporary files to avoid race conditions on file creation, etc.
2092 function wfTempDir() {
2093 global $wgTmpDirectory;
2095 if ( $wgTmpDirectory !== false ) {
2096 return $wgTmpDirectory;
2099 return TempFSFile
::getUsableTempDirectory();
2103 * Make directory, and make all parent directories if they don't exist
2105 * @param string $dir Full path to directory to create
2106 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2107 * @param string $caller Optional caller param for debugging.
2108 * @throws MWException
2111 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2112 global $wgDirectoryMode;
2114 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2115 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2118 if ( !is_null( $caller ) ) {
2119 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2122 if ( strval( $dir ) === '' ||
is_dir( $dir ) ) {
2126 $dir = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR
, $dir );
2128 if ( is_null( $mode ) ) {
2129 $mode = $wgDirectoryMode;
2132 // Turn off the normal warning, we're doing our own below
2133 MediaWiki\
suppressWarnings();
2134 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2135 MediaWiki\restoreWarnings
();
2138 // directory may have been created on another request since we last checked
2139 if ( is_dir( $dir ) ) {
2143 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2144 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2150 * Remove a directory and all its content.
2151 * Does not hide error.
2152 * @param string $dir
2154 function wfRecursiveRemoveDir( $dir ) {
2155 wfDebug( __FUNCTION__
. "( $dir )\n" );
2156 // taken from https://secure.php.net/manual/en/function.rmdir.php#98622
2157 if ( is_dir( $dir ) ) {
2158 $objects = scandir( $dir );
2159 foreach ( $objects as $object ) {
2160 if ( $object != "." && $object != ".." ) {
2161 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2162 wfRecursiveRemoveDir( $dir . '/' . $object );
2164 unlink( $dir . '/' . $object );
2174 * @param int $nr The number to format
2175 * @param int $acc The number of digits after the decimal point, default 2
2176 * @param bool $round Whether or not to round the value, default true
2179 function wfPercent( $nr, $acc = 2, $round = true ) {
2180 $ret = sprintf( "%.${acc}f", $nr );
2181 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2185 * Safety wrapper around ini_get() for boolean settings.
2186 * The values returned from ini_get() are pre-normalized for settings
2187 * set via php.ini or php_flag/php_admin_flag... but *not*
2188 * for those set via php_value/php_admin_value.
2190 * It's fairly common for people to use php_value instead of php_flag,
2191 * which can leave you with an 'off' setting giving a false positive
2192 * for code that just takes the ini_get() return value as a boolean.
2194 * To make things extra interesting, setting via php_value accepts
2195 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2196 * Unrecognized values go false... again opposite PHP's own coercion
2197 * from string to bool.
2199 * Luckily, 'properly' set settings will always come back as '0' or '1',
2200 * so we only have to worry about them and the 'improper' settings.
2202 * I frickin' hate PHP... :P
2204 * @param string $setting
2207 function wfIniGetBool( $setting ) {
2208 $val = strtolower( ini_get( $setting ) );
2209 // 'on' and 'true' can't have whitespace around them, but '1' can.
2213 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2217 * Version of escapeshellarg() that works better on Windows.
2219 * Originally, this fixed the incorrect use of single quotes on Windows
2220 * (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in
2221 * PHP 5.2.6+ (bug backported to earlier distro releases of PHP).
2223 * @param string ... strings to escape and glue together, or a single array of strings parameter
2226 function wfEscapeShellArg( /*...*/ ) {
2227 $args = func_get_args();
2228 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
2229 // If only one argument has been passed, and that argument is an array,
2230 // treat it as a list of arguments
2231 $args = reset( $args );
2236 foreach ( $args as $arg ) {
2243 if ( wfIsWindows() ) {
2244 // Escaping for an MSVC-style command line parser and CMD.EXE
2245 // @codingStandardsIgnoreStart For long URLs
2247 // * https://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2248 // * https://technet.microsoft.com/en-us/library/cc723564.aspx
2251 // Double the backslashes before any double quotes. Escape the double quotes.
2252 // @codingStandardsIgnoreEnd
2253 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2256 foreach ( $tokens as $token ) {
2257 if ( $iteration %
2 == 1 ) {
2258 // Delimiter, a double quote preceded by zero or more slashes
2259 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2260 } elseif ( $iteration %
4 == 2 ) {
2261 // ^ in $token will be outside quotes, need to be escaped
2262 $arg .= str_replace( '^', '^^', $token );
2263 } else { // $iteration % 4 == 0
2264 // ^ in $token will appear inside double quotes, so leave as is
2269 // Double the backslashes before the end of the string, because
2270 // we will soon add a quote
2272 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2273 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2276 // Add surrounding quotes
2277 $retVal .= '"' . $arg . '"';
2279 $retVal .= escapeshellarg( $arg );
2286 * Check if wfShellExec() is effectively disabled via php.ini config
2288 * @return bool|string False or 'disabled'
2291 function wfShellExecDisabled() {
2292 static $disabled = null;
2293 if ( is_null( $disabled ) ) {
2294 if ( !function_exists( 'proc_open' ) ) {
2295 wfDebug( "proc_open() is disabled\n" );
2296 $disabled = 'disabled';
2305 * Execute a shell command, with time and memory limits mirrored from the PHP
2306 * configuration if supported.
2308 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2309 * or an array of unescaped arguments, in which case each value will be escaped
2310 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2311 * @param null|mixed &$retval Optional, will receive the program's exit code.
2312 * (non-zero is usually failure). If there is an error from
2313 * read, select, or proc_open(), this will be set to -1.
2314 * @param array $environ Optional environment variables which should be
2315 * added to the executed command environment.
2316 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2317 * this overwrites the global wgMaxShell* limits.
2318 * @param array $options Array of options:
2319 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2320 * including errors from limit.sh
2321 * - profileMethod: By default this function will profile based on the calling
2322 * method. Set this to a string for an alternative method to profile from
2324 * @return string Collected stdout as a string
2326 function wfShellExec( $cmd, &$retval = null, $environ = [],
2327 $limits = [], $options = []
2329 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2330 $wgMaxShellWallClockTime, $wgShellCgroup;
2332 $disabled = wfShellExecDisabled();
2335 return 'Unable to run external programs, proc_open() is disabled.';
2338 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2339 $profileMethod = isset( $options['profileMethod'] ) ?
$options['profileMethod'] : wfGetCaller();
2342 foreach ( $environ as $k => $v ) {
2343 if ( wfIsWindows() ) {
2344 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2345 * appear in the environment variable, so we must use carat escaping as documented in
2346 * https://technet.microsoft.com/en-us/library/cc723564.aspx
2347 * Note however that the quote isn't listed there, but is needed, and the parentheses
2348 * are listed there but doesn't appear to need it.
2350 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2352 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2353 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2355 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2358 if ( is_array( $cmd ) ) {
2359 $cmd = wfEscapeShellArg( $cmd );
2362 $cmd = $envcmd . $cmd;
2364 $useLogPipe = false;
2365 if ( is_executable( '/bin/bash' ) ) {
2366 $time = intval( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2367 if ( isset( $limits['walltime'] ) ) {
2368 $wallTime = intval( $limits['walltime'] );
2369 } elseif ( isset( $limits['time'] ) ) {
2372 $wallTime = intval( $wgMaxShellWallClockTime );
2374 $mem = intval( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2375 $filesize = intval( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2377 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2378 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2379 escapeshellarg( $cmd ) . ' ' .
2381 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2382 "MW_CPU_LIMIT=$time; " .
2383 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2384 "MW_MEM_LIMIT=$mem; " .
2385 "MW_FILE_SIZE_LIMIT=$filesize; " .
2386 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2387 "MW_USE_LOG_PIPE=yes"
2390 } elseif ( $includeStderr ) {
2393 } elseif ( $includeStderr ) {
2396 wfDebug( "wfShellExec: $cmd\n" );
2398 // Don't try to execute commands that exceed Linux's MAX_ARG_STRLEN.
2399 // Other platforms may be more accomodating, but we don't want to be
2400 // accomodating, because very long commands probably include user
2401 // input. See T129506.
2402 if ( strlen( $cmd ) > SHELL_MAX_ARG_STRLEN
) {
2403 throw new Exception( __METHOD__
.
2404 '(): total length of $cmd must not exceed SHELL_MAX_ARG_STRLEN' );
2408 0 => [ 'file', 'php://stdin', 'r' ],
2409 1 => [ 'pipe', 'w' ],
2410 2 => [ 'file', 'php://stderr', 'w' ] ];
2411 if ( $useLogPipe ) {
2412 $desc[3] = [ 'pipe', 'w' ];
2415 $scoped = Profiler
::instance()->scopedProfileIn( __FUNCTION__
. '-' . $profileMethod );
2416 $proc = proc_open( $cmd, $desc, $pipes );
2418 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2422 $outBuffer = $logBuffer = '';
2427 /* According to the documentation, it is possible for stream_select()
2428 * to fail due to EINTR. I haven't managed to induce this in testing
2429 * despite sending various signals. If it did happen, the error
2430 * message would take the form:
2432 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2434 * where [4] is the value of the macro EINTR and "Interrupted system
2435 * call" is string which according to the Linux manual is "possibly"
2436 * localised according to LC_MESSAGES.
2438 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2439 $eintrMessage = "stream_select(): unable to select [$eintr]";
2445 while ( $running === true ||
$numReadyPipes !== 0 ) {
2447 $status = proc_get_status( $proc );
2448 // If the process has terminated, switch to nonblocking selects
2449 // for getting any data still waiting to be read.
2450 if ( !$status['running'] ) {
2456 $readyPipes = $pipes;
2459 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2460 @trigger_error
( '' );
2461 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
2462 if ( $numReadyPipes === false ) {
2463 // @codingStandardsIgnoreEnd
2464 $error = error_get_last();
2465 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2468 trigger_error( $error['message'], E_USER_WARNING
);
2469 $logMsg = $error['message'];
2473 foreach ( $readyPipes as $fd => $pipe ) {
2474 $block = fread( $pipe, 65536 );
2475 if ( $block === '' ) {
2477 fclose( $pipes[$fd] );
2478 unset( $pipes[$fd] );
2482 } elseif ( $block === false ) {
2484 $logMsg = "Error reading from pipe";
2486 } elseif ( $fd == 1 ) {
2488 $outBuffer .= $block;
2489 } elseif ( $fd == 3 ) {
2491 $logBuffer .= $block;
2492 if ( strpos( $block, "\n" ) !== false ) {
2493 $lines = explode( "\n", $logBuffer );
2494 $logBuffer = array_pop( $lines );
2495 foreach ( $lines as $line ) {
2496 wfDebugLog( 'exec', $line );
2503 foreach ( $pipes as $pipe ) {
2507 // Use the status previously collected if possible, since proc_get_status()
2508 // just calls waitpid() which will not return anything useful the second time.
2510 $status = proc_get_status( $proc );
2513 if ( $logMsg !== false ) {
2514 // Read/select error
2516 proc_close( $proc );
2517 } elseif ( $status['signaled'] ) {
2518 $logMsg = "Exited with signal {$status['termsig']}";
2519 $retval = 128 +
$status['termsig'];
2520 proc_close( $proc );
2522 if ( $status['running'] ) {
2523 $retval = proc_close( $proc );
2525 $retval = $status['exitcode'];
2526 proc_close( $proc );
2528 if ( $retval == 127 ) {
2529 $logMsg = "Possibly missing executable file";
2530 } elseif ( $retval >= 129 && $retval <= 192 ) {
2531 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2535 if ( $logMsg !== false ) {
2536 wfDebugLog( 'exec', "$logMsg: $cmd" );
2543 * Execute a shell command, returning both stdout and stderr. Convenience
2544 * function, as all the arguments to wfShellExec can become unwieldy.
2546 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2547 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2548 * or an array of unescaped arguments, in which case each value will be escaped
2549 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2550 * @param null|mixed &$retval Optional, will receive the program's exit code.
2551 * (non-zero is usually failure)
2552 * @param array $environ Optional environment variables which should be
2553 * added to the executed command environment.
2554 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2555 * this overwrites the global wgMaxShell* limits.
2556 * @return string Collected stdout and stderr as a string
2558 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = [], $limits = [] ) {
2559 return wfShellExec( $cmd, $retval, $environ, $limits,
2560 [ 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ] );
2564 * Formerly set the locale for locale-sensitive operations
2566 * This is now done in Setup.php.
2568 * @deprecated since 1.30, no longer needed
2569 * @see $wgShellLocale
2571 function wfInitShellLocale() {
2575 * Generate a shell-escaped command line string to run a MediaWiki cli script.
2576 * Note that $parameters should be a flat array and an option with an argument
2577 * should consist of two consecutive items in the array (do not use "--option value").
2579 * @param string $script MediaWiki cli script path
2580 * @param array $parameters Arguments and options to the script
2581 * @param array $options Associative array of options:
2582 * 'php': The path to the php executable
2583 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
2586 function wfShellWikiCmd( $script, array $parameters = [], array $options = [] ) {
2588 // Give site config file a chance to run the script in a wrapper.
2589 // The caller may likely want to call wfBasename() on $script.
2590 Hooks
::run( 'wfShellWikiCmd', [ &$script, &$parameters, &$options ] );
2591 $cmd = isset( $options['php'] ) ?
[ $options['php'] ] : [ $wgPhpCli ];
2592 if ( isset( $options['wrapper'] ) ) {
2593 $cmd[] = $options['wrapper'];
2596 // Escape each parameter for shell
2597 return wfEscapeShellArg( array_merge( $cmd, $parameters ) );
2601 * wfMerge attempts to merge differences between three texts.
2602 * Returns true for a clean merge and false for failure or a conflict.
2604 * @param string $old
2605 * @param string $mine
2606 * @param string $yours
2607 * @param string $result
2610 function wfMerge( $old, $mine, $yours, &$result ) {
2613 # This check may also protect against code injection in
2614 # case of broken installations.
2615 MediaWiki\
suppressWarnings();
2616 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2617 MediaWiki\restoreWarnings
();
2619 if ( !$haveDiff3 ) {
2620 wfDebug( "diff3 not found\n" );
2624 # Make temporary files
2626 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2627 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2628 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2630 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2631 # a newline character. To avoid this, we normalize the trailing whitespace before
2632 # creating the diff.
2634 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2635 fclose( $oldtextFile );
2636 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2637 fclose( $mytextFile );
2638 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2639 fclose( $yourtextFile );
2641 # Check for a conflict
2642 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '--overlap-only', $mytextName,
2643 $oldtextName, $yourtextName );
2644 $handle = popen( $cmd, 'r' );
2646 if ( fgets( $handle, 1024 ) ) {
2654 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '-e', '--merge', $mytextName,
2655 $oldtextName, $yourtextName );
2656 $handle = popen( $cmd, 'r' );
2659 $data = fread( $handle, 8192 );
2660 if ( strlen( $data ) == 0 ) {
2666 unlink( $mytextName );
2667 unlink( $oldtextName );
2668 unlink( $yourtextName );
2670 if ( $result === '' && $old !== '' && !$conflict ) {
2671 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
2678 * Returns unified plain-text diff of two texts.
2679 * "Useful" for machine processing of diffs.
2681 * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly
2683 * @param string $before The text before the changes.
2684 * @param string $after The text after the changes.
2685 * @param string $params Command-line options for the diff command.
2686 * @return string Unified diff of $before and $after
2688 function wfDiff( $before, $after, $params = '-u' ) {
2689 if ( $before == $after ) {
2694 MediaWiki\
suppressWarnings();
2695 $haveDiff = $wgDiff && file_exists( $wgDiff );
2696 MediaWiki\restoreWarnings
();
2698 # This check may also protect against code injection in
2699 # case of broken installations.
2701 wfDebug( "diff executable not found\n" );
2702 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2703 $format = new UnifiedDiffFormatter();
2704 return $format->format( $diffs );
2707 # Make temporary files
2709 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2710 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2712 fwrite( $oldtextFile, $before );
2713 fclose( $oldtextFile );
2714 fwrite( $newtextFile, $after );
2715 fclose( $newtextFile );
2717 // Get the diff of the two files
2718 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
2720 $h = popen( $cmd, 'r' );
2722 unlink( $oldtextName );
2723 unlink( $newtextName );
2724 throw new Exception( __METHOD__
. '(): popen() failed' );
2730 $data = fread( $h, 8192 );
2731 if ( strlen( $data ) == 0 ) {
2739 unlink( $oldtextName );
2740 unlink( $newtextName );
2742 // Kill the --- and +++ lines. They're not useful.
2743 $diff_lines = explode( "\n", $diff );
2744 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
2745 unset( $diff_lines[0] );
2747 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
2748 unset( $diff_lines[1] );
2751 $diff = implode( "\n", $diff_lines );
2757 * This function works like "use VERSION" in Perl, the program will die with a
2758 * backtrace if the current version of PHP is less than the version provided
2760 * This is useful for extensions which due to their nature are not kept in sync
2761 * with releases, and might depend on other versions of PHP than the main code
2763 * Note: PHP might die due to parsing errors in some cases before it ever
2764 * manages to call this function, such is life
2766 * @see perldoc -f use
2768 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
2769 * @throws MWException
2771 function wfUsePHP( $req_ver ) {
2772 $php_ver = PHP_VERSION
;
2774 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
2775 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2780 * This function works like "use VERSION" in Perl except it checks the version
2781 * of MediaWiki, the program will die with a backtrace if the current version
2782 * of MediaWiki is less than the version provided.
2784 * This is useful for extensions which due to their nature are not kept in sync
2787 * Note: Due to the behavior of PHP's version_compare() which is used in this
2788 * function, if you want to allow the 'wmf' development versions add a 'c' (or
2789 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
2790 * targeted version number. For example if you wanted to allow any variation
2791 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
2792 * not result in the same comparison due to the internal logic of
2793 * version_compare().
2795 * @see perldoc -f use
2797 * @deprecated since 1.26, use the "requires' property of extension.json
2798 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
2799 * @throws MWException
2801 function wfUseMW( $req_ver ) {
2804 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
2805 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2810 * Return the final portion of a pathname.
2811 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
2812 * https://bugs.php.net/bug.php?id=33898
2814 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2815 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
2817 * @param string $path
2818 * @param string $suffix String to remove if present
2821 function wfBaseName( $path, $suffix = '' ) {
2822 if ( $suffix == '' ) {
2825 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
2829 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2837 * Generate a relative path name to the given file.
2838 * May explode on non-matching case-insensitive paths,
2839 * funky symlinks, etc.
2841 * @param string $path Absolute destination path including target filename
2842 * @param string $from Absolute source path, directory only
2845 function wfRelativePath( $path, $from ) {
2846 // Normalize mixed input on Windows...
2847 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2848 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2850 // Trim trailing slashes -- fix for drive root
2851 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2852 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2854 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2855 $against = explode( DIRECTORY_SEPARATOR
, $from );
2857 if ( $pieces[0] !== $against[0] ) {
2858 // Non-matching Windows drive letters?
2859 // Return a full path.
2863 // Trim off common prefix
2864 while ( count( $pieces ) && count( $against )
2865 && $pieces[0] == $against[0] ) {
2866 array_shift( $pieces );
2867 array_shift( $against );
2870 // relative dots to bump us to the parent
2871 while ( count( $against ) ) {
2872 array_unshift( $pieces, '..' );
2873 array_shift( $against );
2876 array_push( $pieces, wfBaseName( $path ) );
2878 return implode( DIRECTORY_SEPARATOR
, $pieces );
2882 * Convert an arbitrarily-long digit string from one numeric base
2883 * to another, optionally zero-padding to a minimum column width.
2885 * Supports base 2 through 36; digit values 10-36 are represented
2886 * as lowercase letters a-z. Input is case-insensitive.
2888 * @deprecated since 1.27 Use Wikimedia\base_convert() directly
2890 * @param string $input Input number
2891 * @param int $sourceBase Base of the input number
2892 * @param int $destBase Desired base of the output
2893 * @param int $pad Minimum number of digits in the output (pad with zeroes)
2894 * @param bool $lowercase Whether to output in lowercase or uppercase
2895 * @param string $engine Either "gmp", "bcmath", or "php"
2896 * @return string|bool The output number as a string, or false on error
2898 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
2899 $lowercase = true, $engine = 'auto'
2901 return Wikimedia\base_convert
( $input, $sourceBase, $destBase, $pad, $lowercase, $engine );
2905 * @deprecated since 1.27, PHP's session generation isn't used with
2906 * MediaWiki\Session\SessionManager
2908 function wfFixSessionID() {
2909 wfDeprecated( __FUNCTION__
, '1.27' );
2913 * Reset the session id
2915 * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead
2918 function wfResetSessionID() {
2919 wfDeprecated( __FUNCTION__
, '1.27' );
2920 $session = SessionManager
::getGlobalSession();
2921 $delay = $session->delaySave();
2923 $session->resetId();
2925 // Make sure a session is started, since that's what the old
2926 // wfResetSessionID() did.
2927 if ( session_id() !== $session->getId() ) {
2928 wfSetupSession( $session->getId() );
2931 ScopedCallback
::consume( $delay );
2935 * Initialise php session
2937 * @deprecated since 1.27, use MediaWiki\Session\SessionManager instead.
2938 * Generally, "using" SessionManager will be calling ->getSessionById() or
2939 * ::getGlobalSession() (depending on whether you were passing $sessionId
2940 * here), then calling $session->persist().
2941 * @param bool|string $sessionId
2943 function wfSetupSession( $sessionId = false ) {
2944 wfDeprecated( __FUNCTION__
, '1.27' );
2947 session_id( $sessionId );
2950 $session = SessionManager
::getGlobalSession();
2951 $session->persist();
2953 if ( session_id() !== $session->getId() ) {
2954 session_id( $session->getId() );
2956 MediaWiki\
quietCall( 'session_start' );
2960 * Get an object from the precompiled serialized directory
2962 * @param string $name
2963 * @return mixed The variable on success, false on failure
2965 function wfGetPrecompiledData( $name ) {
2968 $file = "$IP/serialized/$name";
2969 if ( file_exists( $file ) ) {
2970 $blob = file_get_contents( $file );
2972 return unserialize( $blob );
2979 * Make a cache key for the local wiki.
2981 * @deprecated since 1.30 Call makeKey on a BagOStuff instance
2982 * @param string $args,...
2985 function wfMemcKey( /*...*/ ) {
2986 return call_user_func_array(
2987 [ ObjectCache
::getLocalClusterInstance(), 'makeKey' ],
2993 * Make a cache key for a foreign DB.
2995 * Must match what wfMemcKey() would produce in context of the foreign wiki.
2998 * @param string $prefix
2999 * @param string $args,...
3002 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3003 $args = array_slice( func_get_args(), 2 );
3004 $keyspace = $prefix ?
"$db-$prefix" : $db;
3005 return call_user_func_array(
3006 [ ObjectCache
::getLocalClusterInstance(), 'makeKeyInternal' ],
3007 [ $keyspace, $args ]
3012 * Make a cache key with database-agnostic prefix.
3014 * Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix
3015 * instead. Must have a prefix as otherwise keys that use a database name
3016 * in the first segment will clash with wfMemcKey/wfForeignMemcKey.
3018 * @deprecated since 1.30 Call makeGlobalKey on a BagOStuff instance
3020 * @param string $args,...
3023 function wfGlobalCacheKey( /*...*/ ) {
3024 return call_user_func_array(
3025 [ ObjectCache
::getLocalClusterInstance(), 'makeGlobalKey' ],
3031 * Get an ASCII string identifying this wiki
3032 * This is used as a prefix in memcached keys
3036 function wfWikiID() {
3037 global $wgDBprefix, $wgDBname;
3038 if ( $wgDBprefix ) {
3039 return "$wgDBname-$wgDBprefix";
3046 * Split a wiki ID into DB name and table prefix
3048 * @param string $wiki
3052 function wfSplitWikiID( $wiki ) {
3053 $bits = explode( '-', $wiki, 2 );
3054 if ( count( $bits ) < 2 ) {
3061 * Get a Database object.
3063 * @param int $db Index of the connection to get. May be DB_MASTER for the
3064 * master (for write queries), DB_REPLICA for potentially lagged read
3065 * queries, or an integer >= 0 for a particular server.
3067 * @param string|string[] $groups Query groups. An array of group names that this query
3068 * belongs to. May contain a single string if the query is only
3071 * @param string|bool $wiki The wiki ID, or false for the current wiki
3073 * Note: multiple calls to wfGetDB(DB_REPLICA) during the course of one request
3074 * will always return the same object, unless the underlying connection or load
3075 * balancer is manually destroyed.
3077 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3078 * updater to ensure that a proper database is being updated.
3080 * @todo Replace calls to wfGetDB with calls to LoadBalancer::getConnection()
3081 * on an injected instance of LoadBalancer.
3083 * @return \Wikimedia\Rdbms\Database
3085 function wfGetDB( $db, $groups = [], $wiki = false ) {
3086 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3090 * Get a load balancer object.
3092 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancer()
3093 * or MediaWikiServices::getDBLoadBalancerFactory() instead.
3095 * @param string|bool $wiki Wiki ID, or false for the current wiki
3096 * @return \Wikimedia\Rdbms\LoadBalancer
3098 function wfGetLB( $wiki = false ) {
3099 if ( $wiki === false ) {
3100 return MediaWikiServices
::getInstance()->getDBLoadBalancer();
3102 $factory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3103 return $factory->getMainLB( $wiki );
3108 * Get the load balancer factory object
3110 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
3112 * @return \Wikimedia\Rdbms\LBFactory
3114 function wfGetLBFactory() {
3115 return MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3120 * Shortcut for RepoGroup::singleton()->findFile()
3122 * @param string $title String or Title object
3123 * @param array $options Associative array of options (see RepoGroup::findFile)
3124 * @return File|bool File, or false if the file does not exist
3126 function wfFindFile( $title, $options = [] ) {
3127 return RepoGroup
::singleton()->findFile( $title, $options );
3131 * Get an object referring to a locally registered file.
3132 * Returns a valid placeholder object if the file does not exist.
3134 * @param Title|string $title
3135 * @return LocalFile|null A File, or null if passed an invalid Title
3137 function wfLocalFile( $title ) {
3138 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3142 * Should low-performance queries be disabled?
3145 * @codeCoverageIgnore
3147 function wfQueriesMustScale() {
3148 global $wgMiserMode;
3150 ||
( SiteStats
::pages() > 100000
3151 && SiteStats
::edits() > 1000000
3152 && SiteStats
::users() > 10000 );
3156 * Get the path to a specified script file, respecting file
3157 * extensions; this is a wrapper around $wgScriptPath etc.
3158 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3160 * @param string $script Script filename, sans extension
3163 function wfScript( $script = 'index' ) {
3164 global $wgScriptPath, $wgScript, $wgLoadScript;
3165 if ( $script === 'index' ) {
3167 } elseif ( $script === 'load' ) {
3168 return $wgLoadScript;
3170 return "{$wgScriptPath}/{$script}.php";
3175 * Get the script URL.
3177 * @return string Script URL
3179 function wfGetScriptUrl() {
3180 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3181 /* as it was called, minus the query string.
3183 * Some sites use Apache rewrite rules to handle subdomains,
3184 * and have PHP set up in a weird way that causes PHP_SELF
3185 * to contain the rewritten URL instead of the one that the
3186 * outside world sees.
3188 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
3189 * provides containing the "before" URL.
3191 return $_SERVER['SCRIPT_NAME'];
3193 return $_SERVER['URL'];
3198 * Convenience function converts boolean values into "true"
3199 * or "false" (string) values
3201 * @param bool $value
3204 function wfBoolToStr( $value ) {
3205 return $value ?
'true' : 'false';
3209 * Get a platform-independent path to the null file, e.g. /dev/null
3213 function wfGetNull() {
3214 return wfIsWindows() ?
'NUL' : '/dev/null';
3218 * Waits for the replica DBs to catch up to the master position
3220 * Use this when updating very large numbers of rows, as in maintenance scripts,
3221 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
3223 * By default this waits on the main DB cluster of the current wiki.
3224 * If $cluster is set to "*" it will wait on all DB clusters, including
3225 * external ones. If the lag being waiting on is caused by the code that
3226 * does this check, it makes since to use $ifWritesSince, particularly if
3227 * cluster is "*", to avoid excess overhead.
3229 * Never call this function after a big DB write that is still in a transaction.
3230 * This only makes sense after the possible lag inducing changes were committed.
3232 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3233 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3234 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3235 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3236 * @return bool Success (able to connect and no timeouts reached)
3237 * @deprecated since 1.27 Use LBFactory::waitForReplication
3239 function wfWaitForSlaves(
3240 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3242 if ( $timeout === null ) {
3243 $timeout = ( PHP_SAPI
=== 'cli' ) ?
86400 : 10;
3246 if ( $cluster === '*' ) {
3249 } elseif ( $wiki === false ) {
3254 wfGetLBFactory()->waitForReplication( [
3256 'cluster' => $cluster,
3257 'timeout' => $timeout,
3258 // B/C: first argument used to be "max seconds of lag"; ignore such values
3259 'ifWritesSince' => ( $ifWritesSince > 1e9
) ?
$ifWritesSince : null
3261 } catch ( DBReplicationWaitError
$e ) {
3269 * Count down from $seconds to zero on the terminal, with a one-second pause
3270 * between showing each number. For use in command-line scripts.
3272 * @codeCoverageIgnore
3273 * @param int $seconds
3275 function wfCountDown( $seconds ) {
3276 for ( $i = $seconds; $i >= 0; $i-- ) {
3277 if ( $i != $seconds ) {
3278 echo str_repeat( "\x08", strlen( $i +
1 ) );
3290 * Replace all invalid characters with '-'.
3291 * Additional characters can be defined in $wgIllegalFileChars (see T22489).
3292 * By default, $wgIllegalFileChars includes ':', '/', '\'.
3294 * @param string $name Filename to process
3297 function wfStripIllegalFilenameChars( $name ) {
3298 global $wgIllegalFileChars;
3299 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3300 $name = preg_replace(
3301 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3305 // $wgIllegalFileChars may not include '/' and '\', so we still need to do this
3306 $name = wfBaseName( $name );
3311 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit
3313 * @return int Resulting value of the memory limit.
3315 function wfMemoryLimit() {
3316 global $wgMemoryLimit;
3317 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3318 if ( $memlimit != -1 ) {
3319 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3320 if ( $conflimit == -1 ) {
3321 wfDebug( "Removing PHP's memory limit\n" );
3322 MediaWiki\
suppressWarnings();
3323 ini_set( 'memory_limit', $conflimit );
3324 MediaWiki\restoreWarnings
();
3326 } elseif ( $conflimit > $memlimit ) {
3327 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3328 MediaWiki\
suppressWarnings();
3329 ini_set( 'memory_limit', $conflimit );
3330 MediaWiki\restoreWarnings
();
3338 * Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit
3340 * @return int Prior time limit
3343 function wfTransactionalTimeLimit() {
3344 global $wgTransactionalTimeLimit;
3346 $timeLimit = ini_get( 'max_execution_time' );
3347 // Note that CLI scripts use 0
3348 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
3349 set_time_limit( $wgTransactionalTimeLimit );
3352 ignore_user_abort( true ); // ignore client disconnects
3358 * Converts shorthand byte notation to integer form
3360 * @param string $string
3361 * @param int $default Returned if $string is empty
3364 function wfShorthandToInteger( $string = '', $default = -1 ) {
3365 $string = trim( $string );
3366 if ( $string === '' ) {
3369 $last = $string[strlen( $string ) - 1];
3370 $val = intval( $string );
3375 // break intentionally missing
3379 // break intentionally missing
3389 * Get the normalised IETF language tag
3390 * See unit test for examples.
3392 * @param string $code The language code.
3393 * @return string The language code which complying with BCP 47 standards.
3395 function wfBCP47( $code ) {
3396 $codeSegment = explode( '-', $code );
3398 foreach ( $codeSegment as $segNo => $seg ) {
3399 // when previous segment is x, it is a private segment and should be lc
3400 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3401 $codeBCP[$segNo] = strtolower( $seg );
3402 // ISO 3166 country code
3403 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3404 $codeBCP[$segNo] = strtoupper( $seg );
3405 // ISO 15924 script code
3406 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3407 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3408 // Use lowercase for other cases
3410 $codeBCP[$segNo] = strtolower( $seg );
3413 $langCode = implode( '-', $codeBCP );
3418 * Get a specific cache object.
3420 * @param int|string $cacheType A CACHE_* constants, or other key in $wgObjectCaches
3423 function wfGetCache( $cacheType ) {
3424 return ObjectCache
::getInstance( $cacheType );
3428 * Get the main cache object
3432 function wfGetMainCache() {
3433 global $wgMainCacheType;
3434 return ObjectCache
::getInstance( $wgMainCacheType );
3438 * Get the cache object used by the message cache
3442 function wfGetMessageCacheStorage() {
3443 global $wgMessageCacheType;
3444 return ObjectCache
::getInstance( $wgMessageCacheType );
3448 * Get the cache object used by the parser cache
3452 function wfGetParserCacheStorage() {
3453 global $wgParserCacheType;
3454 return ObjectCache
::getInstance( $wgParserCacheType );
3458 * Call hook functions defined in $wgHooks
3460 * @param string $event Event name
3461 * @param array $args Parameters passed to hook functions
3462 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
3464 * @return bool True if no handler aborted the hook
3465 * @deprecated since 1.25 - use Hooks::run
3467 function wfRunHooks( $event, array $args = [], $deprecatedVersion = null ) {
3468 return Hooks
::run( $event, $args, $deprecatedVersion );
3472 * Wrapper around php's unpack.
3474 * @param string $format The format string (See php's docs)
3475 * @param string $data A binary string of binary data
3476 * @param int|bool $length The minimum length of $data or false. This is to
3477 * prevent reading beyond the end of $data. false to disable the check.
3479 * Also be careful when using this function to read unsigned 32 bit integer
3480 * because php might make it negative.
3482 * @throws MWException If $data not long enough, or if unpack fails
3483 * @return array Associative array of the extracted data
3485 function wfUnpack( $format, $data, $length = false ) {
3486 if ( $length !== false ) {
3487 $realLen = strlen( $data );
3488 if ( $realLen < $length ) {
3489 throw new MWException( "Tried to use wfUnpack on a "
3490 . "string of length $realLen, but needed one "
3491 . "of at least length $length."
3496 MediaWiki\
suppressWarnings();
3497 $result = unpack( $format, $data );
3498 MediaWiki\restoreWarnings
();
3500 if ( $result === false ) {
3501 // If it cannot extract the packed data.
3502 throw new MWException( "unpack could not unpack binary data" );
3508 * Determine if an image exists on the 'bad image list'.
3510 * The format of MediaWiki:Bad_image_list is as follows:
3511 * * Only list items (lines starting with "*") are considered
3512 * * The first link on a line must be a link to a bad image
3513 * * Any subsequent links on the same line are considered to be exceptions,
3514 * i.e. articles where the image may occur inline.
3516 * @param string $name The image name to check
3517 * @param Title|bool $contextTitle The page on which the image occurs, if known
3518 * @param string $blacklist Wikitext of a file blacklist
3521 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
3522 # Handle redirects; callers almost always hit wfFindFile() anyway,
3523 # so just use that method because it has a fast process cache.
3524 $file = wfFindFile( $name ); // get the final name
3525 $name = $file ?
$file->getTitle()->getDBkey() : $name;
3527 # Run the extension hook
3529 if ( !Hooks
::run( 'BadImage', [ $name, &$bad ] ) ) {
3533 $cache = ObjectCache
::getLocalServerInstance( 'hash' );
3534 $key = $cache->makeKey(
3535 'bad-image-list', ( $blacklist === null ) ?
'default' : md5( $blacklist )
3537 $badImages = $cache->get( $key );
3539 if ( $badImages === false ) { // cache miss
3540 if ( $blacklist === null ) {
3541 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
3543 # Build the list now
3545 $lines = explode( "\n", $blacklist );
3546 foreach ( $lines as $line ) {
3548 if ( substr( $line, 0, 1 ) !== '*' ) {
3554 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
3559 $imageDBkey = false;
3560 foreach ( $m[1] as $i => $titleText ) {
3561 $title = Title
::newFromText( $titleText );
3562 if ( !is_null( $title ) ) {
3564 $imageDBkey = $title->getDBkey();
3566 $exceptions[$title->getPrefixedDBkey()] = true;
3571 if ( $imageDBkey !== false ) {
3572 $badImages[$imageDBkey] = $exceptions;
3575 $cache->set( $key, $badImages, 60 );
3578 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
3579 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
3585 * Determine whether the client at a given source IP is likely to be able to
3586 * access the wiki via HTTPS.
3588 * @param string $ip The IPv4/6 address in the normal human-readable form
3591 function wfCanIPUseHTTPS( $ip ) {
3593 Hooks
::run( 'CanIPUseHTTPS', [ $ip, &$canDo ] );
3598 * Determine input string is represents as infinity
3600 * @param string $str The string to determine
3604 function wfIsInfinity( $str ) {
3605 $infinityValues = [ 'infinite', 'indefinite', 'infinity', 'never' ];
3606 return in_array( $str, $infinityValues );
3610 * Returns true if these thumbnail parameters match one that MediaWiki
3611 * requests from file description pages and/or parser output.
3613 * $params is considered non-standard if they involve a non-standard
3614 * width or any non-default parameters aside from width and page number.
3615 * The number of possible files with standard parameters is far less than
3616 * that of all combinations; rate-limiting for them can thus be more generious.
3619 * @param array $params
3621 * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25
3623 function wfThumbIsStandard( File
$file, array $params ) {
3624 global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages;
3626 $multipliers = [ 1 ];
3627 if ( $wgResponsiveImages ) {
3628 // These available sizes are hardcoded currently elsewhere in MediaWiki.
3629 // @see Linker::processResponsiveImages
3630 $multipliers[] = 1.5;
3634 $handler = $file->getHandler();
3635 if ( !$handler ||
!isset( $params['width'] ) ) {
3640 if ( isset( $params['page'] ) ) {
3641 $basicParams['page'] = $params['page'];
3646 // Expand limits to account for multipliers
3647 foreach ( $multipliers as $multiplier ) {
3648 $thumbLimits = array_merge( $thumbLimits, array_map(
3649 function ( $width ) use ( $multiplier ) {
3650 return round( $width * $multiplier );
3653 $imageLimits = array_merge( $imageLimits, array_map(
3654 function ( $pair ) use ( $multiplier ) {
3656 round( $pair[0] * $multiplier ),
3657 round( $pair[1] * $multiplier ),
3663 // Check if the width matches one of $wgThumbLimits
3664 if ( in_array( $params['width'], $thumbLimits ) ) {
3665 $normalParams = $basicParams +
[ 'width' => $params['width'] ];
3666 // Append any default values to the map (e.g. "lossy", "lossless", ...)
3667 $handler->normaliseParams( $file, $normalParams );
3669 // If not, then check if the width matchs one of $wgImageLimits
3671 foreach ( $imageLimits as $pair ) {
3672 $normalParams = $basicParams +
[ 'width' => $pair[0], 'height' => $pair[1] ];
3673 // Decide whether the thumbnail should be scaled on width or height.
3674 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
3675 $handler->normaliseParams( $file, $normalParams );
3676 // Check if this standard thumbnail size maps to the given width
3677 if ( $normalParams['width'] == $params['width'] ) {
3683 return false; // not standard for description pages
3687 // Check that the given values for non-page, non-width, params are just defaults
3688 foreach ( $params as $key => $value ) {
3689 if ( !isset( $normalParams[$key] ) ||
$normalParams[$key] != $value ) {
3698 * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
3700 * Values that exist in both values will be combined with += (all values of the array
3701 * of $newValues will be added to the values of the array of $baseArray, while values,
3702 * that exists in both, the value of $baseArray will be used).
3704 * @param array $baseArray The array where you want to add the values of $newValues to
3705 * @param array $newValues An array with new values
3706 * @return array The combined array
3709 function wfArrayPlus2d( array $baseArray, array $newValues ) {
3710 // First merge items that are in both arrays
3711 foreach ( $baseArray as $name => &$groupVal ) {
3712 if ( isset( $newValues[$name] ) ) {
3713 $groupVal +
= $newValues[$name];
3716 // Now add items that didn't exist yet
3717 $baseArray +
= $newValues;