Move MemcachedBagOStuff b/c logic to ObjectCache
[mediawiki.git] / includes / GlobalFunctions.php
blobcda3154253dd3d5dff9546385d73460db59b5dda
1 <?php
2 /**
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
20 * @file
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
31 /// @cond
33 /**
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' ) ) {
42 /**
43 * @codeCoverageIgnore
44 * @see Fallback::mb_substr
45 * @return string
47 function mb_substr( $str, $start, $count = 'end' ) {
48 return Fallback::mb_substr( $str, $start, $count );
51 /**
52 * @codeCoverageIgnore
53 * @see Fallback::mb_substr_split_unicode
54 * @return int
56 function mb_substr_split_unicode( $str, $splitPos ) {
57 return Fallback::mb_substr_split_unicode( $str, $splitPos );
61 if ( !function_exists( 'mb_strlen' ) ) {
62 /**
63 * @codeCoverageIgnore
64 * @see Fallback::mb_strlen
65 * @return int
67 function mb_strlen( $str, $enc = '' ) {
68 return Fallback::mb_strlen( $str, $enc );
72 if ( !function_exists( 'mb_strpos' ) ) {
73 /**
74 * @codeCoverageIgnore
75 * @see Fallback::mb_strpos
76 * @return int
78 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
79 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
83 if ( !function_exists( 'mb_strrpos' ) ) {
84 /**
85 * @codeCoverageIgnore
86 * @see Fallback::mb_strrpos
87 * @return int
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' ) ) {
97 /**
98 * @codeCoverageIgnore
99 * @param string $data
100 * @return string
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 );
141 return false;
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 );
148 return false;
151 $known_string_len = strlen( $known_string );
152 if ( $known_string_len !== strlen( $user_string ) ) {
153 return false;
156 $result = 0;
157 for ( $i = 0; $i < $known_string_len; $i++ ) {
158 $result |= ord( $known_string[$i] ) ^ ord( $user_string[$i] );
161 return ( $result === 0 );
164 /// @endcond
167 * Load an extension
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
174 * @since 1.25
176 function wfLoadExtension( $ext, $path = null ) {
177 if ( !$path ) {
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
195 * @since 1.25
197 function wfLoadExtensions( array $exts ) {
198 global $wgExtensionDirectory;
199 $registry = ExtensionRegistry::getInstance();
200 foreach ( $exts as $ext ) {
201 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
206 * Load a skin
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
211 * @since 1.25
213 function wfLoadSkin( $skin, $path = null ) {
214 if ( !$path ) {
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
226 * @since 1.25
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.
238 * @param array $a
239 * @param array $b
240 * @return array
242 function wfArrayDiff2( $a, $b ) {
243 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
247 * @param array|string $a
248 * @param array|string $b
249 * @return int
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;
256 } else {
257 reset( $a );
258 reset( $b );
259 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
260 $cmp = strcmp( $valueA, $valueB );
261 if ( $cmp !== 0 ) {
262 return $cmp;
265 return 0;
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
289 * e.g.
290 * wfMergeErrorArrays(
291 * array( array( 'x' ) ),
292 * array( array( 'x', '2' ) ),
293 * array( array( 'x' ) ),
294 * array( array( 'y' ) )
295 * );
296 * returns:
297 * array(
298 * array( 'x', '2' ),
299 * array( 'x' ),
300 * array( 'y' )
303 * @param array $array1,...
304 * @return array
306 function wfMergeErrorArrays( /*...*/ ) {
307 $args = func_get_args();
308 $out = array();
309 foreach ( $args as $errors ) {
310 foreach ( $errors as $params ) {
311 # @todo FIXME: Sometimes get nested arrays for $params,
312 # which leads to E_NOTICEs
313 $spec = implode( "\t", $params );
314 $out[$spec] = $params;
317 return array_values( $out );
321 * Insert array into another array after the specified *KEY*
323 * @param array $array The array.
324 * @param array $insert The array to insert.
325 * @param mixed $after The key to insert after
326 * @return array
328 function wfArrayInsertAfter( array $array, array $insert, $after ) {
329 // Find the offset of the element to insert after.
330 $keys = array_keys( $array );
331 $offsetByKey = array_flip( $keys );
333 $offset = $offsetByKey[$after];
335 // Insert at the specified offset
336 $before = array_slice( $array, 0, $offset + 1, true );
337 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
339 $output = $before + $insert + $after;
341 return $output;
345 * Recursively converts the parameter (an object) to an array with the same data
347 * @param object|array $objOrArray
348 * @param bool $recursive
349 * @return array
351 function wfObjectToArray( $objOrArray, $recursive = true ) {
352 $array = array();
353 if ( is_object( $objOrArray ) ) {
354 $objOrArray = get_object_vars( $objOrArray );
356 foreach ( $objOrArray as $key => $value ) {
357 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
358 $value = wfObjectToArray( $value );
361 $array[$key] = $value;
364 return $array;
368 * Get a random decimal value between 0 and 1, in a way
369 * not likely to give duplicate values for any realistic
370 * number of articles.
372 * @return string
374 function wfRandom() {
375 # The maximum random value is "only" 2^31-1, so get two random
376 # values to reduce the chance of dupes
377 $max = mt_getrandmax() + 1;
378 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
380 return $rand;
384 * Get a random string containing a number of pseudo-random hex
385 * characters.
386 * @note This is not secure, if you are trying to generate some sort
387 * of token please use MWCryptRand instead.
389 * @param int $length The length of the string to generate
390 * @return string
391 * @since 1.20
393 function wfRandomString( $length = 32 ) {
394 $str = '';
395 for ( $n = 0; $n < $length; $n += 7 ) {
396 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
398 return substr( $str, 0, $length );
402 * We want some things to be included as literal characters in our title URLs
403 * for prettiness, which urlencode encodes by default. According to RFC 1738,
404 * all of the following should be safe:
406 * ;:@&=$-_.+!*'(),
408 * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved
409 * character which should not be encoded. More importantly, google chrome
410 * always converts %7E back to ~, and converting it in this function can
411 * cause a redirect loop (T105265).
413 * But + is not safe because it's used to indicate a space; &= are only safe in
414 * paths and not in queries (and we don't distinguish here); ' seems kind of
415 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
416 * is reserved, we don't care. So the list we unescape is:
418 * ;:@$!*(),/~
420 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
421 * so no fancy : for IIS7.
423 * %2F in the page titles seems to fatally break for some reason.
425 * @param string $s
426 * @return string
428 function wfUrlencode( $s ) {
429 static $needle;
431 if ( is_null( $s ) ) {
432 $needle = null;
433 return '';
436 if ( is_null( $needle ) ) {
437 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' );
438 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
439 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
441 $needle[] = '%3A';
445 $s = urlencode( $s );
446 $s = str_ireplace(
447 $needle,
448 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ),
452 return $s;
456 * This function takes two arrays as input, and returns a CGI-style string, e.g.
457 * "days=7&limit=100". Options in the first array override options in the second.
458 * Options set to null or false will not be output.
460 * @param array $array1 ( String|Array )
461 * @param array $array2 ( String|Array )
462 * @param string $prefix
463 * @return string
465 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
466 if ( !is_null( $array2 ) ) {
467 $array1 = $array1 + $array2;
470 $cgi = '';
471 foreach ( $array1 as $key => $value ) {
472 if ( !is_null( $value ) && $value !== false ) {
473 if ( $cgi != '' ) {
474 $cgi .= '&';
476 if ( $prefix !== '' ) {
477 $key = $prefix . "[$key]";
479 if ( is_array( $value ) ) {
480 $firstTime = true;
481 foreach ( $value as $k => $v ) {
482 $cgi .= $firstTime ? '' : '&';
483 if ( is_array( $v ) ) {
484 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
485 } else {
486 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
488 $firstTime = false;
490 } else {
491 if ( is_object( $value ) ) {
492 $value = $value->__toString();
494 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
498 return $cgi;
502 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
503 * its argument and returns the same string in array form. This allows compatibility
504 * with legacy functions that accept raw query strings instead of nice
505 * arrays. Of course, keys and values are urldecode()d.
507 * @param string $query Query string
508 * @return string[] Array version of input
510 function wfCgiToArray( $query ) {
511 if ( isset( $query[0] ) && $query[0] == '?' ) {
512 $query = substr( $query, 1 );
514 $bits = explode( '&', $query );
515 $ret = array();
516 foreach ( $bits as $bit ) {
517 if ( $bit === '' ) {
518 continue;
520 if ( strpos( $bit, '=' ) === false ) {
521 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
522 $key = $bit;
523 $value = '';
524 } else {
525 list( $key, $value ) = explode( '=', $bit );
527 $key = urldecode( $key );
528 $value = urldecode( $value );
529 if ( strpos( $key, '[' ) !== false ) {
530 $keys = array_reverse( explode( '[', $key ) );
531 $key = array_pop( $keys );
532 $temp = $value;
533 foreach ( $keys as $k ) {
534 $k = substr( $k, 0, -1 );
535 $temp = array( $k => $temp );
537 if ( isset( $ret[$key] ) ) {
538 $ret[$key] = array_merge( $ret[$key], $temp );
539 } else {
540 $ret[$key] = $temp;
542 } else {
543 $ret[$key] = $value;
546 return $ret;
550 * Append a query string to an existing URL, which may or may not already
551 * have query string parameters already. If so, they will be combined.
553 * @param string $url
554 * @param string|string[] $query String or associative array
555 * @return string
557 function wfAppendQuery( $url, $query ) {
558 if ( is_array( $query ) ) {
559 $query = wfArrayToCgi( $query );
561 if ( $query != '' ) {
562 if ( false === strpos( $url, '?' ) ) {
563 $url .= '?';
564 } else {
565 $url .= '&';
567 $url .= $query;
569 return $url;
573 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
574 * is correct.
576 * The meaning of the PROTO_* constants is as follows:
577 * PROTO_HTTP: Output a URL starting with http://
578 * PROTO_HTTPS: Output a URL starting with https://
579 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
580 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
581 * on which protocol was used for the current incoming request
582 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
583 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
584 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
586 * @todo this won't work with current-path-relative URLs
587 * like "subdir/foo.html", etc.
589 * @param string $url Either fully-qualified or a local path + query
590 * @param string $defaultProto One of the PROTO_* constants. Determines the
591 * protocol to use if $url or $wgServer is protocol-relative
592 * @return string Fully-qualified URL, current-path-relative URL or false if
593 * no valid URL can be constructed
595 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
596 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
597 $wgHttpsPort;
598 if ( $defaultProto === PROTO_CANONICAL ) {
599 $serverUrl = $wgCanonicalServer;
600 } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
601 // Make $wgInternalServer fall back to $wgServer if not set
602 $serverUrl = $wgInternalServer;
603 } else {
604 $serverUrl = $wgServer;
605 if ( $defaultProto === PROTO_CURRENT ) {
606 $defaultProto = $wgRequest->getProtocol() . '://';
610 // Analyze $serverUrl to obtain its protocol
611 $bits = wfParseUrl( $serverUrl );
612 $serverHasProto = $bits && $bits['scheme'] != '';
614 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
615 if ( $serverHasProto ) {
616 $defaultProto = $bits['scheme'] . '://';
617 } else {
618 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
619 // This really isn't supposed to happen. Fall back to HTTP in this
620 // ridiculous case.
621 $defaultProto = PROTO_HTTP;
625 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
627 if ( substr( $url, 0, 2 ) == '//' ) {
628 $url = $defaultProtoWithoutSlashes . $url;
629 } elseif ( substr( $url, 0, 1 ) == '/' ) {
630 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
631 // otherwise leave it alone.
632 $url = ( $serverHasProto ? '' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
635 $bits = wfParseUrl( $url );
637 // ensure proper port for HTTPS arrives in URL
638 // https://phabricator.wikimedia.org/T67184
639 if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
640 $bits['port'] = $wgHttpsPort;
643 if ( $bits && isset( $bits['path'] ) ) {
644 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
645 return wfAssembleUrl( $bits );
646 } elseif ( $bits ) {
647 # No path to expand
648 return $url;
649 } elseif ( substr( $url, 0, 1 ) != '/' ) {
650 # URL is a relative path
651 return wfRemoveDotSegments( $url );
654 # Expanded URL is not valid.
655 return false;
659 * This function will reassemble a URL parsed with wfParseURL. This is useful
660 * if you need to edit part of a URL and put it back together.
662 * This is the basic structure used (brackets contain keys for $urlParts):
663 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
665 * @todo Need to integrate this into wfExpandUrl (bug 32168)
667 * @since 1.19
668 * @param array $urlParts URL parts, as output from wfParseUrl
669 * @return string URL assembled from its component parts
671 function wfAssembleUrl( $urlParts ) {
672 $result = '';
674 if ( isset( $urlParts['delimiter'] ) ) {
675 if ( isset( $urlParts['scheme'] ) ) {
676 $result .= $urlParts['scheme'];
679 $result .= $urlParts['delimiter'];
682 if ( isset( $urlParts['host'] ) ) {
683 if ( isset( $urlParts['user'] ) ) {
684 $result .= $urlParts['user'];
685 if ( isset( $urlParts['pass'] ) ) {
686 $result .= ':' . $urlParts['pass'];
688 $result .= '@';
691 $result .= $urlParts['host'];
693 if ( isset( $urlParts['port'] ) ) {
694 $result .= ':' . $urlParts['port'];
698 if ( isset( $urlParts['path'] ) ) {
699 $result .= $urlParts['path'];
702 if ( isset( $urlParts['query'] ) ) {
703 $result .= '?' . $urlParts['query'];
706 if ( isset( $urlParts['fragment'] ) ) {
707 $result .= '#' . $urlParts['fragment'];
710 return $result;
714 * Remove all dot-segments in the provided URL path. For example,
715 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
716 * RFC3986 section 5.2.4.
718 * @todo Need to integrate this into wfExpandUrl (bug 32168)
720 * @param string $urlPath URL path, potentially containing dot-segments
721 * @return string URL path with all dot-segments removed
723 function wfRemoveDotSegments( $urlPath ) {
724 $output = '';
725 $inputOffset = 0;
726 $inputLength = strlen( $urlPath );
728 while ( $inputOffset < $inputLength ) {
729 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
730 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
731 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
732 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
733 $trimOutput = false;
735 if ( $prefixLengthTwo == './' ) {
736 # Step A, remove leading "./"
737 $inputOffset += 2;
738 } elseif ( $prefixLengthThree == '../' ) {
739 # Step A, remove leading "../"
740 $inputOffset += 3;
741 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
742 # Step B, replace leading "/.$" with "/"
743 $inputOffset += 1;
744 $urlPath[$inputOffset] = '/';
745 } elseif ( $prefixLengthThree == '/./' ) {
746 # Step B, replace leading "/./" with "/"
747 $inputOffset += 2;
748 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
749 # Step C, replace leading "/..$" with "/" and
750 # remove last path component in output
751 $inputOffset += 2;
752 $urlPath[$inputOffset] = '/';
753 $trimOutput = true;
754 } elseif ( $prefixLengthFour == '/../' ) {
755 # Step C, replace leading "/../" with "/" and
756 # remove last path component in output
757 $inputOffset += 3;
758 $trimOutput = true;
759 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
760 # Step D, remove "^.$"
761 $inputOffset += 1;
762 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
763 # Step D, remove "^..$"
764 $inputOffset += 2;
765 } else {
766 # Step E, move leading path segment to output
767 if ( $prefixLengthOne == '/' ) {
768 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
769 } else {
770 $slashPos = strpos( $urlPath, '/', $inputOffset );
772 if ( $slashPos === false ) {
773 $output .= substr( $urlPath, $inputOffset );
774 $inputOffset = $inputLength;
775 } else {
776 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
777 $inputOffset += $slashPos - $inputOffset;
781 if ( $trimOutput ) {
782 $slashPos = strrpos( $output, '/' );
783 if ( $slashPos === false ) {
784 $output = '';
785 } else {
786 $output = substr( $output, 0, $slashPos );
791 return $output;
795 * Returns a regular expression of url protocols
797 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
798 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
799 * @return string
801 function wfUrlProtocols( $includeProtocolRelative = true ) {
802 global $wgUrlProtocols;
804 // Cache return values separately based on $includeProtocolRelative
805 static $withProtRel = null, $withoutProtRel = null;
806 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
807 if ( !is_null( $cachedValue ) ) {
808 return $cachedValue;
811 // Support old-style $wgUrlProtocols strings, for backwards compatibility
812 // with LocalSettings files from 1.5
813 if ( is_array( $wgUrlProtocols ) ) {
814 $protocols = array();
815 foreach ( $wgUrlProtocols as $protocol ) {
816 // Filter out '//' if !$includeProtocolRelative
817 if ( $includeProtocolRelative || $protocol !== '//' ) {
818 $protocols[] = preg_quote( $protocol, '/' );
822 $retval = implode( '|', $protocols );
823 } else {
824 // Ignore $includeProtocolRelative in this case
825 // This case exists for pre-1.6 compatibility, and we can safely assume
826 // that '//' won't appear in a pre-1.6 config because protocol-relative
827 // URLs weren't supported until 1.18
828 $retval = $wgUrlProtocols;
831 // Cache return value
832 if ( $includeProtocolRelative ) {
833 $withProtRel = $retval;
834 } else {
835 $withoutProtRel = $retval;
837 return $retval;
841 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
842 * you need a regex that matches all URL protocols but does not match protocol-
843 * relative URLs
844 * @return string
846 function wfUrlProtocolsWithoutProtRel() {
847 return wfUrlProtocols( false );
851 * parse_url() work-alike, but non-broken. Differences:
853 * 1) Does not raise warnings on bad URLs (just returns false).
854 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
855 * protocol-relative URLs) correctly.
856 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
858 * @param string $url A URL to parse
859 * @return string[] Bits of the URL in an associative array, per PHP docs
861 function wfParseUrl( $url ) {
862 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
864 // Protocol-relative URLs are handled really badly by parse_url(). It's so
865 // bad that the easiest way to handle them is to just prepend 'http:' and
866 // strip the protocol out later.
867 $wasRelative = substr( $url, 0, 2 ) == '//';
868 if ( $wasRelative ) {
869 $url = "http:$url";
871 MediaWiki\suppressWarnings();
872 $bits = parse_url( $url );
873 MediaWiki\restoreWarnings();
874 // parse_url() returns an array without scheme for some invalid URLs, e.g.
875 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
876 if ( !$bits || !isset( $bits['scheme'] ) ) {
877 return false;
880 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
881 $bits['scheme'] = strtolower( $bits['scheme'] );
883 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
884 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
885 $bits['delimiter'] = '://';
886 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
887 $bits['delimiter'] = ':';
888 // parse_url detects for news: and mailto: the host part of an url as path
889 // We have to correct this wrong detection
890 if ( isset( $bits['path'] ) ) {
891 $bits['host'] = $bits['path'];
892 $bits['path'] = '';
894 } else {
895 return false;
898 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
899 if ( !isset( $bits['host'] ) ) {
900 $bits['host'] = '';
902 // bug 45069
903 if ( isset( $bits['path'] ) ) {
904 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
905 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
906 $bits['path'] = '/' . $bits['path'];
908 } else {
909 $bits['path'] = '';
913 // If the URL was protocol-relative, fix scheme and delimiter
914 if ( $wasRelative ) {
915 $bits['scheme'] = '';
916 $bits['delimiter'] = '//';
918 return $bits;
922 * Take a URL, make sure it's expanded to fully qualified, and replace any
923 * encoded non-ASCII Unicode characters with their UTF-8 original forms
924 * for more compact display and legibility for local audiences.
926 * @todo handle punycode domains too
928 * @param string $url
929 * @return string
931 function wfExpandIRI( $url ) {
932 return preg_replace_callback(
933 '/((?:%[89A-F][0-9A-F])+)/i',
934 'wfExpandIRI_callback',
935 wfExpandUrl( $url )
940 * Private callback for wfExpandIRI
941 * @param array $matches
942 * @return string
944 function wfExpandIRI_callback( $matches ) {
945 return urldecode( $matches[1] );
949 * Make URL indexes, appropriate for the el_index field of externallinks.
951 * @param string $url
952 * @return array
954 function wfMakeUrlIndexes( $url ) {
955 $bits = wfParseUrl( $url );
957 // Reverse the labels in the hostname, convert to lower case
958 // For emails reverse domainpart only
959 if ( $bits['scheme'] == 'mailto' ) {
960 $mailparts = explode( '@', $bits['host'], 2 );
961 if ( count( $mailparts ) === 2 ) {
962 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
963 } else {
964 // No domain specified, don't mangle it
965 $domainpart = '';
967 $reversedHost = $domainpart . '@' . $mailparts[0];
968 } else {
969 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
971 // Add an extra dot to the end
972 // Why? Is it in wrong place in mailto links?
973 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
974 $reversedHost .= '.';
976 // Reconstruct the pseudo-URL
977 $prot = $bits['scheme'];
978 $index = $prot . $bits['delimiter'] . $reversedHost;
979 // Leave out user and password. Add the port, path, query and fragment
980 if ( isset( $bits['port'] ) ) {
981 $index .= ':' . $bits['port'];
983 if ( isset( $bits['path'] ) ) {
984 $index .= $bits['path'];
985 } else {
986 $index .= '/';
988 if ( isset( $bits['query'] ) ) {
989 $index .= '?' . $bits['query'];
991 if ( isset( $bits['fragment'] ) ) {
992 $index .= '#' . $bits['fragment'];
995 if ( $prot == '' ) {
996 return array( "http:$index", "https:$index" );
997 } else {
998 return array( $index );
1003 * Check whether a given URL has a domain that occurs in a given set of domains
1004 * @param string $url URL
1005 * @param array $domains Array of domains (strings)
1006 * @return bool True if the host part of $url ends in one of the strings in $domains
1008 function wfMatchesDomainList( $url, $domains ) {
1009 $bits = wfParseUrl( $url );
1010 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1011 $host = '.' . $bits['host'];
1012 foreach ( (array)$domains as $domain ) {
1013 $domain = '.' . $domain;
1014 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
1015 return true;
1019 return false;
1023 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
1024 * In normal operation this is a NOP.
1026 * Controlling globals:
1027 * $wgDebugLogFile - points to the log file
1028 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
1029 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
1031 * @since 1.25 support for additional context data
1033 * @param string $text
1034 * @param string|bool $dest Unused
1035 * @param array $context Additional logging context data
1037 function wfDebug( $text, $dest = 'all', array $context = array() ) {
1038 global $wgDebugRawPage, $wgDebugLogPrefix;
1039 global $wgDebugTimestamps, $wgRequestTime;
1041 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1042 return;
1045 $text = trim( $text );
1047 // Inline logic from deprecated wfDebugTimer()
1048 if ( $wgDebugTimestamps ) {
1049 $context['seconds_elapsed'] = sprintf(
1050 '%6.4f',
1051 microtime( true ) - $wgRequestTime
1053 $context['memory_used'] = sprintf(
1054 '%5.1fM',
1055 ( memory_get_usage( true ) / ( 1024 * 1024 ) )
1059 if ( $wgDebugLogPrefix !== '' ) {
1060 $context['prefix'] = $wgDebugLogPrefix;
1063 $logger = LoggerFactory::getInstance( 'wfDebug' );
1064 $logger->debug( $text, $context );
1068 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1069 * @return bool
1071 function wfIsDebugRawPage() {
1072 static $cache;
1073 if ( $cache !== null ) {
1074 return $cache;
1076 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1077 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1078 || (
1079 isset( $_SERVER['SCRIPT_NAME'] )
1080 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1083 $cache = true;
1084 } else {
1085 $cache = false;
1087 return $cache;
1091 * Get microsecond timestamps for debug logs
1093 * @deprecated since 1.25
1094 * @return string
1096 function wfDebugTimer() {
1097 global $wgDebugTimestamps, $wgRequestTime;
1099 wfDeprecated( __METHOD__, '1.25' );
1101 if ( !$wgDebugTimestamps ) {
1102 return '';
1105 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1106 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1107 return "$prefix $mem ";
1111 * Send a line giving PHP memory usage.
1113 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1115 function wfDebugMem( $exact = false ) {
1116 $mem = memory_get_usage();
1117 if ( !$exact ) {
1118 $mem = floor( $mem / 1024 ) . ' KiB';
1119 } else {
1120 $mem .= ' B';
1122 wfDebug( "Memory usage: $mem\n" );
1126 * Send a line to a supplementary debug log file, if configured, or main debug
1127 * log if not.
1129 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
1130 * a string filename or an associative array mapping 'destination' to the
1131 * desired filename. The associative array may also contain a 'sample' key
1132 * with an integer value, specifying a sampling factor. Sampled log events
1133 * will be emitted with a 1 in N random chance.
1135 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1136 * @since 1.25 support for additional context data
1137 * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
1139 * @param string $logGroup
1140 * @param string $text
1141 * @param string|bool $dest Destination of the message:
1142 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1143 * - 'log': only to the log and not in HTML
1144 * - 'private': only to the specific log if set in $wgDebugLogGroups and
1145 * discarded otherwise
1146 * For backward compatibility, it can also take a boolean:
1147 * - true: same as 'all'
1148 * - false: same as 'private'
1149 * @param array $context Additional logging context data
1151 function wfDebugLog(
1152 $logGroup, $text, $dest = 'all', array $context = array()
1154 // Turn $dest into a string if it's a boolean (for b/c)
1155 if ( $dest === true ) {
1156 $dest = 'all';
1157 } elseif ( $dest === false ) {
1158 $dest = 'private';
1161 $text = trim( $text );
1163 $logger = LoggerFactory::getInstance( $logGroup );
1164 $context['private'] = ( $dest === 'private' );
1165 $logger->info( $text, $context );
1169 * Log for database errors
1171 * @since 1.25 support for additional context data
1173 * @param string $text Database error message.
1174 * @param array $context Additional logging context data
1176 function wfLogDBError( $text, array $context = array() ) {
1177 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1178 $logger->error( trim( $text ), $context );
1182 * Throws a warning that $function is deprecated
1184 * @param string $function
1185 * @param string|bool $version Version of MediaWiki that the function
1186 * was deprecated in (Added in 1.19).
1187 * @param string|bool $component Added in 1.19.
1188 * @param int $callerOffset How far up the call stack is the original
1189 * caller. 2 = function that called the function that called
1190 * wfDeprecated (Added in 1.20)
1192 * @return null
1194 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1195 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1199 * Send a warning either to the debug log or in a PHP error depending on
1200 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1202 * @param string $msg Message to send
1203 * @param int $callerOffset Number of items to go back in the backtrace to
1204 * find the correct caller (1 = function calling wfWarn, ...)
1205 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1206 * only used when $wgDevelopmentWarnings is true
1208 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1209 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1213 * Send a warning as a PHP error and the debug log. This is intended for logging
1214 * warnings in production. For logging development warnings, use WfWarn instead.
1216 * @param string $msg Message to send
1217 * @param int $callerOffset Number of items to go back in the backtrace to
1218 * find the correct caller (1 = function calling wfLogWarning, ...)
1219 * @param int $level PHP error level; defaults to E_USER_WARNING
1221 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1222 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1226 * Log to a file without getting "file size exceeded" signals.
1228 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1229 * send lines to the specified port, prefixed by the specified prefix and a space.
1230 * @since 1.25 support for additional context data
1232 * @param string $text
1233 * @param string $file Filename
1234 * @param array $context Additional logging context data
1235 * @throws MWException
1236 * @deprecated since 1.25 Use \\MediaWiki\\Logger\\LegacyLogger::emit or UDPTransport
1238 function wfErrorLog( $text, $file, array $context = array() ) {
1239 wfDeprecated( __METHOD__, '1.25' );
1240 $logger = LoggerFactory::getInstance( 'wfErrorLog' );
1241 $context['destination'] = $file;
1242 $logger->info( trim( $text ), $context );
1246 * @todo document
1248 function wfLogProfilingData() {
1249 global $wgDebugLogGroups, $wgDebugRawPage;
1251 $context = RequestContext::getMain();
1252 $request = $context->getRequest();
1254 $profiler = Profiler::instance();
1255 $profiler->setContext( $context );
1256 $profiler->logData();
1258 $config = $context->getConfig();
1259 if ( $config->get( 'StatsdServer' ) ) {
1260 try {
1261 $statsdServer = explode( ':', $config->get( 'StatsdServer' ) );
1262 $statsdHost = $statsdServer[0];
1263 $statsdPort = isset( $statsdServer[1] ) ? $statsdServer[1] : 8125;
1264 $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1265 $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
1266 $statsdClient->send( $context->getStats()->getBuffer() );
1267 } catch ( Exception $ex ) {
1268 MWExceptionHandler::logException( $ex );
1272 # Profiling must actually be enabled...
1273 if ( $profiler instanceof ProfilerStub ) {
1274 return;
1277 if ( isset( $wgDebugLogGroups['profileoutput'] )
1278 && $wgDebugLogGroups['profileoutput'] === false
1280 // Explicitly disabled
1281 return;
1283 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1284 return;
1287 $ctx = array( 'elapsed' => $request->getElapsedTime() );
1288 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1289 $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
1291 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1292 $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP'];
1294 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1295 $ctx['from'] = $_SERVER['HTTP_FROM'];
1297 if ( isset( $ctx['forwarded_for'] ) ||
1298 isset( $ctx['client_ip'] ) ||
1299 isset( $ctx['from'] ) ) {
1300 $ctx['proxy'] = $_SERVER['REMOTE_ADDR'];
1303 // Don't load $wgUser at this late stage just for statistics purposes
1304 // @todo FIXME: We can detect some anons even if it is not loaded.
1305 // See User::getId()
1306 $user = $context->getUser();
1307 $ctx['anon'] = $user->isItemLoaded( 'id' ) && $user->isAnon();
1309 // Command line script uses a FauxRequest object which does not have
1310 // any knowledge about an URL and throw an exception instead.
1311 try {
1312 $ctx['url'] = urldecode( $request->getRequestURL() );
1313 } catch ( Exception $ignored ) {
1314 // no-op
1317 $ctx['output'] = $profiler->getOutput();
1319 $log = LoggerFactory::getInstance( 'profileoutput' );
1320 $log->info( "Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx );
1324 * Increment a statistics counter
1326 * @param string $key
1327 * @param int $count
1328 * @return void
1330 function wfIncrStats( $key, $count = 1 ) {
1331 $stats = RequestContext::getMain()->getStats();
1332 $stats->updateCount( $key, $count );
1336 * Check whether the wiki is in read-only mode.
1338 * @return bool
1340 function wfReadOnly() {
1341 return wfReadOnlyReason() !== false;
1345 * Check if the site is in read-only mode and return the message if so
1347 * This checks wfConfiguredReadOnlyReason() and the main load balancer
1348 * for slave lag. This may result in DB_SLAVE connection being made.
1350 * @return string|bool String when in read-only mode; false otherwise
1352 function wfReadOnlyReason() {
1353 $readOnly = wfConfiguredReadOnlyReason();
1354 if ( $readOnly !== false ) {
1355 return $readOnly;
1358 static $lbReadOnly = null;
1359 if ( $lbReadOnly === null ) {
1360 // Callers use this method to be aware that data presented to a user
1361 // may be very stale and thus allowing submissions can be problematic.
1362 $lbReadOnly = wfGetLB()->getReadOnlyReason();
1365 return $lbReadOnly;
1369 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1371 * @return string|bool String when in read-only mode; false otherwise
1372 * @since 1.27
1374 function wfConfiguredReadOnlyReason() {
1375 global $wgReadOnly, $wgReadOnlyFile;
1377 if ( $wgReadOnly === null ) {
1378 // Set $wgReadOnly for faster access next time
1379 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1380 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1381 } else {
1382 $wgReadOnly = false;
1386 return $wgReadOnly;
1390 * Return a Language object from $langcode
1392 * @param Language|string|bool $langcode Either:
1393 * - a Language object
1394 * - code of the language to get the message for, if it is
1395 * a valid code create a language for that language, if
1396 * it is a string but not a valid code then make a basic
1397 * language object
1398 * - a boolean: if it's false then use the global object for
1399 * the current user's language (as a fallback for the old parameter
1400 * functionality), or if it is true then use global object
1401 * for the wiki's content language.
1402 * @return Language
1404 function wfGetLangObj( $langcode = false ) {
1405 # Identify which language to get or create a language object for.
1406 # Using is_object here due to Stub objects.
1407 if ( is_object( $langcode ) ) {
1408 # Great, we already have the object (hopefully)!
1409 return $langcode;
1412 global $wgContLang, $wgLanguageCode;
1413 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1414 # $langcode is the language code of the wikis content language object.
1415 # or it is a boolean and value is true
1416 return $wgContLang;
1419 global $wgLang;
1420 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1421 # $langcode is the language code of user language object.
1422 # or it was a boolean and value is false
1423 return $wgLang;
1426 $validCodes = array_keys( Language::fetchLanguageNames() );
1427 if ( in_array( $langcode, $validCodes ) ) {
1428 # $langcode corresponds to a valid language.
1429 return Language::factory( $langcode );
1432 # $langcode is a string, but not a valid language code; use content language.
1433 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1434 return $wgContLang;
1438 * This is the function for getting translated interface messages.
1440 * @see Message class for documentation how to use them.
1441 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1443 * This function replaces all old wfMsg* functions.
1445 * @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier
1446 * @param mixed $params,... Normal message parameters
1447 * @return Message
1449 * @since 1.17
1451 * @see Message::__construct
1453 function wfMessage( $key /*...*/ ) {
1454 $params = func_get_args();
1455 array_shift( $params );
1456 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1457 $params = $params[0];
1459 return new Message( $key, $params );
1463 * This function accepts multiple message keys and returns a message instance
1464 * for the first message which is non-empty. If all messages are empty then an
1465 * instance of the first message key is returned.
1467 * @param string|string[] $keys,... Message keys
1468 * @return Message
1470 * @since 1.18
1472 * @see Message::newFallbackSequence
1474 function wfMessageFallback( /*...*/ ) {
1475 $args = func_get_args();
1476 return call_user_func_array( 'Message::newFallbackSequence', $args );
1480 * Get a message from anywhere, for the current user language.
1482 * Use wfMsgForContent() instead if the message should NOT
1483 * change depending on the user preferences.
1485 * @deprecated since 1.18
1487 * @param string $key Lookup key for the message, usually
1488 * defined in languages/Language.php
1490 * Parameters to the message, which can be used to insert variable text into
1491 * it, can be passed to this function in the following formats:
1492 * - One per argument, starting at the second parameter
1493 * - As an array in the second parameter
1494 * These are not shown in the function definition.
1496 * @return string
1498 function wfMsg( $key ) {
1499 wfDeprecated( __METHOD__, '1.21' );
1501 $args = func_get_args();
1502 array_shift( $args );
1503 return wfMsgReal( $key, $args );
1507 * Same as above except doesn't transform the message
1509 * @deprecated since 1.18
1511 * @param string $key
1512 * @return string
1514 function wfMsgNoTrans( $key ) {
1515 wfDeprecated( __METHOD__, '1.21' );
1517 $args = func_get_args();
1518 array_shift( $args );
1519 return wfMsgReal( $key, $args, true, false, false );
1523 * Get a message from anywhere, for the current global language
1524 * set with $wgLanguageCode.
1526 * Use this if the message should NOT change dependent on the
1527 * language set in the user's preferences. This is the case for
1528 * most text written into logs, as well as link targets (such as
1529 * the name of the copyright policy page). Link titles, on the
1530 * other hand, should be shown in the UI language.
1532 * Note that MediaWiki allows users to change the user interface
1533 * language in their preferences, but a single installation
1534 * typically only contains content in one language.
1536 * Be wary of this distinction: If you use wfMsg() where you should
1537 * use wfMsgForContent(), a user of the software may have to
1538 * customize potentially hundreds of messages in
1539 * order to, e.g., fix a link in every possible language.
1541 * @deprecated since 1.18
1543 * @param string $key Lookup key for the message, usually
1544 * defined in languages/Language.php
1545 * @return string
1547 function wfMsgForContent( $key ) {
1548 wfDeprecated( __METHOD__, '1.21' );
1550 global $wgForceUIMsgAsContentMsg;
1551 $args = func_get_args();
1552 array_shift( $args );
1553 $forcontent = true;
1554 if ( is_array( $wgForceUIMsgAsContentMsg )
1555 && in_array( $key, $wgForceUIMsgAsContentMsg )
1557 $forcontent = false;
1559 return wfMsgReal( $key, $args, true, $forcontent );
1563 * Same as above except doesn't transform the message
1565 * @deprecated since 1.18
1567 * @param string $key
1568 * @return string
1570 function wfMsgForContentNoTrans( $key ) {
1571 wfDeprecated( __METHOD__, '1.21' );
1573 global $wgForceUIMsgAsContentMsg;
1574 $args = func_get_args();
1575 array_shift( $args );
1576 $forcontent = true;
1577 if ( is_array( $wgForceUIMsgAsContentMsg )
1578 && in_array( $key, $wgForceUIMsgAsContentMsg )
1580 $forcontent = false;
1582 return wfMsgReal( $key, $args, true, $forcontent, false );
1586 * Really get a message
1588 * @deprecated since 1.18
1590 * @param string $key Key to get.
1591 * @param array $args
1592 * @param bool $useDB
1593 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1594 * @param bool $transform Whether or not to transform the message.
1595 * @return string The requested message.
1597 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1598 wfDeprecated( __METHOD__, '1.21' );
1600 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1601 $message = wfMsgReplaceArgs( $message, $args );
1602 return $message;
1606 * Fetch a message string value, but don't replace any keys yet.
1608 * @deprecated since 1.18
1610 * @param string $key
1611 * @param bool $useDB
1612 * @param string|bool $langCode Code of the language to get the message for, or
1613 * behaves as a content language switch if it is a boolean.
1614 * @param bool $transform Whether to parse magic words, etc.
1615 * @return string
1617 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1618 wfDeprecated( __METHOD__, '1.21' );
1620 Hooks::run( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1622 $cache = MessageCache::singleton();
1623 $message = $cache->get( $key, $useDB, $langCode );
1624 if ( $message === false ) {
1625 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
1626 } elseif ( $transform ) {
1627 $message = $cache->transform( $message );
1629 return $message;
1633 * Replace message parameter keys on the given formatted output.
1635 * @param string $message
1636 * @param array $args
1637 * @return string
1638 * @private
1640 function wfMsgReplaceArgs( $message, $args ) {
1641 # Fix windows line-endings
1642 # Some messages are split with explode("\n", $msg)
1643 $message = str_replace( "\r", '', $message );
1645 // Replace arguments
1646 if ( count( $args ) ) {
1647 if ( is_array( $args[0] ) ) {
1648 $args = array_values( $args[0] );
1650 $replacementKeys = array();
1651 foreach ( $args as $n => $param ) {
1652 $replacementKeys['$' . ( $n + 1 )] = $param;
1654 $message = strtr( $message, $replacementKeys );
1657 return $message;
1661 * Return an HTML-escaped version of a message.
1662 * Parameter replacements, if any, are done *after* the HTML-escaping,
1663 * so parameters may contain HTML (eg links or form controls). Be sure
1664 * to pre-escape them if you really do want plaintext, or just wrap
1665 * the whole thing in htmlspecialchars().
1667 * @deprecated since 1.18
1669 * @param string $key
1670 * @param string $args,... Parameters
1671 * @return string
1673 function wfMsgHtml( $key ) {
1674 wfDeprecated( __METHOD__, '1.21' );
1676 $args = func_get_args();
1677 array_shift( $args );
1678 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1682 * Return an HTML version of message
1683 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1684 * so parameters may contain HTML (eg links or form controls). Be sure
1685 * to pre-escape them if you really do want plaintext, or just wrap
1686 * the whole thing in htmlspecialchars().
1688 * @deprecated since 1.18
1690 * @param string $key
1691 * @param string $args,... Parameters
1692 * @return string
1694 function wfMsgWikiHtml( $key ) {
1695 wfDeprecated( __METHOD__, '1.21' );
1697 $args = func_get_args();
1698 array_shift( $args );
1699 return wfMsgReplaceArgs(
1700 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
1701 /* can't be set to false */ true, /* interface */ true )->getText(),
1702 $args );
1706 * Returns message in the requested format
1708 * @deprecated since 1.18
1710 * @param string $key Key of the message
1711 * @param array $options Processing rules.
1712 * Can take the following options:
1713 * parse: parses wikitext to HTML
1714 * parseinline: parses wikitext to HTML and removes the surrounding
1715 * p's added by parser or tidy
1716 * escape: filters message through htmlspecialchars
1717 * escapenoentities: same, but allows entity references like &#160; through
1718 * replaceafter: parameters are substituted after parsing or escaping
1719 * parsemag: transform the message using magic phrases
1720 * content: fetch message for content language instead of interface
1721 * Also can accept a single associative argument, of the form 'language' => 'xx':
1722 * language: Language object or language code to fetch message for
1723 * (overridden by content).
1724 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1726 * @return string
1728 function wfMsgExt( $key, $options ) {
1729 wfDeprecated( __METHOD__, '1.21' );
1731 $args = func_get_args();
1732 array_shift( $args );
1733 array_shift( $args );
1734 $options = (array)$options;
1735 $validOptions = array( 'parse', 'parseinline', 'escape', 'escapenoentities', 'replaceafter',
1736 'parsemag', 'content' );
1738 foreach ( $options as $arrayKey => $option ) {
1739 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1740 // An unknown index, neither numeric nor "language"
1741 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
1742 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option, $validOptions ) ) {
1743 // A numeric index with unknown value
1744 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
1748 if ( in_array( 'content', $options, true ) ) {
1749 $forContent = true;
1750 $langCode = true;
1751 $langCodeObj = null;
1752 } elseif ( array_key_exists( 'language', $options ) ) {
1753 $forContent = false;
1754 $langCode = wfGetLangObj( $options['language'] );
1755 $langCodeObj = $langCode;
1756 } else {
1757 $forContent = false;
1758 $langCode = false;
1759 $langCodeObj = null;
1762 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1764 if ( !in_array( 'replaceafter', $options, true ) ) {
1765 $string = wfMsgReplaceArgs( $string, $args );
1768 $messageCache = MessageCache::singleton();
1769 $parseInline = in_array( 'parseinline', $options, true );
1770 if ( in_array( 'parse', $options, true ) || $parseInline ) {
1771 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1772 if ( $string instanceof ParserOutput ) {
1773 $string = $string->getText();
1776 if ( $parseInline ) {
1777 $string = Parser::stripOuterParagraph( $string );
1779 } elseif ( in_array( 'parsemag', $options, true ) ) {
1780 $string = $messageCache->transform( $string,
1781 !$forContent, $langCodeObj );
1784 if ( in_array( 'escape', $options, true ) ) {
1785 $string = htmlspecialchars( $string );
1786 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1787 $string = Sanitizer::escapeHtmlAllowEntities( $string );
1790 if ( in_array( 'replaceafter', $options, true ) ) {
1791 $string = wfMsgReplaceArgs( $string, $args );
1794 return $string;
1798 * Since wfMsg() and co suck, they don't return false if the message key they
1799 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1800 * nonexistence of messages by checking the MessageCache::get() result directly.
1802 * @deprecated since 1.18. Use Message::isDisabled().
1804 * @param string $key The message key looked up
1805 * @return bool True if the message *doesn't* exist.
1807 function wfEmptyMsg( $key ) {
1808 wfDeprecated( __METHOD__, '1.21' );
1810 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1814 * Fetch server name for use in error reporting etc.
1815 * Use real server name if available, so we know which machine
1816 * in a server farm generated the current page.
1818 * @return string
1820 function wfHostname() {
1821 static $host;
1822 if ( is_null( $host ) ) {
1824 # Hostname overriding
1825 global $wgOverrideHostname;
1826 if ( $wgOverrideHostname !== false ) {
1827 # Set static and skip any detection
1828 $host = $wgOverrideHostname;
1829 return $host;
1832 if ( function_exists( 'posix_uname' ) ) {
1833 // This function not present on Windows
1834 $uname = posix_uname();
1835 } else {
1836 $uname = false;
1838 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1839 $host = $uname['nodename'];
1840 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1841 # Windows computer name
1842 $host = getenv( 'COMPUTERNAME' );
1843 } else {
1844 # This may be a virtual server.
1845 $host = $_SERVER['SERVER_NAME'];
1848 return $host;
1852 * Returns a script tag that stores the amount of time it took MediaWiki to
1853 * handle the request in milliseconds as 'wgBackendResponseTime'.
1855 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1856 * hostname of the server handling the request.
1858 * @return string
1860 function wfReportTime() {
1861 global $wgRequestTime, $wgShowHostnames;
1863 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1864 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1865 if ( $wgShowHostnames ) {
1866 $reportVars['wgHostname'] = wfHostname();
1868 return Skin::makeVariablesScript( $reportVars );
1872 * Safety wrapper for debug_backtrace().
1874 * Will return an empty array if debug_backtrace is disabled, otherwise
1875 * the output from debug_backtrace() (trimmed).
1877 * @param int $limit This parameter can be used to limit the number of stack frames returned
1879 * @return array Array of backtrace information
1881 function wfDebugBacktrace( $limit = 0 ) {
1882 static $disabled = null;
1884 if ( is_null( $disabled ) ) {
1885 $disabled = !function_exists( 'debug_backtrace' );
1886 if ( $disabled ) {
1887 wfDebug( "debug_backtrace() is disabled\n" );
1890 if ( $disabled ) {
1891 return array();
1894 if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
1895 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1896 } else {
1897 return array_slice( debug_backtrace(), 1 );
1902 * Get a debug backtrace as a string
1904 * @param bool|null $raw If true, the return value is plain text. If false, HTML.
1905 * Defaults to $wgCommandLineMode if unset.
1906 * @return string
1907 * @since 1.25 Supports $raw parameter.
1909 function wfBacktrace( $raw = null ) {
1910 global $wgCommandLineMode;
1912 if ( $raw === null ) {
1913 $raw = $wgCommandLineMode;
1916 if ( $raw ) {
1917 $frameFormat = "%s line %s calls %s()\n";
1918 $traceFormat = "%s";
1919 } else {
1920 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1921 $traceFormat = "<ul>\n%s</ul>\n";
1924 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1925 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1926 $line = isset( $frame['line'] ) ? $frame['line'] : '-';
1927 $call = $frame['function'];
1928 if ( !empty( $frame['class'] ) ) {
1929 $call = $frame['class'] . $frame['type'] . $call;
1931 return sprintf( $frameFormat, $file, $line, $call );
1932 }, wfDebugBacktrace() );
1934 return sprintf( $traceFormat, implode( '', $frames ) );
1938 * Get the name of the function which called this function
1939 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1940 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1941 * wfGetCaller( 3 ) is the parent of that.
1943 * @param int $level
1944 * @return string
1946 function wfGetCaller( $level = 2 ) {
1947 $backtrace = wfDebugBacktrace( $level + 1 );
1948 if ( isset( $backtrace[$level] ) ) {
1949 return wfFormatStackFrame( $backtrace[$level] );
1950 } else {
1951 return 'unknown';
1956 * Return a string consisting of callers in the stack. Useful sometimes
1957 * for profiling specific points.
1959 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1960 * @return string
1962 function wfGetAllCallers( $limit = 3 ) {
1963 $trace = array_reverse( wfDebugBacktrace() );
1964 if ( !$limit || $limit > count( $trace ) - 1 ) {
1965 $limit = count( $trace ) - 1;
1967 $trace = array_slice( $trace, -$limit - 1, $limit );
1968 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1972 * Return a string representation of frame
1974 * @param array $frame
1975 * @return string
1977 function wfFormatStackFrame( $frame ) {
1978 if ( !isset( $frame['function'] ) ) {
1979 return 'NO_FUNCTION_GIVEN';
1981 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1982 $frame['class'] . $frame['type'] . $frame['function'] :
1983 $frame['function'];
1986 /* Some generic result counters, pulled out of SearchEngine */
1989 * @todo document
1991 * @param int $offset
1992 * @param int $limit
1993 * @return string
1995 function wfShowingResults( $offset, $limit ) {
1996 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
2000 * @todo document
2001 * @todo FIXME: We may want to blacklist some broken browsers
2003 * @param bool $force
2004 * @return bool Whereas client accept gzip compression
2006 function wfClientAcceptsGzip( $force = false ) {
2007 static $result = null;
2008 if ( $result === null || $force ) {
2009 $result = false;
2010 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
2011 # @todo FIXME: We may want to blacklist some broken browsers
2012 $m = array();
2013 if ( preg_match(
2014 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
2015 $_SERVER['HTTP_ACCEPT_ENCODING'],
2019 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2020 $result = false;
2021 return $result;
2023 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2024 $result = true;
2028 return $result;
2032 * Obtain the offset and limit values from the request string;
2033 * used in special pages
2035 * @param int $deflimit Default limit if none supplied
2036 * @param string $optionname Name of a user preference to check against
2037 * @return array
2038 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2040 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2041 global $wgRequest;
2042 wfDeprecated( __METHOD__, '1.24' );
2043 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2047 * Escapes the given text so that it may be output using addWikiText()
2048 * without any linking, formatting, etc. making its way through. This
2049 * is achieved by substituting certain characters with HTML entities.
2050 * As required by the callers, "<nowiki>" is not used.
2052 * @param string $text Text to be escaped
2053 * @return string
2055 function wfEscapeWikiText( $text ) {
2056 static $repl = null, $repl2 = null;
2057 if ( $repl === null ) {
2058 $repl = array(
2059 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
2060 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
2061 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
2062 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
2063 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
2064 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
2065 "\n " => "\n&#32;", "\r " => "\r&#32;",
2066 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
2067 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
2068 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
2069 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
2070 '__' => '_&#95;', '://' => '&#58;//',
2073 // We have to catch everything "\s" matches in PCRE
2074 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2075 $repl["$magic "] = "$magic&#32;";
2076 $repl["$magic\t"] = "$magic&#9;";
2077 $repl["$magic\r"] = "$magic&#13;";
2078 $repl["$magic\n"] = "$magic&#10;";
2079 $repl["$magic\f"] = "$magic&#12;";
2082 // And handle protocols that don't use "://"
2083 global $wgUrlProtocols;
2084 $repl2 = array();
2085 foreach ( $wgUrlProtocols as $prot ) {
2086 if ( substr( $prot, -1 ) === ':' ) {
2087 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2090 $repl2 = $repl2 ? '/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2092 $text = substr( strtr( "\n$text", $repl ), 1 );
2093 $text = preg_replace( $repl2, '$1&#58;', $text );
2094 return $text;
2098 * Sets dest to source and returns the original value of dest
2099 * If source is NULL, it just returns the value, it doesn't set the variable
2100 * If force is true, it will set the value even if source is NULL
2102 * @param mixed $dest
2103 * @param mixed $source
2104 * @param bool $force
2105 * @return mixed
2107 function wfSetVar( &$dest, $source, $force = false ) {
2108 $temp = $dest;
2109 if ( !is_null( $source ) || $force ) {
2110 $dest = $source;
2112 return $temp;
2116 * As for wfSetVar except setting a bit
2118 * @param int $dest
2119 * @param int $bit
2120 * @param bool $state
2122 * @return bool
2124 function wfSetBit( &$dest, $bit, $state = true ) {
2125 $temp = (bool)( $dest & $bit );
2126 if ( !is_null( $state ) ) {
2127 if ( $state ) {
2128 $dest |= $bit;
2129 } else {
2130 $dest &= ~$bit;
2133 return $temp;
2137 * A wrapper around the PHP function var_export().
2138 * Either print it or add it to the regular output ($wgOut).
2140 * @param mixed $var A PHP variable to dump.
2142 function wfVarDump( $var ) {
2143 global $wgOut;
2144 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2145 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
2146 print $s;
2147 } else {
2148 $wgOut->addHTML( $s );
2153 * Provide a simple HTTP error.
2155 * @param int|string $code
2156 * @param string $label
2157 * @param string $desc
2159 function wfHttpError( $code, $label, $desc ) {
2160 global $wgOut;
2161 HttpStatus::header( $code );
2162 if ( $wgOut ) {
2163 $wgOut->disable();
2164 $wgOut->sendCacheControl();
2167 header( 'Content-type: text/html; charset=utf-8' );
2168 print '<!DOCTYPE html>' .
2169 '<html><head><title>' .
2170 htmlspecialchars( $label ) .
2171 '</title></head><body><h1>' .
2172 htmlspecialchars( $label ) .
2173 '</h1><p>' .
2174 nl2br( htmlspecialchars( $desc ) ) .
2175 "</p></body></html>\n";
2179 * Clear away any user-level output buffers, discarding contents.
2181 * Suitable for 'starting afresh', for instance when streaming
2182 * relatively large amounts of data without buffering, or wanting to
2183 * output image files without ob_gzhandler's compression.
2185 * The optional $resetGzipEncoding parameter controls suppression of
2186 * the Content-Encoding header sent by ob_gzhandler; by default it
2187 * is left. See comments for wfClearOutputBuffers() for why it would
2188 * be used.
2190 * Note that some PHP configuration options may add output buffer
2191 * layers which cannot be removed; these are left in place.
2193 * @param bool $resetGzipEncoding
2195 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2196 if ( $resetGzipEncoding ) {
2197 // Suppress Content-Encoding and Content-Length
2198 // headers from 1.10+s wfOutputHandler
2199 global $wgDisableOutputCompression;
2200 $wgDisableOutputCompression = true;
2202 while ( $status = ob_get_status() ) {
2203 if ( isset( $status['flags'] ) ) {
2204 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
2205 $deleteable = ( $status['flags'] & $flags ) === $flags;
2206 } elseif ( isset( $status['del'] ) ) {
2207 $deleteable = $status['del'];
2208 } else {
2209 // Guess that any PHP-internal setting can't be removed.
2210 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
2212 if ( !$deleteable ) {
2213 // Give up, and hope the result doesn't break
2214 // output behavior.
2215 break;
2217 if ( $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ) {
2218 // Unit testing barrier to prevent this function from breaking PHPUnit.
2219 break;
2221 if ( !ob_end_clean() ) {
2222 // Could not remove output buffer handler; abort now
2223 // to avoid getting in some kind of infinite loop.
2224 break;
2226 if ( $resetGzipEncoding ) {
2227 if ( $status['name'] == 'ob_gzhandler' ) {
2228 // Reset the 'Content-Encoding' field set by this handler
2229 // so we can start fresh.
2230 header_remove( 'Content-Encoding' );
2231 break;
2238 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2240 * Clear away output buffers, but keep the Content-Encoding header
2241 * produced by ob_gzhandler, if any.
2243 * This should be used for HTTP 304 responses, where you need to
2244 * preserve the Content-Encoding header of the real result, but
2245 * also need to suppress the output of ob_gzhandler to keep to spec
2246 * and avoid breaking Firefox in rare cases where the headers and
2247 * body are broken over two packets.
2249 function wfClearOutputBuffers() {
2250 wfResetOutputBuffers( false );
2254 * Converts an Accept-* header into an array mapping string values to quality
2255 * factors
2257 * @param string $accept
2258 * @param string $def Default
2259 * @return float[] Associative array of string => float pairs
2261 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2262 # No arg means accept anything (per HTTP spec)
2263 if ( !$accept ) {
2264 return array( $def => 1.0 );
2267 $prefs = array();
2269 $parts = explode( ',', $accept );
2271 foreach ( $parts as $part ) {
2272 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2273 $values = explode( ';', trim( $part ) );
2274 $match = array();
2275 if ( count( $values ) == 1 ) {
2276 $prefs[$values[0]] = 1.0;
2277 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2278 $prefs[$values[0]] = floatval( $match[1] );
2282 return $prefs;
2286 * Checks if a given MIME type matches any of the keys in the given
2287 * array. Basic wildcards are accepted in the array keys.
2289 * Returns the matching MIME type (or wildcard) if a match, otherwise
2290 * NULL if no match.
2292 * @param string $type
2293 * @param array $avail
2294 * @return string
2295 * @private
2297 function mimeTypeMatch( $type, $avail ) {
2298 if ( array_key_exists( $type, $avail ) ) {
2299 return $type;
2300 } else {
2301 $parts = explode( '/', $type );
2302 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2303 return $parts[0] . '/*';
2304 } elseif ( array_key_exists( '*/*', $avail ) ) {
2305 return '*/*';
2306 } else {
2307 return null;
2313 * Returns the 'best' match between a client's requested internet media types
2314 * and the server's list of available types. Each list should be an associative
2315 * array of type to preference (preference is a float between 0.0 and 1.0).
2316 * Wildcards in the types are acceptable.
2318 * @param array $cprefs Client's acceptable type list
2319 * @param array $sprefs Server's offered types
2320 * @return string
2322 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2323 * XXX: generalize to negotiate other stuff
2325 function wfNegotiateType( $cprefs, $sprefs ) {
2326 $combine = array();
2328 foreach ( array_keys( $sprefs ) as $type ) {
2329 $parts = explode( '/', $type );
2330 if ( $parts[1] != '*' ) {
2331 $ckey = mimeTypeMatch( $type, $cprefs );
2332 if ( $ckey ) {
2333 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2338 foreach ( array_keys( $cprefs ) as $type ) {
2339 $parts = explode( '/', $type );
2340 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2341 $skey = mimeTypeMatch( $type, $sprefs );
2342 if ( $skey ) {
2343 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2348 $bestq = 0;
2349 $besttype = null;
2351 foreach ( array_keys( $combine ) as $type ) {
2352 if ( $combine[$type] > $bestq ) {
2353 $besttype = $type;
2354 $bestq = $combine[$type];
2358 return $besttype;
2362 * Reference-counted warning suppression
2364 * @deprecated since 1.26, use MediaWiki\suppressWarnings() directly
2365 * @param bool $end
2367 function wfSuppressWarnings( $end = false ) {
2368 MediaWiki\suppressWarnings( $end );
2372 * @deprecated since 1.26, use MediaWiki\restoreWarnings() directly
2373 * Restore error level to previous value
2375 function wfRestoreWarnings() {
2376 MediaWiki\suppressWarnings( true );
2379 # Autodetect, convert and provide timestamps of various types
2382 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2384 define( 'TS_UNIX', 0 );
2387 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2389 define( 'TS_MW', 1 );
2392 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2394 define( 'TS_DB', 2 );
2397 * RFC 2822 format, for E-mail and HTTP headers
2399 define( 'TS_RFC2822', 3 );
2402 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2404 * This is used by Special:Export
2406 define( 'TS_ISO_8601', 4 );
2409 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2411 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2412 * DateTime tag and page 36 for the DateTimeOriginal and
2413 * DateTimeDigitized tags.
2415 define( 'TS_EXIF', 5 );
2418 * Oracle format time.
2420 define( 'TS_ORACLE', 6 );
2423 * Postgres format time.
2425 define( 'TS_POSTGRES', 7 );
2428 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2430 define( 'TS_ISO_8601_BASIC', 9 );
2433 * Get a timestamp string in one of various formats
2435 * @param mixed $outputtype A timestamp in one of the supported formats, the
2436 * function will autodetect which format is supplied and act accordingly.
2437 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2438 * @return string|bool String / false The same date in the format specified in $outputtype or false
2440 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2441 try {
2442 $timestamp = new MWTimestamp( $ts );
2443 return $timestamp->getTimestamp( $outputtype );
2444 } catch ( TimestampException $e ) {
2445 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2446 return false;
2451 * Return a formatted timestamp, or null if input is null.
2452 * For dealing with nullable timestamp columns in the database.
2454 * @param int $outputtype
2455 * @param string $ts
2456 * @return string
2458 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2459 if ( is_null( $ts ) ) {
2460 return null;
2461 } else {
2462 return wfTimestamp( $outputtype, $ts );
2467 * Convenience function; returns MediaWiki timestamp for the present time.
2469 * @return string
2471 function wfTimestampNow() {
2472 # return NOW
2473 return wfTimestamp( TS_MW, time() );
2477 * Check if the operating system is Windows
2479 * @return bool True if it's Windows, false otherwise.
2481 function wfIsWindows() {
2482 static $isWindows = null;
2483 if ( $isWindows === null ) {
2484 $isWindows = strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN';
2486 return $isWindows;
2490 * Check if we are running under HHVM
2492 * @return bool
2494 function wfIsHHVM() {
2495 return defined( 'HHVM_VERSION' );
2499 * Tries to get the system directory for temporary files. First
2500 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2501 * environment variables are then checked in sequence, and if none are
2502 * set try sys_get_temp_dir().
2504 * NOTE: When possible, use instead the tmpfile() function to create
2505 * temporary files to avoid race conditions on file creation, etc.
2507 * @return string
2509 function wfTempDir() {
2510 global $wgTmpDirectory;
2512 if ( $wgTmpDirectory !== false ) {
2513 return $wgTmpDirectory;
2516 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2518 foreach ( $tmpDir as $tmp ) {
2519 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2520 return $tmp;
2523 return sys_get_temp_dir();
2527 * Make directory, and make all parent directories if they don't exist
2529 * @param string $dir Full path to directory to create
2530 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2531 * @param string $caller Optional caller param for debugging.
2532 * @throws MWException
2533 * @return bool
2535 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2536 global $wgDirectoryMode;
2538 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
2539 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
2542 if ( !is_null( $caller ) ) {
2543 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2546 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
2547 return true;
2550 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2552 if ( is_null( $mode ) ) {
2553 $mode = $wgDirectoryMode;
2556 // Turn off the normal warning, we're doing our own below
2557 MediaWiki\suppressWarnings();
2558 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2559 MediaWiki\restoreWarnings();
2561 if ( !$ok ) {
2562 // directory may have been created on another request since we last checked
2563 if ( is_dir( $dir ) ) {
2564 return true;
2567 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2568 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2570 return $ok;
2574 * Remove a directory and all its content.
2575 * Does not hide error.
2576 * @param string $dir
2578 function wfRecursiveRemoveDir( $dir ) {
2579 wfDebug( __FUNCTION__ . "( $dir )\n" );
2580 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2581 if ( is_dir( $dir ) ) {
2582 $objects = scandir( $dir );
2583 foreach ( $objects as $object ) {
2584 if ( $object != "." && $object != ".." ) {
2585 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2586 wfRecursiveRemoveDir( $dir . '/' . $object );
2587 } else {
2588 unlink( $dir . '/' . $object );
2592 reset( $objects );
2593 rmdir( $dir );
2598 * @param int $nr The number to format
2599 * @param int $acc The number of digits after the decimal point, default 2
2600 * @param bool $round Whether or not to round the value, default true
2601 * @return string
2603 function wfPercent( $nr, $acc = 2, $round = true ) {
2604 $ret = sprintf( "%.${acc}f", $nr );
2605 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2609 * Safety wrapper around ini_get() for boolean settings.
2610 * The values returned from ini_get() are pre-normalized for settings
2611 * set via php.ini or php_flag/php_admin_flag... but *not*
2612 * for those set via php_value/php_admin_value.
2614 * It's fairly common for people to use php_value instead of php_flag,
2615 * which can leave you with an 'off' setting giving a false positive
2616 * for code that just takes the ini_get() return value as a boolean.
2618 * To make things extra interesting, setting via php_value accepts
2619 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2620 * Unrecognized values go false... again opposite PHP's own coercion
2621 * from string to bool.
2623 * Luckily, 'properly' set settings will always come back as '0' or '1',
2624 * so we only have to worry about them and the 'improper' settings.
2626 * I frickin' hate PHP... :P
2628 * @param string $setting
2629 * @return bool
2631 function wfIniGetBool( $setting ) {
2632 $val = strtolower( ini_get( $setting ) );
2633 // 'on' and 'true' can't have whitespace around them, but '1' can.
2634 return $val == 'on'
2635 || $val == 'true'
2636 || $val == 'yes'
2637 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2641 * Windows-compatible version of escapeshellarg()
2642 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2643 * function puts single quotes in regardless of OS.
2645 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2646 * earlier distro releases of PHP)
2648 * @param string ... strings to escape and glue together, or a single array of strings parameter
2649 * @return string
2651 function wfEscapeShellArg( /*...*/ ) {
2652 wfInitShellLocale();
2654 $args = func_get_args();
2655 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
2656 // If only one argument has been passed, and that argument is an array,
2657 // treat it as a list of arguments
2658 $args = reset( $args );
2661 $first = true;
2662 $retVal = '';
2663 foreach ( $args as $arg ) {
2664 if ( !$first ) {
2665 $retVal .= ' ';
2666 } else {
2667 $first = false;
2670 if ( wfIsWindows() ) {
2671 // Escaping for an MSVC-style command line parser and CMD.EXE
2672 // @codingStandardsIgnoreStart For long URLs
2673 // Refs:
2674 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2675 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2676 // * Bug #13518
2677 // * CR r63214
2678 // Double the backslashes before any double quotes. Escape the double quotes.
2679 // @codingStandardsIgnoreEnd
2680 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
2681 $arg = '';
2682 $iteration = 0;
2683 foreach ( $tokens as $token ) {
2684 if ( $iteration % 2 == 1 ) {
2685 // Delimiter, a double quote preceded by zero or more slashes
2686 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2687 } elseif ( $iteration % 4 == 2 ) {
2688 // ^ in $token will be outside quotes, need to be escaped
2689 $arg .= str_replace( '^', '^^', $token );
2690 } else { // $iteration % 4 == 0
2691 // ^ in $token will appear inside double quotes, so leave as is
2692 $arg .= $token;
2694 $iteration++;
2696 // Double the backslashes before the end of the string, because
2697 // we will soon add a quote
2698 $m = array();
2699 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2700 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2703 // Add surrounding quotes
2704 $retVal .= '"' . $arg . '"';
2705 } else {
2706 $retVal .= escapeshellarg( $arg );
2709 return $retVal;
2713 * Check if wfShellExec() is effectively disabled via php.ini config
2715 * @return bool|string False or one of (safemode,disabled)
2716 * @since 1.22
2718 function wfShellExecDisabled() {
2719 static $disabled = null;
2720 if ( is_null( $disabled ) ) {
2721 if ( wfIniGetBool( 'safe_mode' ) ) {
2722 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2723 $disabled = 'safemode';
2724 } elseif ( !function_exists( 'proc_open' ) ) {
2725 wfDebug( "proc_open() is disabled\n" );
2726 $disabled = 'disabled';
2727 } else {
2728 $disabled = false;
2731 return $disabled;
2735 * Execute a shell command, with time and memory limits mirrored from the PHP
2736 * configuration if supported.
2738 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2739 * or an array of unescaped arguments, in which case each value will be escaped
2740 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2741 * @param null|mixed &$retval Optional, will receive the program's exit code.
2742 * (non-zero is usually failure). If there is an error from
2743 * read, select, or proc_open(), this will be set to -1.
2744 * @param array $environ Optional environment variables which should be
2745 * added to the executed command environment.
2746 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2747 * this overwrites the global wgMaxShell* limits.
2748 * @param array $options Array of options:
2749 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2750 * including errors from limit.sh
2751 * - profileMethod: By default this function will profile based on the calling
2752 * method. Set this to a string for an alternative method to profile from
2754 * @return string Collected stdout as a string
2756 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2757 $limits = array(), $options = array()
2759 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2760 $wgMaxShellWallClockTime, $wgShellCgroup;
2762 $disabled = wfShellExecDisabled();
2763 if ( $disabled ) {
2764 $retval = 1;
2765 return $disabled == 'safemode' ?
2766 'Unable to run external programs in safe mode.' :
2767 'Unable to run external programs, proc_open() is disabled.';
2770 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2771 $profileMethod = isset( $options['profileMethod'] ) ? $options['profileMethod'] : wfGetCaller();
2773 wfInitShellLocale();
2775 $envcmd = '';
2776 foreach ( $environ as $k => $v ) {
2777 if ( wfIsWindows() ) {
2778 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2779 * appear in the environment variable, so we must use carat escaping as documented in
2780 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2781 * Note however that the quote isn't listed there, but is needed, and the parentheses
2782 * are listed there but doesn't appear to need it.
2784 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2785 } else {
2786 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2787 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2789 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2792 if ( is_array( $cmd ) ) {
2793 $cmd = wfEscapeShellArg( $cmd );
2796 $cmd = $envcmd . $cmd;
2798 $useLogPipe = false;
2799 if ( is_executable( '/bin/bash' ) ) {
2800 $time = intval( isset( $limits['time'] ) ? $limits['time'] : $wgMaxShellTime );
2801 if ( isset( $limits['walltime'] ) ) {
2802 $wallTime = intval( $limits['walltime'] );
2803 } elseif ( isset( $limits['time'] ) ) {
2804 $wallTime = $time;
2805 } else {
2806 $wallTime = intval( $wgMaxShellWallClockTime );
2808 $mem = intval( isset( $limits['memory'] ) ? $limits['memory'] : $wgMaxShellMemory );
2809 $filesize = intval( isset( $limits['filesize'] ) ? $limits['filesize'] : $wgMaxShellFileSize );
2811 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
2812 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2813 escapeshellarg( $cmd ) . ' ' .
2814 escapeshellarg(
2815 "MW_INCLUDE_STDERR=" . ( $includeStderr ? '1' : '' ) . ';' .
2816 "MW_CPU_LIMIT=$time; " .
2817 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2818 "MW_MEM_LIMIT=$mem; " .
2819 "MW_FILE_SIZE_LIMIT=$filesize; " .
2820 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2821 "MW_USE_LOG_PIPE=yes"
2823 $useLogPipe = true;
2824 } elseif ( $includeStderr ) {
2825 $cmd .= ' 2>&1';
2827 } elseif ( $includeStderr ) {
2828 $cmd .= ' 2>&1';
2830 wfDebug( "wfShellExec: $cmd\n" );
2832 $desc = array(
2833 0 => array( 'file', 'php://stdin', 'r' ),
2834 1 => array( 'pipe', 'w' ),
2835 2 => array( 'file', 'php://stderr', 'w' ) );
2836 if ( $useLogPipe ) {
2837 $desc[3] = array( 'pipe', 'w' );
2839 $pipes = null;
2840 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
2841 $proc = proc_open( $cmd, $desc, $pipes );
2842 if ( !$proc ) {
2843 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2844 $retval = -1;
2845 return '';
2847 $outBuffer = $logBuffer = '';
2848 $emptyArray = array();
2849 $status = false;
2850 $logMsg = false;
2852 /* According to the documentation, it is possible for stream_select()
2853 * to fail due to EINTR. I haven't managed to induce this in testing
2854 * despite sending various signals. If it did happen, the error
2855 * message would take the form:
2857 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2859 * where [4] is the value of the macro EINTR and "Interrupted system
2860 * call" is string which according to the Linux manual is "possibly"
2861 * localised according to LC_MESSAGES.
2863 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
2864 $eintrMessage = "stream_select(): unable to select [$eintr]";
2866 // Build a table mapping resource IDs to pipe FDs to work around a
2867 // PHP 5.3 issue in which stream_select() does not preserve array keys
2868 // <https://bugs.php.net/bug.php?id=53427>.
2869 $fds = array();
2870 foreach ( $pipes as $fd => $pipe ) {
2871 $fds[(int)$pipe] = $fd;
2874 $running = true;
2875 $timeout = null;
2876 $numReadyPipes = 0;
2878 while ( $running === true || $numReadyPipes !== 0 ) {
2879 if ( $running ) {
2880 $status = proc_get_status( $proc );
2881 // If the process has terminated, switch to nonblocking selects
2882 // for getting any data still waiting to be read.
2883 if ( !$status['running'] ) {
2884 $running = false;
2885 $timeout = 0;
2889 $readyPipes = $pipes;
2891 // Clear last error
2892 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2893 @trigger_error( '' );
2894 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
2895 if ( $numReadyPipes === false ) {
2896 // @codingStandardsIgnoreEnd
2897 $error = error_get_last();
2898 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2899 continue;
2900 } else {
2901 trigger_error( $error['message'], E_USER_WARNING );
2902 $logMsg = $error['message'];
2903 break;
2906 foreach ( $readyPipes as $pipe ) {
2907 $block = fread( $pipe, 65536 );
2908 $fd = $fds[(int)$pipe];
2909 if ( $block === '' ) {
2910 // End of file
2911 fclose( $pipes[$fd] );
2912 unset( $pipes[$fd] );
2913 if ( !$pipes ) {
2914 break 2;
2916 } elseif ( $block === false ) {
2917 // Read error
2918 $logMsg = "Error reading from pipe";
2919 break 2;
2920 } elseif ( $fd == 1 ) {
2921 // From stdout
2922 $outBuffer .= $block;
2923 } elseif ( $fd == 3 ) {
2924 // From log FD
2925 $logBuffer .= $block;
2926 if ( strpos( $block, "\n" ) !== false ) {
2927 $lines = explode( "\n", $logBuffer );
2928 $logBuffer = array_pop( $lines );
2929 foreach ( $lines as $line ) {
2930 wfDebugLog( 'exec', $line );
2937 foreach ( $pipes as $pipe ) {
2938 fclose( $pipe );
2941 // Use the status previously collected if possible, since proc_get_status()
2942 // just calls waitpid() which will not return anything useful the second time.
2943 if ( $running ) {
2944 $status = proc_get_status( $proc );
2947 if ( $logMsg !== false ) {
2948 // Read/select error
2949 $retval = -1;
2950 proc_close( $proc );
2951 } elseif ( $status['signaled'] ) {
2952 $logMsg = "Exited with signal {$status['termsig']}";
2953 $retval = 128 + $status['termsig'];
2954 proc_close( $proc );
2955 } else {
2956 if ( $status['running'] ) {
2957 $retval = proc_close( $proc );
2958 } else {
2959 $retval = $status['exitcode'];
2960 proc_close( $proc );
2962 if ( $retval == 127 ) {
2963 $logMsg = "Possibly missing executable file";
2964 } elseif ( $retval >= 129 && $retval <= 192 ) {
2965 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2969 if ( $logMsg !== false ) {
2970 wfDebugLog( 'exec', "$logMsg: $cmd" );
2973 return $outBuffer;
2977 * Execute a shell command, returning both stdout and stderr. Convenience
2978 * function, as all the arguments to wfShellExec can become unwieldy.
2980 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2981 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2982 * or an array of unescaped arguments, in which case each value will be escaped
2983 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2984 * @param null|mixed &$retval Optional, will receive the program's exit code.
2985 * (non-zero is usually failure)
2986 * @param array $environ Optional environment variables which should be
2987 * added to the executed command environment.
2988 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2989 * this overwrites the global wgMaxShell* limits.
2990 * @return string Collected stdout and stderr as a string
2992 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2993 return wfShellExec( $cmd, $retval, $environ, $limits,
2994 array( 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ) );
2998 * Workaround for http://bugs.php.net/bug.php?id=45132
2999 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
3001 function wfInitShellLocale() {
3002 static $done = false;
3003 if ( $done ) {
3004 return;
3006 $done = true;
3007 global $wgShellLocale;
3008 if ( !wfIniGetBool( 'safe_mode' ) ) {
3009 putenv( "LC_CTYPE=$wgShellLocale" );
3010 setlocale( LC_CTYPE, $wgShellLocale );
3015 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3016 * Note that $parameters should be a flat array and an option with an argument
3017 * should consist of two consecutive items in the array (do not use "--option value").
3019 * @param string $script MediaWiki cli script path
3020 * @param array $parameters Arguments and options to the script
3021 * @param array $options Associative array of options:
3022 * 'php': The path to the php executable
3023 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3024 * @return string
3026 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3027 global $wgPhpCli;
3028 // Give site config file a chance to run the script in a wrapper.
3029 // The caller may likely want to call wfBasename() on $script.
3030 Hooks::run( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3031 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
3032 if ( isset( $options['wrapper'] ) ) {
3033 $cmd[] = $options['wrapper'];
3035 $cmd[] = $script;
3036 // Escape each parameter for shell
3037 return wfEscapeShellArg( array_merge( $cmd, $parameters ) );
3041 * wfMerge attempts to merge differences between three texts.
3042 * Returns true for a clean merge and false for failure or a conflict.
3044 * @param string $old
3045 * @param string $mine
3046 * @param string $yours
3047 * @param string $result
3048 * @return bool
3050 function wfMerge( $old, $mine, $yours, &$result ) {
3051 global $wgDiff3;
3053 # This check may also protect against code injection in
3054 # case of broken installations.
3055 MediaWiki\suppressWarnings();
3056 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3057 MediaWiki\restoreWarnings();
3059 if ( !$haveDiff3 ) {
3060 wfDebug( "diff3 not found\n" );
3061 return false;
3064 # Make temporary files
3065 $td = wfTempDir();
3066 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3067 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3068 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3070 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3071 # a newline character. To avoid this, we normalize the trailing whitespace before
3072 # creating the diff.
3074 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3075 fclose( $oldtextFile );
3076 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3077 fclose( $mytextFile );
3078 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3079 fclose( $yourtextFile );
3081 # Check for a conflict
3082 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '--overlap-only', $mytextName,
3083 $oldtextName, $yourtextName );
3084 $handle = popen( $cmd, 'r' );
3086 if ( fgets( $handle, 1024 ) ) {
3087 $conflict = true;
3088 } else {
3089 $conflict = false;
3091 pclose( $handle );
3093 # Merge differences
3094 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '-e', '--merge', $mytextName,
3095 $oldtextName, $yourtextName );
3096 $handle = popen( $cmd, 'r' );
3097 $result = '';
3098 do {
3099 $data = fread( $handle, 8192 );
3100 if ( strlen( $data ) == 0 ) {
3101 break;
3103 $result .= $data;
3104 } while ( true );
3105 pclose( $handle );
3106 unlink( $mytextName );
3107 unlink( $oldtextName );
3108 unlink( $yourtextName );
3110 if ( $result === '' && $old !== '' && !$conflict ) {
3111 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3112 $conflict = true;
3114 return !$conflict;
3118 * Returns unified plain-text diff of two texts.
3119 * "Useful" for machine processing of diffs.
3121 * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly
3123 * @param string $before The text before the changes.
3124 * @param string $after The text after the changes.
3125 * @param string $params Command-line options for the diff command.
3126 * @return string Unified diff of $before and $after
3128 function wfDiff( $before, $after, $params = '-u' ) {
3129 if ( $before == $after ) {
3130 return '';
3133 global $wgDiff;
3134 MediaWiki\suppressWarnings();
3135 $haveDiff = $wgDiff && file_exists( $wgDiff );
3136 MediaWiki\restoreWarnings();
3138 # This check may also protect against code injection in
3139 # case of broken installations.
3140 if ( !$haveDiff ) {
3141 wfDebug( "diff executable not found\n" );
3142 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3143 $format = new UnifiedDiffFormatter();
3144 return $format->format( $diffs );
3147 # Make temporary files
3148 $td = wfTempDir();
3149 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3150 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3152 fwrite( $oldtextFile, $before );
3153 fclose( $oldtextFile );
3154 fwrite( $newtextFile, $after );
3155 fclose( $newtextFile );
3157 // Get the diff of the two files
3158 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3160 $h = popen( $cmd, 'r' );
3161 if ( !$h ) {
3162 unlink( $oldtextName );
3163 unlink( $newtextName );
3164 throw new Exception( __METHOD__ . '(): popen() failed' );
3167 $diff = '';
3169 do {
3170 $data = fread( $h, 8192 );
3171 if ( strlen( $data ) == 0 ) {
3172 break;
3174 $diff .= $data;
3175 } while ( true );
3177 // Clean up
3178 pclose( $h );
3179 unlink( $oldtextName );
3180 unlink( $newtextName );
3182 // Kill the --- and +++ lines. They're not useful.
3183 $diff_lines = explode( "\n", $diff );
3184 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
3185 unset( $diff_lines[0] );
3187 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
3188 unset( $diff_lines[1] );
3191 $diff = implode( "\n", $diff_lines );
3193 return $diff;
3197 * This function works like "use VERSION" in Perl, the program will die with a
3198 * backtrace if the current version of PHP is less than the version provided
3200 * This is useful for extensions which due to their nature are not kept in sync
3201 * with releases, and might depend on other versions of PHP than the main code
3203 * Note: PHP might die due to parsing errors in some cases before it ever
3204 * manages to call this function, such is life
3206 * @see perldoc -f use
3208 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3209 * @throws MWException
3211 function wfUsePHP( $req_ver ) {
3212 $php_ver = PHP_VERSION;
3214 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3215 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3220 * This function works like "use VERSION" in Perl except it checks the version
3221 * of MediaWiki, the program will die with a backtrace if the current version
3222 * of MediaWiki is less than the version provided.
3224 * This is useful for extensions which due to their nature are not kept in sync
3225 * with releases
3227 * Note: Due to the behavior of PHP's version_compare() which is used in this
3228 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3229 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3230 * targeted version number. For example if you wanted to allow any variation
3231 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3232 * not result in the same comparison due to the internal logic of
3233 * version_compare().
3235 * @see perldoc -f use
3237 * @deprecated since 1.26, use the "requires' property of extension.json
3238 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3239 * @throws MWException
3241 function wfUseMW( $req_ver ) {
3242 global $wgVersion;
3244 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3245 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3250 * Return the final portion of a pathname.
3251 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3252 * http://bugs.php.net/bug.php?id=33898
3254 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3255 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3257 * @param string $path
3258 * @param string $suffix String to remove if present
3259 * @return string
3261 function wfBaseName( $path, $suffix = '' ) {
3262 if ( $suffix == '' ) {
3263 $encSuffix = '';
3264 } else {
3265 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3268 $matches = array();
3269 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3270 return $matches[1];
3271 } else {
3272 return '';
3277 * Generate a relative path name to the given file.
3278 * May explode on non-matching case-insensitive paths,
3279 * funky symlinks, etc.
3281 * @param string $path Absolute destination path including target filename
3282 * @param string $from Absolute source path, directory only
3283 * @return string
3285 function wfRelativePath( $path, $from ) {
3286 // Normalize mixed input on Windows...
3287 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
3288 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
3290 // Trim trailing slashes -- fix for drive root
3291 $path = rtrim( $path, DIRECTORY_SEPARATOR );
3292 $from = rtrim( $from, DIRECTORY_SEPARATOR );
3294 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
3295 $against = explode( DIRECTORY_SEPARATOR, $from );
3297 if ( $pieces[0] !== $against[0] ) {
3298 // Non-matching Windows drive letters?
3299 // Return a full path.
3300 return $path;
3303 // Trim off common prefix
3304 while ( count( $pieces ) && count( $against )
3305 && $pieces[0] == $against[0] ) {
3306 array_shift( $pieces );
3307 array_shift( $against );
3310 // relative dots to bump us to the parent
3311 while ( count( $against ) ) {
3312 array_unshift( $pieces, '..' );
3313 array_shift( $against );
3316 array_push( $pieces, wfBaseName( $path ) );
3318 return implode( DIRECTORY_SEPARATOR, $pieces );
3322 * Convert an arbitrarily-long digit string from one numeric base
3323 * to another, optionally zero-padding to a minimum column width.
3325 * Supports base 2 through 36; digit values 10-36 are represented
3326 * as lowercase letters a-z. Input is case-insensitive.
3328 * @param string $input Input number
3329 * @param int $sourceBase Base of the input number
3330 * @param int $destBase Desired base of the output
3331 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3332 * @param bool $lowercase Whether to output in lowercase or uppercase
3333 * @param string $engine Either "gmp", "bcmath", or "php"
3334 * @return string|bool The output number as a string, or false on error
3336 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3337 $lowercase = true, $engine = 'auto'
3339 $input = (string)$input;
3340 if (
3341 $sourceBase < 2 ||
3342 $sourceBase > 36 ||
3343 $destBase < 2 ||
3344 $destBase > 36 ||
3345 $sourceBase != (int)$sourceBase ||
3346 $destBase != (int)$destBase ||
3347 $pad != (int)$pad ||
3348 !preg_match(
3349 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3350 $input
3353 return false;
3356 static $baseChars = array(
3357 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3358 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3359 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3360 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3361 34 => 'y', 35 => 'z',
3363 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3364 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3365 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3366 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3367 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3368 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3371 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' || $engine == 'gmp' ) ) {
3372 // Removing leading zeros works around broken base detection code in
3373 // some PHP versions (see <https://bugs.php.net/bug.php?id=50175> and
3374 // <https://bugs.php.net/bug.php?id=55398>).
3375 $result = gmp_strval( gmp_init( ltrim( $input, '0' ) ?: '0', $sourceBase ), $destBase );
3376 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' || $engine == 'bcmath' ) ) {
3377 $decimal = '0';
3378 foreach ( str_split( strtolower( $input ) ) as $char ) {
3379 $decimal = bcmul( $decimal, $sourceBase );
3380 $decimal = bcadd( $decimal, $baseChars[$char] );
3383 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3384 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3385 $result .= $baseChars[bcmod( $decimal, $destBase )];
3387 // @codingStandardsIgnoreEnd
3389 $result = strrev( $result );
3390 } else {
3391 $inDigits = array();
3392 foreach ( str_split( strtolower( $input ) ) as $char ) {
3393 $inDigits[] = $baseChars[$char];
3396 // Iterate over the input, modulo-ing out an output digit
3397 // at a time until input is gone.
3398 $result = '';
3399 while ( $inDigits ) {
3400 $work = 0;
3401 $workDigits = array();
3403 // Long division...
3404 foreach ( $inDigits as $digit ) {
3405 $work *= $sourceBase;
3406 $work += $digit;
3408 if ( $workDigits || $work >= $destBase ) {
3409 $workDigits[] = (int)( $work / $destBase );
3411 $work %= $destBase;
3414 // All that division leaves us with a remainder,
3415 // which is conveniently our next output digit.
3416 $result .= $baseChars[$work];
3418 // And we continue!
3419 $inDigits = $workDigits;
3422 $result = strrev( $result );
3425 if ( !$lowercase ) {
3426 $result = strtoupper( $result );
3429 return str_pad( $result, $pad, '0', STR_PAD_LEFT );
3433 * Check if there is sufficient entropy in php's built-in session generation
3435 * @return bool True = there is sufficient entropy
3437 function wfCheckEntropy() {
3438 return (
3439 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
3440 || ini_get( 'session.entropy_file' )
3442 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3446 * Override session_id before session startup if php's built-in
3447 * session generation code is not secure.
3449 function wfFixSessionID() {
3450 // If the cookie or session id is already set we already have a session and should abort
3451 if ( isset( $_COOKIE[session_name()] ) || session_id() ) {
3452 return;
3455 // PHP's built-in session entropy is enabled if:
3456 // - entropy_file is set or you're on Windows with php 5.3.3+
3457 // - AND entropy_length is > 0
3458 // We treat it as disabled if it doesn't have an entropy length of at least 32
3459 $entropyEnabled = wfCheckEntropy();
3461 // If built-in entropy is not enabled or not sufficient override PHP's
3462 // built in session id generation code
3463 if ( !$entropyEnabled ) {
3464 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, " .
3465 "overriding session id generation using our cryptrand source.\n" );
3466 session_id( MWCryptRand::generateHex( 32 ) );
3471 * Reset the session_id
3473 * @since 1.22
3475 function wfResetSessionID() {
3476 global $wgCookieSecure;
3477 $oldSessionId = session_id();
3478 $cookieParams = session_get_cookie_params();
3479 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3480 session_regenerate_id( false );
3481 } else {
3482 $tmp = $_SESSION;
3483 session_destroy();
3484 wfSetupSession( MWCryptRand::generateHex( 32 ) );
3485 $_SESSION = $tmp;
3487 $newSessionId = session_id();
3491 * Initialise php session
3493 * @param bool $sessionId
3495 function wfSetupSession( $sessionId = false ) {
3496 global $wgSessionsInObjectCache, $wgSessionHandler;
3497 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
3499 if ( $wgSessionsInObjectCache ) {
3500 ObjectCacheSessionHandler::install();
3501 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3502 # Only set this if $wgSessionHandler isn't null and session.save_handler
3503 # hasn't already been set to the desired value (that causes errors)
3504 ini_set( 'session.save_handler', $wgSessionHandler );
3507 session_set_cookie_params(
3508 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3509 session_cache_limiter( 'private, must-revalidate' );
3510 if ( $sessionId ) {
3511 session_id( $sessionId );
3512 } else {
3513 wfFixSessionID();
3516 MediaWiki\suppressWarnings();
3517 session_start();
3518 MediaWiki\restoreWarnings();
3520 if ( $wgSessionsInObjectCache ) {
3521 ObjectCacheSessionHandler::renewCurrentSession();
3526 * Get an object from the precompiled serialized directory
3528 * @param string $name
3529 * @return mixed The variable on success, false on failure
3531 function wfGetPrecompiledData( $name ) {
3532 global $IP;
3534 $file = "$IP/serialized/$name";
3535 if ( file_exists( $file ) ) {
3536 $blob = file_get_contents( $file );
3537 if ( $blob ) {
3538 return unserialize( $blob );
3541 return false;
3545 * Make a cache key for the local wiki.
3547 * @param string $args,...
3548 * @return string
3550 function wfMemcKey( /*...*/ ) {
3551 return call_user_func_array(
3552 array( ObjectCache::getLocalClusterInstance(), 'makeKey' ),
3553 func_get_args()
3558 * Make a cache key for a foreign DB.
3560 * Must match what wfMemcKey() would produce in context of the foreign wiki.
3562 * @param string $db
3563 * @param string $prefix
3564 * @param string $args,...
3565 * @return string
3567 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3568 $args = array_slice( func_get_args(), 2 );
3569 $keyspace = $prefix ? "$db-$prefix" : $db;
3570 return call_user_func_array(
3571 array( ObjectCache::getLocalClusterInstance(), 'makeKeyInternal' ),
3572 array( $keyspace, $args )
3577 * Make a cache key with database-agnostic prefix.
3579 * Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix
3580 * instead. Must have a prefix as otherwise keys that use a database name
3581 * in the first segment will clash with wfMemcKey/wfForeignMemcKey.
3583 * @since 1.26
3584 * @param string $args,...
3585 * @return string
3587 function wfGlobalCacheKey( /*...*/ ) {
3588 return call_user_func_array(
3589 array( ObjectCache::getLocalClusterInstance(), 'makeGlobalKey' ),
3590 func_get_args()
3595 * Get an ASCII string identifying this wiki
3596 * This is used as a prefix in memcached keys
3598 * @return string
3600 function wfWikiID() {
3601 global $wgDBprefix, $wgDBname;
3602 if ( $wgDBprefix ) {
3603 return "$wgDBname-$wgDBprefix";
3604 } else {
3605 return $wgDBname;
3610 * Split a wiki ID into DB name and table prefix
3612 * @param string $wiki
3614 * @return array
3616 function wfSplitWikiID( $wiki ) {
3617 $bits = explode( '-', $wiki, 2 );
3618 if ( count( $bits ) < 2 ) {
3619 $bits[] = '';
3621 return $bits;
3625 * Get a Database object.
3627 * @param int $db Index of the connection to get. May be DB_MASTER for the
3628 * master (for write queries), DB_SLAVE for potentially lagged read
3629 * queries, or an integer >= 0 for a particular server.
3631 * @param string|string[] $groups Query groups. An array of group names that this query
3632 * belongs to. May contain a single string if the query is only
3633 * in one group.
3635 * @param string|bool $wiki The wiki ID, or false for the current wiki
3637 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3638 * will always return the same object, unless the underlying connection or load
3639 * balancer is manually destroyed.
3641 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3642 * updater to ensure that a proper database is being updated.
3644 * @return DatabaseBase
3646 function wfGetDB( $db, $groups = array(), $wiki = false ) {
3647 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3651 * Get a load balancer object.
3653 * @param string|bool $wiki Wiki ID, or false for the current wiki
3654 * @return LoadBalancer
3656 function wfGetLB( $wiki = false ) {
3657 return wfGetLBFactory()->getMainLB( $wiki );
3661 * Get the load balancer factory object
3663 * @return LBFactory
3665 function wfGetLBFactory() {
3666 return LBFactory::singleton();
3670 * Find a file.
3671 * Shortcut for RepoGroup::singleton()->findFile()
3673 * @param string $title String or Title object
3674 * @param array $options Associative array of options (see RepoGroup::findFile)
3675 * @return File|bool File, or false if the file does not exist
3677 function wfFindFile( $title, $options = array() ) {
3678 return RepoGroup::singleton()->findFile( $title, $options );
3682 * Get an object referring to a locally registered file.
3683 * Returns a valid placeholder object if the file does not exist.
3685 * @param Title|string $title
3686 * @return LocalFile|null A File, or null if passed an invalid Title
3688 function wfLocalFile( $title ) {
3689 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3693 * Should low-performance queries be disabled?
3695 * @return bool
3696 * @codeCoverageIgnore
3698 function wfQueriesMustScale() {
3699 global $wgMiserMode;
3700 return $wgMiserMode
3701 || ( SiteStats::pages() > 100000
3702 && SiteStats::edits() > 1000000
3703 && SiteStats::users() > 10000 );
3707 * Get the path to a specified script file, respecting file
3708 * extensions; this is a wrapper around $wgScriptPath etc.
3709 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3711 * @param string $script Script filename, sans extension
3712 * @return string
3714 function wfScript( $script = 'index' ) {
3715 global $wgScriptPath, $wgScript, $wgLoadScript;
3716 if ( $script === 'index' ) {
3717 return $wgScript;
3718 } elseif ( $script === 'load' ) {
3719 return $wgLoadScript;
3720 } else {
3721 return "{$wgScriptPath}/{$script}.php";
3726 * Get the script URL.
3728 * @return string Script URL
3730 function wfGetScriptUrl() {
3731 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3732 /* as it was called, minus the query string.
3734 * Some sites use Apache rewrite rules to handle subdomains,
3735 * and have PHP set up in a weird way that causes PHP_SELF
3736 * to contain the rewritten URL instead of the one that the
3737 * outside world sees.
3739 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
3740 * provides containing the "before" URL.
3742 return $_SERVER['SCRIPT_NAME'];
3743 } else {
3744 return $_SERVER['URL'];
3749 * Convenience function converts boolean values into "true"
3750 * or "false" (string) values
3752 * @param bool $value
3753 * @return string
3755 function wfBoolToStr( $value ) {
3756 return $value ? 'true' : 'false';
3760 * Get a platform-independent path to the null file, e.g. /dev/null
3762 * @return string
3764 function wfGetNull() {
3765 return wfIsWindows() ? 'NUL' : '/dev/null';
3769 * Waits for the slaves to catch up to the master position
3771 * Use this when updating very large numbers of rows, as in maintenance scripts,
3772 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
3774 * By default this waits on the main DB cluster of the current wiki.
3775 * If $cluster is set to "*" it will wait on all DB clusters, including
3776 * external ones. If the lag being waiting on is caused by the code that
3777 * does this check, it makes since to use $ifWritesSince, particularly if
3778 * cluster is "*", to avoid excess overhead.
3780 * Never call this function after a big DB write that is still in a transaction.
3781 * This only makes sense after the possible lag inducing changes were committed.
3783 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3784 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3785 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3786 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3787 * @return bool Success (able to connect and no timeouts reached)
3789 function wfWaitForSlaves(
3790 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3792 // B/C: first argument used to be "max seconds of lag"; ignore such values
3793 $ifWritesSince = ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null;
3795 if ( $timeout === null ) {
3796 $timeout = ( PHP_SAPI === 'cli' ) ? 86400 : 10;
3799 // Figure out which clusters need to be checked
3800 /** @var LoadBalancer[] $lbs */
3801 $lbs = array();
3802 if ( $cluster === '*' ) {
3803 wfGetLBFactory()->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
3804 $lbs[] = $lb;
3805 } );
3806 } elseif ( $cluster !== false ) {
3807 $lbs[] = wfGetLBFactory()->getExternalLB( $cluster );
3808 } else {
3809 $lbs[] = wfGetLB( $wiki );
3812 // Get all the master positions of applicable DBs right now.
3813 // This can be faster since waiting on one cluster reduces the
3814 // time needed to wait on the next clusters.
3815 $masterPositions = array_fill( 0, count( $lbs ), false );
3816 foreach ( $lbs as $i => $lb ) {
3817 if ( $lb->getServerCount() <= 1 ) {
3818 // Bug 27975 - Don't try to wait for slaves if there are none
3819 // Prevents permission error when getting master position
3820 continue;
3821 } elseif ( $ifWritesSince && $lb->lastMasterChangeTimestamp() < $ifWritesSince ) {
3822 continue; // no writes since the last wait
3824 $masterPositions[$i] = $lb->getMasterPos();
3827 $ok = true;
3828 foreach ( $lbs as $i => $lb ) {
3829 if ( $masterPositions[$i] ) {
3830 // The DBMS may not support getMasterPos() or the whole
3831 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3832 $ok = $lb->waitForAll( $masterPositions[$i], $timeout ) && $ok;
3836 return $ok;
3840 * Count down from $seconds to zero on the terminal, with a one-second pause
3841 * between showing each number. For use in command-line scripts.
3843 * @codeCoverageIgnore
3844 * @param int $seconds
3846 function wfCountDown( $seconds ) {
3847 for ( $i = $seconds; $i >= 0; $i-- ) {
3848 if ( $i != $seconds ) {
3849 echo str_repeat( "\x08", strlen( $i + 1 ) );
3851 echo $i;
3852 flush();
3853 if ( $i ) {
3854 sleep( 1 );
3857 echo "\n";
3861 * Replace all invalid characters with -
3862 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3863 * By default, $wgIllegalFileChars = ':'
3865 * @param string $name Filename to process
3866 * @return string
3868 function wfStripIllegalFilenameChars( $name ) {
3869 global $wgIllegalFileChars;
3870 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
3871 $name = wfBaseName( $name );
3872 $name = preg_replace(
3873 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
3874 '-',
3875 $name
3877 return $name;
3881 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit
3883 * @return int Resulting value of the memory limit.
3885 function wfMemoryLimit() {
3886 global $wgMemoryLimit;
3887 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3888 if ( $memlimit != -1 ) {
3889 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3890 if ( $conflimit == -1 ) {
3891 wfDebug( "Removing PHP's memory limit\n" );
3892 MediaWiki\suppressWarnings();
3893 ini_set( 'memory_limit', $conflimit );
3894 MediaWiki\restoreWarnings();
3895 return $conflimit;
3896 } elseif ( $conflimit > $memlimit ) {
3897 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3898 MediaWiki\suppressWarnings();
3899 ini_set( 'memory_limit', $conflimit );
3900 MediaWiki\restoreWarnings();
3901 return $conflimit;
3904 return $memlimit;
3908 * Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit
3910 * @return int Prior time limit
3911 * @since 1.26
3913 function wfTransactionalTimeLimit() {
3914 global $wgTransactionalTimeLimit;
3916 $timeLimit = ini_get( 'max_execution_time' );
3917 // Note that CLI scripts use 0
3918 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
3919 set_time_limit( $wgTransactionalTimeLimit );
3922 ignore_user_abort( true ); // ignore client disconnects
3924 return $timeLimit;
3928 * Converts shorthand byte notation to integer form
3930 * @param string $string
3931 * @param int $default Returned if $string is empty
3932 * @return int
3934 function wfShorthandToInteger( $string = '', $default = -1 ) {
3935 $string = trim( $string );
3936 if ( $string === '' ) {
3937 return $default;
3939 $last = $string[strlen( $string ) - 1];
3940 $val = intval( $string );
3941 switch ( $last ) {
3942 case 'g':
3943 case 'G':
3944 $val *= 1024;
3945 // break intentionally missing
3946 case 'm':
3947 case 'M':
3948 $val *= 1024;
3949 // break intentionally missing
3950 case 'k':
3951 case 'K':
3952 $val *= 1024;
3955 return $val;
3959 * Get the normalised IETF language tag
3960 * See unit test for examples.
3962 * @param string $code The language code.
3963 * @return string The language code which complying with BCP 47 standards.
3965 function wfBCP47( $code ) {
3966 $codeSegment = explode( '-', $code );
3967 $codeBCP = array();
3968 foreach ( $codeSegment as $segNo => $seg ) {
3969 // when previous segment is x, it is a private segment and should be lc
3970 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3971 $codeBCP[$segNo] = strtolower( $seg );
3972 // ISO 3166 country code
3973 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3974 $codeBCP[$segNo] = strtoupper( $seg );
3975 // ISO 15924 script code
3976 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3977 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3978 // Use lowercase for other cases
3979 } else {
3980 $codeBCP[$segNo] = strtolower( $seg );
3983 $langCode = implode( '-', $codeBCP );
3984 return $langCode;
3988 * Get a specific cache object.
3990 * @param int|string $cacheType A CACHE_* constants, or other key in $wgObjectCaches
3991 * @return BagOStuff
3993 function wfGetCache( $cacheType ) {
3994 return ObjectCache::getInstance( $cacheType );
3998 * Get the main cache object
4000 * @return BagOStuff
4002 function wfGetMainCache() {
4003 global $wgMainCacheType;
4004 return ObjectCache::getInstance( $wgMainCacheType );
4008 * Get the cache object used by the message cache
4010 * @return BagOStuff
4012 function wfGetMessageCacheStorage() {
4013 global $wgMessageCacheType;
4014 return ObjectCache::getInstance( $wgMessageCacheType );
4018 * Get the cache object used by the parser cache
4020 * @return BagOStuff
4022 function wfGetParserCacheStorage() {
4023 global $wgParserCacheType;
4024 return ObjectCache::getInstance( $wgParserCacheType );
4028 * Call hook functions defined in $wgHooks
4030 * @param string $event Event name
4031 * @param array $args Parameters passed to hook functions
4032 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
4034 * @return bool True if no handler aborted the hook
4035 * @deprecated 1.25 - use Hooks::run
4037 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
4038 return Hooks::run( $event, $args, $deprecatedVersion );
4042 * Wrapper around php's unpack.
4044 * @param string $format The format string (See php's docs)
4045 * @param string $data A binary string of binary data
4046 * @param int|bool $length The minimum length of $data or false. This is to
4047 * prevent reading beyond the end of $data. false to disable the check.
4049 * Also be careful when using this function to read unsigned 32 bit integer
4050 * because php might make it negative.
4052 * @throws MWException If $data not long enough, or if unpack fails
4053 * @return array Associative array of the extracted data
4055 function wfUnpack( $format, $data, $length = false ) {
4056 if ( $length !== false ) {
4057 $realLen = strlen( $data );
4058 if ( $realLen < $length ) {
4059 throw new MWException( "Tried to use wfUnpack on a "
4060 . "string of length $realLen, but needed one "
4061 . "of at least length $length."
4066 MediaWiki\suppressWarnings();
4067 $result = unpack( $format, $data );
4068 MediaWiki\restoreWarnings();
4070 if ( $result === false ) {
4071 // If it cannot extract the packed data.
4072 throw new MWException( "unpack could not unpack binary data" );
4074 return $result;
4078 * Determine if an image exists on the 'bad image list'.
4080 * The format of MediaWiki:Bad_image_list is as follows:
4081 * * Only list items (lines starting with "*") are considered
4082 * * The first link on a line must be a link to a bad image
4083 * * Any subsequent links on the same line are considered to be exceptions,
4084 * i.e. articles where the image may occur inline.
4086 * @param string $name The image name to check
4087 * @param Title|bool $contextTitle The page on which the image occurs, if known
4088 * @param string $blacklist Wikitext of a file blacklist
4089 * @return bool
4091 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4092 # Handle redirects; callers almost always hit wfFindFile() anyway,
4093 # so just use that method because it has a fast process cache.
4094 $file = wfFindFile( $name ); // get the final name
4095 $name = $file ? $file->getTitle()->getDBkey() : $name;
4097 # Run the extension hook
4098 $bad = false;
4099 if ( !Hooks::run( 'BadImage', array( $name, &$bad ) ) ) {
4100 return $bad;
4103 $cache = ObjectCache::newAccelerator( 'hash' );
4104 $key = wfMemcKey( 'bad-image-list', ( $blacklist === null ) ? 'default' : md5( $blacklist ) );
4105 $badImages = $cache->get( $key );
4107 if ( $badImages === false ) { // cache miss
4108 if ( $blacklist === null ) {
4109 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4111 # Build the list now
4112 $badImages = array();
4113 $lines = explode( "\n", $blacklist );
4114 foreach ( $lines as $line ) {
4115 # List items only
4116 if ( substr( $line, 0, 1 ) !== '*' ) {
4117 continue;
4120 # Find all links
4121 $m = array();
4122 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4123 continue;
4126 $exceptions = array();
4127 $imageDBkey = false;
4128 foreach ( $m[1] as $i => $titleText ) {
4129 $title = Title::newFromText( $titleText );
4130 if ( !is_null( $title ) ) {
4131 if ( $i == 0 ) {
4132 $imageDBkey = $title->getDBkey();
4133 } else {
4134 $exceptions[$title->getPrefixedDBkey()] = true;
4139 if ( $imageDBkey !== false ) {
4140 $badImages[$imageDBkey] = $exceptions;
4143 $cache->set( $key, $badImages, 60 );
4146 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
4147 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4149 return $bad;
4153 * Determine whether the client at a given source IP is likely to be able to
4154 * access the wiki via HTTPS.
4156 * @param string $ip The IPv4/6 address in the normal human-readable form
4157 * @return bool
4159 function wfCanIPUseHTTPS( $ip ) {
4160 $canDo = true;
4161 Hooks::run( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4162 return !!$canDo;
4166 * Determine input string is represents as infinity
4168 * @param string $str The string to determine
4169 * @return bool
4170 * @since 1.25
4172 function wfIsInfinity( $str ) {
4173 $infinityValues = array( 'infinite', 'indefinite', 'infinity', 'never' );
4174 return in_array( $str, $infinityValues );
4178 * Work out the IP address based on various globals
4179 * For trusted proxies, use the XFF client IP (first of the chain)
4181 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4182 * @return string
4184 function wfGetIP() {
4185 wfDeprecated( __METHOD__, '1.19' );
4186 global $wgRequest;
4187 return $wgRequest->getIP();
4191 * Checks if an IP is a trusted proxy provider.
4192 * Useful to tell if X-Forwarded-For data is possibly bogus.
4193 * Squid cache servers for the site are whitelisted.
4194 * @deprecated Since 1.24, use IP::isTrustedProxy()
4196 * @param string $ip
4197 * @return bool
4199 function wfIsTrustedProxy( $ip ) {
4200 wfDeprecated( __METHOD__, '1.24' );
4201 return IP::isTrustedProxy( $ip );
4205 * Checks if an IP matches a proxy we've configured.
4206 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4208 * @param string $ip
4209 * @return bool
4210 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4212 function wfIsConfiguredProxy( $ip ) {
4213 wfDeprecated( __METHOD__, '1.24' );
4214 return IP::isConfiguredProxy( $ip );
4218 * Returns true if these thumbnail parameters match one that MediaWiki
4219 * requests from file description pages and/or parser output.
4221 * $params is considered non-standard if they involve a non-standard
4222 * width or any non-default parameters aside from width and page number.
4223 * The number of possible files with standard parameters is far less than
4224 * that of all combinations; rate-limiting for them can thus be more generious.
4226 * @param File $file
4227 * @param array $params
4228 * @return bool
4229 * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25
4231 function wfThumbIsStandard( File $file, array $params ) {
4232 global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages;
4234 $multipliers = array( 1 );
4235 if ( $wgResponsiveImages ) {
4236 // These available sizes are hardcoded currently elsewhere in MediaWiki.
4237 // @see Linker::processResponsiveImages
4238 $multipliers[] = 1.5;
4239 $multipliers[] = 2;
4242 $handler = $file->getHandler();
4243 if ( !$handler || !isset( $params['width'] ) ) {
4244 return false;
4247 $basicParams = array();
4248 if ( isset( $params['page'] ) ) {
4249 $basicParams['page'] = $params['page'];
4252 $thumbLimits = array();
4253 $imageLimits = array();
4254 // Expand limits to account for multipliers
4255 foreach ( $multipliers as $multiplier ) {
4256 $thumbLimits = array_merge( $thumbLimits, array_map(
4257 function ( $width ) use ( $multiplier ) {
4258 return round( $width * $multiplier );
4259 }, $wgThumbLimits )
4261 $imageLimits = array_merge( $imageLimits, array_map(
4262 function ( $pair ) use ( $multiplier ) {
4263 return array(
4264 round( $pair[0] * $multiplier ),
4265 round( $pair[1] * $multiplier ),
4267 }, $wgImageLimits )
4271 // Check if the width matches one of $wgThumbLimits
4272 if ( in_array( $params['width'], $thumbLimits ) ) {
4273 $normalParams = $basicParams + array( 'width' => $params['width'] );
4274 // Append any default values to the map (e.g. "lossy", "lossless", ...)
4275 $handler->normaliseParams( $file, $normalParams );
4276 } else {
4277 // If not, then check if the width matchs one of $wgImageLimits
4278 $match = false;
4279 foreach ( $imageLimits as $pair ) {
4280 $normalParams = $basicParams + array( 'width' => $pair[0], 'height' => $pair[1] );
4281 // Decide whether the thumbnail should be scaled on width or height.
4282 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
4283 $handler->normaliseParams( $file, $normalParams );
4284 // Check if this standard thumbnail size maps to the given width
4285 if ( $normalParams['width'] == $params['width'] ) {
4286 $match = true;
4287 break;
4290 if ( !$match ) {
4291 return false; // not standard for description pages
4295 // Check that the given values for non-page, non-width, params are just defaults
4296 foreach ( $params as $key => $value ) {
4297 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
4298 return false;
4302 return true;
4306 * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
4308 * Values that exist in both values will be combined with += (all values of the array
4309 * of $newValues will be added to the values of the array of $baseArray, while values,
4310 * that exists in both, the value of $baseArray will be used).
4312 * @param array $baseArray The array where you want to add the values of $newValues to
4313 * @param array $newValues An array with new values
4314 * @return array The combined array
4315 * @since 1.26
4317 function wfArrayPlus2d( array $baseArray, array $newValues ) {
4318 // First merge items that are in both arrays
4319 foreach ( $baseArray as $name => &$groupVal ) {
4320 if ( isset( $newValues[$name] ) ) {
4321 $groupVal += $newValues[$name];
4324 // Now add items that didn't exist yet
4325 $baseArray += $newValues;
4327 return $baseArray;