Remove redundant testGetMulti() assertion
[mediawiki.git] / includes / GlobalFunctions.php
blob43b936b54bf2ea5fe398a0a2d133a4316d6c59db
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 $originalParams = $params;
312 if ( $params[0] instanceof MessageSpecifier ) {
313 $msg = $params[0];
314 $params = array_merge( array( $msg->getKey() ), $msg->getParams() );
316 # @todo FIXME: Sometimes get nested arrays for $params,
317 # which leads to E_NOTICEs
318 $spec = implode( "\t", $params );
319 $out[$spec] = $originalParams;
322 return array_values( $out );
326 * Insert array into another array after the specified *KEY*
328 * @param array $array The array.
329 * @param array $insert The array to insert.
330 * @param mixed $after The key to insert after
331 * @return array
333 function wfArrayInsertAfter( array $array, array $insert, $after ) {
334 // Find the offset of the element to insert after.
335 $keys = array_keys( $array );
336 $offsetByKey = array_flip( $keys );
338 $offset = $offsetByKey[$after];
340 // Insert at the specified offset
341 $before = array_slice( $array, 0, $offset + 1, true );
342 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
344 $output = $before + $insert + $after;
346 return $output;
350 * Recursively converts the parameter (an object) to an array with the same data
352 * @param object|array $objOrArray
353 * @param bool $recursive
354 * @return array
356 function wfObjectToArray( $objOrArray, $recursive = true ) {
357 $array = array();
358 if ( is_object( $objOrArray ) ) {
359 $objOrArray = get_object_vars( $objOrArray );
361 foreach ( $objOrArray as $key => $value ) {
362 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
363 $value = wfObjectToArray( $value );
366 $array[$key] = $value;
369 return $array;
373 * Get a random decimal value between 0 and 1, in a way
374 * not likely to give duplicate values for any realistic
375 * number of articles.
377 * @return string
379 function wfRandom() {
380 # The maximum random value is "only" 2^31-1, so get two random
381 # values to reduce the chance of dupes
382 $max = mt_getrandmax() + 1;
383 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
385 return $rand;
389 * Get a random string containing a number of pseudo-random hex
390 * characters.
391 * @note This is not secure, if you are trying to generate some sort
392 * of token please use MWCryptRand instead.
394 * @param int $length The length of the string to generate
395 * @return string
396 * @since 1.20
398 function wfRandomString( $length = 32 ) {
399 $str = '';
400 for ( $n = 0; $n < $length; $n += 7 ) {
401 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
403 return substr( $str, 0, $length );
407 * We want some things to be included as literal characters in our title URLs
408 * for prettiness, which urlencode encodes by default. According to RFC 1738,
409 * all of the following should be safe:
411 * ;:@&=$-_.+!*'(),
413 * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved
414 * character which should not be encoded. More importantly, google chrome
415 * always converts %7E back to ~, and converting it in this function can
416 * cause a redirect loop (T105265).
418 * But + is not safe because it's used to indicate a space; &= are only safe in
419 * paths and not in queries (and we don't distinguish here); ' seems kind of
420 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
421 * is reserved, we don't care. So the list we unescape is:
423 * ;:@$!*(),/~
425 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
426 * so no fancy : for IIS7.
428 * %2F in the page titles seems to fatally break for some reason.
430 * @param string $s
431 * @return string
433 function wfUrlencode( $s ) {
434 static $needle;
436 if ( is_null( $s ) ) {
437 $needle = null;
438 return '';
441 if ( is_null( $needle ) ) {
442 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' );
443 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
444 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
446 $needle[] = '%3A';
450 $s = urlencode( $s );
451 $s = str_ireplace(
452 $needle,
453 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ),
457 return $s;
461 * This function takes two arrays as input, and returns a CGI-style string, e.g.
462 * "days=7&limit=100". Options in the first array override options in the second.
463 * Options set to null or false will not be output.
465 * @param array $array1 ( String|Array )
466 * @param array $array2 ( String|Array )
467 * @param string $prefix
468 * @return string
470 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
471 if ( !is_null( $array2 ) ) {
472 $array1 = $array1 + $array2;
475 $cgi = '';
476 foreach ( $array1 as $key => $value ) {
477 if ( !is_null( $value ) && $value !== false ) {
478 if ( $cgi != '' ) {
479 $cgi .= '&';
481 if ( $prefix !== '' ) {
482 $key = $prefix . "[$key]";
484 if ( is_array( $value ) ) {
485 $firstTime = true;
486 foreach ( $value as $k => $v ) {
487 $cgi .= $firstTime ? '' : '&';
488 if ( is_array( $v ) ) {
489 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
490 } else {
491 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
493 $firstTime = false;
495 } else {
496 if ( is_object( $value ) ) {
497 $value = $value->__toString();
499 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
503 return $cgi;
507 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
508 * its argument and returns the same string in array form. This allows compatibility
509 * with legacy functions that accept raw query strings instead of nice
510 * arrays. Of course, keys and values are urldecode()d.
512 * @param string $query Query string
513 * @return string[] Array version of input
515 function wfCgiToArray( $query ) {
516 if ( isset( $query[0] ) && $query[0] == '?' ) {
517 $query = substr( $query, 1 );
519 $bits = explode( '&', $query );
520 $ret = array();
521 foreach ( $bits as $bit ) {
522 if ( $bit === '' ) {
523 continue;
525 if ( strpos( $bit, '=' ) === false ) {
526 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
527 $key = $bit;
528 $value = '';
529 } else {
530 list( $key, $value ) = explode( '=', $bit );
532 $key = urldecode( $key );
533 $value = urldecode( $value );
534 if ( strpos( $key, '[' ) !== false ) {
535 $keys = array_reverse( explode( '[', $key ) );
536 $key = array_pop( $keys );
537 $temp = $value;
538 foreach ( $keys as $k ) {
539 $k = substr( $k, 0, -1 );
540 $temp = array( $k => $temp );
542 if ( isset( $ret[$key] ) ) {
543 $ret[$key] = array_merge( $ret[$key], $temp );
544 } else {
545 $ret[$key] = $temp;
547 } else {
548 $ret[$key] = $value;
551 return $ret;
555 * Append a query string to an existing URL, which may or may not already
556 * have query string parameters already. If so, they will be combined.
558 * @param string $url
559 * @param string|string[] $query String or associative array
560 * @return string
562 function wfAppendQuery( $url, $query ) {
563 if ( is_array( $query ) ) {
564 $query = wfArrayToCgi( $query );
566 if ( $query != '' ) {
567 if ( false === strpos( $url, '?' ) ) {
568 $url .= '?';
569 } else {
570 $url .= '&';
572 $url .= $query;
574 return $url;
578 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
579 * is correct.
581 * The meaning of the PROTO_* constants is as follows:
582 * PROTO_HTTP: Output a URL starting with http://
583 * PROTO_HTTPS: Output a URL starting with https://
584 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
585 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
586 * on which protocol was used for the current incoming request
587 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
588 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
589 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
591 * @todo this won't work with current-path-relative URLs
592 * like "subdir/foo.html", etc.
594 * @param string $url Either fully-qualified or a local path + query
595 * @param string $defaultProto One of the PROTO_* constants. Determines the
596 * protocol to use if $url or $wgServer is protocol-relative
597 * @return string Fully-qualified URL, current-path-relative URL or false if
598 * no valid URL can be constructed
600 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
601 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
602 $wgHttpsPort;
603 if ( $defaultProto === PROTO_CANONICAL ) {
604 $serverUrl = $wgCanonicalServer;
605 } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
606 // Make $wgInternalServer fall back to $wgServer if not set
607 $serverUrl = $wgInternalServer;
608 } else {
609 $serverUrl = $wgServer;
610 if ( $defaultProto === PROTO_CURRENT ) {
611 $defaultProto = $wgRequest->getProtocol() . '://';
615 // Analyze $serverUrl to obtain its protocol
616 $bits = wfParseUrl( $serverUrl );
617 $serverHasProto = $bits && $bits['scheme'] != '';
619 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
620 if ( $serverHasProto ) {
621 $defaultProto = $bits['scheme'] . '://';
622 } else {
623 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
624 // This really isn't supposed to happen. Fall back to HTTP in this
625 // ridiculous case.
626 $defaultProto = PROTO_HTTP;
630 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
632 if ( substr( $url, 0, 2 ) == '//' ) {
633 $url = $defaultProtoWithoutSlashes . $url;
634 } elseif ( substr( $url, 0, 1 ) == '/' ) {
635 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
636 // otherwise leave it alone.
637 $url = ( $serverHasProto ? '' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
640 $bits = wfParseUrl( $url );
642 // ensure proper port for HTTPS arrives in URL
643 // https://phabricator.wikimedia.org/T67184
644 if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
645 $bits['port'] = $wgHttpsPort;
648 if ( $bits && isset( $bits['path'] ) ) {
649 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
650 return wfAssembleUrl( $bits );
651 } elseif ( $bits ) {
652 # No path to expand
653 return $url;
654 } elseif ( substr( $url, 0, 1 ) != '/' ) {
655 # URL is a relative path
656 return wfRemoveDotSegments( $url );
659 # Expanded URL is not valid.
660 return false;
664 * This function will reassemble a URL parsed with wfParseURL. This is useful
665 * if you need to edit part of a URL and put it back together.
667 * This is the basic structure used (brackets contain keys for $urlParts):
668 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
670 * @todo Need to integrate this into wfExpandUrl (bug 32168)
672 * @since 1.19
673 * @param array $urlParts URL parts, as output from wfParseUrl
674 * @return string URL assembled from its component parts
676 function wfAssembleUrl( $urlParts ) {
677 $result = '';
679 if ( isset( $urlParts['delimiter'] ) ) {
680 if ( isset( $urlParts['scheme'] ) ) {
681 $result .= $urlParts['scheme'];
684 $result .= $urlParts['delimiter'];
687 if ( isset( $urlParts['host'] ) ) {
688 if ( isset( $urlParts['user'] ) ) {
689 $result .= $urlParts['user'];
690 if ( isset( $urlParts['pass'] ) ) {
691 $result .= ':' . $urlParts['pass'];
693 $result .= '@';
696 $result .= $urlParts['host'];
698 if ( isset( $urlParts['port'] ) ) {
699 $result .= ':' . $urlParts['port'];
703 if ( isset( $urlParts['path'] ) ) {
704 $result .= $urlParts['path'];
707 if ( isset( $urlParts['query'] ) ) {
708 $result .= '?' . $urlParts['query'];
711 if ( isset( $urlParts['fragment'] ) ) {
712 $result .= '#' . $urlParts['fragment'];
715 return $result;
719 * Remove all dot-segments in the provided URL path. For example,
720 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
721 * RFC3986 section 5.2.4.
723 * @todo Need to integrate this into wfExpandUrl (bug 32168)
725 * @param string $urlPath URL path, potentially containing dot-segments
726 * @return string URL path with all dot-segments removed
728 function wfRemoveDotSegments( $urlPath ) {
729 $output = '';
730 $inputOffset = 0;
731 $inputLength = strlen( $urlPath );
733 while ( $inputOffset < $inputLength ) {
734 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
735 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
736 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
737 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
738 $trimOutput = false;
740 if ( $prefixLengthTwo == './' ) {
741 # Step A, remove leading "./"
742 $inputOffset += 2;
743 } elseif ( $prefixLengthThree == '../' ) {
744 # Step A, remove leading "../"
745 $inputOffset += 3;
746 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
747 # Step B, replace leading "/.$" with "/"
748 $inputOffset += 1;
749 $urlPath[$inputOffset] = '/';
750 } elseif ( $prefixLengthThree == '/./' ) {
751 # Step B, replace leading "/./" with "/"
752 $inputOffset += 2;
753 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
754 # Step C, replace leading "/..$" with "/" and
755 # remove last path component in output
756 $inputOffset += 2;
757 $urlPath[$inputOffset] = '/';
758 $trimOutput = true;
759 } elseif ( $prefixLengthFour == '/../' ) {
760 # Step C, replace leading "/../" with "/" and
761 # remove last path component in output
762 $inputOffset += 3;
763 $trimOutput = true;
764 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
765 # Step D, remove "^.$"
766 $inputOffset += 1;
767 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
768 # Step D, remove "^..$"
769 $inputOffset += 2;
770 } else {
771 # Step E, move leading path segment to output
772 if ( $prefixLengthOne == '/' ) {
773 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
774 } else {
775 $slashPos = strpos( $urlPath, '/', $inputOffset );
777 if ( $slashPos === false ) {
778 $output .= substr( $urlPath, $inputOffset );
779 $inputOffset = $inputLength;
780 } else {
781 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
782 $inputOffset += $slashPos - $inputOffset;
786 if ( $trimOutput ) {
787 $slashPos = strrpos( $output, '/' );
788 if ( $slashPos === false ) {
789 $output = '';
790 } else {
791 $output = substr( $output, 0, $slashPos );
796 return $output;
800 * Returns a regular expression of url protocols
802 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
803 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
804 * @return string
806 function wfUrlProtocols( $includeProtocolRelative = true ) {
807 global $wgUrlProtocols;
809 // Cache return values separately based on $includeProtocolRelative
810 static $withProtRel = null, $withoutProtRel = null;
811 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
812 if ( !is_null( $cachedValue ) ) {
813 return $cachedValue;
816 // Support old-style $wgUrlProtocols strings, for backwards compatibility
817 // with LocalSettings files from 1.5
818 if ( is_array( $wgUrlProtocols ) ) {
819 $protocols = array();
820 foreach ( $wgUrlProtocols as $protocol ) {
821 // Filter out '//' if !$includeProtocolRelative
822 if ( $includeProtocolRelative || $protocol !== '//' ) {
823 $protocols[] = preg_quote( $protocol, '/' );
827 $retval = implode( '|', $protocols );
828 } else {
829 // Ignore $includeProtocolRelative in this case
830 // This case exists for pre-1.6 compatibility, and we can safely assume
831 // that '//' won't appear in a pre-1.6 config because protocol-relative
832 // URLs weren't supported until 1.18
833 $retval = $wgUrlProtocols;
836 // Cache return value
837 if ( $includeProtocolRelative ) {
838 $withProtRel = $retval;
839 } else {
840 $withoutProtRel = $retval;
842 return $retval;
846 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
847 * you need a regex that matches all URL protocols but does not match protocol-
848 * relative URLs
849 * @return string
851 function wfUrlProtocolsWithoutProtRel() {
852 return wfUrlProtocols( false );
856 * parse_url() work-alike, but non-broken. Differences:
858 * 1) Does not raise warnings on bad URLs (just returns false).
859 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
860 * protocol-relative URLs) correctly.
861 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
863 * @param string $url A URL to parse
864 * @return string[] Bits of the URL in an associative array, per PHP docs
866 function wfParseUrl( $url ) {
867 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
869 // Protocol-relative URLs are handled really badly by parse_url(). It's so
870 // bad that the easiest way to handle them is to just prepend 'http:' and
871 // strip the protocol out later.
872 $wasRelative = substr( $url, 0, 2 ) == '//';
873 if ( $wasRelative ) {
874 $url = "http:$url";
876 MediaWiki\suppressWarnings();
877 $bits = parse_url( $url );
878 MediaWiki\restoreWarnings();
879 // parse_url() returns an array without scheme for some invalid URLs, e.g.
880 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
881 if ( !$bits || !isset( $bits['scheme'] ) ) {
882 return false;
885 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
886 $bits['scheme'] = strtolower( $bits['scheme'] );
888 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
889 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
890 $bits['delimiter'] = '://';
891 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
892 $bits['delimiter'] = ':';
893 // parse_url detects for news: and mailto: the host part of an url as path
894 // We have to correct this wrong detection
895 if ( isset( $bits['path'] ) ) {
896 $bits['host'] = $bits['path'];
897 $bits['path'] = '';
899 } else {
900 return false;
903 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
904 if ( !isset( $bits['host'] ) ) {
905 $bits['host'] = '';
907 // bug 45069
908 if ( isset( $bits['path'] ) ) {
909 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
910 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
911 $bits['path'] = '/' . $bits['path'];
913 } else {
914 $bits['path'] = '';
918 // If the URL was protocol-relative, fix scheme and delimiter
919 if ( $wasRelative ) {
920 $bits['scheme'] = '';
921 $bits['delimiter'] = '//';
923 return $bits;
927 * Take a URL, make sure it's expanded to fully qualified, and replace any
928 * encoded non-ASCII Unicode characters with their UTF-8 original forms
929 * for more compact display and legibility for local audiences.
931 * @todo handle punycode domains too
933 * @param string $url
934 * @return string
936 function wfExpandIRI( $url ) {
937 return preg_replace_callback(
938 '/((?:%[89A-F][0-9A-F])+)/i',
939 'wfExpandIRI_callback',
940 wfExpandUrl( $url )
945 * Private callback for wfExpandIRI
946 * @param array $matches
947 * @return string
949 function wfExpandIRI_callback( $matches ) {
950 return urldecode( $matches[1] );
954 * Make URL indexes, appropriate for the el_index field of externallinks.
956 * @param string $url
957 * @return array
959 function wfMakeUrlIndexes( $url ) {
960 $bits = wfParseUrl( $url );
962 // Reverse the labels in the hostname, convert to lower case
963 // For emails reverse domainpart only
964 if ( $bits['scheme'] == 'mailto' ) {
965 $mailparts = explode( '@', $bits['host'], 2 );
966 if ( count( $mailparts ) === 2 ) {
967 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
968 } else {
969 // No domain specified, don't mangle it
970 $domainpart = '';
972 $reversedHost = $domainpart . '@' . $mailparts[0];
973 } else {
974 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
976 // Add an extra dot to the end
977 // Why? Is it in wrong place in mailto links?
978 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
979 $reversedHost .= '.';
981 // Reconstruct the pseudo-URL
982 $prot = $bits['scheme'];
983 $index = $prot . $bits['delimiter'] . $reversedHost;
984 // Leave out user and password. Add the port, path, query and fragment
985 if ( isset( $bits['port'] ) ) {
986 $index .= ':' . $bits['port'];
988 if ( isset( $bits['path'] ) ) {
989 $index .= $bits['path'];
990 } else {
991 $index .= '/';
993 if ( isset( $bits['query'] ) ) {
994 $index .= '?' . $bits['query'];
996 if ( isset( $bits['fragment'] ) ) {
997 $index .= '#' . $bits['fragment'];
1000 if ( $prot == '' ) {
1001 return array( "http:$index", "https:$index" );
1002 } else {
1003 return array( $index );
1008 * Check whether a given URL has a domain that occurs in a given set of domains
1009 * @param string $url URL
1010 * @param array $domains Array of domains (strings)
1011 * @return bool True if the host part of $url ends in one of the strings in $domains
1013 function wfMatchesDomainList( $url, $domains ) {
1014 $bits = wfParseUrl( $url );
1015 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1016 $host = '.' . $bits['host'];
1017 foreach ( (array)$domains as $domain ) {
1018 $domain = '.' . $domain;
1019 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
1020 return true;
1024 return false;
1028 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
1029 * In normal operation this is a NOP.
1031 * Controlling globals:
1032 * $wgDebugLogFile - points to the log file
1033 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
1034 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
1036 * @since 1.25 support for additional context data
1038 * @param string $text
1039 * @param string|bool $dest Unused
1040 * @param array $context Additional logging context data
1042 function wfDebug( $text, $dest = 'all', array $context = array() ) {
1043 global $wgDebugRawPage, $wgDebugLogPrefix;
1044 global $wgDebugTimestamps, $wgRequestTime;
1046 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1047 return;
1050 $text = trim( $text );
1052 // Inline logic from deprecated wfDebugTimer()
1053 if ( $wgDebugTimestamps ) {
1054 $context['seconds_elapsed'] = sprintf(
1055 '%6.4f',
1056 microtime( true ) - $wgRequestTime
1058 $context['memory_used'] = sprintf(
1059 '%5.1fM',
1060 ( memory_get_usage( true ) / ( 1024 * 1024 ) )
1064 if ( $wgDebugLogPrefix !== '' ) {
1065 $context['prefix'] = $wgDebugLogPrefix;
1068 $logger = LoggerFactory::getInstance( 'wfDebug' );
1069 $logger->debug( $text, $context );
1073 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1074 * @return bool
1076 function wfIsDebugRawPage() {
1077 static $cache;
1078 if ( $cache !== null ) {
1079 return $cache;
1081 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1082 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1083 || (
1084 isset( $_SERVER['SCRIPT_NAME'] )
1085 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1088 $cache = true;
1089 } else {
1090 $cache = false;
1092 return $cache;
1096 * Get microsecond timestamps for debug logs
1098 * @deprecated since 1.25
1099 * @return string
1101 function wfDebugTimer() {
1102 global $wgDebugTimestamps, $wgRequestTime;
1104 wfDeprecated( __METHOD__, '1.25' );
1106 if ( !$wgDebugTimestamps ) {
1107 return '';
1110 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1111 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1112 return "$prefix $mem ";
1116 * Send a line giving PHP memory usage.
1118 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1120 function wfDebugMem( $exact = false ) {
1121 $mem = memory_get_usage();
1122 if ( !$exact ) {
1123 $mem = floor( $mem / 1024 ) . ' KiB';
1124 } else {
1125 $mem .= ' B';
1127 wfDebug( "Memory usage: $mem\n" );
1131 * Send a line to a supplementary debug log file, if configured, or main debug
1132 * log if not.
1134 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
1135 * a string filename or an associative array mapping 'destination' to the
1136 * desired filename. The associative array may also contain a 'sample' key
1137 * with an integer value, specifying a sampling factor. Sampled log events
1138 * will be emitted with a 1 in N random chance.
1140 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1141 * @since 1.25 support for additional context data
1142 * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
1144 * @param string $logGroup
1145 * @param string $text
1146 * @param string|bool $dest Destination of the message:
1147 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1148 * - 'log': only to the log and not in HTML
1149 * - 'private': only to the specific log if set in $wgDebugLogGroups and
1150 * discarded otherwise
1151 * For backward compatibility, it can also take a boolean:
1152 * - true: same as 'all'
1153 * - false: same as 'private'
1154 * @param array $context Additional logging context data
1156 function wfDebugLog(
1157 $logGroup, $text, $dest = 'all', array $context = array()
1159 // Turn $dest into a string if it's a boolean (for b/c)
1160 if ( $dest === true ) {
1161 $dest = 'all';
1162 } elseif ( $dest === false ) {
1163 $dest = 'private';
1166 $text = trim( $text );
1168 $logger = LoggerFactory::getInstance( $logGroup );
1169 $context['private'] = ( $dest === 'private' );
1170 $logger->info( $text, $context );
1174 * Log for database errors
1176 * @since 1.25 support for additional context data
1178 * @param string $text Database error message.
1179 * @param array $context Additional logging context data
1181 function wfLogDBError( $text, array $context = array() ) {
1182 $logger = LoggerFactory::getInstance( 'wfLogDBError' );
1183 $logger->error( trim( $text ), $context );
1187 * Throws a warning that $function is deprecated
1189 * @param string $function
1190 * @param string|bool $version Version of MediaWiki that the function
1191 * was deprecated in (Added in 1.19).
1192 * @param string|bool $component Added in 1.19.
1193 * @param int $callerOffset How far up the call stack is the original
1194 * caller. 2 = function that called the function that called
1195 * wfDeprecated (Added in 1.20)
1197 * @return null
1199 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1200 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1204 * Send a warning either to the debug log or in a PHP error depending on
1205 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1207 * @param string $msg Message to send
1208 * @param int $callerOffset Number of items to go back in the backtrace to
1209 * find the correct caller (1 = function calling wfWarn, ...)
1210 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1211 * only used when $wgDevelopmentWarnings is true
1213 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1214 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1218 * Send a warning as a PHP error and the debug log. This is intended for logging
1219 * warnings in production. For logging development warnings, use WfWarn instead.
1221 * @param string $msg Message to send
1222 * @param int $callerOffset Number of items to go back in the backtrace to
1223 * find the correct caller (1 = function calling wfLogWarning, ...)
1224 * @param int $level PHP error level; defaults to E_USER_WARNING
1226 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1227 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1231 * Log to a file without getting "file size exceeded" signals.
1233 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1234 * send lines to the specified port, prefixed by the specified prefix and a space.
1235 * @since 1.25 support for additional context data
1237 * @param string $text
1238 * @param string $file Filename
1239 * @param array $context Additional logging context data
1240 * @throws MWException
1241 * @deprecated since 1.25 Use \MediaWiki\Logger\LegacyLogger::emit or UDPTransport
1243 function wfErrorLog( $text, $file, array $context = array() ) {
1244 wfDeprecated( __METHOD__, '1.25' );
1245 $logger = LoggerFactory::getInstance( 'wfErrorLog' );
1246 $context['destination'] = $file;
1247 $logger->info( trim( $text ), $context );
1251 * @todo document
1253 function wfLogProfilingData() {
1254 global $wgDebugLogGroups, $wgDebugRawPage;
1256 $context = RequestContext::getMain();
1257 $request = $context->getRequest();
1259 $profiler = Profiler::instance();
1260 $profiler->setContext( $context );
1261 $profiler->logData();
1263 $config = $context->getConfig();
1264 if ( $config->get( 'StatsdServer' ) ) {
1265 try {
1266 $statsdServer = explode( ':', $config->get( 'StatsdServer' ) );
1267 $statsdHost = $statsdServer[0];
1268 $statsdPort = isset( $statsdServer[1] ) ? $statsdServer[1] : 8125;
1269 $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1270 $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
1271 $statsdClient->send( $context->getStats()->getBuffer() );
1272 } catch ( Exception $ex ) {
1273 MWExceptionHandler::logException( $ex );
1277 # Profiling must actually be enabled...
1278 if ( $profiler instanceof ProfilerStub ) {
1279 return;
1282 if ( isset( $wgDebugLogGroups['profileoutput'] )
1283 && $wgDebugLogGroups['profileoutput'] === false
1285 // Explicitly disabled
1286 return;
1288 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1289 return;
1292 $ctx = array( 'elapsed' => $request->getElapsedTime() );
1293 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1294 $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
1296 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1297 $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP'];
1299 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1300 $ctx['from'] = $_SERVER['HTTP_FROM'];
1302 if ( isset( $ctx['forwarded_for'] ) ||
1303 isset( $ctx['client_ip'] ) ||
1304 isset( $ctx['from'] ) ) {
1305 $ctx['proxy'] = $_SERVER['REMOTE_ADDR'];
1308 // Don't load $wgUser at this late stage just for statistics purposes
1309 // @todo FIXME: We can detect some anons even if it is not loaded.
1310 // See User::getId()
1311 $user = $context->getUser();
1312 $ctx['anon'] = $user->isItemLoaded( 'id' ) && $user->isAnon();
1314 // Command line script uses a FauxRequest object which does not have
1315 // any knowledge about an URL and throw an exception instead.
1316 try {
1317 $ctx['url'] = urldecode( $request->getRequestURL() );
1318 } catch ( Exception $ignored ) {
1319 // no-op
1322 $ctx['output'] = $profiler->getOutput();
1324 $log = LoggerFactory::getInstance( 'profileoutput' );
1325 $log->info( "Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx );
1329 * Increment a statistics counter
1331 * @param string $key
1332 * @param int $count
1333 * @return void
1335 function wfIncrStats( $key, $count = 1 ) {
1336 $stats = RequestContext::getMain()->getStats();
1337 $stats->updateCount( $key, $count );
1341 * Check whether the wiki is in read-only mode.
1343 * @return bool
1345 function wfReadOnly() {
1346 return wfReadOnlyReason() !== false;
1350 * Check if the site is in read-only mode and return the message if so
1352 * This checks wfConfiguredReadOnlyReason() and the main load balancer
1353 * for slave lag. This may result in DB_SLAVE connection being made.
1355 * @return string|bool String when in read-only mode; false otherwise
1357 function wfReadOnlyReason() {
1358 $readOnly = wfConfiguredReadOnlyReason();
1359 if ( $readOnly !== false ) {
1360 return $readOnly;
1363 static $lbReadOnly = null;
1364 if ( $lbReadOnly === null ) {
1365 // Callers use this method to be aware that data presented to a user
1366 // may be very stale and thus allowing submissions can be problematic.
1367 $lbReadOnly = wfGetLB()->getReadOnlyReason();
1370 return $lbReadOnly;
1374 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1376 * @return string|bool String when in read-only mode; false otherwise
1377 * @since 1.27
1379 function wfConfiguredReadOnlyReason() {
1380 global $wgReadOnly, $wgReadOnlyFile;
1382 if ( $wgReadOnly === null ) {
1383 // Set $wgReadOnly for faster access next time
1384 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1385 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1386 } else {
1387 $wgReadOnly = false;
1391 return $wgReadOnly;
1395 * Return a Language object from $langcode
1397 * @param Language|string|bool $langcode Either:
1398 * - a Language object
1399 * - code of the language to get the message for, if it is
1400 * a valid code create a language for that language, if
1401 * it is a string but not a valid code then make a basic
1402 * language object
1403 * - a boolean: if it's false then use the global object for
1404 * the current user's language (as a fallback for the old parameter
1405 * functionality), or if it is true then use global object
1406 * for the wiki's content language.
1407 * @return Language
1409 function wfGetLangObj( $langcode = false ) {
1410 # Identify which language to get or create a language object for.
1411 # Using is_object here due to Stub objects.
1412 if ( is_object( $langcode ) ) {
1413 # Great, we already have the object (hopefully)!
1414 return $langcode;
1417 global $wgContLang, $wgLanguageCode;
1418 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1419 # $langcode is the language code of the wikis content language object.
1420 # or it is a boolean and value is true
1421 return $wgContLang;
1424 global $wgLang;
1425 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1426 # $langcode is the language code of user language object.
1427 # or it was a boolean and value is false
1428 return $wgLang;
1431 $validCodes = array_keys( Language::fetchLanguageNames() );
1432 if ( in_array( $langcode, $validCodes ) ) {
1433 # $langcode corresponds to a valid language.
1434 return Language::factory( $langcode );
1437 # $langcode is a string, but not a valid language code; use content language.
1438 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1439 return $wgContLang;
1443 * This is the function for getting translated interface messages.
1445 * @see Message class for documentation how to use them.
1446 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1448 * This function replaces all old wfMsg* functions.
1450 * @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier
1451 * @param mixed $params,... Normal message parameters
1452 * @return Message
1454 * @since 1.17
1456 * @see Message::__construct
1458 function wfMessage( $key /*...*/ ) {
1459 $params = func_get_args();
1460 array_shift( $params );
1461 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1462 $params = $params[0];
1464 return new Message( $key, $params );
1468 * This function accepts multiple message keys and returns a message instance
1469 * for the first message which is non-empty. If all messages are empty then an
1470 * instance of the first message key is returned.
1472 * @param string|string[] $keys,... Message keys
1473 * @return Message
1475 * @since 1.18
1477 * @see Message::newFallbackSequence
1479 function wfMessageFallback( /*...*/ ) {
1480 $args = func_get_args();
1481 return call_user_func_array( 'Message::newFallbackSequence', $args );
1485 * Get a message from anywhere, for the current user language.
1487 * Use wfMsgForContent() instead if the message should NOT
1488 * change depending on the user preferences.
1490 * @deprecated since 1.18
1492 * @param string $key Lookup key for the message, usually
1493 * defined in languages/Language.php
1495 * Parameters to the message, which can be used to insert variable text into
1496 * it, can be passed to this function in the following formats:
1497 * - One per argument, starting at the second parameter
1498 * - As an array in the second parameter
1499 * These are not shown in the function definition.
1501 * @return string
1503 function wfMsg( $key ) {
1504 wfDeprecated( __METHOD__, '1.21' );
1506 $args = func_get_args();
1507 array_shift( $args );
1508 return wfMsgReal( $key, $args );
1512 * Same as above except doesn't transform the message
1514 * @deprecated since 1.18
1516 * @param string $key
1517 * @return string
1519 function wfMsgNoTrans( $key ) {
1520 wfDeprecated( __METHOD__, '1.21' );
1522 $args = func_get_args();
1523 array_shift( $args );
1524 return wfMsgReal( $key, $args, true, false, false );
1528 * Get a message from anywhere, for the current global language
1529 * set with $wgLanguageCode.
1531 * Use this if the message should NOT change dependent on the
1532 * language set in the user's preferences. This is the case for
1533 * most text written into logs, as well as link targets (such as
1534 * the name of the copyright policy page). Link titles, on the
1535 * other hand, should be shown in the UI language.
1537 * Note that MediaWiki allows users to change the user interface
1538 * language in their preferences, but a single installation
1539 * typically only contains content in one language.
1541 * Be wary of this distinction: If you use wfMsg() where you should
1542 * use wfMsgForContent(), a user of the software may have to
1543 * customize potentially hundreds of messages in
1544 * order to, e.g., fix a link in every possible language.
1546 * @deprecated since 1.18
1548 * @param string $key Lookup key for the message, usually
1549 * defined in languages/Language.php
1550 * @return string
1552 function wfMsgForContent( $key ) {
1553 wfDeprecated( __METHOD__, '1.21' );
1555 global $wgForceUIMsgAsContentMsg;
1556 $args = func_get_args();
1557 array_shift( $args );
1558 $forcontent = true;
1559 if ( is_array( $wgForceUIMsgAsContentMsg )
1560 && in_array( $key, $wgForceUIMsgAsContentMsg )
1562 $forcontent = false;
1564 return wfMsgReal( $key, $args, true, $forcontent );
1568 * Same as above except doesn't transform the message
1570 * @deprecated since 1.18
1572 * @param string $key
1573 * @return string
1575 function wfMsgForContentNoTrans( $key ) {
1576 wfDeprecated( __METHOD__, '1.21' );
1578 global $wgForceUIMsgAsContentMsg;
1579 $args = func_get_args();
1580 array_shift( $args );
1581 $forcontent = true;
1582 if ( is_array( $wgForceUIMsgAsContentMsg )
1583 && in_array( $key, $wgForceUIMsgAsContentMsg )
1585 $forcontent = false;
1587 return wfMsgReal( $key, $args, true, $forcontent, false );
1591 * Really get a message
1593 * @deprecated since 1.18
1595 * @param string $key Key to get.
1596 * @param array $args
1597 * @param bool $useDB
1598 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1599 * @param bool $transform Whether or not to transform the message.
1600 * @return string The requested message.
1602 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1603 wfDeprecated( __METHOD__, '1.21' );
1605 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1606 $message = wfMsgReplaceArgs( $message, $args );
1607 return $message;
1611 * Fetch a message string value, but don't replace any keys yet.
1613 * @deprecated since 1.18
1615 * @param string $key
1616 * @param bool $useDB
1617 * @param string|bool $langCode Code of the language to get the message for, or
1618 * behaves as a content language switch if it is a boolean.
1619 * @param bool $transform Whether to parse magic words, etc.
1620 * @return string
1622 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1623 wfDeprecated( __METHOD__, '1.21' );
1625 Hooks::run( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1627 $cache = MessageCache::singleton();
1628 $message = $cache->get( $key, $useDB, $langCode );
1629 if ( $message === false ) {
1630 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
1631 } elseif ( $transform ) {
1632 $message = $cache->transform( $message );
1634 return $message;
1638 * Replace message parameter keys on the given formatted output.
1640 * @param string $message
1641 * @param array $args
1642 * @return string
1643 * @private
1645 function wfMsgReplaceArgs( $message, $args ) {
1646 # Fix windows line-endings
1647 # Some messages are split with explode("\n", $msg)
1648 $message = str_replace( "\r", '', $message );
1650 // Replace arguments
1651 if ( count( $args ) ) {
1652 if ( is_array( $args[0] ) ) {
1653 $args = array_values( $args[0] );
1655 $replacementKeys = array();
1656 foreach ( $args as $n => $param ) {
1657 $replacementKeys['$' . ( $n + 1 )] = $param;
1659 $message = strtr( $message, $replacementKeys );
1662 return $message;
1666 * Return an HTML-escaped version of a message.
1667 * Parameter replacements, if any, are done *after* the HTML-escaping,
1668 * so parameters may contain HTML (eg links or form controls). Be sure
1669 * to pre-escape them if you really do want plaintext, or just wrap
1670 * the whole thing in htmlspecialchars().
1672 * @deprecated since 1.18
1674 * @param string $key
1675 * @param string $args,... Parameters
1676 * @return string
1678 function wfMsgHtml( $key ) {
1679 wfDeprecated( __METHOD__, '1.21' );
1681 $args = func_get_args();
1682 array_shift( $args );
1683 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1687 * Return an HTML version of message
1688 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1689 * so parameters may contain HTML (eg links or form controls). Be sure
1690 * to pre-escape them if you really do want plaintext, or just wrap
1691 * the whole thing in htmlspecialchars().
1693 * @deprecated since 1.18
1695 * @param string $key
1696 * @param string $args,... Parameters
1697 * @return string
1699 function wfMsgWikiHtml( $key ) {
1700 wfDeprecated( __METHOD__, '1.21' );
1702 $args = func_get_args();
1703 array_shift( $args );
1704 return wfMsgReplaceArgs(
1705 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
1706 /* can't be set to false */ true, /* interface */ true )->getText(),
1707 $args );
1711 * Returns message in the requested format
1713 * @deprecated since 1.18
1715 * @param string $key Key of the message
1716 * @param array $options Processing rules.
1717 * Can take the following options:
1718 * parse: parses wikitext to HTML
1719 * parseinline: parses wikitext to HTML and removes the surrounding
1720 * p's added by parser or tidy
1721 * escape: filters message through htmlspecialchars
1722 * escapenoentities: same, but allows entity references like &#160; through
1723 * replaceafter: parameters are substituted after parsing or escaping
1724 * parsemag: transform the message using magic phrases
1725 * content: fetch message for content language instead of interface
1726 * Also can accept a single associative argument, of the form 'language' => 'xx':
1727 * language: Language object or language code to fetch message for
1728 * (overridden by content).
1729 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1731 * @return string
1733 function wfMsgExt( $key, $options ) {
1734 wfDeprecated( __METHOD__, '1.21' );
1736 $args = func_get_args();
1737 array_shift( $args );
1738 array_shift( $args );
1739 $options = (array)$options;
1740 $validOptions = array( 'parse', 'parseinline', 'escape', 'escapenoentities', 'replaceafter',
1741 'parsemag', 'content' );
1743 foreach ( $options as $arrayKey => $option ) {
1744 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1745 // An unknown index, neither numeric nor "language"
1746 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
1747 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option, $validOptions ) ) {
1748 // A numeric index with unknown value
1749 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
1753 if ( in_array( 'content', $options, true ) ) {
1754 $forContent = true;
1755 $langCode = true;
1756 $langCodeObj = null;
1757 } elseif ( array_key_exists( 'language', $options ) ) {
1758 $forContent = false;
1759 $langCode = wfGetLangObj( $options['language'] );
1760 $langCodeObj = $langCode;
1761 } else {
1762 $forContent = false;
1763 $langCode = false;
1764 $langCodeObj = null;
1767 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1769 if ( !in_array( 'replaceafter', $options, true ) ) {
1770 $string = wfMsgReplaceArgs( $string, $args );
1773 $messageCache = MessageCache::singleton();
1774 $parseInline = in_array( 'parseinline', $options, true );
1775 if ( in_array( 'parse', $options, true ) || $parseInline ) {
1776 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1777 if ( $string instanceof ParserOutput ) {
1778 $string = $string->getText();
1781 if ( $parseInline ) {
1782 $string = Parser::stripOuterParagraph( $string );
1784 } elseif ( in_array( 'parsemag', $options, true ) ) {
1785 $string = $messageCache->transform( $string,
1786 !$forContent, $langCodeObj );
1789 if ( in_array( 'escape', $options, true ) ) {
1790 $string = htmlspecialchars( $string );
1791 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1792 $string = Sanitizer::escapeHtmlAllowEntities( $string );
1795 if ( in_array( 'replaceafter', $options, true ) ) {
1796 $string = wfMsgReplaceArgs( $string, $args );
1799 return $string;
1803 * Since wfMsg() and co suck, they don't return false if the message key they
1804 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1805 * nonexistence of messages by checking the MessageCache::get() result directly.
1807 * @deprecated since 1.18. Use Message::isDisabled().
1809 * @param string $key The message key looked up
1810 * @return bool True if the message *doesn't* exist.
1812 function wfEmptyMsg( $key ) {
1813 wfDeprecated( __METHOD__, '1.21' );
1815 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1819 * Fetch server name for use in error reporting etc.
1820 * Use real server name if available, so we know which machine
1821 * in a server farm generated the current page.
1823 * @return string
1825 function wfHostname() {
1826 static $host;
1827 if ( is_null( $host ) ) {
1829 # Hostname overriding
1830 global $wgOverrideHostname;
1831 if ( $wgOverrideHostname !== false ) {
1832 # Set static and skip any detection
1833 $host = $wgOverrideHostname;
1834 return $host;
1837 if ( function_exists( 'posix_uname' ) ) {
1838 // This function not present on Windows
1839 $uname = posix_uname();
1840 } else {
1841 $uname = false;
1843 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1844 $host = $uname['nodename'];
1845 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1846 # Windows computer name
1847 $host = getenv( 'COMPUTERNAME' );
1848 } else {
1849 # This may be a virtual server.
1850 $host = $_SERVER['SERVER_NAME'];
1853 return $host;
1857 * Returns a script tag that stores the amount of time it took MediaWiki to
1858 * handle the request in milliseconds as 'wgBackendResponseTime'.
1860 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1861 * hostname of the server handling the request.
1863 * @return string
1865 function wfReportTime() {
1866 global $wgRequestTime, $wgShowHostnames;
1868 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1869 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1870 if ( $wgShowHostnames ) {
1871 $reportVars['wgHostname'] = wfHostname();
1873 return Skin::makeVariablesScript( $reportVars );
1877 * Safety wrapper for debug_backtrace().
1879 * Will return an empty array if debug_backtrace is disabled, otherwise
1880 * the output from debug_backtrace() (trimmed).
1882 * @param int $limit This parameter can be used to limit the number of stack frames returned
1884 * @return array Array of backtrace information
1886 function wfDebugBacktrace( $limit = 0 ) {
1887 static $disabled = null;
1889 if ( is_null( $disabled ) ) {
1890 $disabled = !function_exists( 'debug_backtrace' );
1891 if ( $disabled ) {
1892 wfDebug( "debug_backtrace() is disabled\n" );
1895 if ( $disabled ) {
1896 return array();
1899 if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
1900 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1901 } else {
1902 return array_slice( debug_backtrace(), 1 );
1907 * Get a debug backtrace as a string
1909 * @param bool|null $raw If true, the return value is plain text. If false, HTML.
1910 * Defaults to $wgCommandLineMode if unset.
1911 * @return string
1912 * @since 1.25 Supports $raw parameter.
1914 function wfBacktrace( $raw = null ) {
1915 global $wgCommandLineMode;
1917 if ( $raw === null ) {
1918 $raw = $wgCommandLineMode;
1921 if ( $raw ) {
1922 $frameFormat = "%s line %s calls %s()\n";
1923 $traceFormat = "%s";
1924 } else {
1925 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1926 $traceFormat = "<ul>\n%s</ul>\n";
1929 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1930 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1931 $line = isset( $frame['line'] ) ? $frame['line'] : '-';
1932 $call = $frame['function'];
1933 if ( !empty( $frame['class'] ) ) {
1934 $call = $frame['class'] . $frame['type'] . $call;
1936 return sprintf( $frameFormat, $file, $line, $call );
1937 }, wfDebugBacktrace() );
1939 return sprintf( $traceFormat, implode( '', $frames ) );
1943 * Get the name of the function which called this function
1944 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1945 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1946 * wfGetCaller( 3 ) is the parent of that.
1948 * @param int $level
1949 * @return string
1951 function wfGetCaller( $level = 2 ) {
1952 $backtrace = wfDebugBacktrace( $level + 1 );
1953 if ( isset( $backtrace[$level] ) ) {
1954 return wfFormatStackFrame( $backtrace[$level] );
1955 } else {
1956 return 'unknown';
1961 * Return a string consisting of callers in the stack. Useful sometimes
1962 * for profiling specific points.
1964 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1965 * @return string
1967 function wfGetAllCallers( $limit = 3 ) {
1968 $trace = array_reverse( wfDebugBacktrace() );
1969 if ( !$limit || $limit > count( $trace ) - 1 ) {
1970 $limit = count( $trace ) - 1;
1972 $trace = array_slice( $trace, -$limit - 1, $limit );
1973 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1977 * Return a string representation of frame
1979 * @param array $frame
1980 * @return string
1982 function wfFormatStackFrame( $frame ) {
1983 if ( !isset( $frame['function'] ) ) {
1984 return 'NO_FUNCTION_GIVEN';
1986 return isset( $frame['class'] ) && isset( $frame['type'] ) ?
1987 $frame['class'] . $frame['type'] . $frame['function'] :
1988 $frame['function'];
1991 /* Some generic result counters, pulled out of SearchEngine */
1994 * @todo document
1996 * @param int $offset
1997 * @param int $limit
1998 * @return string
2000 function wfShowingResults( $offset, $limit ) {
2001 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
2005 * @todo document
2006 * @todo FIXME: We may want to blacklist some broken browsers
2008 * @param bool $force
2009 * @return bool Whereas client accept gzip compression
2011 function wfClientAcceptsGzip( $force = false ) {
2012 static $result = null;
2013 if ( $result === null || $force ) {
2014 $result = false;
2015 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
2016 # @todo FIXME: We may want to blacklist some broken browsers
2017 $m = array();
2018 if ( preg_match(
2019 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
2020 $_SERVER['HTTP_ACCEPT_ENCODING'],
2024 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2025 $result = false;
2026 return $result;
2028 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2029 $result = true;
2033 return $result;
2037 * Obtain the offset and limit values from the request string;
2038 * used in special pages
2040 * @param int $deflimit Default limit if none supplied
2041 * @param string $optionname Name of a user preference to check against
2042 * @return array
2043 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2045 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2046 global $wgRequest;
2047 wfDeprecated( __METHOD__, '1.24' );
2048 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2052 * Escapes the given text so that it may be output using addWikiText()
2053 * without any linking, formatting, etc. making its way through. This
2054 * is achieved by substituting certain characters with HTML entities.
2055 * As required by the callers, "<nowiki>" is not used.
2057 * @param string $text Text to be escaped
2058 * @return string
2060 function wfEscapeWikiText( $text ) {
2061 static $repl = null, $repl2 = null;
2062 if ( $repl === null ) {
2063 $repl = array(
2064 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
2065 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
2066 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
2067 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
2068 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
2069 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
2070 "\n " => "\n&#32;", "\r " => "\r&#32;",
2071 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
2072 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
2073 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
2074 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
2075 '__' => '_&#95;', '://' => '&#58;//',
2078 // We have to catch everything "\s" matches in PCRE
2079 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2080 $repl["$magic "] = "$magic&#32;";
2081 $repl["$magic\t"] = "$magic&#9;";
2082 $repl["$magic\r"] = "$magic&#13;";
2083 $repl["$magic\n"] = "$magic&#10;";
2084 $repl["$magic\f"] = "$magic&#12;";
2087 // And handle protocols that don't use "://"
2088 global $wgUrlProtocols;
2089 $repl2 = array();
2090 foreach ( $wgUrlProtocols as $prot ) {
2091 if ( substr( $prot, -1 ) === ':' ) {
2092 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2095 $repl2 = $repl2 ? '/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2097 $text = substr( strtr( "\n$text", $repl ), 1 );
2098 $text = preg_replace( $repl2, '$1&#58;', $text );
2099 return $text;
2103 * Sets dest to source and returns the original value of dest
2104 * If source is NULL, it just returns the value, it doesn't set the variable
2105 * If force is true, it will set the value even if source is NULL
2107 * @param mixed $dest
2108 * @param mixed $source
2109 * @param bool $force
2110 * @return mixed
2112 function wfSetVar( &$dest, $source, $force = false ) {
2113 $temp = $dest;
2114 if ( !is_null( $source ) || $force ) {
2115 $dest = $source;
2117 return $temp;
2121 * As for wfSetVar except setting a bit
2123 * @param int $dest
2124 * @param int $bit
2125 * @param bool $state
2127 * @return bool
2129 function wfSetBit( &$dest, $bit, $state = true ) {
2130 $temp = (bool)( $dest & $bit );
2131 if ( !is_null( $state ) ) {
2132 if ( $state ) {
2133 $dest |= $bit;
2134 } else {
2135 $dest &= ~$bit;
2138 return $temp;
2142 * A wrapper around the PHP function var_export().
2143 * Either print it or add it to the regular output ($wgOut).
2145 * @param mixed $var A PHP variable to dump.
2147 function wfVarDump( $var ) {
2148 global $wgOut;
2149 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2150 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
2151 print $s;
2152 } else {
2153 $wgOut->addHTML( $s );
2158 * Provide a simple HTTP error.
2160 * @param int|string $code
2161 * @param string $label
2162 * @param string $desc
2164 function wfHttpError( $code, $label, $desc ) {
2165 global $wgOut;
2166 HttpStatus::header( $code );
2167 if ( $wgOut ) {
2168 $wgOut->disable();
2169 $wgOut->sendCacheControl();
2172 header( 'Content-type: text/html; charset=utf-8' );
2173 print '<!DOCTYPE html>' .
2174 '<html><head><title>' .
2175 htmlspecialchars( $label ) .
2176 '</title></head><body><h1>' .
2177 htmlspecialchars( $label ) .
2178 '</h1><p>' .
2179 nl2br( htmlspecialchars( $desc ) ) .
2180 "</p></body></html>\n";
2184 * Clear away any user-level output buffers, discarding contents.
2186 * Suitable for 'starting afresh', for instance when streaming
2187 * relatively large amounts of data without buffering, or wanting to
2188 * output image files without ob_gzhandler's compression.
2190 * The optional $resetGzipEncoding parameter controls suppression of
2191 * the Content-Encoding header sent by ob_gzhandler; by default it
2192 * is left. See comments for wfClearOutputBuffers() for why it would
2193 * be used.
2195 * Note that some PHP configuration options may add output buffer
2196 * layers which cannot be removed; these are left in place.
2198 * @param bool $resetGzipEncoding
2200 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2201 if ( $resetGzipEncoding ) {
2202 // Suppress Content-Encoding and Content-Length
2203 // headers from 1.10+s wfOutputHandler
2204 global $wgDisableOutputCompression;
2205 $wgDisableOutputCompression = true;
2207 while ( $status = ob_get_status() ) {
2208 if ( isset( $status['flags'] ) ) {
2209 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE;
2210 $deleteable = ( $status['flags'] & $flags ) === $flags;
2211 } elseif ( isset( $status['del'] ) ) {
2212 $deleteable = $status['del'];
2213 } else {
2214 // Guess that any PHP-internal setting can't be removed.
2215 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
2217 if ( !$deleteable ) {
2218 // Give up, and hope the result doesn't break
2219 // output behavior.
2220 break;
2222 if ( $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ) {
2223 // Unit testing barrier to prevent this function from breaking PHPUnit.
2224 break;
2226 if ( !ob_end_clean() ) {
2227 // Could not remove output buffer handler; abort now
2228 // to avoid getting in some kind of infinite loop.
2229 break;
2231 if ( $resetGzipEncoding ) {
2232 if ( $status['name'] == 'ob_gzhandler' ) {
2233 // Reset the 'Content-Encoding' field set by this handler
2234 // so we can start fresh.
2235 header_remove( 'Content-Encoding' );
2236 break;
2243 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2245 * Clear away output buffers, but keep the Content-Encoding header
2246 * produced by ob_gzhandler, if any.
2248 * This should be used for HTTP 304 responses, where you need to
2249 * preserve the Content-Encoding header of the real result, but
2250 * also need to suppress the output of ob_gzhandler to keep to spec
2251 * and avoid breaking Firefox in rare cases where the headers and
2252 * body are broken over two packets.
2254 function wfClearOutputBuffers() {
2255 wfResetOutputBuffers( false );
2259 * Converts an Accept-* header into an array mapping string values to quality
2260 * factors
2262 * @param string $accept
2263 * @param string $def Default
2264 * @return float[] Associative array of string => float pairs
2266 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2267 # No arg means accept anything (per HTTP spec)
2268 if ( !$accept ) {
2269 return array( $def => 1.0 );
2272 $prefs = array();
2274 $parts = explode( ',', $accept );
2276 foreach ( $parts as $part ) {
2277 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2278 $values = explode( ';', trim( $part ) );
2279 $match = array();
2280 if ( count( $values ) == 1 ) {
2281 $prefs[$values[0]] = 1.0;
2282 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2283 $prefs[$values[0]] = floatval( $match[1] );
2287 return $prefs;
2291 * Checks if a given MIME type matches any of the keys in the given
2292 * array. Basic wildcards are accepted in the array keys.
2294 * Returns the matching MIME type (or wildcard) if a match, otherwise
2295 * NULL if no match.
2297 * @param string $type
2298 * @param array $avail
2299 * @return string
2300 * @private
2302 function mimeTypeMatch( $type, $avail ) {
2303 if ( array_key_exists( $type, $avail ) ) {
2304 return $type;
2305 } else {
2306 $parts = explode( '/', $type );
2307 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2308 return $parts[0] . '/*';
2309 } elseif ( array_key_exists( '*/*', $avail ) ) {
2310 return '*/*';
2311 } else {
2312 return null;
2318 * Returns the 'best' match between a client's requested internet media types
2319 * and the server's list of available types. Each list should be an associative
2320 * array of type to preference (preference is a float between 0.0 and 1.0).
2321 * Wildcards in the types are acceptable.
2323 * @param array $cprefs Client's acceptable type list
2324 * @param array $sprefs Server's offered types
2325 * @return string
2327 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2328 * XXX: generalize to negotiate other stuff
2330 function wfNegotiateType( $cprefs, $sprefs ) {
2331 $combine = array();
2333 foreach ( array_keys( $sprefs ) as $type ) {
2334 $parts = explode( '/', $type );
2335 if ( $parts[1] != '*' ) {
2336 $ckey = mimeTypeMatch( $type, $cprefs );
2337 if ( $ckey ) {
2338 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2343 foreach ( array_keys( $cprefs ) as $type ) {
2344 $parts = explode( '/', $type );
2345 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2346 $skey = mimeTypeMatch( $type, $sprefs );
2347 if ( $skey ) {
2348 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2353 $bestq = 0;
2354 $besttype = null;
2356 foreach ( array_keys( $combine ) as $type ) {
2357 if ( $combine[$type] > $bestq ) {
2358 $besttype = $type;
2359 $bestq = $combine[$type];
2363 return $besttype;
2367 * Reference-counted warning suppression
2369 * @deprecated since 1.26, use MediaWiki\suppressWarnings() directly
2370 * @param bool $end
2372 function wfSuppressWarnings( $end = false ) {
2373 MediaWiki\suppressWarnings( $end );
2377 * @deprecated since 1.26, use MediaWiki\restoreWarnings() directly
2378 * Restore error level to previous value
2380 function wfRestoreWarnings() {
2381 MediaWiki\suppressWarnings( true );
2384 # Autodetect, convert and provide timestamps of various types
2387 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2389 define( 'TS_UNIX', 0 );
2392 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2394 define( 'TS_MW', 1 );
2397 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2399 define( 'TS_DB', 2 );
2402 * RFC 2822 format, for E-mail and HTTP headers
2404 define( 'TS_RFC2822', 3 );
2407 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2409 * This is used by Special:Export
2411 define( 'TS_ISO_8601', 4 );
2414 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2416 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2417 * DateTime tag and page 36 for the DateTimeOriginal and
2418 * DateTimeDigitized tags.
2420 define( 'TS_EXIF', 5 );
2423 * Oracle format time.
2425 define( 'TS_ORACLE', 6 );
2428 * Postgres format time.
2430 define( 'TS_POSTGRES', 7 );
2433 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2435 define( 'TS_ISO_8601_BASIC', 9 );
2438 * Get a timestamp string in one of various formats
2440 * @param mixed $outputtype A timestamp in one of the supported formats, the
2441 * function will autodetect which format is supplied and act accordingly.
2442 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2443 * @return string|bool String / false The same date in the format specified in $outputtype or false
2445 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2446 try {
2447 $timestamp = new MWTimestamp( $ts );
2448 return $timestamp->getTimestamp( $outputtype );
2449 } catch ( TimestampException $e ) {
2450 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2451 return false;
2456 * Return a formatted timestamp, or null if input is null.
2457 * For dealing with nullable timestamp columns in the database.
2459 * @param int $outputtype
2460 * @param string $ts
2461 * @return string
2463 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2464 if ( is_null( $ts ) ) {
2465 return null;
2466 } else {
2467 return wfTimestamp( $outputtype, $ts );
2472 * Convenience function; returns MediaWiki timestamp for the present time.
2474 * @return string
2476 function wfTimestampNow() {
2477 # return NOW
2478 return wfTimestamp( TS_MW, time() );
2482 * Check if the operating system is Windows
2484 * @return bool True if it's Windows, false otherwise.
2486 function wfIsWindows() {
2487 static $isWindows = null;
2488 if ( $isWindows === null ) {
2489 $isWindows = strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN';
2491 return $isWindows;
2495 * Check if we are running under HHVM
2497 * @return bool
2499 function wfIsHHVM() {
2500 return defined( 'HHVM_VERSION' );
2504 * Tries to get the system directory for temporary files. First
2505 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2506 * environment variables are then checked in sequence, and if none are
2507 * set try sys_get_temp_dir().
2509 * NOTE: When possible, use instead the tmpfile() function to create
2510 * temporary files to avoid race conditions on file creation, etc.
2512 * @return string
2514 function wfTempDir() {
2515 global $wgTmpDirectory;
2517 if ( $wgTmpDirectory !== false ) {
2518 return $wgTmpDirectory;
2521 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2523 foreach ( $tmpDir as $tmp ) {
2524 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2525 return $tmp;
2528 return sys_get_temp_dir();
2532 * Make directory, and make all parent directories if they don't exist
2534 * @param string $dir Full path to directory to create
2535 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2536 * @param string $caller Optional caller param for debugging.
2537 * @throws MWException
2538 * @return bool
2540 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2541 global $wgDirectoryMode;
2543 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
2544 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
2547 if ( !is_null( $caller ) ) {
2548 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2551 if ( strval( $dir ) === '' || is_dir( $dir ) ) {
2552 return true;
2555 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2557 if ( is_null( $mode ) ) {
2558 $mode = $wgDirectoryMode;
2561 // Turn off the normal warning, we're doing our own below
2562 MediaWiki\suppressWarnings();
2563 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2564 MediaWiki\restoreWarnings();
2566 if ( !$ok ) {
2567 // directory may have been created on another request since we last checked
2568 if ( is_dir( $dir ) ) {
2569 return true;
2572 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2573 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2575 return $ok;
2579 * Remove a directory and all its content.
2580 * Does not hide error.
2581 * @param string $dir
2583 function wfRecursiveRemoveDir( $dir ) {
2584 wfDebug( __FUNCTION__ . "( $dir )\n" );
2585 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2586 if ( is_dir( $dir ) ) {
2587 $objects = scandir( $dir );
2588 foreach ( $objects as $object ) {
2589 if ( $object != "." && $object != ".." ) {
2590 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2591 wfRecursiveRemoveDir( $dir . '/' . $object );
2592 } else {
2593 unlink( $dir . '/' . $object );
2597 reset( $objects );
2598 rmdir( $dir );
2603 * @param int $nr The number to format
2604 * @param int $acc The number of digits after the decimal point, default 2
2605 * @param bool $round Whether or not to round the value, default true
2606 * @return string
2608 function wfPercent( $nr, $acc = 2, $round = true ) {
2609 $ret = sprintf( "%.${acc}f", $nr );
2610 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2614 * Safety wrapper around ini_get() for boolean settings.
2615 * The values returned from ini_get() are pre-normalized for settings
2616 * set via php.ini or php_flag/php_admin_flag... but *not*
2617 * for those set via php_value/php_admin_value.
2619 * It's fairly common for people to use php_value instead of php_flag,
2620 * which can leave you with an 'off' setting giving a false positive
2621 * for code that just takes the ini_get() return value as a boolean.
2623 * To make things extra interesting, setting via php_value accepts
2624 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2625 * Unrecognized values go false... again opposite PHP's own coercion
2626 * from string to bool.
2628 * Luckily, 'properly' set settings will always come back as '0' or '1',
2629 * so we only have to worry about them and the 'improper' settings.
2631 * I frickin' hate PHP... :P
2633 * @param string $setting
2634 * @return bool
2636 function wfIniGetBool( $setting ) {
2637 $val = strtolower( ini_get( $setting ) );
2638 // 'on' and 'true' can't have whitespace around them, but '1' can.
2639 return $val == 'on'
2640 || $val == 'true'
2641 || $val == 'yes'
2642 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2646 * Windows-compatible version of escapeshellarg()
2647 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2648 * function puts single quotes in regardless of OS.
2650 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2651 * earlier distro releases of PHP)
2653 * @param string ... strings to escape and glue together, or a single array of strings parameter
2654 * @return string
2656 function wfEscapeShellArg( /*...*/ ) {
2657 wfInitShellLocale();
2659 $args = func_get_args();
2660 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
2661 // If only one argument has been passed, and that argument is an array,
2662 // treat it as a list of arguments
2663 $args = reset( $args );
2666 $first = true;
2667 $retVal = '';
2668 foreach ( $args as $arg ) {
2669 if ( !$first ) {
2670 $retVal .= ' ';
2671 } else {
2672 $first = false;
2675 if ( wfIsWindows() ) {
2676 // Escaping for an MSVC-style command line parser and CMD.EXE
2677 // @codingStandardsIgnoreStart For long URLs
2678 // Refs:
2679 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2680 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2681 // * Bug #13518
2682 // * CR r63214
2683 // Double the backslashes before any double quotes. Escape the double quotes.
2684 // @codingStandardsIgnoreEnd
2685 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
2686 $arg = '';
2687 $iteration = 0;
2688 foreach ( $tokens as $token ) {
2689 if ( $iteration % 2 == 1 ) {
2690 // Delimiter, a double quote preceded by zero or more slashes
2691 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2692 } elseif ( $iteration % 4 == 2 ) {
2693 // ^ in $token will be outside quotes, need to be escaped
2694 $arg .= str_replace( '^', '^^', $token );
2695 } else { // $iteration % 4 == 0
2696 // ^ in $token will appear inside double quotes, so leave as is
2697 $arg .= $token;
2699 $iteration++;
2701 // Double the backslashes before the end of the string, because
2702 // we will soon add a quote
2703 $m = array();
2704 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2705 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2708 // Add surrounding quotes
2709 $retVal .= '"' . $arg . '"';
2710 } else {
2711 $retVal .= escapeshellarg( $arg );
2714 return $retVal;
2718 * Check if wfShellExec() is effectively disabled via php.ini config
2720 * @return bool|string False or one of (safemode,disabled)
2721 * @since 1.22
2723 function wfShellExecDisabled() {
2724 static $disabled = null;
2725 if ( is_null( $disabled ) ) {
2726 if ( wfIniGetBool( 'safe_mode' ) ) {
2727 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2728 $disabled = 'safemode';
2729 } elseif ( !function_exists( 'proc_open' ) ) {
2730 wfDebug( "proc_open() is disabled\n" );
2731 $disabled = 'disabled';
2732 } else {
2733 $disabled = false;
2736 return $disabled;
2740 * Execute a shell command, with time and memory limits mirrored from the PHP
2741 * configuration if supported.
2743 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2744 * or an array of unescaped arguments, in which case each value will be escaped
2745 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2746 * @param null|mixed &$retval Optional, will receive the program's exit code.
2747 * (non-zero is usually failure). If there is an error from
2748 * read, select, or proc_open(), this will be set to -1.
2749 * @param array $environ Optional environment variables which should be
2750 * added to the executed command environment.
2751 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2752 * this overwrites the global wgMaxShell* limits.
2753 * @param array $options Array of options:
2754 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2755 * including errors from limit.sh
2756 * - profileMethod: By default this function will profile based on the calling
2757 * method. Set this to a string for an alternative method to profile from
2759 * @return string Collected stdout as a string
2761 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2762 $limits = array(), $options = array()
2764 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2765 $wgMaxShellWallClockTime, $wgShellCgroup;
2767 $disabled = wfShellExecDisabled();
2768 if ( $disabled ) {
2769 $retval = 1;
2770 return $disabled == 'safemode' ?
2771 'Unable to run external programs in safe mode.' :
2772 'Unable to run external programs, proc_open() is disabled.';
2775 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2776 $profileMethod = isset( $options['profileMethod'] ) ? $options['profileMethod'] : wfGetCaller();
2778 wfInitShellLocale();
2780 $envcmd = '';
2781 foreach ( $environ as $k => $v ) {
2782 if ( wfIsWindows() ) {
2783 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2784 * appear in the environment variable, so we must use carat escaping as documented in
2785 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2786 * Note however that the quote isn't listed there, but is needed, and the parentheses
2787 * are listed there but doesn't appear to need it.
2789 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2790 } else {
2791 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2792 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2794 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2797 if ( is_array( $cmd ) ) {
2798 $cmd = wfEscapeShellArg( $cmd );
2801 $cmd = $envcmd . $cmd;
2803 $useLogPipe = false;
2804 if ( is_executable( '/bin/bash' ) ) {
2805 $time = intval( isset( $limits['time'] ) ? $limits['time'] : $wgMaxShellTime );
2806 if ( isset( $limits['walltime'] ) ) {
2807 $wallTime = intval( $limits['walltime'] );
2808 } elseif ( isset( $limits['time'] ) ) {
2809 $wallTime = $time;
2810 } else {
2811 $wallTime = intval( $wgMaxShellWallClockTime );
2813 $mem = intval( isset( $limits['memory'] ) ? $limits['memory'] : $wgMaxShellMemory );
2814 $filesize = intval( isset( $limits['filesize'] ) ? $limits['filesize'] : $wgMaxShellFileSize );
2816 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
2817 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2818 escapeshellarg( $cmd ) . ' ' .
2819 escapeshellarg(
2820 "MW_INCLUDE_STDERR=" . ( $includeStderr ? '1' : '' ) . ';' .
2821 "MW_CPU_LIMIT=$time; " .
2822 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2823 "MW_MEM_LIMIT=$mem; " .
2824 "MW_FILE_SIZE_LIMIT=$filesize; " .
2825 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2826 "MW_USE_LOG_PIPE=yes"
2828 $useLogPipe = true;
2829 } elseif ( $includeStderr ) {
2830 $cmd .= ' 2>&1';
2832 } elseif ( $includeStderr ) {
2833 $cmd .= ' 2>&1';
2835 wfDebug( "wfShellExec: $cmd\n" );
2837 $desc = array(
2838 0 => array( 'file', 'php://stdin', 'r' ),
2839 1 => array( 'pipe', 'w' ),
2840 2 => array( 'file', 'php://stderr', 'w' ) );
2841 if ( $useLogPipe ) {
2842 $desc[3] = array( 'pipe', 'w' );
2844 $pipes = null;
2845 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
2846 $proc = proc_open( $cmd, $desc, $pipes );
2847 if ( !$proc ) {
2848 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2849 $retval = -1;
2850 return '';
2852 $outBuffer = $logBuffer = '';
2853 $emptyArray = array();
2854 $status = false;
2855 $logMsg = false;
2857 /* According to the documentation, it is possible for stream_select()
2858 * to fail due to EINTR. I haven't managed to induce this in testing
2859 * despite sending various signals. If it did happen, the error
2860 * message would take the form:
2862 * stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2864 * where [4] is the value of the macro EINTR and "Interrupted system
2865 * call" is string which according to the Linux manual is "possibly"
2866 * localised according to LC_MESSAGES.
2868 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
2869 $eintrMessage = "stream_select(): unable to select [$eintr]";
2871 // Build a table mapping resource IDs to pipe FDs to work around a
2872 // PHP 5.3 issue in which stream_select() does not preserve array keys
2873 // <https://bugs.php.net/bug.php?id=53427>.
2874 $fds = array();
2875 foreach ( $pipes as $fd => $pipe ) {
2876 $fds[(int)$pipe] = $fd;
2879 $running = true;
2880 $timeout = null;
2881 $numReadyPipes = 0;
2883 while ( $running === true || $numReadyPipes !== 0 ) {
2884 if ( $running ) {
2885 $status = proc_get_status( $proc );
2886 // If the process has terminated, switch to nonblocking selects
2887 // for getting any data still waiting to be read.
2888 if ( !$status['running'] ) {
2889 $running = false;
2890 $timeout = 0;
2894 $readyPipes = $pipes;
2896 // Clear last error
2897 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2898 @trigger_error( '' );
2899 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
2900 if ( $numReadyPipes === false ) {
2901 // @codingStandardsIgnoreEnd
2902 $error = error_get_last();
2903 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2904 continue;
2905 } else {
2906 trigger_error( $error['message'], E_USER_WARNING );
2907 $logMsg = $error['message'];
2908 break;
2911 foreach ( $readyPipes as $pipe ) {
2912 $block = fread( $pipe, 65536 );
2913 $fd = $fds[(int)$pipe];
2914 if ( $block === '' ) {
2915 // End of file
2916 fclose( $pipes[$fd] );
2917 unset( $pipes[$fd] );
2918 if ( !$pipes ) {
2919 break 2;
2921 } elseif ( $block === false ) {
2922 // Read error
2923 $logMsg = "Error reading from pipe";
2924 break 2;
2925 } elseif ( $fd == 1 ) {
2926 // From stdout
2927 $outBuffer .= $block;
2928 } elseif ( $fd == 3 ) {
2929 // From log FD
2930 $logBuffer .= $block;
2931 if ( strpos( $block, "\n" ) !== false ) {
2932 $lines = explode( "\n", $logBuffer );
2933 $logBuffer = array_pop( $lines );
2934 foreach ( $lines as $line ) {
2935 wfDebugLog( 'exec', $line );
2942 foreach ( $pipes as $pipe ) {
2943 fclose( $pipe );
2946 // Use the status previously collected if possible, since proc_get_status()
2947 // just calls waitpid() which will not return anything useful the second time.
2948 if ( $running ) {
2949 $status = proc_get_status( $proc );
2952 if ( $logMsg !== false ) {
2953 // Read/select error
2954 $retval = -1;
2955 proc_close( $proc );
2956 } elseif ( $status['signaled'] ) {
2957 $logMsg = "Exited with signal {$status['termsig']}";
2958 $retval = 128 + $status['termsig'];
2959 proc_close( $proc );
2960 } else {
2961 if ( $status['running'] ) {
2962 $retval = proc_close( $proc );
2963 } else {
2964 $retval = $status['exitcode'];
2965 proc_close( $proc );
2967 if ( $retval == 127 ) {
2968 $logMsg = "Possibly missing executable file";
2969 } elseif ( $retval >= 129 && $retval <= 192 ) {
2970 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2974 if ( $logMsg !== false ) {
2975 wfDebugLog( 'exec', "$logMsg: $cmd" );
2978 return $outBuffer;
2982 * Execute a shell command, returning both stdout and stderr. Convenience
2983 * function, as all the arguments to wfShellExec can become unwieldy.
2985 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2986 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2987 * or an array of unescaped arguments, in which case each value will be escaped
2988 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2989 * @param null|mixed &$retval Optional, will receive the program's exit code.
2990 * (non-zero is usually failure)
2991 * @param array $environ Optional environment variables which should be
2992 * added to the executed command environment.
2993 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2994 * this overwrites the global wgMaxShell* limits.
2995 * @return string Collected stdout and stderr as a string
2997 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2998 return wfShellExec( $cmd, $retval, $environ, $limits,
2999 array( 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ) );
3003 * Workaround for http://bugs.php.net/bug.php?id=45132
3004 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
3006 function wfInitShellLocale() {
3007 static $done = false;
3008 if ( $done ) {
3009 return;
3011 $done = true;
3012 global $wgShellLocale;
3013 if ( !wfIniGetBool( 'safe_mode' ) ) {
3014 putenv( "LC_CTYPE=$wgShellLocale" );
3015 setlocale( LC_CTYPE, $wgShellLocale );
3020 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3021 * Note that $parameters should be a flat array and an option with an argument
3022 * should consist of two consecutive items in the array (do not use "--option value").
3024 * @param string $script MediaWiki cli script path
3025 * @param array $parameters Arguments and options to the script
3026 * @param array $options Associative array of options:
3027 * 'php': The path to the php executable
3028 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3029 * @return string
3031 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3032 global $wgPhpCli;
3033 // Give site config file a chance to run the script in a wrapper.
3034 // The caller may likely want to call wfBasename() on $script.
3035 Hooks::run( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3036 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
3037 if ( isset( $options['wrapper'] ) ) {
3038 $cmd[] = $options['wrapper'];
3040 $cmd[] = $script;
3041 // Escape each parameter for shell
3042 return wfEscapeShellArg( array_merge( $cmd, $parameters ) );
3046 * wfMerge attempts to merge differences between three texts.
3047 * Returns true for a clean merge and false for failure or a conflict.
3049 * @param string $old
3050 * @param string $mine
3051 * @param string $yours
3052 * @param string $result
3053 * @return bool
3055 function wfMerge( $old, $mine, $yours, &$result ) {
3056 global $wgDiff3;
3058 # This check may also protect against code injection in
3059 # case of broken installations.
3060 MediaWiki\suppressWarnings();
3061 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3062 MediaWiki\restoreWarnings();
3064 if ( !$haveDiff3 ) {
3065 wfDebug( "diff3 not found\n" );
3066 return false;
3069 # Make temporary files
3070 $td = wfTempDir();
3071 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3072 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3073 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3075 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3076 # a newline character. To avoid this, we normalize the trailing whitespace before
3077 # creating the diff.
3079 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3080 fclose( $oldtextFile );
3081 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3082 fclose( $mytextFile );
3083 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3084 fclose( $yourtextFile );
3086 # Check for a conflict
3087 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '--overlap-only', $mytextName,
3088 $oldtextName, $yourtextName );
3089 $handle = popen( $cmd, 'r' );
3091 if ( fgets( $handle, 1024 ) ) {
3092 $conflict = true;
3093 } else {
3094 $conflict = false;
3096 pclose( $handle );
3098 # Merge differences
3099 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '-e', '--merge', $mytextName,
3100 $oldtextName, $yourtextName );
3101 $handle = popen( $cmd, 'r' );
3102 $result = '';
3103 do {
3104 $data = fread( $handle, 8192 );
3105 if ( strlen( $data ) == 0 ) {
3106 break;
3108 $result .= $data;
3109 } while ( true );
3110 pclose( $handle );
3111 unlink( $mytextName );
3112 unlink( $oldtextName );
3113 unlink( $yourtextName );
3115 if ( $result === '' && $old !== '' && !$conflict ) {
3116 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3117 $conflict = true;
3119 return !$conflict;
3123 * Returns unified plain-text diff of two texts.
3124 * "Useful" for machine processing of diffs.
3126 * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly
3128 * @param string $before The text before the changes.
3129 * @param string $after The text after the changes.
3130 * @param string $params Command-line options for the diff command.
3131 * @return string Unified diff of $before and $after
3133 function wfDiff( $before, $after, $params = '-u' ) {
3134 if ( $before == $after ) {
3135 return '';
3138 global $wgDiff;
3139 MediaWiki\suppressWarnings();
3140 $haveDiff = $wgDiff && file_exists( $wgDiff );
3141 MediaWiki\restoreWarnings();
3143 # This check may also protect against code injection in
3144 # case of broken installations.
3145 if ( !$haveDiff ) {
3146 wfDebug( "diff executable not found\n" );
3147 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3148 $format = new UnifiedDiffFormatter();
3149 return $format->format( $diffs );
3152 # Make temporary files
3153 $td = wfTempDir();
3154 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3155 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3157 fwrite( $oldtextFile, $before );
3158 fclose( $oldtextFile );
3159 fwrite( $newtextFile, $after );
3160 fclose( $newtextFile );
3162 // Get the diff of the two files
3163 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3165 $h = popen( $cmd, 'r' );
3166 if ( !$h ) {
3167 unlink( $oldtextName );
3168 unlink( $newtextName );
3169 throw new Exception( __METHOD__ . '(): popen() failed' );
3172 $diff = '';
3174 do {
3175 $data = fread( $h, 8192 );
3176 if ( strlen( $data ) == 0 ) {
3177 break;
3179 $diff .= $data;
3180 } while ( true );
3182 // Clean up
3183 pclose( $h );
3184 unlink( $oldtextName );
3185 unlink( $newtextName );
3187 // Kill the --- and +++ lines. They're not useful.
3188 $diff_lines = explode( "\n", $diff );
3189 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
3190 unset( $diff_lines[0] );
3192 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
3193 unset( $diff_lines[1] );
3196 $diff = implode( "\n", $diff_lines );
3198 return $diff;
3202 * This function works like "use VERSION" in Perl, the program will die with a
3203 * backtrace if the current version of PHP is less than the version provided
3205 * This is useful for extensions which due to their nature are not kept in sync
3206 * with releases, and might depend on other versions of PHP than the main code
3208 * Note: PHP might die due to parsing errors in some cases before it ever
3209 * manages to call this function, such is life
3211 * @see perldoc -f use
3213 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3214 * @throws MWException
3216 function wfUsePHP( $req_ver ) {
3217 $php_ver = PHP_VERSION;
3219 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3220 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3225 * This function works like "use VERSION" in Perl except it checks the version
3226 * of MediaWiki, the program will die with a backtrace if the current version
3227 * of MediaWiki is less than the version provided.
3229 * This is useful for extensions which due to their nature are not kept in sync
3230 * with releases
3232 * Note: Due to the behavior of PHP's version_compare() which is used in this
3233 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3234 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3235 * targeted version number. For example if you wanted to allow any variation
3236 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3237 * not result in the same comparison due to the internal logic of
3238 * version_compare().
3240 * @see perldoc -f use
3242 * @deprecated since 1.26, use the "requires' property of extension.json
3243 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3244 * @throws MWException
3246 function wfUseMW( $req_ver ) {
3247 global $wgVersion;
3249 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3250 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3255 * Return the final portion of a pathname.
3256 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3257 * http://bugs.php.net/bug.php?id=33898
3259 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3260 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3262 * @param string $path
3263 * @param string $suffix String to remove if present
3264 * @return string
3266 function wfBaseName( $path, $suffix = '' ) {
3267 if ( $suffix == '' ) {
3268 $encSuffix = '';
3269 } else {
3270 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3273 $matches = array();
3274 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3275 return $matches[1];
3276 } else {
3277 return '';
3282 * Generate a relative path name to the given file.
3283 * May explode on non-matching case-insensitive paths,
3284 * funky symlinks, etc.
3286 * @param string $path Absolute destination path including target filename
3287 * @param string $from Absolute source path, directory only
3288 * @return string
3290 function wfRelativePath( $path, $from ) {
3291 // Normalize mixed input on Windows...
3292 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
3293 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
3295 // Trim trailing slashes -- fix for drive root
3296 $path = rtrim( $path, DIRECTORY_SEPARATOR );
3297 $from = rtrim( $from, DIRECTORY_SEPARATOR );
3299 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
3300 $against = explode( DIRECTORY_SEPARATOR, $from );
3302 if ( $pieces[0] !== $against[0] ) {
3303 // Non-matching Windows drive letters?
3304 // Return a full path.
3305 return $path;
3308 // Trim off common prefix
3309 while ( count( $pieces ) && count( $against )
3310 && $pieces[0] == $against[0] ) {
3311 array_shift( $pieces );
3312 array_shift( $against );
3315 // relative dots to bump us to the parent
3316 while ( count( $against ) ) {
3317 array_unshift( $pieces, '..' );
3318 array_shift( $against );
3321 array_push( $pieces, wfBaseName( $path ) );
3323 return implode( DIRECTORY_SEPARATOR, $pieces );
3327 * Convert an arbitrarily-long digit string from one numeric base
3328 * to another, optionally zero-padding to a minimum column width.
3330 * Supports base 2 through 36; digit values 10-36 are represented
3331 * as lowercase letters a-z. Input is case-insensitive.
3333 * @deprecated 1.27 Use Wikimedia\base_convert() directly
3335 * @param string $input Input number
3336 * @param int $sourceBase Base of the input number
3337 * @param int $destBase Desired base of the output
3338 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3339 * @param bool $lowercase Whether to output in lowercase or uppercase
3340 * @param string $engine Either "gmp", "bcmath", or "php"
3341 * @return string|bool The output number as a string, or false on error
3343 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3344 $lowercase = true, $engine = 'auto'
3346 return Wikimedia\base_convert( $input, $sourceBase, $destBase, $pad, $lowercase, $engine );
3350 * Check if there is sufficient entropy in php's built-in session generation
3352 * @return bool True = there is sufficient entropy
3354 function wfCheckEntropy() {
3355 return (
3356 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
3357 || ini_get( 'session.entropy_file' )
3359 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3363 * Override session_id before session startup if php's built-in
3364 * session generation code is not secure.
3366 function wfFixSessionID() {
3367 // If the cookie or session id is already set we already have a session and should abort
3368 if ( isset( $_COOKIE[session_name()] ) || session_id() ) {
3369 return;
3372 // PHP's built-in session entropy is enabled if:
3373 // - entropy_file is set or you're on Windows with php 5.3.3+
3374 // - AND entropy_length is > 0
3375 // We treat it as disabled if it doesn't have an entropy length of at least 32
3376 $entropyEnabled = wfCheckEntropy();
3378 // If built-in entropy is not enabled or not sufficient override PHP's
3379 // built in session id generation code
3380 if ( !$entropyEnabled ) {
3381 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, " .
3382 "overriding session id generation using our cryptrand source.\n" );
3383 session_id( MWCryptRand::generateHex( 32 ) );
3388 * Reset the session_id
3390 * @since 1.22
3392 function wfResetSessionID() {
3393 global $wgCookieSecure;
3394 $oldSessionId = session_id();
3395 $cookieParams = session_get_cookie_params();
3396 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3397 session_regenerate_id( false );
3398 } else {
3399 $tmp = $_SESSION;
3400 session_destroy();
3401 wfSetupSession( MWCryptRand::generateHex( 32 ) );
3402 $_SESSION = $tmp;
3404 $newSessionId = session_id();
3408 * Initialise php session
3410 * @param bool $sessionId
3412 function wfSetupSession( $sessionId = false ) {
3413 global $wgSessionsInObjectCache, $wgSessionHandler;
3414 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
3416 if ( $wgSessionsInObjectCache ) {
3417 ObjectCacheSessionHandler::install();
3418 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3419 # Only set this if $wgSessionHandler isn't null and session.save_handler
3420 # hasn't already been set to the desired value (that causes errors)
3421 ini_set( 'session.save_handler', $wgSessionHandler );
3424 session_set_cookie_params(
3425 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3426 session_cache_limiter( 'private, must-revalidate' );
3427 if ( $sessionId ) {
3428 session_id( $sessionId );
3429 } else {
3430 wfFixSessionID();
3433 MediaWiki\suppressWarnings();
3434 session_start();
3435 MediaWiki\restoreWarnings();
3437 if ( $wgSessionsInObjectCache ) {
3438 ObjectCacheSessionHandler::renewCurrentSession();
3443 * Get an object from the precompiled serialized directory
3445 * @param string $name
3446 * @return mixed The variable on success, false on failure
3448 function wfGetPrecompiledData( $name ) {
3449 global $IP;
3451 $file = "$IP/serialized/$name";
3452 if ( file_exists( $file ) ) {
3453 $blob = file_get_contents( $file );
3454 if ( $blob ) {
3455 return unserialize( $blob );
3458 return false;
3462 * Make a cache key for the local wiki.
3464 * @param string $args,...
3465 * @return string
3467 function wfMemcKey( /*...*/ ) {
3468 return call_user_func_array(
3469 array( ObjectCache::getLocalClusterInstance(), 'makeKey' ),
3470 func_get_args()
3475 * Make a cache key for a foreign DB.
3477 * Must match what wfMemcKey() would produce in context of the foreign wiki.
3479 * @param string $db
3480 * @param string $prefix
3481 * @param string $args,...
3482 * @return string
3484 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3485 $args = array_slice( func_get_args(), 2 );
3486 $keyspace = $prefix ? "$db-$prefix" : $db;
3487 return call_user_func_array(
3488 array( ObjectCache::getLocalClusterInstance(), 'makeKeyInternal' ),
3489 array( $keyspace, $args )
3494 * Make a cache key with database-agnostic prefix.
3496 * Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix
3497 * instead. Must have a prefix as otherwise keys that use a database name
3498 * in the first segment will clash with wfMemcKey/wfForeignMemcKey.
3500 * @since 1.26
3501 * @param string $args,...
3502 * @return string
3504 function wfGlobalCacheKey( /*...*/ ) {
3505 return call_user_func_array(
3506 array( ObjectCache::getLocalClusterInstance(), 'makeGlobalKey' ),
3507 func_get_args()
3512 * Get an ASCII string identifying this wiki
3513 * This is used as a prefix in memcached keys
3515 * @return string
3517 function wfWikiID() {
3518 global $wgDBprefix, $wgDBname;
3519 if ( $wgDBprefix ) {
3520 return "$wgDBname-$wgDBprefix";
3521 } else {
3522 return $wgDBname;
3527 * Split a wiki ID into DB name and table prefix
3529 * @param string $wiki
3531 * @return array
3533 function wfSplitWikiID( $wiki ) {
3534 $bits = explode( '-', $wiki, 2 );
3535 if ( count( $bits ) < 2 ) {
3536 $bits[] = '';
3538 return $bits;
3542 * Get a Database object.
3544 * @param int $db Index of the connection to get. May be DB_MASTER for the
3545 * master (for write queries), DB_SLAVE for potentially lagged read
3546 * queries, or an integer >= 0 for a particular server.
3548 * @param string|string[] $groups Query groups. An array of group names that this query
3549 * belongs to. May contain a single string if the query is only
3550 * in one group.
3552 * @param string|bool $wiki The wiki ID, or false for the current wiki
3554 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3555 * will always return the same object, unless the underlying connection or load
3556 * balancer is manually destroyed.
3558 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3559 * updater to ensure that a proper database is being updated.
3561 * @return DatabaseBase
3563 function wfGetDB( $db, $groups = array(), $wiki = false ) {
3564 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3568 * Get a load balancer object.
3570 * @param string|bool $wiki Wiki ID, or false for the current wiki
3571 * @return LoadBalancer
3573 function wfGetLB( $wiki = false ) {
3574 return wfGetLBFactory()->getMainLB( $wiki );
3578 * Get the load balancer factory object
3580 * @return LBFactory
3582 function wfGetLBFactory() {
3583 return LBFactory::singleton();
3587 * Find a file.
3588 * Shortcut for RepoGroup::singleton()->findFile()
3590 * @param string $title String or Title object
3591 * @param array $options Associative array of options (see RepoGroup::findFile)
3592 * @return File|bool File, or false if the file does not exist
3594 function wfFindFile( $title, $options = array() ) {
3595 return RepoGroup::singleton()->findFile( $title, $options );
3599 * Get an object referring to a locally registered file.
3600 * Returns a valid placeholder object if the file does not exist.
3602 * @param Title|string $title
3603 * @return LocalFile|null A File, or null if passed an invalid Title
3605 function wfLocalFile( $title ) {
3606 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3610 * Should low-performance queries be disabled?
3612 * @return bool
3613 * @codeCoverageIgnore
3615 function wfQueriesMustScale() {
3616 global $wgMiserMode;
3617 return $wgMiserMode
3618 || ( SiteStats::pages() > 100000
3619 && SiteStats::edits() > 1000000
3620 && SiteStats::users() > 10000 );
3624 * Get the path to a specified script file, respecting file
3625 * extensions; this is a wrapper around $wgScriptPath etc.
3626 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3628 * @param string $script Script filename, sans extension
3629 * @return string
3631 function wfScript( $script = 'index' ) {
3632 global $wgScriptPath, $wgScript, $wgLoadScript;
3633 if ( $script === 'index' ) {
3634 return $wgScript;
3635 } elseif ( $script === 'load' ) {
3636 return $wgLoadScript;
3637 } else {
3638 return "{$wgScriptPath}/{$script}.php";
3643 * Get the script URL.
3645 * @return string Script URL
3647 function wfGetScriptUrl() {
3648 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3649 /* as it was called, minus the query string.
3651 * Some sites use Apache rewrite rules to handle subdomains,
3652 * and have PHP set up in a weird way that causes PHP_SELF
3653 * to contain the rewritten URL instead of the one that the
3654 * outside world sees.
3656 * If in this mode, use SCRIPT_URL instead, which mod_rewrite
3657 * provides containing the "before" URL.
3659 return $_SERVER['SCRIPT_NAME'];
3660 } else {
3661 return $_SERVER['URL'];
3666 * Convenience function converts boolean values into "true"
3667 * or "false" (string) values
3669 * @param bool $value
3670 * @return string
3672 function wfBoolToStr( $value ) {
3673 return $value ? 'true' : 'false';
3677 * Get a platform-independent path to the null file, e.g. /dev/null
3679 * @return string
3681 function wfGetNull() {
3682 return wfIsWindows() ? 'NUL' : '/dev/null';
3686 * Waits for the slaves to catch up to the master position
3688 * Use this when updating very large numbers of rows, as in maintenance scripts,
3689 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
3691 * By default this waits on the main DB cluster of the current wiki.
3692 * If $cluster is set to "*" it will wait on all DB clusters, including
3693 * external ones. If the lag being waiting on is caused by the code that
3694 * does this check, it makes since to use $ifWritesSince, particularly if
3695 * cluster is "*", to avoid excess overhead.
3697 * Never call this function after a big DB write that is still in a transaction.
3698 * This only makes sense after the possible lag inducing changes were committed.
3700 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3701 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3702 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3703 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3704 * @return bool Success (able to connect and no timeouts reached)
3706 function wfWaitForSlaves(
3707 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3709 // B/C: first argument used to be "max seconds of lag"; ignore such values
3710 $ifWritesSince = ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null;
3712 if ( $timeout === null ) {
3713 $timeout = ( PHP_SAPI === 'cli' ) ? 86400 : 10;
3716 // Figure out which clusters need to be checked
3717 /** @var LoadBalancer[] $lbs */
3718 $lbs = array();
3719 if ( $cluster === '*' ) {
3720 wfGetLBFactory()->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
3721 $lbs[] = $lb;
3722 } );
3723 } elseif ( $cluster !== false ) {
3724 $lbs[] = wfGetLBFactory()->getExternalLB( $cluster );
3725 } else {
3726 $lbs[] = wfGetLB( $wiki );
3729 // Get all the master positions of applicable DBs right now.
3730 // This can be faster since waiting on one cluster reduces the
3731 // time needed to wait on the next clusters.
3732 $masterPositions = array_fill( 0, count( $lbs ), false );
3733 foreach ( $lbs as $i => $lb ) {
3734 if ( $lb->getServerCount() <= 1 ) {
3735 // Bug 27975 - Don't try to wait for slaves if there are none
3736 // Prevents permission error when getting master position
3737 continue;
3738 } elseif ( $ifWritesSince && $lb->lastMasterChangeTimestamp() < $ifWritesSince ) {
3739 continue; // no writes since the last wait
3741 $masterPositions[$i] = $lb->getMasterPos();
3744 $ok = true;
3745 foreach ( $lbs as $i => $lb ) {
3746 if ( $masterPositions[$i] ) {
3747 // The DBMS may not support getMasterPos() or the whole
3748 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3749 $ok = $lb->waitForAll( $masterPositions[$i], $timeout ) && $ok;
3753 return $ok;
3757 * Count down from $seconds to zero on the terminal, with a one-second pause
3758 * between showing each number. For use in command-line scripts.
3760 * @codeCoverageIgnore
3761 * @param int $seconds
3763 function wfCountDown( $seconds ) {
3764 for ( $i = $seconds; $i >= 0; $i-- ) {
3765 if ( $i != $seconds ) {
3766 echo str_repeat( "\x08", strlen( $i + 1 ) );
3768 echo $i;
3769 flush();
3770 if ( $i ) {
3771 sleep( 1 );
3774 echo "\n";
3778 * Replace all invalid characters with -
3779 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3780 * By default, $wgIllegalFileChars = ':'
3782 * @param string $name Filename to process
3783 * @return string
3785 function wfStripIllegalFilenameChars( $name ) {
3786 global $wgIllegalFileChars;
3787 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
3788 $name = wfBaseName( $name );
3789 $name = preg_replace(
3790 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
3791 '-',
3792 $name
3794 return $name;
3798 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit
3800 * @return int Resulting value of the memory limit.
3802 function wfMemoryLimit() {
3803 global $wgMemoryLimit;
3804 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3805 if ( $memlimit != -1 ) {
3806 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3807 if ( $conflimit == -1 ) {
3808 wfDebug( "Removing PHP's memory limit\n" );
3809 MediaWiki\suppressWarnings();
3810 ini_set( 'memory_limit', $conflimit );
3811 MediaWiki\restoreWarnings();
3812 return $conflimit;
3813 } elseif ( $conflimit > $memlimit ) {
3814 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3815 MediaWiki\suppressWarnings();
3816 ini_set( 'memory_limit', $conflimit );
3817 MediaWiki\restoreWarnings();
3818 return $conflimit;
3821 return $memlimit;
3825 * Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit
3827 * @return int Prior time limit
3828 * @since 1.26
3830 function wfTransactionalTimeLimit() {
3831 global $wgTransactionalTimeLimit;
3833 $timeLimit = ini_get( 'max_execution_time' );
3834 // Note that CLI scripts use 0
3835 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
3836 set_time_limit( $wgTransactionalTimeLimit );
3839 ignore_user_abort( true ); // ignore client disconnects
3841 return $timeLimit;
3845 * Converts shorthand byte notation to integer form
3847 * @param string $string
3848 * @param int $default Returned if $string is empty
3849 * @return int
3851 function wfShorthandToInteger( $string = '', $default = -1 ) {
3852 $string = trim( $string );
3853 if ( $string === '' ) {
3854 return $default;
3856 $last = $string[strlen( $string ) - 1];
3857 $val = intval( $string );
3858 switch ( $last ) {
3859 case 'g':
3860 case 'G':
3861 $val *= 1024;
3862 // break intentionally missing
3863 case 'm':
3864 case 'M':
3865 $val *= 1024;
3866 // break intentionally missing
3867 case 'k':
3868 case 'K':
3869 $val *= 1024;
3872 return $val;
3876 * Get the normalised IETF language tag
3877 * See unit test for examples.
3879 * @param string $code The language code.
3880 * @return string The language code which complying with BCP 47 standards.
3882 function wfBCP47( $code ) {
3883 $codeSegment = explode( '-', $code );
3884 $codeBCP = array();
3885 foreach ( $codeSegment as $segNo => $seg ) {
3886 // when previous segment is x, it is a private segment and should be lc
3887 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3888 $codeBCP[$segNo] = strtolower( $seg );
3889 // ISO 3166 country code
3890 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3891 $codeBCP[$segNo] = strtoupper( $seg );
3892 // ISO 15924 script code
3893 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3894 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3895 // Use lowercase for other cases
3896 } else {
3897 $codeBCP[$segNo] = strtolower( $seg );
3900 $langCode = implode( '-', $codeBCP );
3901 return $langCode;
3905 * Get a specific cache object.
3907 * @param int|string $cacheType A CACHE_* constants, or other key in $wgObjectCaches
3908 * @return BagOStuff
3910 function wfGetCache( $cacheType ) {
3911 return ObjectCache::getInstance( $cacheType );
3915 * Get the main cache object
3917 * @return BagOStuff
3919 function wfGetMainCache() {
3920 global $wgMainCacheType;
3921 return ObjectCache::getInstance( $wgMainCacheType );
3925 * Get the cache object used by the message cache
3927 * @return BagOStuff
3929 function wfGetMessageCacheStorage() {
3930 global $wgMessageCacheType;
3931 return ObjectCache::getInstance( $wgMessageCacheType );
3935 * Get the cache object used by the parser cache
3937 * @return BagOStuff
3939 function wfGetParserCacheStorage() {
3940 global $wgParserCacheType;
3941 return ObjectCache::getInstance( $wgParserCacheType );
3945 * Call hook functions defined in $wgHooks
3947 * @param string $event Event name
3948 * @param array $args Parameters passed to hook functions
3949 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
3951 * @return bool True if no handler aborted the hook
3952 * @deprecated 1.25 - use Hooks::run
3954 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
3955 return Hooks::run( $event, $args, $deprecatedVersion );
3959 * Wrapper around php's unpack.
3961 * @param string $format The format string (See php's docs)
3962 * @param string $data A binary string of binary data
3963 * @param int|bool $length The minimum length of $data or false. This is to
3964 * prevent reading beyond the end of $data. false to disable the check.
3966 * Also be careful when using this function to read unsigned 32 bit integer
3967 * because php might make it negative.
3969 * @throws MWException If $data not long enough, or if unpack fails
3970 * @return array Associative array of the extracted data
3972 function wfUnpack( $format, $data, $length = false ) {
3973 if ( $length !== false ) {
3974 $realLen = strlen( $data );
3975 if ( $realLen < $length ) {
3976 throw new MWException( "Tried to use wfUnpack on a "
3977 . "string of length $realLen, but needed one "
3978 . "of at least length $length."
3983 MediaWiki\suppressWarnings();
3984 $result = unpack( $format, $data );
3985 MediaWiki\restoreWarnings();
3987 if ( $result === false ) {
3988 // If it cannot extract the packed data.
3989 throw new MWException( "unpack could not unpack binary data" );
3991 return $result;
3995 * Determine if an image exists on the 'bad image list'.
3997 * The format of MediaWiki:Bad_image_list is as follows:
3998 * * Only list items (lines starting with "*") are considered
3999 * * The first link on a line must be a link to a bad image
4000 * * Any subsequent links on the same line are considered to be exceptions,
4001 * i.e. articles where the image may occur inline.
4003 * @param string $name The image name to check
4004 * @param Title|bool $contextTitle The page on which the image occurs, if known
4005 * @param string $blacklist Wikitext of a file blacklist
4006 * @return bool
4008 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4009 # Handle redirects; callers almost always hit wfFindFile() anyway,
4010 # so just use that method because it has a fast process cache.
4011 $file = wfFindFile( $name ); // get the final name
4012 $name = $file ? $file->getTitle()->getDBkey() : $name;
4014 # Run the extension hook
4015 $bad = false;
4016 if ( !Hooks::run( 'BadImage', array( $name, &$bad ) ) ) {
4017 return $bad;
4020 $cache = ObjectCache::getLocalServerInstance( 'hash' );
4021 $key = wfMemcKey( 'bad-image-list', ( $blacklist === null ) ? 'default' : md5( $blacklist ) );
4022 $badImages = $cache->get( $key );
4024 if ( $badImages === false ) { // cache miss
4025 if ( $blacklist === null ) {
4026 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4028 # Build the list now
4029 $badImages = array();
4030 $lines = explode( "\n", $blacklist );
4031 foreach ( $lines as $line ) {
4032 # List items only
4033 if ( substr( $line, 0, 1 ) !== '*' ) {
4034 continue;
4037 # Find all links
4038 $m = array();
4039 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4040 continue;
4043 $exceptions = array();
4044 $imageDBkey = false;
4045 foreach ( $m[1] as $i => $titleText ) {
4046 $title = Title::newFromText( $titleText );
4047 if ( !is_null( $title ) ) {
4048 if ( $i == 0 ) {
4049 $imageDBkey = $title->getDBkey();
4050 } else {
4051 $exceptions[$title->getPrefixedDBkey()] = true;
4056 if ( $imageDBkey !== false ) {
4057 $badImages[$imageDBkey] = $exceptions;
4060 $cache->set( $key, $badImages, 60 );
4063 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
4064 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4066 return $bad;
4070 * Determine whether the client at a given source IP is likely to be able to
4071 * access the wiki via HTTPS.
4073 * @param string $ip The IPv4/6 address in the normal human-readable form
4074 * @return bool
4076 function wfCanIPUseHTTPS( $ip ) {
4077 $canDo = true;
4078 Hooks::run( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4079 return !!$canDo;
4083 * Determine input string is represents as infinity
4085 * @param string $str The string to determine
4086 * @return bool
4087 * @since 1.25
4089 function wfIsInfinity( $str ) {
4090 $infinityValues = array( 'infinite', 'indefinite', 'infinity', 'never' );
4091 return in_array( $str, $infinityValues );
4095 * Work out the IP address based on various globals
4096 * For trusted proxies, use the XFF client IP (first of the chain)
4098 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4099 * @return string
4101 function wfGetIP() {
4102 wfDeprecated( __METHOD__, '1.19' );
4103 global $wgRequest;
4104 return $wgRequest->getIP();
4108 * Checks if an IP is a trusted proxy provider.
4109 * Useful to tell if X-Forwarded-For data is possibly bogus.
4110 * Squid cache servers for the site are whitelisted.
4111 * @deprecated Since 1.24, use IP::isTrustedProxy()
4113 * @param string $ip
4114 * @return bool
4116 function wfIsTrustedProxy( $ip ) {
4117 wfDeprecated( __METHOD__, '1.24' );
4118 return IP::isTrustedProxy( $ip );
4122 * Checks if an IP matches a proxy we've configured.
4123 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4125 * @param string $ip
4126 * @return bool
4127 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4129 function wfIsConfiguredProxy( $ip ) {
4130 wfDeprecated( __METHOD__, '1.24' );
4131 return IP::isConfiguredProxy( $ip );
4135 * Returns true if these thumbnail parameters match one that MediaWiki
4136 * requests from file description pages and/or parser output.
4138 * $params is considered non-standard if they involve a non-standard
4139 * width or any non-default parameters aside from width and page number.
4140 * The number of possible files with standard parameters is far less than
4141 * that of all combinations; rate-limiting for them can thus be more generious.
4143 * @param File $file
4144 * @param array $params
4145 * @return bool
4146 * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25
4148 function wfThumbIsStandard( File $file, array $params ) {
4149 global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages;
4151 $multipliers = array( 1 );
4152 if ( $wgResponsiveImages ) {
4153 // These available sizes are hardcoded currently elsewhere in MediaWiki.
4154 // @see Linker::processResponsiveImages
4155 $multipliers[] = 1.5;
4156 $multipliers[] = 2;
4159 $handler = $file->getHandler();
4160 if ( !$handler || !isset( $params['width'] ) ) {
4161 return false;
4164 $basicParams = array();
4165 if ( isset( $params['page'] ) ) {
4166 $basicParams['page'] = $params['page'];
4169 $thumbLimits = array();
4170 $imageLimits = array();
4171 // Expand limits to account for multipliers
4172 foreach ( $multipliers as $multiplier ) {
4173 $thumbLimits = array_merge( $thumbLimits, array_map(
4174 function ( $width ) use ( $multiplier ) {
4175 return round( $width * $multiplier );
4176 }, $wgThumbLimits )
4178 $imageLimits = array_merge( $imageLimits, array_map(
4179 function ( $pair ) use ( $multiplier ) {
4180 return array(
4181 round( $pair[0] * $multiplier ),
4182 round( $pair[1] * $multiplier ),
4184 }, $wgImageLimits )
4188 // Check if the width matches one of $wgThumbLimits
4189 if ( in_array( $params['width'], $thumbLimits ) ) {
4190 $normalParams = $basicParams + array( 'width' => $params['width'] );
4191 // Append any default values to the map (e.g. "lossy", "lossless", ...)
4192 $handler->normaliseParams( $file, $normalParams );
4193 } else {
4194 // If not, then check if the width matchs one of $wgImageLimits
4195 $match = false;
4196 foreach ( $imageLimits as $pair ) {
4197 $normalParams = $basicParams + array( 'width' => $pair[0], 'height' => $pair[1] );
4198 // Decide whether the thumbnail should be scaled on width or height.
4199 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
4200 $handler->normaliseParams( $file, $normalParams );
4201 // Check if this standard thumbnail size maps to the given width
4202 if ( $normalParams['width'] == $params['width'] ) {
4203 $match = true;
4204 break;
4207 if ( !$match ) {
4208 return false; // not standard for description pages
4212 // Check that the given values for non-page, non-width, params are just defaults
4213 foreach ( $params as $key => $value ) {
4214 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
4215 return false;
4219 return true;
4223 * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
4225 * Values that exist in both values will be combined with += (all values of the array
4226 * of $newValues will be added to the values of the array of $baseArray, while values,
4227 * that exists in both, the value of $baseArray will be used).
4229 * @param array $baseArray The array where you want to add the values of $newValues to
4230 * @param array $newValues An array with new values
4231 * @return array The combined array
4232 * @since 1.26
4234 function wfArrayPlus2d( array $baseArray, array $newValues ) {
4235 // First merge items that are in both arrays
4236 foreach ( $baseArray as $name => &$groupVal ) {
4237 if ( isset( $newValues[$name] ) ) {
4238 $groupVal += $newValues[$name];
4241 // Now add items that didn't exist yet
4242 $baseArray += $newValues;
4244 return $baseArray;