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
;
30 // Hide compatibility functions from Doxygen
34 * Compatibility functions
36 * We support PHP 5.3.3 and up.
37 * Re-implementations of newer functions or functions in non-standard
38 * PHP extensions may be included here.
41 if ( !function_exists( 'mb_substr' ) ) {
44 * @see Fallback::mb_substr
47 function mb_substr( $str, $start, $count = 'end' ) {
48 return Fallback
::mb_substr( $str, $start, $count );
53 * @see Fallback::mb_substr_split_unicode
56 function mb_substr_split_unicode( $str, $splitPos ) {
57 return Fallback
::mb_substr_split_unicode( $str, $splitPos );
61 if ( !function_exists( 'mb_strlen' ) ) {
64 * @see Fallback::mb_strlen
67 function mb_strlen( $str, $enc = '' ) {
68 return Fallback
::mb_strlen( $str, $enc );
72 if ( !function_exists( 'mb_strpos' ) ) {
75 * @see Fallback::mb_strpos
78 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
79 return Fallback
::mb_strpos( $haystack, $needle, $offset, $encoding );
83 if ( !function_exists( 'mb_strrpos' ) ) {
86 * @see Fallback::mb_strrpos
89 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
90 return Fallback
::mb_strrpos( $haystack, $needle, $offset, $encoding );
94 // gzdecode function only exists in PHP >= 5.4.0
95 // http://php.net/gzdecode
96 if ( !function_exists( 'gzdecode' ) ) {
102 function gzdecode( $data ) {
103 return gzinflate( substr( $data, 10, -8 ) );
107 // hash_equals function only exists in PHP >= 5.6.0
108 // http://php.net/hash_equals
109 if ( !function_exists( 'hash_equals' ) ) {
111 * Check whether a user-provided string is equal to a fixed-length secret string
112 * without revealing bytes of the secret string through timing differences.
114 * The usual way to compare strings (PHP's === operator or the underlying memcmp()
115 * function in C) is to compare corresponding bytes and stop at the first difference,
116 * which would take longer for a partial match than for a complete mismatch. This
117 * is not secure when one of the strings (e.g. an HMAC or token) must remain secret
118 * and the other may come from an attacker. Statistical analysis of timing measurements
119 * over many requests may allow the attacker to guess the string's bytes one at a time
120 * (and check his guesses) even if the timing differences are extremely small.
122 * When making such a security-sensitive comparison, it is essential that the sequence
123 * in which instructions are executed and memory locations are accessed not depend on
124 * the secret string's value. HOWEVER, for simplicity, we do not attempt to minimize
125 * the inevitable leakage of the string's length. That is generally known anyway as
126 * a chararacteristic of the hash function used to compute the secret value.
128 * Longer explanation: http://www.emerose.com/timing-attacks-explained
130 * @codeCoverageIgnore
131 * @param string $known_string Fixed-length secret string to compare against
132 * @param string $user_string User-provided string
133 * @return bool True if the strings are the same, false otherwise
135 function hash_equals( $known_string, $user_string ) {
136 // Strict type checking as in PHP's native implementation
137 if ( !is_string( $known_string ) ) {
138 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
139 gettype( $known_string ) . ' given', E_USER_WARNING
);
144 if ( !is_string( $user_string ) ) {
145 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
146 gettype( $user_string ) . ' given', E_USER_WARNING
);
151 $known_string_len = strlen( $known_string );
152 if ( $known_string_len !== strlen( $user_string ) ) {
157 for ( $i = 0; $i < $known_string_len; $i++
) {
158 $result |
= ord( $known_string[$i] ) ^
ord( $user_string[$i] );
161 return ( $result === 0 );
169 * This queues an extension to be loaded through
170 * the ExtensionRegistry system.
172 * @param string $ext Name of the extension to load
173 * @param string|null $path Absolute path of where to find the extension.json file
176 function wfLoadExtension( $ext, $path = null ) {
178 global $wgExtensionDirectory;
179 $path = "$wgExtensionDirectory/$ext/extension.json";
181 ExtensionRegistry
::getInstance()->queue( $path );
185 * Load multiple extensions at once
187 * Same as wfLoadExtension, but more efficient if you
188 * are loading multiple extensions.
190 * If you want to specify custom paths, you should interact with
191 * ExtensionRegistry directly.
193 * @see wfLoadExtension
194 * @param string[] $exts Array of extension names to load
197 function wfLoadExtensions( array $exts ) {
198 global $wgExtensionDirectory;
199 $registry = ExtensionRegistry
::getInstance();
200 foreach ( $exts as $ext ) {
201 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
208 * @see wfLoadExtension
209 * @param string $skin Name of the extension to load
210 * @param string|null $path Absolute path of where to find the skin.json file
213 function wfLoadSkin( $skin, $path = null ) {
215 global $wgStyleDirectory;
216 $path = "$wgStyleDirectory/$skin/skin.json";
218 ExtensionRegistry
::getInstance()->queue( $path );
222 * Load multiple skins at once
224 * @see wfLoadExtensions
225 * @param string[] $skins Array of extension names to load
228 function wfLoadSkins( array $skins ) {
229 global $wgStyleDirectory;
230 $registry = ExtensionRegistry
::getInstance();
231 foreach ( $skins as $skin ) {
232 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
237 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
242 function wfArrayDiff2( $a, $b ) {
243 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
247 * @param array|string $a
248 * @param array|string $b
251 function wfArrayDiff2_cmp( $a, $b ) {
252 if ( is_string( $a ) && is_string( $b ) ) {
253 return strcmp( $a, $b );
254 } elseif ( count( $a ) !== count( $b ) ) {
255 return count( $a ) < count( $b ) ?
-1 : 1;
259 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
260 $cmp = strcmp( $valueA, $valueB );
270 * Appends to second array if $value differs from that in $default
272 * @param string|int $key
273 * @param mixed $value
274 * @param mixed $default
275 * @param array $changed Array to alter
276 * @throws MWException
278 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
279 if ( is_null( $changed ) ) {
280 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
282 if ( $default[$key] !== $value ) {
283 $changed[$key] = $value;
288 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
290 * wfMergeErrorArrays(
291 * array( array( 'x' ) ),
292 * array( array( 'x', '2' ) ),
293 * array( array( 'x' ) ),
294 * array( array( 'y' ) )
303 * @param array $array1,...
306 function wfMergeErrorArrays( /*...*/ ) {
307 $args = func_get_args();
309 foreach ( $args as $errors ) {
310 foreach ( $errors as $params ) {
311 $originalParams = $params;
312 if ( $params[0] instanceof MessageSpecifier
) {
314 $params = array_merge( array( $msg->getKey() ), $msg->getParams() );
316 # @todo FIXME: Sometimes get nested arrays for $params,
317 # which leads to E_NOTICEs
318 $spec = implode( "\t", $params );
319 $out[$spec] = $originalParams;
322 return array_values( $out );
326 * Insert array into another array after the specified *KEY*
328 * @param array $array The array.
329 * @param array $insert The array to insert.
330 * @param mixed $after The key to insert after
333 function wfArrayInsertAfter( array $array, array $insert, $after ) {
334 // Find the offset of the element to insert after.
335 $keys = array_keys( $array );
336 $offsetByKey = array_flip( $keys );
338 $offset = $offsetByKey[$after];
340 // Insert at the specified offset
341 $before = array_slice( $array, 0, $offset +
1, true );
342 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
344 $output = $before +
$insert +
$after;
350 * Recursively converts the parameter (an object) to an array with the same data
352 * @param object|array $objOrArray
353 * @param bool $recursive
356 function wfObjectToArray( $objOrArray, $recursive = true ) {
358 if ( is_object( $objOrArray ) ) {
359 $objOrArray = get_object_vars( $objOrArray );
361 foreach ( $objOrArray as $key => $value ) {
362 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
363 $value = wfObjectToArray( $value );
366 $array[$key] = $value;
373 * Get a random decimal value between 0 and 1, in a way
374 * not likely to give duplicate values for any realistic
375 * number of articles.
379 function wfRandom() {
380 # The maximum random value is "only" 2^31-1, so get two random
381 # values to reduce the chance of dupes
382 $max = mt_getrandmax() +
1;
383 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
389 * Get a random string containing a number of pseudo-random hex
391 * @note This is not secure, if you are trying to generate some sort
392 * of token please use MWCryptRand instead.
394 * @param int $length The length of the string to generate
398 function wfRandomString( $length = 32 ) {
400 for ( $n = 0; $n < $length; $n +
= 7 ) {
401 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
403 return substr( $str, 0, $length );
407 * We want some things to be included as literal characters in our title URLs
408 * for prettiness, which urlencode encodes by default. According to RFC 1738,
409 * all of the following should be safe:
413 * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved
414 * character which should not be encoded. More importantly, google chrome
415 * always converts %7E back to ~, and converting it in this function can
416 * cause a redirect loop (T105265).
418 * But + is not safe because it's used to indicate a space; &= are only safe in
419 * paths and not in queries (and we don't distinguish here); ' seems kind of
420 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
421 * is reserved, we don't care. So the list we unescape is:
425 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
426 * so no fancy : for IIS7.
428 * %2F in the page titles seems to fatally break for some reason.
433 function wfUrlencode( $s ) {
436 if ( is_null( $s ) ) {
441 if ( is_null( $needle ) ) {
442 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' );
443 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
444 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
450 $s = urlencode( $s );
453 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ),
461 * This function takes two arrays as input, and returns a CGI-style string, e.g.
462 * "days=7&limit=100". Options in the first array override options in the second.
463 * Options set to null or false will not be output.
465 * @param array $array1 ( String|Array )
466 * @param array $array2 ( String|Array )
467 * @param string $prefix
470 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
471 if ( !is_null( $array2 ) ) {
472 $array1 = $array1 +
$array2;
476 foreach ( $array1 as $key => $value ) {
477 if ( !is_null( $value ) && $value !== false ) {
481 if ( $prefix !== '' ) {
482 $key = $prefix . "[$key]";
484 if ( is_array( $value ) ) {
486 foreach ( $value as $k => $v ) {
487 $cgi .= $firstTime ?
'' : '&';
488 if ( is_array( $v ) ) {
489 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
491 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
496 if ( is_object( $value ) ) {
497 $value = $value->__toString();
499 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
507 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
508 * its argument and returns the same string in array form. This allows compatibility
509 * with legacy functions that accept raw query strings instead of nice
510 * arrays. Of course, keys and values are urldecode()d.
512 * @param string $query Query string
513 * @return string[] Array version of input
515 function wfCgiToArray( $query ) {
516 if ( isset( $query[0] ) && $query[0] == '?' ) {
517 $query = substr( $query, 1 );
519 $bits = explode( '&', $query );
521 foreach ( $bits as $bit ) {
525 if ( strpos( $bit, '=' ) === false ) {
526 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
530 list( $key, $value ) = explode( '=', $bit );
532 $key = urldecode( $key );
533 $value = urldecode( $value );
534 if ( strpos( $key, '[' ) !== false ) {
535 $keys = array_reverse( explode( '[', $key ) );
536 $key = array_pop( $keys );
538 foreach ( $keys as $k ) {
539 $k = substr( $k, 0, -1 );
540 $temp = array( $k => $temp );
542 if ( isset( $ret[$key] ) ) {
543 $ret[$key] = array_merge( $ret[$key], $temp );
555 * Append a query string to an existing URL, which may or may not already
556 * have query string parameters already. If so, they will be combined.
559 * @param string|string[] $query String or associative array
562 function wfAppendQuery( $url, $query ) {
563 if ( is_array( $query ) ) {
564 $query = wfArrayToCgi( $query );
566 if ( $query != '' ) {
567 if ( false === strpos( $url, '?' ) ) {
578 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
581 * The meaning of the PROTO_* constants is as follows:
582 * PROTO_HTTP: Output a URL starting with http://
583 * PROTO_HTTPS: Output a URL starting with https://
584 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
585 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
586 * on which protocol was used for the current incoming request
587 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
588 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
589 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
591 * @todo this won't work with current-path-relative URLs
592 * like "subdir/foo.html", etc.
594 * @param string $url Either fully-qualified or a local path + query
595 * @param string $defaultProto One of the PROTO_* constants. Determines the
596 * protocol to use if $url or $wgServer is protocol-relative
597 * @return string Fully-qualified URL, current-path-relative URL or false if
598 * no valid URL can be constructed
600 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
601 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
603 if ( $defaultProto === PROTO_CANONICAL
) {
604 $serverUrl = $wgCanonicalServer;
605 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
606 // Make $wgInternalServer fall back to $wgServer if not set
607 $serverUrl = $wgInternalServer;
609 $serverUrl = $wgServer;
610 if ( $defaultProto === PROTO_CURRENT
) {
611 $defaultProto = $wgRequest->getProtocol() . '://';
615 // Analyze $serverUrl to obtain its protocol
616 $bits = wfParseUrl( $serverUrl );
617 $serverHasProto = $bits && $bits['scheme'] != '';
619 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
620 if ( $serverHasProto ) {
621 $defaultProto = $bits['scheme'] . '://';
623 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
624 // This really isn't supposed to happen. Fall back to HTTP in this
626 $defaultProto = PROTO_HTTP
;
630 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
632 if ( substr( $url, 0, 2 ) == '//' ) {
633 $url = $defaultProtoWithoutSlashes . $url;
634 } elseif ( substr( $url, 0, 1 ) == '/' ) {
635 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
636 // otherwise leave it alone.
637 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
640 $bits = wfParseUrl( $url );
642 // ensure proper port for HTTPS arrives in URL
643 // https://phabricator.wikimedia.org/T67184
644 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
645 $bits['port'] = $wgHttpsPort;
648 if ( $bits && isset( $bits['path'] ) ) {
649 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
650 return wfAssembleUrl( $bits );
654 } elseif ( substr( $url, 0, 1 ) != '/' ) {
655 # URL is a relative path
656 return wfRemoveDotSegments( $url );
659 # Expanded URL is not valid.
664 * This function will reassemble a URL parsed with wfParseURL. This is useful
665 * if you need to edit part of a URL and put it back together.
667 * This is the basic structure used (brackets contain keys for $urlParts):
668 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
670 * @todo Need to integrate this into wfExpandUrl (bug 32168)
673 * @param array $urlParts URL parts, as output from wfParseUrl
674 * @return string URL assembled from its component parts
676 function wfAssembleUrl( $urlParts ) {
679 if ( isset( $urlParts['delimiter'] ) ) {
680 if ( isset( $urlParts['scheme'] ) ) {
681 $result .= $urlParts['scheme'];
684 $result .= $urlParts['delimiter'];
687 if ( isset( $urlParts['host'] ) ) {
688 if ( isset( $urlParts['user'] ) ) {
689 $result .= $urlParts['user'];
690 if ( isset( $urlParts['pass'] ) ) {
691 $result .= ':' . $urlParts['pass'];
696 $result .= $urlParts['host'];
698 if ( isset( $urlParts['port'] ) ) {
699 $result .= ':' . $urlParts['port'];
703 if ( isset( $urlParts['path'] ) ) {
704 $result .= $urlParts['path'];
707 if ( isset( $urlParts['query'] ) ) {
708 $result .= '?' . $urlParts['query'];
711 if ( isset( $urlParts['fragment'] ) ) {
712 $result .= '#' . $urlParts['fragment'];
719 * Remove all dot-segments in the provided URL path. For example,
720 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
721 * RFC3986 section 5.2.4.
723 * @todo Need to integrate this into wfExpandUrl (bug 32168)
725 * @param string $urlPath URL path, potentially containing dot-segments
726 * @return string URL path with all dot-segments removed
728 function wfRemoveDotSegments( $urlPath ) {
731 $inputLength = strlen( $urlPath );
733 while ( $inputOffset < $inputLength ) {
734 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
735 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
736 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
737 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
740 if ( $prefixLengthTwo == './' ) {
741 # Step A, remove leading "./"
743 } elseif ( $prefixLengthThree == '../' ) {
744 # Step A, remove leading "../"
746 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
747 # Step B, replace leading "/.$" with "/"
749 $urlPath[$inputOffset] = '/';
750 } elseif ( $prefixLengthThree == '/./' ) {
751 # Step B, replace leading "/./" with "/"
753 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
754 # Step C, replace leading "/..$" with "/" and
755 # remove last path component in output
757 $urlPath[$inputOffset] = '/';
759 } elseif ( $prefixLengthFour == '/../' ) {
760 # Step C, replace leading "/../" with "/" and
761 # remove last path component in output
764 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
765 # Step D, remove "^.$"
767 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
768 # Step D, remove "^..$"
771 # Step E, move leading path segment to output
772 if ( $prefixLengthOne == '/' ) {
773 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
775 $slashPos = strpos( $urlPath, '/', $inputOffset );
777 if ( $slashPos === false ) {
778 $output .= substr( $urlPath, $inputOffset );
779 $inputOffset = $inputLength;
781 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
782 $inputOffset +
= $slashPos - $inputOffset;
787 $slashPos = strrpos( $output, '/' );
788 if ( $slashPos === false ) {
791 $output = substr( $output, 0, $slashPos );
800 * Returns a regular expression of url protocols
802 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
803 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
806 function wfUrlProtocols( $includeProtocolRelative = true ) {
807 global $wgUrlProtocols;
809 // Cache return values separately based on $includeProtocolRelative
810 static $withProtRel = null, $withoutProtRel = null;
811 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
812 if ( !is_null( $cachedValue ) ) {
816 // Support old-style $wgUrlProtocols strings, for backwards compatibility
817 // with LocalSettings files from 1.5
818 if ( is_array( $wgUrlProtocols ) ) {
819 $protocols = array();
820 foreach ( $wgUrlProtocols as $protocol ) {
821 // Filter out '//' if !$includeProtocolRelative
822 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
823 $protocols[] = preg_quote( $protocol, '/' );
827 $retval = implode( '|', $protocols );
829 // Ignore $includeProtocolRelative in this case
830 // This case exists for pre-1.6 compatibility, and we can safely assume
831 // that '//' won't appear in a pre-1.6 config because protocol-relative
832 // URLs weren't supported until 1.18
833 $retval = $wgUrlProtocols;
836 // Cache return value
837 if ( $includeProtocolRelative ) {
838 $withProtRel = $retval;
840 $withoutProtRel = $retval;
846 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
847 * you need a regex that matches all URL protocols but does not match protocol-
851 function wfUrlProtocolsWithoutProtRel() {
852 return wfUrlProtocols( false );
856 * parse_url() work-alike, but non-broken. Differences:
858 * 1) Does not raise warnings on bad URLs (just returns false).
859 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
860 * protocol-relative URLs) correctly.
861 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
863 * @param string $url A URL to parse
864 * @return string[] Bits of the URL in an associative array, per PHP docs
866 function wfParseUrl( $url ) {
867 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
869 // Protocol-relative URLs are handled really badly by parse_url(). It's so
870 // bad that the easiest way to handle them is to just prepend 'http:' and
871 // strip the protocol out later.
872 $wasRelative = substr( $url, 0, 2 ) == '//';
873 if ( $wasRelative ) {
876 MediaWiki\
suppressWarnings();
877 $bits = parse_url( $url );
878 MediaWiki\restoreWarnings
();
879 // parse_url() returns an array without scheme for some invalid URLs, e.g.
880 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
881 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
885 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
886 $bits['scheme'] = strtolower( $bits['scheme'] );
888 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
889 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
890 $bits['delimiter'] = '://';
891 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
892 $bits['delimiter'] = ':';
893 // parse_url detects for news: and mailto: the host part of an url as path
894 // We have to correct this wrong detection
895 if ( isset( $bits['path'] ) ) {
896 $bits['host'] = $bits['path'];
903 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
904 if ( !isset( $bits['host'] ) ) {
908 if ( isset( $bits['path'] ) ) {
909 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
910 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
911 $bits['path'] = '/' . $bits['path'];
918 // If the URL was protocol-relative, fix scheme and delimiter
919 if ( $wasRelative ) {
920 $bits['scheme'] = '';
921 $bits['delimiter'] = '//';
927 * Take a URL, make sure it's expanded to fully qualified, and replace any
928 * encoded non-ASCII Unicode characters with their UTF-8 original forms
929 * for more compact display and legibility for local audiences.
931 * @todo handle punycode domains too
936 function wfExpandIRI( $url ) {
937 return preg_replace_callback(
938 '/((?:%[89A-F][0-9A-F])+)/i',
939 'wfExpandIRI_callback',
945 * Private callback for wfExpandIRI
946 * @param array $matches
949 function wfExpandIRI_callback( $matches ) {
950 return urldecode( $matches[1] );
954 * Make URL indexes, appropriate for the el_index field of externallinks.
959 function wfMakeUrlIndexes( $url ) {
960 $bits = wfParseUrl( $url );
962 // Reverse the labels in the hostname, convert to lower case
963 // For emails reverse domainpart only
964 if ( $bits['scheme'] == 'mailto' ) {
965 $mailparts = explode( '@', $bits['host'], 2 );
966 if ( count( $mailparts ) === 2 ) {
967 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
969 // No domain specified, don't mangle it
972 $reversedHost = $domainpart . '@' . $mailparts[0];
974 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
976 // Add an extra dot to the end
977 // Why? Is it in wrong place in mailto links?
978 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
979 $reversedHost .= '.';
981 // Reconstruct the pseudo-URL
982 $prot = $bits['scheme'];
983 $index = $prot . $bits['delimiter'] . $reversedHost;
984 // Leave out user and password. Add the port, path, query and fragment
985 if ( isset( $bits['port'] ) ) {
986 $index .= ':' . $bits['port'];
988 if ( isset( $bits['path'] ) ) {
989 $index .= $bits['path'];
993 if ( isset( $bits['query'] ) ) {
994 $index .= '?' . $bits['query'];
996 if ( isset( $bits['fragment'] ) ) {
997 $index .= '#' . $bits['fragment'];
1000 if ( $prot == '' ) {
1001 return array( "http:$index", "https:$index" );
1003 return array( $index );
1008 * Check whether a given URL has a domain that occurs in a given set of domains
1009 * @param string $url URL
1010 * @param array $domains Array of domains (strings)
1011 * @return bool True if the host part of $url ends in one of the strings in $domains
1013 function wfMatchesDomainList( $url, $domains ) {
1014 $bits = wfParseUrl( $url );
1015 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1016 $host = '.' . $bits['host'];
1017 foreach ( (array)$domains as $domain ) {
1018 $domain = '.' . $domain;
1019 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
1028 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
1029 * In normal operation this is a NOP.
1031 * Controlling globals:
1032 * $wgDebugLogFile - points to the log file
1033 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
1034 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
1036 * @since 1.25 support for additional context data
1038 * @param string $text
1039 * @param string|bool $dest Unused
1040 * @param array $context Additional logging context data
1042 function wfDebug( $text, $dest = 'all', array $context = array() ) {
1043 global $wgDebugRawPage, $wgDebugLogPrefix;
1044 global $wgDebugTimestamps, $wgRequestTime;
1046 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1050 $text = trim( $text );
1052 // Inline logic from deprecated wfDebugTimer()
1053 if ( $wgDebugTimestamps ) {
1054 $context['seconds_elapsed'] = sprintf(
1056 microtime( true ) - $wgRequestTime
1058 $context['memory_used'] = sprintf(
1060 ( memory_get_usage( true ) / ( 1024 * 1024 ) )
1064 if ( $wgDebugLogPrefix !== '' ) {
1065 $context['prefix'] = $wgDebugLogPrefix;
1068 $logger = LoggerFactory
::getInstance( 'wfDebug' );
1069 $logger->debug( $text, $context );
1073 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1076 function wfIsDebugRawPage() {
1078 if ( $cache !== null ) {
1081 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1082 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1084 isset( $_SERVER['SCRIPT_NAME'] )
1085 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1096 * Get microsecond timestamps for debug logs
1098 * @deprecated since 1.25
1101 function wfDebugTimer() {
1102 global $wgDebugTimestamps, $wgRequestTime;
1104 wfDeprecated( __METHOD__
, '1.25' );
1106 if ( !$wgDebugTimestamps ) {
1110 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1111 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1112 return "$prefix $mem ";
1116 * Send a line giving PHP memory usage.
1118 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1120 function wfDebugMem( $exact = false ) {
1121 $mem = memory_get_usage();
1123 $mem = floor( $mem / 1024 ) . ' KiB';
1127 wfDebug( "Memory usage: $mem\n" );
1131 * Send a line to a supplementary debug log file, if configured, or main debug
1134 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
1135 * a string filename or an associative array mapping 'destination' to the
1136 * desired filename. The associative array may also contain a 'sample' key
1137 * with an integer value, specifying a sampling factor. Sampled log events
1138 * will be emitted with a 1 in N random chance.
1140 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1141 * @since 1.25 support for additional context data
1142 * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
1144 * @param string $logGroup
1145 * @param string $text
1146 * @param string|bool $dest Destination of the message:
1147 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1148 * - 'log': only to the log and not in HTML
1149 * - 'private': only to the specific log if set in $wgDebugLogGroups and
1150 * discarded otherwise
1151 * For backward compatibility, it can also take a boolean:
1152 * - true: same as 'all'
1153 * - false: same as 'private'
1154 * @param array $context Additional logging context data
1156 function wfDebugLog(
1157 $logGroup, $text, $dest = 'all', array $context = array()
1159 // Turn $dest into a string if it's a boolean (for b/c)
1160 if ( $dest === true ) {
1162 } elseif ( $dest === false ) {
1166 $text = trim( $text );
1168 $logger = LoggerFactory
::getInstance( $logGroup );
1169 $context['private'] = ( $dest === 'private' );
1170 $logger->info( $text, $context );
1174 * Log for database errors
1176 * @since 1.25 support for additional context data
1178 * @param string $text Database error message.
1179 * @param array $context Additional logging context data
1181 function wfLogDBError( $text, array $context = array() ) {
1182 $logger = LoggerFactory
::getInstance( 'wfLogDBError' );
1183 $logger->error( trim( $text ), $context );
1187 * Throws a warning that $function is deprecated
1189 * @param string $function
1190 * @param string|bool $version Version of MediaWiki that the function
1191 * was deprecated in (Added in 1.19).
1192 * @param string|bool $component Added in 1.19.
1193 * @param int $callerOffset How far up the call stack is the original
1194 * caller. 2 = function that called the function that called
1195 * wfDeprecated (Added in 1.20)
1199 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1200 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1204 * Send a warning either to the debug log or in a PHP error depending on
1205 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1207 * @param string $msg Message to send
1208 * @param int $callerOffset Number of items to go back in the backtrace to
1209 * find the correct caller (1 = function calling wfWarn, ...)
1210 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1211 * only used when $wgDevelopmentWarnings is true
1213 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1214 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1218 * Send a warning as a PHP error and the debug log. This is intended for logging
1219 * warnings in production. For logging development warnings, use WfWarn instead.
1221 * @param string $msg Message to send
1222 * @param int $callerOffset Number of items to go back in the backtrace to
1223 * find the correct caller (1 = function calling wfLogWarning, ...)
1224 * @param int $level PHP error level; defaults to E_USER_WARNING
1226 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1227 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1231 * Log to a file without getting "file size exceeded" signals.
1233 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1234 * send lines to the specified port, prefixed by the specified prefix and a space.
1235 * @since 1.25 support for additional context data
1237 * @param string $text
1238 * @param string $file Filename
1239 * @param array $context Additional logging context data
1240 * @throws MWException
1241 * @deprecated since 1.25 Use \MediaWiki\Logger\LegacyLogger::emit or UDPTransport
1243 function wfErrorLog( $text, $file, array $context = array() ) {
1244 wfDeprecated( __METHOD__
, '1.25' );
1245 $logger = LoggerFactory
::getInstance( 'wfErrorLog' );
1246 $context['destination'] = $file;
1247 $logger->info( trim( $text ), $context );
1253 function wfLogProfilingData() {
1254 global $wgDebugLogGroups, $wgDebugRawPage;
1256 $context = RequestContext
::getMain();
1257 $request = $context->getRequest();
1259 $profiler = Profiler
::instance();
1260 $profiler->setContext( $context );
1261 $profiler->logData();
1263 $config = $context->getConfig();
1264 if ( $config->get( 'StatsdServer' ) ) {
1266 $statsdServer = explode( ':', $config->get( 'StatsdServer' ) );
1267 $statsdHost = $statsdServer[0];
1268 $statsdPort = isset( $statsdServer[1] ) ?
$statsdServer[1] : 8125;
1269 $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1270 $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
1271 $statsdClient->send( $context->getStats()->getBuffer() );
1272 } catch ( Exception
$ex ) {
1273 MWExceptionHandler
::logException( $ex );
1277 # Profiling must actually be enabled...
1278 if ( $profiler instanceof ProfilerStub
) {
1282 if ( isset( $wgDebugLogGroups['profileoutput'] )
1283 && $wgDebugLogGroups['profileoutput'] === false
1285 // Explicitly disabled
1288 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1292 $ctx = array( 'elapsed' => $request->getElapsedTime() );
1293 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1294 $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
1296 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1297 $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP'];
1299 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1300 $ctx['from'] = $_SERVER['HTTP_FROM'];
1302 if ( isset( $ctx['forwarded_for'] ) ||
1303 isset( $ctx['client_ip'] ) ||
1304 isset( $ctx['from'] ) ) {
1305 $ctx['proxy'] = $_SERVER['REMOTE_ADDR'];
1308 // Don't load $wgUser at this late stage just for statistics purposes
1309 // @todo FIXME: We can detect some anons even if it is not loaded.
1310 // See User::getId()
1311 $user = $context->getUser();
1312 $ctx['anon'] = $user->isItemLoaded( 'id' ) && $user->isAnon();
1314 // Command line script uses a FauxRequest object which does not have
1315 // any knowledge about an URL and throw an exception instead.
1317 $ctx['url'] = urldecode( $request->getRequestURL() );
1318 } catch ( Exception
$ignored ) {
1322 $ctx['output'] = $profiler->getOutput();
1324 $log = LoggerFactory
::getInstance( 'profileoutput' );
1325 $log->info( "Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx );
1329 * Increment a statistics counter
1331 * @param string $key
1335 function wfIncrStats( $key, $count = 1 ) {
1336 $stats = RequestContext
::getMain()->getStats();
1337 $stats->updateCount( $key, $count );
1341 * Check whether the wiki is in read-only mode.
1345 function wfReadOnly() {
1346 return wfReadOnlyReason() !== false;
1350 * Check if the site is in read-only mode and return the message if so
1352 * This checks wfConfiguredReadOnlyReason() and the main load balancer
1353 * for slave lag. This may result in DB_SLAVE connection being made.
1355 * @return string|bool String when in read-only mode; false otherwise
1357 function wfReadOnlyReason() {
1358 $readOnly = wfConfiguredReadOnlyReason();
1359 if ( $readOnly !== false ) {
1363 static $lbReadOnly = null;
1364 if ( $lbReadOnly === null ) {
1365 // Callers use this method to be aware that data presented to a user
1366 // may be very stale and thus allowing submissions can be problematic.
1367 $lbReadOnly = wfGetLB()->getReadOnlyReason();
1374 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1376 * @return string|bool String when in read-only mode; false otherwise
1379 function wfConfiguredReadOnlyReason() {
1380 global $wgReadOnly, $wgReadOnlyFile;
1382 if ( $wgReadOnly === null ) {
1383 // Set $wgReadOnly for faster access next time
1384 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1385 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1387 $wgReadOnly = false;
1395 * Return a Language object from $langcode
1397 * @param Language|string|bool $langcode Either:
1398 * - a Language object
1399 * - code of the language to get the message for, if it is
1400 * a valid code create a language for that language, if
1401 * it is a string but not a valid code then make a basic
1403 * - a boolean: if it's false then use the global object for
1404 * the current user's language (as a fallback for the old parameter
1405 * functionality), or if it is true then use global object
1406 * for the wiki's content language.
1409 function wfGetLangObj( $langcode = false ) {
1410 # Identify which language to get or create a language object for.
1411 # Using is_object here due to Stub objects.
1412 if ( is_object( $langcode ) ) {
1413 # Great, we already have the object (hopefully)!
1417 global $wgContLang, $wgLanguageCode;
1418 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1419 # $langcode is the language code of the wikis content language object.
1420 # or it is a boolean and value is true
1425 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1426 # $langcode is the language code of user language object.
1427 # or it was a boolean and value is false
1431 $validCodes = array_keys( Language
::fetchLanguageNames() );
1432 if ( in_array( $langcode, $validCodes ) ) {
1433 # $langcode corresponds to a valid language.
1434 return Language
::factory( $langcode );
1437 # $langcode is a string, but not a valid language code; use content language.
1438 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1443 * This is the function for getting translated interface messages.
1445 * @see Message class for documentation how to use them.
1446 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1448 * This function replaces all old wfMsg* functions.
1450 * @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier
1451 * @param mixed $params,... Normal message parameters
1456 * @see Message::__construct
1458 function wfMessage( $key /*...*/ ) {
1459 $params = func_get_args();
1460 array_shift( $params );
1461 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1462 $params = $params[0];
1464 return new Message( $key, $params );
1468 * This function accepts multiple message keys and returns a message instance
1469 * for the first message which is non-empty. If all messages are empty then an
1470 * instance of the first message key is returned.
1472 * @param string|string[] $keys,... Message keys
1477 * @see Message::newFallbackSequence
1479 function wfMessageFallback( /*...*/ ) {
1480 $args = func_get_args();
1481 return call_user_func_array( 'Message::newFallbackSequence', $args );
1485 * Get a message from anywhere, for the current user language.
1487 * Use wfMsgForContent() instead if the message should NOT
1488 * change depending on the user preferences.
1490 * @deprecated since 1.18
1492 * @param string $key Lookup key for the message, usually
1493 * defined in languages/Language.php
1495 * Parameters to the message, which can be used to insert variable text into
1496 * it, can be passed to this function in the following formats:
1497 * - One per argument, starting at the second parameter
1498 * - As an array in the second parameter
1499 * These are not shown in the function definition.
1503 function wfMsg( $key ) {
1504 wfDeprecated( __METHOD__
, '1.21' );
1506 $args = func_get_args();
1507 array_shift( $args );
1508 return wfMsgReal( $key, $args );
1512 * Same as above except doesn't transform the message
1514 * @deprecated since 1.18
1516 * @param string $key
1519 function wfMsgNoTrans( $key ) {
1520 wfDeprecated( __METHOD__
, '1.21' );
1522 $args = func_get_args();
1523 array_shift( $args );
1524 return wfMsgReal( $key, $args, true, false, false );
1528 * Get a message from anywhere, for the current global language
1529 * set with $wgLanguageCode.
1531 * Use this if the message should NOT change dependent on the
1532 * language set in the user's preferences. This is the case for
1533 * most text written into logs, as well as link targets (such as
1534 * the name of the copyright policy page). Link titles, on the
1535 * other hand, should be shown in the UI language.
1537 * Note that MediaWiki allows users to change the user interface
1538 * language in their preferences, but a single installation
1539 * typically only contains content in one language.
1541 * Be wary of this distinction: If you use wfMsg() where you should
1542 * use wfMsgForContent(), a user of the software may have to
1543 * customize potentially hundreds of messages in
1544 * order to, e.g., fix a link in every possible language.
1546 * @deprecated since 1.18
1548 * @param string $key Lookup key for the message, usually
1549 * defined in languages/Language.php
1552 function wfMsgForContent( $key ) {
1553 wfDeprecated( __METHOD__
, '1.21' );
1555 global $wgForceUIMsgAsContentMsg;
1556 $args = func_get_args();
1557 array_shift( $args );
1559 if ( is_array( $wgForceUIMsgAsContentMsg )
1560 && in_array( $key, $wgForceUIMsgAsContentMsg )
1562 $forcontent = false;
1564 return wfMsgReal( $key, $args, true, $forcontent );
1568 * Same as above except doesn't transform the message
1570 * @deprecated since 1.18
1572 * @param string $key
1575 function wfMsgForContentNoTrans( $key ) {
1576 wfDeprecated( __METHOD__
, '1.21' );
1578 global $wgForceUIMsgAsContentMsg;
1579 $args = func_get_args();
1580 array_shift( $args );
1582 if ( is_array( $wgForceUIMsgAsContentMsg )
1583 && in_array( $key, $wgForceUIMsgAsContentMsg )
1585 $forcontent = false;
1587 return wfMsgReal( $key, $args, true, $forcontent, false );
1591 * Really get a message
1593 * @deprecated since 1.18
1595 * @param string $key Key to get.
1596 * @param array $args
1597 * @param bool $useDB
1598 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1599 * @param bool $transform Whether or not to transform the message.
1600 * @return string The requested message.
1602 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1603 wfDeprecated( __METHOD__
, '1.21' );
1605 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1606 $message = wfMsgReplaceArgs( $message, $args );
1611 * Fetch a message string value, but don't replace any keys yet.
1613 * @deprecated since 1.18
1615 * @param string $key
1616 * @param bool $useDB
1617 * @param string|bool $langCode Code of the language to get the message for, or
1618 * behaves as a content language switch if it is a boolean.
1619 * @param bool $transform Whether to parse magic words, etc.
1622 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1623 wfDeprecated( __METHOD__
, '1.21' );
1625 Hooks
::run( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1627 $cache = MessageCache
::singleton();
1628 $message = $cache->get( $key, $useDB, $langCode );
1629 if ( $message === false ) {
1630 $message = '<' . htmlspecialchars( $key ) . '>';
1631 } elseif ( $transform ) {
1632 $message = $cache->transform( $message );
1638 * Replace message parameter keys on the given formatted output.
1640 * @param string $message
1641 * @param array $args
1645 function wfMsgReplaceArgs( $message, $args ) {
1646 # Fix windows line-endings
1647 # Some messages are split with explode("\n", $msg)
1648 $message = str_replace( "\r", '', $message );
1650 // Replace arguments
1651 if ( count( $args ) ) {
1652 if ( is_array( $args[0] ) ) {
1653 $args = array_values( $args[0] );
1655 $replacementKeys = array();
1656 foreach ( $args as $n => $param ) {
1657 $replacementKeys['$' . ( $n +
1 )] = $param;
1659 $message = strtr( $message, $replacementKeys );
1666 * Return an HTML-escaped version of a message.
1667 * Parameter replacements, if any, are done *after* the HTML-escaping,
1668 * so parameters may contain HTML (eg links or form controls). Be sure
1669 * to pre-escape them if you really do want plaintext, or just wrap
1670 * the whole thing in htmlspecialchars().
1672 * @deprecated since 1.18
1674 * @param string $key
1675 * @param string $args,... Parameters
1678 function wfMsgHtml( $key ) {
1679 wfDeprecated( __METHOD__
, '1.21' );
1681 $args = func_get_args();
1682 array_shift( $args );
1683 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1687 * Return an HTML version of message
1688 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1689 * so parameters may contain HTML (eg links or form controls). Be sure
1690 * to pre-escape them if you really do want plaintext, or just wrap
1691 * the whole thing in htmlspecialchars().
1693 * @deprecated since 1.18
1695 * @param string $key
1696 * @param string $args,... Parameters
1699 function wfMsgWikiHtml( $key ) {
1700 wfDeprecated( __METHOD__
, '1.21' );
1702 $args = func_get_args();
1703 array_shift( $args );
1704 return wfMsgReplaceArgs(
1705 MessageCache
::singleton()->parse( wfMsgGetKey( $key ), null,
1706 /* can't be set to false */ true, /* interface */ true )->getText(),
1711 * Returns message in the requested format
1713 * @deprecated since 1.18
1715 * @param string $key Key of the message
1716 * @param array $options Processing rules.
1717 * Can take the following options:
1718 * parse: parses wikitext to HTML
1719 * parseinline: parses wikitext to HTML and removes the surrounding
1720 * p's added by parser or tidy
1721 * escape: filters message through htmlspecialchars
1722 * escapenoentities: same, but allows entity references like   through
1723 * replaceafter: parameters are substituted after parsing or escaping
1724 * parsemag: transform the message using magic phrases
1725 * content: fetch message for content language instead of interface
1726 * Also can accept a single associative argument, of the form 'language' => 'xx':
1727 * language: Language object or language code to fetch message for
1728 * (overridden by content).
1729 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1733 function wfMsgExt( $key, $options ) {
1734 wfDeprecated( __METHOD__
, '1.21' );
1736 $args = func_get_args();
1737 array_shift( $args );
1738 array_shift( $args );
1739 $options = (array)$options;
1740 $validOptions = array( 'parse', 'parseinline', 'escape', 'escapenoentities', 'replaceafter',
1741 'parsemag', 'content' );
1743 foreach ( $options as $arrayKey => $option ) {
1744 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1745 // An unknown index, neither numeric nor "language"
1746 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
1747 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option, $validOptions ) ) {
1748 // A numeric index with unknown value
1749 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
1753 if ( in_array( 'content', $options, true ) ) {
1756 $langCodeObj = null;
1757 } elseif ( array_key_exists( 'language', $options ) ) {
1758 $forContent = false;
1759 $langCode = wfGetLangObj( $options['language'] );
1760 $langCodeObj = $langCode;
1762 $forContent = false;
1764 $langCodeObj = null;
1767 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1769 if ( !in_array( 'replaceafter', $options, true ) ) {
1770 $string = wfMsgReplaceArgs( $string, $args );
1773 $messageCache = MessageCache
::singleton();
1774 $parseInline = in_array( 'parseinline', $options, true );
1775 if ( in_array( 'parse', $options, true ) ||
$parseInline ) {
1776 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1777 if ( $string instanceof ParserOutput
) {
1778 $string = $string->getText();
1781 if ( $parseInline ) {
1782 $string = Parser
::stripOuterParagraph( $string );
1784 } elseif ( in_array( 'parsemag', $options, true ) ) {
1785 $string = $messageCache->transform( $string,
1786 !$forContent, $langCodeObj );
1789 if ( in_array( 'escape', $options, true ) ) {
1790 $string = htmlspecialchars( $string );
1791 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1792 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
1795 if ( in_array( 'replaceafter', $options, true ) ) {
1796 $string = wfMsgReplaceArgs( $string, $args );
1803 * Since wfMsg() and co suck, they don't return false if the message key they
1804 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1805 * nonexistence of messages by checking the MessageCache::get() result directly.
1807 * @deprecated since 1.18. Use Message::isDisabled().
1809 * @param string $key The message key looked up
1810 * @return bool True if the message *doesn't* exist.
1812 function wfEmptyMsg( $key ) {
1813 wfDeprecated( __METHOD__
, '1.21' );
1815 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1819 * Fetch server name for use in error reporting etc.
1820 * Use real server name if available, so we know which machine
1821 * in a server farm generated the current page.
1825 function wfHostname() {
1827 if ( is_null( $host ) ) {
1829 # Hostname overriding
1830 global $wgOverrideHostname;
1831 if ( $wgOverrideHostname !== false ) {
1832 # Set static and skip any detection
1833 $host = $wgOverrideHostname;
1837 if ( function_exists( 'posix_uname' ) ) {
1838 // This function not present on Windows
1839 $uname = posix_uname();
1843 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1844 $host = $uname['nodename'];
1845 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1846 # Windows computer name
1847 $host = getenv( 'COMPUTERNAME' );
1849 # This may be a virtual server.
1850 $host = $_SERVER['SERVER_NAME'];
1857 * Returns a script tag that stores the amount of time it took MediaWiki to
1858 * handle the request in milliseconds as 'wgBackendResponseTime'.
1860 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1861 * hostname of the server handling the request.
1865 function wfReportTime() {
1866 global $wgRequestTime, $wgShowHostnames;
1868 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1869 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1870 if ( $wgShowHostnames ) {
1871 $reportVars['wgHostname'] = wfHostname();
1873 return Skin
::makeVariablesScript( $reportVars );
1877 * Safety wrapper for debug_backtrace().
1879 * Will return an empty array if debug_backtrace is disabled, otherwise
1880 * the output from debug_backtrace() (trimmed).
1882 * @param int $limit This parameter can be used to limit the number of stack frames returned
1884 * @return array Array of backtrace information
1886 function wfDebugBacktrace( $limit = 0 ) {
1887 static $disabled = null;
1889 if ( is_null( $disabled ) ) {
1890 $disabled = !function_exists( 'debug_backtrace' );
1892 wfDebug( "debug_backtrace() is disabled\n" );
1899 if ( $limit && version_compare( PHP_VERSION
, '5.4.0', '>=' ) ) {
1900 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1902 return array_slice( debug_backtrace(), 1 );
1907 * Get a debug backtrace as a string
1909 * @param bool|null $raw If true, the return value is plain text. If false, HTML.
1910 * Defaults to $wgCommandLineMode if unset.
1912 * @since 1.25 Supports $raw parameter.
1914 function wfBacktrace( $raw = null ) {
1915 global $wgCommandLineMode;
1917 if ( $raw === null ) {
1918 $raw = $wgCommandLineMode;
1922 $frameFormat = "%s line %s calls %s()\n";
1923 $traceFormat = "%s";
1925 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1926 $traceFormat = "<ul>\n%s</ul>\n";
1929 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1930 $file = !empty( $frame['file'] ) ?
basename( $frame['file'] ) : '-';
1931 $line = isset( $frame['line'] ) ?
$frame['line'] : '-';
1932 $call = $frame['function'];
1933 if ( !empty( $frame['class'] ) ) {
1934 $call = $frame['class'] . $frame['type'] . $call;
1936 return sprintf( $frameFormat, $file, $line, $call );
1937 }, wfDebugBacktrace() );
1939 return sprintf( $traceFormat, implode( '', $frames ) );
1943 * Get the name of the function which called this function
1944 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1945 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1946 * wfGetCaller( 3 ) is the parent of that.
1951 function wfGetCaller( $level = 2 ) {
1952 $backtrace = wfDebugBacktrace( $level +
1 );
1953 if ( isset( $backtrace[$level] ) ) {
1954 return wfFormatStackFrame( $backtrace[$level] );
1961 * Return a string consisting of callers in the stack. Useful sometimes
1962 * for profiling specific points.
1964 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1967 function wfGetAllCallers( $limit = 3 ) {
1968 $trace = array_reverse( wfDebugBacktrace() );
1969 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1970 $limit = count( $trace ) - 1;
1972 $trace = array_slice( $trace, -$limit - 1, $limit );
1973 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1977 * Return a string representation of frame
1979 * @param array $frame
1982 function wfFormatStackFrame( $frame ) {
1983 if ( !isset( $frame['function'] ) ) {
1984 return 'NO_FUNCTION_GIVEN';
1986 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1987 $frame['class'] . $frame['type'] . $frame['function'] :
1991 /* Some generic result counters, pulled out of SearchEngine */
1996 * @param int $offset
2000 function wfShowingResults( $offset, $limit ) {
2001 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
2006 * @todo FIXME: We may want to blacklist some broken browsers
2008 * @param bool $force
2009 * @return bool Whereas client accept gzip compression
2011 function wfClientAcceptsGzip( $force = false ) {
2012 static $result = null;
2013 if ( $result === null ||
$force ) {
2015 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
2016 # @todo FIXME: We may want to blacklist some broken browsers
2019 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
2020 $_SERVER['HTTP_ACCEPT_ENCODING'],
2024 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2028 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2037 * Obtain the offset and limit values from the request string;
2038 * used in special pages
2040 * @param int $deflimit Default limit if none supplied
2041 * @param string $optionname Name of a user preference to check against
2043 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2045 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2047 wfDeprecated( __METHOD__
, '1.24' );
2048 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2052 * Escapes the given text so that it may be output using addWikiText()
2053 * without any linking, formatting, etc. making its way through. This
2054 * is achieved by substituting certain characters with HTML entities.
2055 * As required by the callers, "<nowiki>" is not used.
2057 * @param string $text Text to be escaped
2060 function wfEscapeWikiText( $text ) {
2061 static $repl = null, $repl2 = null;
2062 if ( $repl === null ) {
2064 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
2065 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
2066 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
2067 "\n#" => "\n#", "\r#" => "\r#",
2068 "\n*" => "\n*", "\r*" => "\r*",
2069 "\n:" => "\n:", "\r:" => "\r:",
2070 "\n " => "\n ", "\r " => "\r ",
2071 "\n\n" => "\n ", "\r\n" => " \n",
2072 "\n\r" => "\n ", "\r\r" => "\r ",
2073 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
2074 "\n----" => "\n----", "\r----" => "\r----",
2075 '__' => '__', '://' => '://',
2078 // We have to catch everything "\s" matches in PCRE
2079 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2080 $repl["$magic "] = "$magic ";
2081 $repl["$magic\t"] = "$magic	";
2082 $repl["$magic\r"] = "$magic ";
2083 $repl["$magic\n"] = "$magic ";
2084 $repl["$magic\f"] = "$magic";
2087 // And handle protocols that don't use "://"
2088 global $wgUrlProtocols;
2090 foreach ( $wgUrlProtocols as $prot ) {
2091 if ( substr( $prot, -1 ) === ':' ) {
2092 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2095 $repl2 = $repl2 ?
'/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2097 $text = substr( strtr( "\n$text", $repl ), 1 );
2098 $text = preg_replace( $repl2, '$1:', $text );
2103 * Sets dest to source and returns the original value of dest
2104 * If source is NULL, it just returns the value, it doesn't set the variable
2105 * If force is true, it will set the value even if source is NULL
2107 * @param mixed $dest
2108 * @param mixed $source
2109 * @param bool $force
2112 function wfSetVar( &$dest, $source, $force = false ) {
2114 if ( !is_null( $source ) ||
$force ) {
2121 * As for wfSetVar except setting a bit
2125 * @param bool $state
2129 function wfSetBit( &$dest, $bit, $state = true ) {
2130 $temp = (bool)( $dest & $bit );
2131 if ( !is_null( $state ) ) {
2142 * A wrapper around the PHP function var_export().
2143 * Either print it or add it to the regular output ($wgOut).
2145 * @param mixed $var A PHP variable to dump.
2147 function wfVarDump( $var ) {
2149 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2150 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
2153 $wgOut->addHTML( $s );
2158 * Provide a simple HTTP error.
2160 * @param int|string $code
2161 * @param string $label
2162 * @param string $desc
2164 function wfHttpError( $code, $label, $desc ) {
2166 HttpStatus
::header( $code );
2169 $wgOut->sendCacheControl();
2172 header( 'Content-type: text/html; charset=utf-8' );
2173 print '<!DOCTYPE html>' .
2174 '<html><head><title>' .
2175 htmlspecialchars( $label ) .
2176 '</title></head><body><h1>' .
2177 htmlspecialchars( $label ) .
2179 nl2br( htmlspecialchars( $desc ) ) .
2180 "</p></body></html>\n";
2184 * Clear away any user-level output buffers, discarding contents.
2186 * Suitable for 'starting afresh', for instance when streaming
2187 * relatively large amounts of data without buffering, or wanting to
2188 * output image files without ob_gzhandler's compression.
2190 * The optional $resetGzipEncoding parameter controls suppression of
2191 * the Content-Encoding header sent by ob_gzhandler; by default it
2192 * is left. See comments for wfClearOutputBuffers() for why it would
2195 * Note that some PHP configuration options may add output buffer
2196 * layers which cannot be removed; these are left in place.
2198 * @param bool $resetGzipEncoding
2200 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2201 if ( $resetGzipEncoding ) {
2202 // Suppress Content-Encoding and Content-Length
2203 // headers from 1.10+s wfOutputHandler
2204 global $wgDisableOutputCompression;
2205 $wgDisableOutputCompression = true;
2207 while ( $status = ob_get_status() ) {
2208 if ( isset( $status['flags'] ) ) {
2209 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE
;
2210 $deleteable = ( $status['flags'] & $flags ) === $flags;
2211 } elseif ( isset( $status['del'] ) ) {
2212 $deleteable = $status['del'];
2214 // Guess that any PHP-internal setting can't be removed.
2215 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
2217 if ( !$deleteable ) {
2218 // Give up, and hope the result doesn't break
2222 if ( $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ) {
2223 // Unit testing barrier to prevent this function from breaking PHPUnit.
2226 if ( !ob_end_clean() ) {
2227 // Could not remove output buffer handler; abort now
2228 // to avoid getting in some kind of infinite loop.
2231 if ( $resetGzipEncoding ) {
2232 if ( $status['name'] == 'ob_gzhandler' ) {
2233 // Reset the 'Content-Encoding' field set by this handler
2234 // so we can start fresh.
2235 header_remove( 'Content-Encoding' );
2243 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2245 * Clear away output buffers, but keep the Content-Encoding header
2246 * produced by ob_gzhandler, if any.
2248 * This should be used for HTTP 304 responses, where you need to
2249 * preserve the Content-Encoding header of the real result, but
2250 * also need to suppress the output of ob_gzhandler to keep to spec
2251 * and avoid breaking Firefox in rare cases where the headers and
2252 * body are broken over two packets.
2254 function wfClearOutputBuffers() {
2255 wfResetOutputBuffers( false );
2259 * Converts an Accept-* header into an array mapping string values to quality
2262 * @param string $accept
2263 * @param string $def Default
2264 * @return float[] Associative array of string => float pairs
2266 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2267 # No arg means accept anything (per HTTP spec)
2269 return array( $def => 1.0 );
2274 $parts = explode( ',', $accept );
2276 foreach ( $parts as $part ) {
2277 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2278 $values = explode( ';', trim( $part ) );
2280 if ( count( $values ) == 1 ) {
2281 $prefs[$values[0]] = 1.0;
2282 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2283 $prefs[$values[0]] = floatval( $match[1] );
2291 * Checks if a given MIME type matches any of the keys in the given
2292 * array. Basic wildcards are accepted in the array keys.
2294 * Returns the matching MIME type (or wildcard) if a match, otherwise
2297 * @param string $type
2298 * @param array $avail
2302 function mimeTypeMatch( $type, $avail ) {
2303 if ( array_key_exists( $type, $avail ) ) {
2306 $parts = explode( '/', $type );
2307 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2308 return $parts[0] . '/*';
2309 } elseif ( array_key_exists( '*/*', $avail ) ) {
2318 * Returns the 'best' match between a client's requested internet media types
2319 * and the server's list of available types. Each list should be an associative
2320 * array of type to preference (preference is a float between 0.0 and 1.0).
2321 * Wildcards in the types are acceptable.
2323 * @param array $cprefs Client's acceptable type list
2324 * @param array $sprefs Server's offered types
2327 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2328 * XXX: generalize to negotiate other stuff
2330 function wfNegotiateType( $cprefs, $sprefs ) {
2333 foreach ( array_keys( $sprefs ) as $type ) {
2334 $parts = explode( '/', $type );
2335 if ( $parts[1] != '*' ) {
2336 $ckey = mimeTypeMatch( $type, $cprefs );
2338 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2343 foreach ( array_keys( $cprefs ) as $type ) {
2344 $parts = explode( '/', $type );
2345 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2346 $skey = mimeTypeMatch( $type, $sprefs );
2348 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2356 foreach ( array_keys( $combine ) as $type ) {
2357 if ( $combine[$type] > $bestq ) {
2359 $bestq = $combine[$type];
2367 * Reference-counted warning suppression
2369 * @deprecated since 1.26, use MediaWiki\suppressWarnings() directly
2372 function wfSuppressWarnings( $end = false ) {
2373 MediaWiki\
suppressWarnings( $end );
2377 * @deprecated since 1.26, use MediaWiki\restoreWarnings() directly
2378 * Restore error level to previous value
2380 function wfRestoreWarnings() {
2381 MediaWiki\
suppressWarnings( true );
2384 # Autodetect, convert and provide timestamps of various types
2387 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2389 define( 'TS_UNIX', 0 );
2392 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2394 define( 'TS_MW', 1 );
2397 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2399 define( 'TS_DB', 2 );
2402 * RFC 2822 format, for E-mail and HTTP headers
2404 define( 'TS_RFC2822', 3 );
2407 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2409 * This is used by Special:Export
2411 define( 'TS_ISO_8601', 4 );
2414 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2416 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2417 * DateTime tag and page 36 for the DateTimeOriginal and
2418 * DateTimeDigitized tags.
2420 define( 'TS_EXIF', 5 );
2423 * Oracle format time.
2425 define( 'TS_ORACLE', 6 );
2428 * Postgres format time.
2430 define( 'TS_POSTGRES', 7 );
2433 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2435 define( 'TS_ISO_8601_BASIC', 9 );
2438 * Get a timestamp string in one of various formats
2440 * @param mixed $outputtype A timestamp in one of the supported formats, the
2441 * function will autodetect which format is supplied and act accordingly.
2442 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2443 * @return string|bool String / false The same date in the format specified in $outputtype or false
2445 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2447 $timestamp = new MWTimestamp( $ts );
2448 return $timestamp->getTimestamp( $outputtype );
2449 } catch ( TimestampException
$e ) {
2450 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2456 * Return a formatted timestamp, or null if input is null.
2457 * For dealing with nullable timestamp columns in the database.
2459 * @param int $outputtype
2463 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2464 if ( is_null( $ts ) ) {
2467 return wfTimestamp( $outputtype, $ts );
2472 * Convenience function; returns MediaWiki timestamp for the present time.
2476 function wfTimestampNow() {
2478 return wfTimestamp( TS_MW
, time() );
2482 * Check if the operating system is Windows
2484 * @return bool True if it's Windows, false otherwise.
2486 function wfIsWindows() {
2487 static $isWindows = null;
2488 if ( $isWindows === null ) {
2489 $isWindows = strtoupper( substr( PHP_OS
, 0, 3 ) ) === 'WIN';
2495 * Check if we are running under HHVM
2499 function wfIsHHVM() {
2500 return defined( 'HHVM_VERSION' );
2504 * Tries to get the system directory for temporary files. First
2505 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2506 * environment variables are then checked in sequence, and if none are
2507 * set try sys_get_temp_dir().
2509 * NOTE: When possible, use instead the tmpfile() function to create
2510 * temporary files to avoid race conditions on file creation, etc.
2514 function wfTempDir() {
2515 global $wgTmpDirectory;
2517 if ( $wgTmpDirectory !== false ) {
2518 return $wgTmpDirectory;
2521 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2523 foreach ( $tmpDir as $tmp ) {
2524 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2528 return sys_get_temp_dir();
2532 * Make directory, and make all parent directories if they don't exist
2534 * @param string $dir Full path to directory to create
2535 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2536 * @param string $caller Optional caller param for debugging.
2537 * @throws MWException
2540 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2541 global $wgDirectoryMode;
2543 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2544 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2547 if ( !is_null( $caller ) ) {
2548 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2551 if ( strval( $dir ) === '' ||
is_dir( $dir ) ) {
2555 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2557 if ( is_null( $mode ) ) {
2558 $mode = $wgDirectoryMode;
2561 // Turn off the normal warning, we're doing our own below
2562 MediaWiki\
suppressWarnings();
2563 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2564 MediaWiki\restoreWarnings
();
2567 // directory may have been created on another request since we last checked
2568 if ( is_dir( $dir ) ) {
2572 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2573 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2579 * Remove a directory and all its content.
2580 * Does not hide error.
2581 * @param string $dir
2583 function wfRecursiveRemoveDir( $dir ) {
2584 wfDebug( __FUNCTION__
. "( $dir )\n" );
2585 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2586 if ( is_dir( $dir ) ) {
2587 $objects = scandir( $dir );
2588 foreach ( $objects as $object ) {
2589 if ( $object != "." && $object != ".." ) {
2590 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2591 wfRecursiveRemoveDir( $dir . '/' . $object );
2593 unlink( $dir . '/' . $object );
2603 * @param int $nr The number to format
2604 * @param int $acc The number of digits after the decimal point, default 2
2605 * @param bool $round Whether or not to round the value, default true
2608 function wfPercent( $nr, $acc = 2, $round = true ) {
2609 $ret = sprintf( "%.${acc}f", $nr );
2610 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2614 * Safety wrapper around ini_get() for boolean settings.
2615 * The values returned from ini_get() are pre-normalized for settings
2616 * set via php.ini or php_flag/php_admin_flag... but *not*
2617 * for those set via php_value/php_admin_value.
2619 * It's fairly common for people to use php_value instead of php_flag,
2620 * which can leave you with an 'off' setting giving a false positive
2621 * for code that just takes the ini_get() return value as a boolean.
2623 * To make things extra interesting, setting via php_value accepts
2624 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2625 * Unrecognized values go false... again opposite PHP's own coercion
2626 * from string to bool.
2628 * Luckily, 'properly' set settings will always come back as '0' or '1',
2629 * so we only have to worry about them and the 'improper' settings.
2631 * I frickin' hate PHP... :P
2633 * @param string $setting
2636 function wfIniGetBool( $setting ) {
2637 $val = strtolower( ini_get( $setting ) );
2638 // 'on' and 'true' can't have whitespace around them, but '1' can.
2642 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2646 * Windows-compatible version of escapeshellarg()
2647 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2648 * function puts single quotes in regardless of OS.
2650 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2651 * earlier distro releases of PHP)
2653 * @param string ... strings to escape and glue together, or a single array of strings parameter
2656 function wfEscapeShellArg( /*...*/ ) {
2657 wfInitShellLocale();
2659 $args = func_get_args();
2660 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
2661 // If only one argument has been passed, and that argument is an array,
2662 // treat it as a list of arguments
2663 $args = reset( $args );
2668 foreach ( $args as $arg ) {
2675 if ( wfIsWindows() ) {
2676 // Escaping for an MSVC-style command line parser and CMD.EXE
2677 // @codingStandardsIgnoreStart For long URLs
2679 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2680 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2683 // Double the backslashes before any double quotes. Escape the double quotes.
2684 // @codingStandardsIgnoreEnd
2685 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2688 foreach ( $tokens as $token ) {
2689 if ( $iteration %
2 == 1 ) {
2690 // Delimiter, a double quote preceded by zero or more slashes
2691 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2692 } elseif ( $iteration %
4 == 2 ) {
2693 // ^ in $token will be outside quotes, need to be escaped
2694 $arg .= str_replace( '^', '^^', $token );
2695 } else { // $iteration % 4 == 0
2696 // ^ in $token will appear inside double quotes, so leave as is
2701 // Double the backslashes before the end of the string, because
2702 // we will soon add a quote
2704 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2705 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2708 // Add surrounding quotes
2709 $retVal .= '"' . $arg . '"';
2711 $retVal .= escapeshellarg( $arg );
2718 * Check if wfShellExec() is effectively disabled via php.ini config
2720 * @return bool|string False or one of (safemode,disabled)
2723 function wfShellExecDisabled() {
2724 static $disabled = null;
2725 if ( is_null( $disabled ) ) {
2726 if ( wfIniGetBool( 'safe_mode' ) ) {
2727 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2728 $disabled = 'safemode';
2729 } elseif ( !function_exists( 'proc_open' ) ) {
2730 wfDebug( "proc_open() is disabled\n" );
2731 $disabled = 'disabled';
2740 * Execute a shell command, with time and memory limits mirrored from the PHP
2741 * configuration if supported.
2743 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2744 * or an array of unescaped arguments, in which case each value will be escaped
2745 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2746 * @param null|mixed &$retval Optional, will receive the program's exit code.
2747 * (non-zero is usually failure). If there is an error from
2748 * read, select, or proc_open(), this will be set to -1.
2749 * @param array $environ Optional environment variables which should be
2750 * added to the executed command environment.
2751 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2752 * this overwrites the global wgMaxShell* limits.
2753 * @param array $options Array of options:
2754 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2755 * including errors from limit.sh
2756 * - profileMethod: By default this function will profile based on the calling
2757 * method. Set this to a string for an alternative method to profile from
2759 * @return string Collected stdout as a string
2761 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2762 $limits = array(), $options = array()
2764 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2765 $wgMaxShellWallClockTime, $wgShellCgroup;
2767 $disabled = wfShellExecDisabled();
2770 return $disabled == 'safemode' ?
2771 'Unable to run external programs in safe mode.' :
2772 'Unable to run external programs, proc_open() is disabled.';
2775 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2776 $profileMethod = isset( $options['profileMethod'] ) ?
$options['profileMethod'] : wfGetCaller();
2778 wfInitShellLocale();
2781 foreach ( $environ as $k => $v ) {
2782 if ( wfIsWindows() ) {
2783 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2784 * appear in the environment variable, so we must use carat escaping as documented in
2785 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2786 * Note however that the quote isn't listed there, but is needed, and the parentheses
2787 * are listed there but doesn't appear to need it.
2789 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2791 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2792 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2794 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2797 if ( is_array( $cmd ) ) {
2798 $cmd = wfEscapeShellArg( $cmd );
2801 $cmd = $envcmd . $cmd;
2803 $useLogPipe = false;
2804 if ( is_executable( '/bin/bash' ) ) {
2805 $time = intval( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2806 if ( isset( $limits['walltime'] ) ) {
2807 $wallTime = intval( $limits['walltime'] );
2808 } elseif ( isset( $limits['time'] ) ) {
2811 $wallTime = intval( $wgMaxShellWallClockTime );
2813 $mem = intval( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2814 $filesize = intval( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2816 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2817 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2818 escapeshellarg( $cmd ) . ' ' .
2820 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2821 "MW_CPU_LIMIT=$time; " .
2822 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2823 "MW_MEM_LIMIT=$mem; " .
2824 "MW_FILE_SIZE_LIMIT=$filesize; " .
2825 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2826 "MW_USE_LOG_PIPE=yes"
2829 } elseif ( $includeStderr ) {
2832 } elseif ( $includeStderr ) {
2835 wfDebug( "wfShellExec: $cmd\n" );
2838 0 => array( 'file', 'php://stdin', 'r' ),
2839 1 => array( 'pipe', 'w' ),
2840 2 => array( 'file', 'php://stderr', 'w' ) );
2841 if ( $useLogPipe ) {
2842 $desc[3] = array( 'pipe', 'w' );
2845 $scoped = Profiler
::instance()->scopedProfileIn( __FUNCTION__
. '-' . $profileMethod );
2846 $proc = proc_open( $cmd, $desc, $pipes );
2848 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2852 $outBuffer = $logBuffer = '';
2853 $emptyArray = array();
2857 /* According to the documentation, it is possible for stream_select()
2858 * to fail due to EINTR. I haven't managed to induce this in testing
2859 * despite sending various signals. If it did happen, the error
2860 * message would take the form:
2862 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2864 * where [4] is the value of the macro EINTR and "Interrupted system
2865 * call" is string which according to the Linux manual is "possibly"
2866 * localised according to LC_MESSAGES.
2868 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2869 $eintrMessage = "stream_select(): unable to select [$eintr]";
2871 // Build a table mapping resource IDs to pipe FDs to work around a
2872 // PHP 5.3 issue in which stream_select() does not preserve array keys
2873 // <https://bugs.php.net/bug.php?id=53427>.
2875 foreach ( $pipes as $fd => $pipe ) {
2876 $fds[(int)$pipe] = $fd;
2883 while ( $running === true ||
$numReadyPipes !== 0 ) {
2885 $status = proc_get_status( $proc );
2886 // If the process has terminated, switch to nonblocking selects
2887 // for getting any data still waiting to be read.
2888 if ( !$status['running'] ) {
2894 $readyPipes = $pipes;
2897 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2898 @trigger_error
( '' );
2899 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
2900 if ( $numReadyPipes === false ) {
2901 // @codingStandardsIgnoreEnd
2902 $error = error_get_last();
2903 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2906 trigger_error( $error['message'], E_USER_WARNING
);
2907 $logMsg = $error['message'];
2911 foreach ( $readyPipes as $pipe ) {
2912 $block = fread( $pipe, 65536 );
2913 $fd = $fds[(int)$pipe];
2914 if ( $block === '' ) {
2916 fclose( $pipes[$fd] );
2917 unset( $pipes[$fd] );
2921 } elseif ( $block === false ) {
2923 $logMsg = "Error reading from pipe";
2925 } elseif ( $fd == 1 ) {
2927 $outBuffer .= $block;
2928 } elseif ( $fd == 3 ) {
2930 $logBuffer .= $block;
2931 if ( strpos( $block, "\n" ) !== false ) {
2932 $lines = explode( "\n", $logBuffer );
2933 $logBuffer = array_pop( $lines );
2934 foreach ( $lines as $line ) {
2935 wfDebugLog( 'exec', $line );
2942 foreach ( $pipes as $pipe ) {
2946 // Use the status previously collected if possible, since proc_get_status()
2947 // just calls waitpid() which will not return anything useful the second time.
2949 $status = proc_get_status( $proc );
2952 if ( $logMsg !== false ) {
2953 // Read/select error
2955 proc_close( $proc );
2956 } elseif ( $status['signaled'] ) {
2957 $logMsg = "Exited with signal {$status['termsig']}";
2958 $retval = 128 +
$status['termsig'];
2959 proc_close( $proc );
2961 if ( $status['running'] ) {
2962 $retval = proc_close( $proc );
2964 $retval = $status['exitcode'];
2965 proc_close( $proc );
2967 if ( $retval == 127 ) {
2968 $logMsg = "Possibly missing executable file";
2969 } elseif ( $retval >= 129 && $retval <= 192 ) {
2970 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2974 if ( $logMsg !== false ) {
2975 wfDebugLog( 'exec', "$logMsg: $cmd" );
2982 * Execute a shell command, returning both stdout and stderr. Convenience
2983 * function, as all the arguments to wfShellExec can become unwieldy.
2985 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2986 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2987 * or an array of unescaped arguments, in which case each value will be escaped
2988 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2989 * @param null|mixed &$retval Optional, will receive the program's exit code.
2990 * (non-zero is usually failure)
2991 * @param array $environ Optional environment variables which should be
2992 * added to the executed command environment.
2993 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2994 * this overwrites the global wgMaxShell* limits.
2995 * @return string Collected stdout and stderr as a string
2997 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2998 return wfShellExec( $cmd, $retval, $environ, $limits,
2999 array( 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ) );
3003 * Workaround for http://bugs.php.net/bug.php?id=45132
3004 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
3006 function wfInitShellLocale() {
3007 static $done = false;
3012 global $wgShellLocale;
3013 if ( !wfIniGetBool( 'safe_mode' ) ) {
3014 putenv( "LC_CTYPE=$wgShellLocale" );
3015 setlocale( LC_CTYPE
, $wgShellLocale );
3020 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3021 * Note that $parameters should be a flat array and an option with an argument
3022 * should consist of two consecutive items in the array (do not use "--option value").
3024 * @param string $script MediaWiki cli script path
3025 * @param array $parameters Arguments and options to the script
3026 * @param array $options Associative array of options:
3027 * 'php': The path to the php executable
3028 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3031 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3033 // Give site config file a chance to run the script in a wrapper.
3034 // The caller may likely want to call wfBasename() on $script.
3035 Hooks
::run( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3036 $cmd = isset( $options['php'] ) ?
array( $options['php'] ) : array( $wgPhpCli );
3037 if ( isset( $options['wrapper'] ) ) {
3038 $cmd[] = $options['wrapper'];
3041 // Escape each parameter for shell
3042 return wfEscapeShellArg( array_merge( $cmd, $parameters ) );
3046 * wfMerge attempts to merge differences between three texts.
3047 * Returns true for a clean merge and false for failure or a conflict.
3049 * @param string $old
3050 * @param string $mine
3051 * @param string $yours
3052 * @param string $result
3055 function wfMerge( $old, $mine, $yours, &$result ) {
3058 # This check may also protect against code injection in
3059 # case of broken installations.
3060 MediaWiki\
suppressWarnings();
3061 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3062 MediaWiki\restoreWarnings
();
3064 if ( !$haveDiff3 ) {
3065 wfDebug( "diff3 not found\n" );
3069 # Make temporary files
3071 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3072 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3073 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3075 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3076 # a newline character. To avoid this, we normalize the trailing whitespace before
3077 # creating the diff.
3079 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3080 fclose( $oldtextFile );
3081 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3082 fclose( $mytextFile );
3083 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3084 fclose( $yourtextFile );
3086 # Check for a conflict
3087 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '--overlap-only', $mytextName,
3088 $oldtextName, $yourtextName );
3089 $handle = popen( $cmd, 'r' );
3091 if ( fgets( $handle, 1024 ) ) {
3099 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '-e', '--merge', $mytextName,
3100 $oldtextName, $yourtextName );
3101 $handle = popen( $cmd, 'r' );
3104 $data = fread( $handle, 8192 );
3105 if ( strlen( $data ) == 0 ) {
3111 unlink( $mytextName );
3112 unlink( $oldtextName );
3113 unlink( $yourtextName );
3115 if ( $result === '' && $old !== '' && !$conflict ) {
3116 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3123 * Returns unified plain-text diff of two texts.
3124 * "Useful" for machine processing of diffs.
3126 * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly
3128 * @param string $before The text before the changes.
3129 * @param string $after The text after the changes.
3130 * @param string $params Command-line options for the diff command.
3131 * @return string Unified diff of $before and $after
3133 function wfDiff( $before, $after, $params = '-u' ) {
3134 if ( $before == $after ) {
3139 MediaWiki\
suppressWarnings();
3140 $haveDiff = $wgDiff && file_exists( $wgDiff );
3141 MediaWiki\restoreWarnings
();
3143 # This check may also protect against code injection in
3144 # case of broken installations.
3146 wfDebug( "diff executable not found\n" );
3147 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3148 $format = new UnifiedDiffFormatter();
3149 return $format->format( $diffs );
3152 # Make temporary files
3154 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3155 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3157 fwrite( $oldtextFile, $before );
3158 fclose( $oldtextFile );
3159 fwrite( $newtextFile, $after );
3160 fclose( $newtextFile );
3162 // Get the diff of the two files
3163 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3165 $h = popen( $cmd, 'r' );
3167 unlink( $oldtextName );
3168 unlink( $newtextName );
3169 throw new Exception( __METHOD__
. '(): popen() failed' );
3175 $data = fread( $h, 8192 );
3176 if ( strlen( $data ) == 0 ) {
3184 unlink( $oldtextName );
3185 unlink( $newtextName );
3187 // Kill the --- and +++ lines. They're not useful.
3188 $diff_lines = explode( "\n", $diff );
3189 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
3190 unset( $diff_lines[0] );
3192 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
3193 unset( $diff_lines[1] );
3196 $diff = implode( "\n", $diff_lines );
3202 * This function works like "use VERSION" in Perl, the program will die with a
3203 * backtrace if the current version of PHP is less than the version provided
3205 * This is useful for extensions which due to their nature are not kept in sync
3206 * with releases, and might depend on other versions of PHP than the main code
3208 * Note: PHP might die due to parsing errors in some cases before it ever
3209 * manages to call this function, such is life
3211 * @see perldoc -f use
3213 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3214 * @throws MWException
3216 function wfUsePHP( $req_ver ) {
3217 $php_ver = PHP_VERSION
;
3219 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3220 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3225 * This function works like "use VERSION" in Perl except it checks the version
3226 * of MediaWiki, the program will die with a backtrace if the current version
3227 * of MediaWiki is less than the version provided.
3229 * This is useful for extensions which due to their nature are not kept in sync
3232 * Note: Due to the behavior of PHP's version_compare() which is used in this
3233 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3234 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3235 * targeted version number. For example if you wanted to allow any variation
3236 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3237 * not result in the same comparison due to the internal logic of
3238 * version_compare().
3240 * @see perldoc -f use
3242 * @deprecated since 1.26, use the "requires' property of extension.json
3243 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3244 * @throws MWException
3246 function wfUseMW( $req_ver ) {
3249 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3250 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3255 * Return the final portion of a pathname.
3256 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3257 * http://bugs.php.net/bug.php?id=33898
3259 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3260 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3262 * @param string $path
3263 * @param string $suffix String to remove if present
3266 function wfBaseName( $path, $suffix = '' ) {
3267 if ( $suffix == '' ) {
3270 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3274 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3282 * Generate a relative path name to the given file.
3283 * May explode on non-matching case-insensitive paths,
3284 * funky symlinks, etc.
3286 * @param string $path Absolute destination path including target filename
3287 * @param string $from Absolute source path, directory only
3290 function wfRelativePath( $path, $from ) {
3291 // Normalize mixed input on Windows...
3292 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
3293 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
3295 // Trim trailing slashes -- fix for drive root
3296 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
3297 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
3299 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
3300 $against = explode( DIRECTORY_SEPARATOR
, $from );
3302 if ( $pieces[0] !== $against[0] ) {
3303 // Non-matching Windows drive letters?
3304 // Return a full path.
3308 // Trim off common prefix
3309 while ( count( $pieces ) && count( $against )
3310 && $pieces[0] == $against[0] ) {
3311 array_shift( $pieces );
3312 array_shift( $against );
3315 // relative dots to bump us to the parent
3316 while ( count( $against ) ) {
3317 array_unshift( $pieces, '..' );
3318 array_shift( $against );
3321 array_push( $pieces, wfBaseName( $path ) );
3323 return implode( DIRECTORY_SEPARATOR
, $pieces );
3327 * Convert an arbitrarily-long digit string from one numeric base
3328 * to another, optionally zero-padding to a minimum column width.
3330 * Supports base 2 through 36; digit values 10-36 are represented
3331 * as lowercase letters a-z. Input is case-insensitive.
3333 * @param string $input Input number
3334 * @param int $sourceBase Base of the input number
3335 * @param int $destBase Desired base of the output
3336 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3337 * @param bool $lowercase Whether to output in lowercase or uppercase
3338 * @param string $engine Either "gmp", "bcmath", or "php"
3339 * @return string|bool The output number as a string, or false on error
3341 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3342 $lowercase = true, $engine = 'auto'
3344 return Wikimedia\base_convert
( $input, $sourceBase, $destBase, $pad, $lowercase, $engine );
3348 * Check if there is sufficient entropy in php's built-in session generation
3350 * @return bool True = there is sufficient entropy
3352 function wfCheckEntropy() {
3354 ( wfIsWindows() && version_compare( PHP_VERSION
, '5.3.3', '>=' ) )
3355 ||
ini_get( 'session.entropy_file' )
3357 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3361 * Override session_id before session startup if php's built-in
3362 * session generation code is not secure.
3364 function wfFixSessionID() {
3365 // If the cookie or session id is already set we already have a session and should abort
3366 if ( isset( $_COOKIE[session_name()] ) ||
session_id() ) {
3370 // PHP's built-in session entropy is enabled if:
3371 // - entropy_file is set or you're on Windows with php 5.3.3+
3372 // - AND entropy_length is > 0
3373 // We treat it as disabled if it doesn't have an entropy length of at least 32
3374 $entropyEnabled = wfCheckEntropy();
3376 // If built-in entropy is not enabled or not sufficient override PHP's
3377 // built in session id generation code
3378 if ( !$entropyEnabled ) {
3379 wfDebug( __METHOD__
. ": PHP's built in entropy is disabled or not sufficient, " .
3380 "overriding session id generation using our cryptrand source.\n" );
3381 session_id( MWCryptRand
::generateHex( 32 ) );
3386 * Reset the session_id
3390 function wfResetSessionID() {
3391 global $wgCookieSecure;
3392 $oldSessionId = session_id();
3393 $cookieParams = session_get_cookie_params();
3394 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3395 session_regenerate_id( false );
3399 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
3402 $newSessionId = session_id();
3406 * Initialise php session
3408 * @param bool $sessionId
3410 function wfSetupSession( $sessionId = false ) {
3411 global $wgSessionsInObjectCache, $wgSessionHandler;
3412 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
3414 if ( $wgSessionsInObjectCache ) {
3415 ObjectCacheSessionHandler
::install();
3416 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3417 # Only set this if $wgSessionHandler isn't null and session.save_handler
3418 # hasn't already been set to the desired value (that causes errors)
3419 ini_set( 'session.save_handler', $wgSessionHandler );
3422 session_set_cookie_params(
3423 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3424 session_cache_limiter( 'private, must-revalidate' );
3426 session_id( $sessionId );
3431 MediaWiki\
suppressWarnings();
3433 MediaWiki\restoreWarnings
();
3435 if ( $wgSessionsInObjectCache ) {
3436 ObjectCacheSessionHandler
::renewCurrentSession();
3441 * Get an object from the precompiled serialized directory
3443 * @param string $name
3444 * @return mixed The variable on success, false on failure
3446 function wfGetPrecompiledData( $name ) {
3449 $file = "$IP/serialized/$name";
3450 if ( file_exists( $file ) ) {
3451 $blob = file_get_contents( $file );
3453 return unserialize( $blob );
3460 * Make a cache key for the local wiki.
3462 * @param string $args,...
3465 function wfMemcKey( /*...*/ ) {
3466 return call_user_func_array(
3467 array( ObjectCache
::getLocalClusterInstance(), 'makeKey' ),
3473 * Make a cache key for a foreign DB.
3475 * Must match what wfMemcKey() would produce in context of the foreign wiki.
3478 * @param string $prefix
3479 * @param string $args,...
3482 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3483 $args = array_slice( func_get_args(), 2 );
3484 $keyspace = $prefix ?
"$db-$prefix" : $db;
3485 return call_user_func_array(
3486 array( ObjectCache
::getLocalClusterInstance(), 'makeKeyInternal' ),
3487 array( $keyspace, $args )
3492 * Make a cache key with database-agnostic prefix.
3494 * Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix
3495 * instead. Must have a prefix as otherwise keys that use a database name
3496 * in the first segment will clash with wfMemcKey/wfForeignMemcKey.
3499 * @param string $args,...
3502 function wfGlobalCacheKey( /*...*/ ) {
3503 return call_user_func_array(
3504 array( ObjectCache
::getLocalClusterInstance(), 'makeGlobalKey' ),
3510 * Get an ASCII string identifying this wiki
3511 * This is used as a prefix in memcached keys
3515 function wfWikiID() {
3516 global $wgDBprefix, $wgDBname;
3517 if ( $wgDBprefix ) {
3518 return "$wgDBname-$wgDBprefix";
3525 * Split a wiki ID into DB name and table prefix
3527 * @param string $wiki
3531 function wfSplitWikiID( $wiki ) {
3532 $bits = explode( '-', $wiki, 2 );
3533 if ( count( $bits ) < 2 ) {
3540 * Get a Database object.
3542 * @param int $db Index of the connection to get. May be DB_MASTER for the
3543 * master (for write queries), DB_SLAVE for potentially lagged read
3544 * queries, or an integer >= 0 for a particular server.
3546 * @param string|string[] $groups Query groups. An array of group names that this query
3547 * belongs to. May contain a single string if the query is only
3550 * @param string|bool $wiki The wiki ID, or false for the current wiki
3552 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3553 * will always return the same object, unless the underlying connection or load
3554 * balancer is manually destroyed.
3556 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3557 * updater to ensure that a proper database is being updated.
3559 * @return DatabaseBase
3561 function wfGetDB( $db, $groups = array(), $wiki = false ) {
3562 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3566 * Get a load balancer object.
3568 * @param string|bool $wiki Wiki ID, or false for the current wiki
3569 * @return LoadBalancer
3571 function wfGetLB( $wiki = false ) {
3572 return wfGetLBFactory()->getMainLB( $wiki );
3576 * Get the load balancer factory object
3580 function wfGetLBFactory() {
3581 return LBFactory
::singleton();
3586 * Shortcut for RepoGroup::singleton()->findFile()
3588 * @param string $title String or Title object
3589 * @param array $options Associative array of options (see RepoGroup::findFile)
3590 * @return File|bool File, or false if the file does not exist
3592 function wfFindFile( $title, $options = array() ) {
3593 return RepoGroup
::singleton()->findFile( $title, $options );
3597 * Get an object referring to a locally registered file.
3598 * Returns a valid placeholder object if the file does not exist.
3600 * @param Title|string $title
3601 * @return LocalFile|null A File, or null if passed an invalid Title
3603 function wfLocalFile( $title ) {
3604 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3608 * Should low-performance queries be disabled?
3611 * @codeCoverageIgnore
3613 function wfQueriesMustScale() {
3614 global $wgMiserMode;
3616 ||
( SiteStats
::pages() > 100000
3617 && SiteStats
::edits() > 1000000
3618 && SiteStats
::users() > 10000 );
3622 * Get the path to a specified script file, respecting file
3623 * extensions; this is a wrapper around $wgScriptPath etc.
3624 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3626 * @param string $script Script filename, sans extension
3629 function wfScript( $script = 'index' ) {
3630 global $wgScriptPath, $wgScript, $wgLoadScript;
3631 if ( $script === 'index' ) {
3633 } elseif ( $script === 'load' ) {
3634 return $wgLoadScript;
3636 return "{$wgScriptPath}/{$script}.php";
3641 * Get the script URL.
3643 * @return string Script URL
3645 function wfGetScriptUrl() {
3646 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3647 /* as it was called, minus the query string.
3649 * Some sites use Apache rewrite rules to handle subdomains,
3650 * and have PHP set up in a weird way that causes PHP_SELF
3651 * to contain the rewritten URL instead of the one that the
3652 * outside world sees.
3654 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
3655 * provides containing the "before" URL.
3657 return $_SERVER['SCRIPT_NAME'];
3659 return $_SERVER['URL'];
3664 * Convenience function converts boolean values into "true"
3665 * or "false" (string) values
3667 * @param bool $value
3670 function wfBoolToStr( $value ) {
3671 return $value ?
'true' : 'false';
3675 * Get a platform-independent path to the null file, e.g. /dev/null
3679 function wfGetNull() {
3680 return wfIsWindows() ?
'NUL' : '/dev/null';
3684 * Waits for the slaves to catch up to the master position
3686 * Use this when updating very large numbers of rows, as in maintenance scripts,
3687 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
3689 * By default this waits on the main DB cluster of the current wiki.
3690 * If $cluster is set to "*" it will wait on all DB clusters, including
3691 * external ones. If the lag being waiting on is caused by the code that
3692 * does this check, it makes since to use $ifWritesSince, particularly if
3693 * cluster is "*", to avoid excess overhead.
3695 * Never call this function after a big DB write that is still in a transaction.
3696 * This only makes sense after the possible lag inducing changes were committed.
3698 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3699 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3700 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3701 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3702 * @return bool Success (able to connect and no timeouts reached)
3704 function wfWaitForSlaves(
3705 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3707 // B/C: first argument used to be "max seconds of lag"; ignore such values
3708 $ifWritesSince = ( $ifWritesSince > 1e9
) ?
$ifWritesSince : null;
3710 if ( $timeout === null ) {
3711 $timeout = ( PHP_SAPI
=== 'cli' ) ?
86400 : 10;
3714 // Figure out which clusters need to be checked
3715 /** @var LoadBalancer[] $lbs */
3717 if ( $cluster === '*' ) {
3718 wfGetLBFactory()->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
3721 } elseif ( $cluster !== false ) {
3722 $lbs[] = wfGetLBFactory()->getExternalLB( $cluster );
3724 $lbs[] = wfGetLB( $wiki );
3727 // Get all the master positions of applicable DBs right now.
3728 // This can be faster since waiting on one cluster reduces the
3729 // time needed to wait on the next clusters.
3730 $masterPositions = array_fill( 0, count( $lbs ), false );
3731 foreach ( $lbs as $i => $lb ) {
3732 if ( $lb->getServerCount() <= 1 ) {
3733 // Bug 27975 - Don't try to wait for slaves if there are none
3734 // Prevents permission error when getting master position
3736 } elseif ( $ifWritesSince && $lb->lastMasterChangeTimestamp() < $ifWritesSince ) {
3737 continue; // no writes since the last wait
3739 $masterPositions[$i] = $lb->getMasterPos();
3743 foreach ( $lbs as $i => $lb ) {
3744 if ( $masterPositions[$i] ) {
3745 // The DBMS may not support getMasterPos() or the whole
3746 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3747 $ok = $lb->waitForAll( $masterPositions[$i], $timeout ) && $ok;
3755 * Count down from $seconds to zero on the terminal, with a one-second pause
3756 * between showing each number. For use in command-line scripts.
3758 * @codeCoverageIgnore
3759 * @param int $seconds
3761 function wfCountDown( $seconds ) {
3762 for ( $i = $seconds; $i >= 0; $i-- ) {
3763 if ( $i != $seconds ) {
3764 echo str_repeat( "\x08", strlen( $i +
1 ) );
3776 * Replace all invalid characters with -
3777 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3778 * By default, $wgIllegalFileChars = ':'
3780 * @param string $name Filename to process
3783 function wfStripIllegalFilenameChars( $name ) {
3784 global $wgIllegalFileChars;
3785 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3786 $name = wfBaseName( $name );
3787 $name = preg_replace(
3788 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3796 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit
3798 * @return int Resulting value of the memory limit.
3800 function wfMemoryLimit() {
3801 global $wgMemoryLimit;
3802 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3803 if ( $memlimit != -1 ) {
3804 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3805 if ( $conflimit == -1 ) {
3806 wfDebug( "Removing PHP's memory limit\n" );
3807 MediaWiki\
suppressWarnings();
3808 ini_set( 'memory_limit', $conflimit );
3809 MediaWiki\restoreWarnings
();
3811 } elseif ( $conflimit > $memlimit ) {
3812 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3813 MediaWiki\
suppressWarnings();
3814 ini_set( 'memory_limit', $conflimit );
3815 MediaWiki\restoreWarnings
();
3823 * Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit
3825 * @return int Prior time limit
3828 function wfTransactionalTimeLimit() {
3829 global $wgTransactionalTimeLimit;
3831 $timeLimit = ini_get( 'max_execution_time' );
3832 // Note that CLI scripts use 0
3833 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
3834 set_time_limit( $wgTransactionalTimeLimit );
3837 ignore_user_abort( true ); // ignore client disconnects
3843 * Converts shorthand byte notation to integer form
3845 * @param string $string
3846 * @param int $default Returned if $string is empty
3849 function wfShorthandToInteger( $string = '', $default = -1 ) {
3850 $string = trim( $string );
3851 if ( $string === '' ) {
3854 $last = $string[strlen( $string ) - 1];
3855 $val = intval( $string );
3860 // break intentionally missing
3864 // break intentionally missing
3874 * Get the normalised IETF language tag
3875 * See unit test for examples.
3877 * @param string $code The language code.
3878 * @return string The language code which complying with BCP 47 standards.
3880 function wfBCP47( $code ) {
3881 $codeSegment = explode( '-', $code );
3883 foreach ( $codeSegment as $segNo => $seg ) {
3884 // when previous segment is x, it is a private segment and should be lc
3885 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3886 $codeBCP[$segNo] = strtolower( $seg );
3887 // ISO 3166 country code
3888 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3889 $codeBCP[$segNo] = strtoupper( $seg );
3890 // ISO 15924 script code
3891 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3892 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3893 // Use lowercase for other cases
3895 $codeBCP[$segNo] = strtolower( $seg );
3898 $langCode = implode( '-', $codeBCP );
3903 * Get a specific cache object.
3905 * @param int|string $cacheType A CACHE_* constants, or other key in $wgObjectCaches
3908 function wfGetCache( $cacheType ) {
3909 return ObjectCache
::getInstance( $cacheType );
3913 * Get the main cache object
3917 function wfGetMainCache() {
3918 global $wgMainCacheType;
3919 return ObjectCache
::getInstance( $wgMainCacheType );
3923 * Get the cache object used by the message cache
3927 function wfGetMessageCacheStorage() {
3928 global $wgMessageCacheType;
3929 return ObjectCache
::getInstance( $wgMessageCacheType );
3933 * Get the cache object used by the parser cache
3937 function wfGetParserCacheStorage() {
3938 global $wgParserCacheType;
3939 return ObjectCache
::getInstance( $wgParserCacheType );
3943 * Call hook functions defined in $wgHooks
3945 * @param string $event Event name
3946 * @param array $args Parameters passed to hook functions
3947 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
3949 * @return bool True if no handler aborted the hook
3950 * @deprecated 1.25 - use Hooks::run
3952 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
3953 return Hooks
::run( $event, $args, $deprecatedVersion );
3957 * Wrapper around php's unpack.
3959 * @param string $format The format string (See php's docs)
3960 * @param string $data A binary string of binary data
3961 * @param int|bool $length The minimum length of $data or false. This is to
3962 * prevent reading beyond the end of $data. false to disable the check.
3964 * Also be careful when using this function to read unsigned 32 bit integer
3965 * because php might make it negative.
3967 * @throws MWException If $data not long enough, or if unpack fails
3968 * @return array Associative array of the extracted data
3970 function wfUnpack( $format, $data, $length = false ) {
3971 if ( $length !== false ) {
3972 $realLen = strlen( $data );
3973 if ( $realLen < $length ) {
3974 throw new MWException( "Tried to use wfUnpack on a "
3975 . "string of length $realLen, but needed one "
3976 . "of at least length $length."
3981 MediaWiki\
suppressWarnings();
3982 $result = unpack( $format, $data );
3983 MediaWiki\restoreWarnings
();
3985 if ( $result === false ) {
3986 // If it cannot extract the packed data.
3987 throw new MWException( "unpack could not unpack binary data" );
3993 * Determine if an image exists on the 'bad image list'.
3995 * The format of MediaWiki:Bad_image_list is as follows:
3996 * * Only list items (lines starting with "*") are considered
3997 * * The first link on a line must be a link to a bad image
3998 * * Any subsequent links on the same line are considered to be exceptions,
3999 * i.e. articles where the image may occur inline.
4001 * @param string $name The image name to check
4002 * @param Title|bool $contextTitle The page on which the image occurs, if known
4003 * @param string $blacklist Wikitext of a file blacklist
4006 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4007 # Handle redirects; callers almost always hit wfFindFile() anyway,
4008 # so just use that method because it has a fast process cache.
4009 $file = wfFindFile( $name ); // get the final name
4010 $name = $file ?
$file->getTitle()->getDBkey() : $name;
4012 # Run the extension hook
4014 if ( !Hooks
::run( 'BadImage', array( $name, &$bad ) ) ) {
4018 $cache = ObjectCache
::getLocalServerInstance( 'hash' );
4019 $key = wfMemcKey( 'bad-image-list', ( $blacklist === null ) ?
'default' : md5( $blacklist ) );
4020 $badImages = $cache->get( $key );
4022 if ( $badImages === false ) { // cache miss
4023 if ( $blacklist === null ) {
4024 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4026 # Build the list now
4027 $badImages = array();
4028 $lines = explode( "\n", $blacklist );
4029 foreach ( $lines as $line ) {
4031 if ( substr( $line, 0, 1 ) !== '*' ) {
4037 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4041 $exceptions = array();
4042 $imageDBkey = false;
4043 foreach ( $m[1] as $i => $titleText ) {
4044 $title = Title
::newFromText( $titleText );
4045 if ( !is_null( $title ) ) {
4047 $imageDBkey = $title->getDBkey();
4049 $exceptions[$title->getPrefixedDBkey()] = true;
4054 if ( $imageDBkey !== false ) {
4055 $badImages[$imageDBkey] = $exceptions;
4058 $cache->set( $key, $badImages, 60 );
4061 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
4062 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4068 * Determine whether the client at a given source IP is likely to be able to
4069 * access the wiki via HTTPS.
4071 * @param string $ip The IPv4/6 address in the normal human-readable form
4074 function wfCanIPUseHTTPS( $ip ) {
4076 Hooks
::run( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4081 * Determine input string is represents as infinity
4083 * @param string $str The string to determine
4087 function wfIsInfinity( $str ) {
4088 $infinityValues = array( 'infinite', 'indefinite', 'infinity', 'never' );
4089 return in_array( $str, $infinityValues );
4093 * Work out the IP address based on various globals
4094 * For trusted proxies, use the XFF client IP (first of the chain)
4096 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4099 function wfGetIP() {
4100 wfDeprecated( __METHOD__
, '1.19' );
4102 return $wgRequest->getIP();
4106 * Checks if an IP is a trusted proxy provider.
4107 * Useful to tell if X-Forwarded-For data is possibly bogus.
4108 * Squid cache servers for the site are whitelisted.
4109 * @deprecated Since 1.24, use IP::isTrustedProxy()
4114 function wfIsTrustedProxy( $ip ) {
4115 wfDeprecated( __METHOD__
, '1.24' );
4116 return IP
::isTrustedProxy( $ip );
4120 * Checks if an IP matches a proxy we've configured.
4121 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4125 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4127 function wfIsConfiguredProxy( $ip ) {
4128 wfDeprecated( __METHOD__
, '1.24' );
4129 return IP
::isConfiguredProxy( $ip );
4133 * Returns true if these thumbnail parameters match one that MediaWiki
4134 * requests from file description pages and/or parser output.
4136 * $params is considered non-standard if they involve a non-standard
4137 * width or any non-default parameters aside from width and page number.
4138 * The number of possible files with standard parameters is far less than
4139 * that of all combinations; rate-limiting for them can thus be more generious.
4142 * @param array $params
4144 * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25
4146 function wfThumbIsStandard( File
$file, array $params ) {
4147 global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages;
4149 $multipliers = array( 1 );
4150 if ( $wgResponsiveImages ) {
4151 // These available sizes are hardcoded currently elsewhere in MediaWiki.
4152 // @see Linker::processResponsiveImages
4153 $multipliers[] = 1.5;
4157 $handler = $file->getHandler();
4158 if ( !$handler ||
!isset( $params['width'] ) ) {
4162 $basicParams = array();
4163 if ( isset( $params['page'] ) ) {
4164 $basicParams['page'] = $params['page'];
4167 $thumbLimits = array();
4168 $imageLimits = array();
4169 // Expand limits to account for multipliers
4170 foreach ( $multipliers as $multiplier ) {
4171 $thumbLimits = array_merge( $thumbLimits, array_map(
4172 function ( $width ) use ( $multiplier ) {
4173 return round( $width * $multiplier );
4176 $imageLimits = array_merge( $imageLimits, array_map(
4177 function ( $pair ) use ( $multiplier ) {
4179 round( $pair[0] * $multiplier ),
4180 round( $pair[1] * $multiplier ),
4186 // Check if the width matches one of $wgThumbLimits
4187 if ( in_array( $params['width'], $thumbLimits ) ) {
4188 $normalParams = $basicParams +
array( 'width' => $params['width'] );
4189 // Append any default values to the map (e.g. "lossy", "lossless", ...)
4190 $handler->normaliseParams( $file, $normalParams );
4192 // If not, then check if the width matchs one of $wgImageLimits
4194 foreach ( $imageLimits as $pair ) {
4195 $normalParams = $basicParams +
array( 'width' => $pair[0], 'height' => $pair[1] );
4196 // Decide whether the thumbnail should be scaled on width or height.
4197 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
4198 $handler->normaliseParams( $file, $normalParams );
4199 // Check if this standard thumbnail size maps to the given width
4200 if ( $normalParams['width'] == $params['width'] ) {
4206 return false; // not standard for description pages
4210 // Check that the given values for non-page, non-width, params are just defaults
4211 foreach ( $params as $key => $value ) {
4212 if ( !isset( $normalParams[$key] ) ||
$normalParams[$key] != $value ) {
4221 * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
4223 * Values that exist in both values will be combined with += (all values of the array
4224 * of $newValues will be added to the values of the array of $baseArray, while values,
4225 * that exists in both, the value of $baseArray will be used).
4227 * @param array $baseArray The array where you want to add the values of $newValues to
4228 * @param array $newValues An array with new values
4229 * @return array The combined array
4232 function wfArrayPlus2d( array $baseArray, array $newValues ) {
4233 // First merge items that are in both arrays
4234 foreach ( $baseArray as $name => &$groupVal ) {
4235 if ( isset( $newValues[$name] ) ) {
4236 $groupVal +
= $newValues[$name];
4239 // Now add items that didn't exist yet
4240 $baseArray +
= $newValues;