3 * Global functions used everywhere.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 if ( !defined( 'MEDIAWIKI' ) ) {
24 die( "This file is part of MediaWiki, it is not a valid entry point" );
27 use Liuggio\StatsdClient\Sender\SocketSender
;
28 use MediaWiki\Logger\LoggerFactory
;
30 // Hide compatibility functions from Doxygen
34 * Compatibility functions
36 * We support PHP 5.3.3 and up.
37 * Re-implementations of newer functions or functions in non-standard
38 * PHP extensions may be included here.
41 if ( !function_exists( 'mb_substr' ) ) {
44 * @see Fallback::mb_substr
47 function mb_substr( $str, $start, $count = 'end' ) {
48 return Fallback
::mb_substr( $str, $start, $count );
53 * @see Fallback::mb_substr_split_unicode
56 function mb_substr_split_unicode( $str, $splitPos ) {
57 return Fallback
::mb_substr_split_unicode( $str, $splitPos );
61 if ( !function_exists( 'mb_strlen' ) ) {
64 * @see Fallback::mb_strlen
67 function mb_strlen( $str, $enc = '' ) {
68 return Fallback
::mb_strlen( $str, $enc );
72 if ( !function_exists( 'mb_strpos' ) ) {
75 * @see Fallback::mb_strpos
78 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
79 return Fallback
::mb_strpos( $haystack, $needle, $offset, $encoding );
83 if ( !function_exists( 'mb_strrpos' ) ) {
86 * @see Fallback::mb_strrpos
89 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
90 return Fallback
::mb_strrpos( $haystack, $needle, $offset, $encoding );
94 // gzdecode function only exists in PHP >= 5.4.0
95 // http://php.net/gzdecode
96 if ( !function_exists( 'gzdecode' ) ) {
102 function gzdecode( $data ) {
103 return gzinflate( substr( $data, 10, -8 ) );
107 // hash_equals function only exists in PHP >= 5.6.0
108 // http://php.net/hash_equals
109 if ( !function_exists( 'hash_equals' ) ) {
111 * Check whether a user-provided string is equal to a fixed-length secret string
112 * without revealing bytes of the secret string through timing differences.
114 * The usual way to compare strings (PHP's === operator or the underlying memcmp()
115 * function in C) is to compare corresponding bytes and stop at the first difference,
116 * which would take longer for a partial match than for a complete mismatch. This
117 * is not secure when one of the strings (e.g. an HMAC or token) must remain secret
118 * and the other may come from an attacker. Statistical analysis of timing measurements
119 * over many requests may allow the attacker to guess the string's bytes one at a time
120 * (and check his guesses) even if the timing differences are extremely small.
122 * When making such a security-sensitive comparison, it is essential that the sequence
123 * in which instructions are executed and memory locations are accessed not depend on
124 * the secret string's value. HOWEVER, for simplicity, we do not attempt to minimize
125 * the inevitable leakage of the string's length. That is generally known anyway as
126 * a chararacteristic of the hash function used to compute the secret value.
128 * Longer explanation: http://www.emerose.com/timing-attacks-explained
130 * @codeCoverageIgnore
131 * @param string $known_string Fixed-length secret string to compare against
132 * @param string $user_string User-provided string
133 * @return bool True if the strings are the same, false otherwise
135 function hash_equals( $known_string, $user_string ) {
136 // Strict type checking as in PHP's native implementation
137 if ( !is_string( $known_string ) ) {
138 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
139 gettype( $known_string ) . ' given', E_USER_WARNING
);
144 if ( !is_string( $user_string ) ) {
145 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
146 gettype( $user_string ) . ' given', E_USER_WARNING
);
151 $known_string_len = strlen( $known_string );
152 if ( $known_string_len !== strlen( $user_string ) ) {
157 for ( $i = 0; $i < $known_string_len; $i++
) {
158 $result |
= ord( $known_string[$i] ) ^
ord( $user_string[$i] );
161 return ( $result === 0 );
169 * This queues an extension to be loaded through
170 * the ExtensionRegistry system.
172 * @param string $ext Name of the extension to load
173 * @param string|null $path Absolute path of where to find the extension.json file
176 function wfLoadExtension( $ext, $path = null ) {
178 global $wgExtensionDirectory;
179 $path = "$wgExtensionDirectory/$ext/extension.json";
181 ExtensionRegistry
::getInstance()->queue( $path );
185 * Load multiple extensions at once
187 * Same as wfLoadExtension, but more efficient if you
188 * are loading multiple extensions.
190 * If you want to specify custom paths, you should interact with
191 * ExtensionRegistry directly.
193 * @see wfLoadExtension
194 * @param string[] $exts Array of extension names to load
197 function wfLoadExtensions( array $exts ) {
198 global $wgExtensionDirectory;
199 $registry = ExtensionRegistry
::getInstance();
200 foreach ( $exts as $ext ) {
201 $registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
208 * @see wfLoadExtension
209 * @param string $skin Name of the extension to load
210 * @param string|null $path Absolute path of where to find the skin.json file
213 function wfLoadSkin( $skin, $path = null ) {
215 global $wgStyleDirectory;
216 $path = "$wgStyleDirectory/$skin/skin.json";
218 ExtensionRegistry
::getInstance()->queue( $path );
222 * Load multiple skins at once
224 * @see wfLoadExtensions
225 * @param string[] $skins Array of extension names to load
228 function wfLoadSkins( array $skins ) {
229 global $wgStyleDirectory;
230 $registry = ExtensionRegistry
::getInstance();
231 foreach ( $skins as $skin ) {
232 $registry->queue( "$wgStyleDirectory/$skin/skin.json" );
237 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
242 function wfArrayDiff2( $a, $b ) {
243 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
247 * @param array|string $a
248 * @param array|string $b
251 function wfArrayDiff2_cmp( $a, $b ) {
252 if ( is_string( $a ) && is_string( $b ) ) {
253 return strcmp( $a, $b );
254 } elseif ( count( $a ) !== count( $b ) ) {
255 return count( $a ) < count( $b ) ?
-1 : 1;
259 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
260 $cmp = strcmp( $valueA, $valueB );
270 * Appends to second array if $value differs from that in $default
272 * @param string|int $key
273 * @param mixed $value
274 * @param mixed $default
275 * @param array $changed Array to alter
276 * @throws MWException
278 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
279 if ( is_null( $changed ) ) {
280 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
282 if ( $default[$key] !== $value ) {
283 $changed[$key] = $value;
288 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
290 * wfMergeErrorArrays(
291 * array( array( 'x' ) ),
292 * array( array( 'x', '2' ) ),
293 * array( array( 'x' ) ),
294 * array( array( 'y' ) )
303 * @param array $array1,...
306 function wfMergeErrorArrays( /*...*/ ) {
307 $args = func_get_args();
309 foreach ( $args as $errors ) {
310 foreach ( $errors as $params ) {
311 # @todo FIXME: Sometimes get nested arrays for $params,
312 # which leads to E_NOTICEs
313 $spec = implode( "\t", $params );
314 $out[$spec] = $params;
317 return array_values( $out );
321 * Insert array into another array after the specified *KEY*
323 * @param array $array The array.
324 * @param array $insert The array to insert.
325 * @param mixed $after The key to insert after
328 function wfArrayInsertAfter( array $array, array $insert, $after ) {
329 // Find the offset of the element to insert after.
330 $keys = array_keys( $array );
331 $offsetByKey = array_flip( $keys );
333 $offset = $offsetByKey[$after];
335 // Insert at the specified offset
336 $before = array_slice( $array, 0, $offset +
1, true );
337 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
339 $output = $before +
$insert +
$after;
345 * Recursively converts the parameter (an object) to an array with the same data
347 * @param object|array $objOrArray
348 * @param bool $recursive
351 function wfObjectToArray( $objOrArray, $recursive = true ) {
353 if ( is_object( $objOrArray ) ) {
354 $objOrArray = get_object_vars( $objOrArray );
356 foreach ( $objOrArray as $key => $value ) {
357 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
358 $value = wfObjectToArray( $value );
361 $array[$key] = $value;
368 * Get a random decimal value between 0 and 1, in a way
369 * not likely to give duplicate values for any realistic
370 * number of articles.
374 function wfRandom() {
375 # The maximum random value is "only" 2^31-1, so get two random
376 # values to reduce the chance of dupes
377 $max = mt_getrandmax() +
1;
378 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
384 * Get a random string containing a number of pseudo-random hex
386 * @note This is not secure, if you are trying to generate some sort
387 * of token please use MWCryptRand instead.
389 * @param int $length The length of the string to generate
393 function wfRandomString( $length = 32 ) {
395 for ( $n = 0; $n < $length; $n +
= 7 ) {
396 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
398 return substr( $str, 0, $length );
402 * We want some things to be included as literal characters in our title URLs
403 * for prettiness, which urlencode encodes by default. According to RFC 1738,
404 * all of the following should be safe:
408 * RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved
409 * character which should not be encoded. More importantly, google chrome
410 * always converts %7E back to ~, and converting it in this function can
411 * cause a redirect loop (T105265).
413 * But + is not safe because it's used to indicate a space; &= are only safe in
414 * paths and not in queries (and we don't distinguish here); ' seems kind of
415 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
416 * is reserved, we don't care. So the list we unescape is:
420 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
421 * so no fancy : for IIS7.
423 * %2F in the page titles seems to fatally break for some reason.
428 function wfUrlencode( $s ) {
431 if ( is_null( $s ) ) {
436 if ( is_null( $needle ) ) {
437 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' );
438 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
439 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
445 $s = urlencode( $s );
448 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ),
456 * This function takes two arrays as input, and returns a CGI-style string, e.g.
457 * "days=7&limit=100". Options in the first array override options in the second.
458 * Options set to null or false will not be output.
460 * @param array $array1 ( String|Array )
461 * @param array $array2 ( String|Array )
462 * @param string $prefix
465 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
466 if ( !is_null( $array2 ) ) {
467 $array1 = $array1 +
$array2;
471 foreach ( $array1 as $key => $value ) {
472 if ( !is_null( $value ) && $value !== false ) {
476 if ( $prefix !== '' ) {
477 $key = $prefix . "[$key]";
479 if ( is_array( $value ) ) {
481 foreach ( $value as $k => $v ) {
482 $cgi .= $firstTime ?
'' : '&';
483 if ( is_array( $v ) ) {
484 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
486 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
491 if ( is_object( $value ) ) {
492 $value = $value->__toString();
494 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
502 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
503 * its argument and returns the same string in array form. This allows compatibility
504 * with legacy functions that accept raw query strings instead of nice
505 * arrays. Of course, keys and values are urldecode()d.
507 * @param string $query Query string
508 * @return string[] Array version of input
510 function wfCgiToArray( $query ) {
511 if ( isset( $query[0] ) && $query[0] == '?' ) {
512 $query = substr( $query, 1 );
514 $bits = explode( '&', $query );
516 foreach ( $bits as $bit ) {
520 if ( strpos( $bit, '=' ) === false ) {
521 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
525 list( $key, $value ) = explode( '=', $bit );
527 $key = urldecode( $key );
528 $value = urldecode( $value );
529 if ( strpos( $key, '[' ) !== false ) {
530 $keys = array_reverse( explode( '[', $key ) );
531 $key = array_pop( $keys );
533 foreach ( $keys as $k ) {
534 $k = substr( $k, 0, -1 );
535 $temp = array( $k => $temp );
537 if ( isset( $ret[$key] ) ) {
538 $ret[$key] = array_merge( $ret[$key], $temp );
550 * Append a query string to an existing URL, which may or may not already
551 * have query string parameters already. If so, they will be combined.
554 * @param string|string[] $query String or associative array
557 function wfAppendQuery( $url, $query ) {
558 if ( is_array( $query ) ) {
559 $query = wfArrayToCgi( $query );
561 if ( $query != '' ) {
562 if ( false === strpos( $url, '?' ) ) {
573 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
576 * The meaning of the PROTO_* constants is as follows:
577 * PROTO_HTTP: Output a URL starting with http://
578 * PROTO_HTTPS: Output a URL starting with https://
579 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
580 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
581 * on which protocol was used for the current incoming request
582 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
583 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
584 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
586 * @todo this won't work with current-path-relative URLs
587 * like "subdir/foo.html", etc.
589 * @param string $url Either fully-qualified or a local path + query
590 * @param string $defaultProto One of the PROTO_* constants. Determines the
591 * protocol to use if $url or $wgServer is protocol-relative
592 * @return string Fully-qualified URL, current-path-relative URL or false if
593 * no valid URL can be constructed
595 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
596 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
598 if ( $defaultProto === PROTO_CANONICAL
) {
599 $serverUrl = $wgCanonicalServer;
600 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
601 // Make $wgInternalServer fall back to $wgServer if not set
602 $serverUrl = $wgInternalServer;
604 $serverUrl = $wgServer;
605 if ( $defaultProto === PROTO_CURRENT
) {
606 $defaultProto = $wgRequest->getProtocol() . '://';
610 // Analyze $serverUrl to obtain its protocol
611 $bits = wfParseUrl( $serverUrl );
612 $serverHasProto = $bits && $bits['scheme'] != '';
614 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
615 if ( $serverHasProto ) {
616 $defaultProto = $bits['scheme'] . '://';
618 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
619 // This really isn't supposed to happen. Fall back to HTTP in this
621 $defaultProto = PROTO_HTTP
;
625 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
627 if ( substr( $url, 0, 2 ) == '//' ) {
628 $url = $defaultProtoWithoutSlashes . $url;
629 } elseif ( substr( $url, 0, 1 ) == '/' ) {
630 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
631 // otherwise leave it alone.
632 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
635 $bits = wfParseUrl( $url );
637 // ensure proper port for HTTPS arrives in URL
638 // https://phabricator.wikimedia.org/T67184
639 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
640 $bits['port'] = $wgHttpsPort;
643 if ( $bits && isset( $bits['path'] ) ) {
644 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
645 return wfAssembleUrl( $bits );
649 } elseif ( substr( $url, 0, 1 ) != '/' ) {
650 # URL is a relative path
651 return wfRemoveDotSegments( $url );
654 # Expanded URL is not valid.
659 * This function will reassemble a URL parsed with wfParseURL. This is useful
660 * if you need to edit part of a URL and put it back together.
662 * This is the basic structure used (brackets contain keys for $urlParts):
663 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
665 * @todo Need to integrate this into wfExpandUrl (bug 32168)
668 * @param array $urlParts URL parts, as output from wfParseUrl
669 * @return string URL assembled from its component parts
671 function wfAssembleUrl( $urlParts ) {
674 if ( isset( $urlParts['delimiter'] ) ) {
675 if ( isset( $urlParts['scheme'] ) ) {
676 $result .= $urlParts['scheme'];
679 $result .= $urlParts['delimiter'];
682 if ( isset( $urlParts['host'] ) ) {
683 if ( isset( $urlParts['user'] ) ) {
684 $result .= $urlParts['user'];
685 if ( isset( $urlParts['pass'] ) ) {
686 $result .= ':' . $urlParts['pass'];
691 $result .= $urlParts['host'];
693 if ( isset( $urlParts['port'] ) ) {
694 $result .= ':' . $urlParts['port'];
698 if ( isset( $urlParts['path'] ) ) {
699 $result .= $urlParts['path'];
702 if ( isset( $urlParts['query'] ) ) {
703 $result .= '?' . $urlParts['query'];
706 if ( isset( $urlParts['fragment'] ) ) {
707 $result .= '#' . $urlParts['fragment'];
714 * Remove all dot-segments in the provided URL path. For example,
715 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
716 * RFC3986 section 5.2.4.
718 * @todo Need to integrate this into wfExpandUrl (bug 32168)
720 * @param string $urlPath URL path, potentially containing dot-segments
721 * @return string URL path with all dot-segments removed
723 function wfRemoveDotSegments( $urlPath ) {
726 $inputLength = strlen( $urlPath );
728 while ( $inputOffset < $inputLength ) {
729 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
730 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
731 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
732 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
735 if ( $prefixLengthTwo == './' ) {
736 # Step A, remove leading "./"
738 } elseif ( $prefixLengthThree == '../' ) {
739 # Step A, remove leading "../"
741 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
742 # Step B, replace leading "/.$" with "/"
744 $urlPath[$inputOffset] = '/';
745 } elseif ( $prefixLengthThree == '/./' ) {
746 # Step B, replace leading "/./" with "/"
748 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
749 # Step C, replace leading "/..$" with "/" and
750 # remove last path component in output
752 $urlPath[$inputOffset] = '/';
754 } elseif ( $prefixLengthFour == '/../' ) {
755 # Step C, replace leading "/../" with "/" and
756 # remove last path component in output
759 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
760 # Step D, remove "^.$"
762 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
763 # Step D, remove "^..$"
766 # Step E, move leading path segment to output
767 if ( $prefixLengthOne == '/' ) {
768 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
770 $slashPos = strpos( $urlPath, '/', $inputOffset );
772 if ( $slashPos === false ) {
773 $output .= substr( $urlPath, $inputOffset );
774 $inputOffset = $inputLength;
776 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
777 $inputOffset +
= $slashPos - $inputOffset;
782 $slashPos = strrpos( $output, '/' );
783 if ( $slashPos === false ) {
786 $output = substr( $output, 0, $slashPos );
795 * Returns a regular expression of url protocols
797 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
798 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
801 function wfUrlProtocols( $includeProtocolRelative = true ) {
802 global $wgUrlProtocols;
804 // Cache return values separately based on $includeProtocolRelative
805 static $withProtRel = null, $withoutProtRel = null;
806 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
807 if ( !is_null( $cachedValue ) ) {
811 // Support old-style $wgUrlProtocols strings, for backwards compatibility
812 // with LocalSettings files from 1.5
813 if ( is_array( $wgUrlProtocols ) ) {
814 $protocols = array();
815 foreach ( $wgUrlProtocols as $protocol ) {
816 // Filter out '//' if !$includeProtocolRelative
817 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
818 $protocols[] = preg_quote( $protocol, '/' );
822 $retval = implode( '|', $protocols );
824 // Ignore $includeProtocolRelative in this case
825 // This case exists for pre-1.6 compatibility, and we can safely assume
826 // that '//' won't appear in a pre-1.6 config because protocol-relative
827 // URLs weren't supported until 1.18
828 $retval = $wgUrlProtocols;
831 // Cache return value
832 if ( $includeProtocolRelative ) {
833 $withProtRel = $retval;
835 $withoutProtRel = $retval;
841 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
842 * you need a regex that matches all URL protocols but does not match protocol-
846 function wfUrlProtocolsWithoutProtRel() {
847 return wfUrlProtocols( false );
851 * parse_url() work-alike, but non-broken. Differences:
853 * 1) Does not raise warnings on bad URLs (just returns false).
854 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
855 * protocol-relative URLs) correctly.
856 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
858 * @param string $url A URL to parse
859 * @return string[] Bits of the URL in an associative array, per PHP docs
861 function wfParseUrl( $url ) {
862 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
864 // Protocol-relative URLs are handled really badly by parse_url(). It's so
865 // bad that the easiest way to handle them is to just prepend 'http:' and
866 // strip the protocol out later.
867 $wasRelative = substr( $url, 0, 2 ) == '//';
868 if ( $wasRelative ) {
871 MediaWiki\
suppressWarnings();
872 $bits = parse_url( $url );
873 MediaWiki\restoreWarnings
();
874 // parse_url() returns an array without scheme for some invalid URLs, e.g.
875 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
876 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
880 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
881 $bits['scheme'] = strtolower( $bits['scheme'] );
883 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
884 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
885 $bits['delimiter'] = '://';
886 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
887 $bits['delimiter'] = ':';
888 // parse_url detects for news: and mailto: the host part of an url as path
889 // We have to correct this wrong detection
890 if ( isset( $bits['path'] ) ) {
891 $bits['host'] = $bits['path'];
898 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
899 if ( !isset( $bits['host'] ) ) {
903 if ( isset( $bits['path'] ) ) {
904 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
905 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
906 $bits['path'] = '/' . $bits['path'];
913 // If the URL was protocol-relative, fix scheme and delimiter
914 if ( $wasRelative ) {
915 $bits['scheme'] = '';
916 $bits['delimiter'] = '//';
922 * Take a URL, make sure it's expanded to fully qualified, and replace any
923 * encoded non-ASCII Unicode characters with their UTF-8 original forms
924 * for more compact display and legibility for local audiences.
926 * @todo handle punycode domains too
931 function wfExpandIRI( $url ) {
932 return preg_replace_callback(
933 '/((?:%[89A-F][0-9A-F])+)/i',
934 'wfExpandIRI_callback',
940 * Private callback for wfExpandIRI
941 * @param array $matches
944 function wfExpandIRI_callback( $matches ) {
945 return urldecode( $matches[1] );
949 * Make URL indexes, appropriate for the el_index field of externallinks.
954 function wfMakeUrlIndexes( $url ) {
955 $bits = wfParseUrl( $url );
957 // Reverse the labels in the hostname, convert to lower case
958 // For emails reverse domainpart only
959 if ( $bits['scheme'] == 'mailto' ) {
960 $mailparts = explode( '@', $bits['host'], 2 );
961 if ( count( $mailparts ) === 2 ) {
962 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
964 // No domain specified, don't mangle it
967 $reversedHost = $domainpart . '@' . $mailparts[0];
969 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
971 // Add an extra dot to the end
972 // Why? Is it in wrong place in mailto links?
973 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
974 $reversedHost .= '.';
976 // Reconstruct the pseudo-URL
977 $prot = $bits['scheme'];
978 $index = $prot . $bits['delimiter'] . $reversedHost;
979 // Leave out user and password. Add the port, path, query and fragment
980 if ( isset( $bits['port'] ) ) {
981 $index .= ':' . $bits['port'];
983 if ( isset( $bits['path'] ) ) {
984 $index .= $bits['path'];
988 if ( isset( $bits['query'] ) ) {
989 $index .= '?' . $bits['query'];
991 if ( isset( $bits['fragment'] ) ) {
992 $index .= '#' . $bits['fragment'];
996 return array( "http:$index", "https:$index" );
998 return array( $index );
1003 * Check whether a given URL has a domain that occurs in a given set of domains
1004 * @param string $url URL
1005 * @param array $domains Array of domains (strings)
1006 * @return bool True if the host part of $url ends in one of the strings in $domains
1008 function wfMatchesDomainList( $url, $domains ) {
1009 $bits = wfParseUrl( $url );
1010 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1011 $host = '.' . $bits['host'];
1012 foreach ( (array)$domains as $domain ) {
1013 $domain = '.' . $domain;
1014 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
1023 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
1024 * In normal operation this is a NOP.
1026 * Controlling globals:
1027 * $wgDebugLogFile - points to the log file
1028 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
1029 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
1031 * @since 1.25 support for additional context data
1033 * @param string $text
1034 * @param string|bool $dest Unused
1035 * @param array $context Additional logging context data
1037 function wfDebug( $text, $dest = 'all', array $context = array() ) {
1038 global $wgDebugRawPage, $wgDebugLogPrefix;
1039 global $wgDebugTimestamps, $wgRequestTime;
1041 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1045 $text = trim( $text );
1047 // Inline logic from deprecated wfDebugTimer()
1048 if ( $wgDebugTimestamps ) {
1049 $context['seconds_elapsed'] = sprintf(
1051 microtime( true ) - $wgRequestTime
1053 $context['memory_used'] = sprintf(
1055 ( memory_get_usage( true ) / ( 1024 * 1024 ) )
1059 if ( $wgDebugLogPrefix !== '' ) {
1060 $context['prefix'] = $wgDebugLogPrefix;
1063 $logger = LoggerFactory
::getInstance( 'wfDebug' );
1064 $logger->debug( $text, $context );
1068 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1071 function wfIsDebugRawPage() {
1073 if ( $cache !== null ) {
1076 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1077 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1079 isset( $_SERVER['SCRIPT_NAME'] )
1080 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1091 * Get microsecond timestamps for debug logs
1093 * @deprecated since 1.25
1096 function wfDebugTimer() {
1097 global $wgDebugTimestamps, $wgRequestTime;
1099 wfDeprecated( __METHOD__
, '1.25' );
1101 if ( !$wgDebugTimestamps ) {
1105 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1106 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1107 return "$prefix $mem ";
1111 * Send a line giving PHP memory usage.
1113 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1115 function wfDebugMem( $exact = false ) {
1116 $mem = memory_get_usage();
1118 $mem = floor( $mem / 1024 ) . ' KiB';
1122 wfDebug( "Memory usage: $mem\n" );
1126 * Send a line to a supplementary debug log file, if configured, or main debug
1129 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
1130 * a string filename or an associative array mapping 'destination' to the
1131 * desired filename. The associative array may also contain a 'sample' key
1132 * with an integer value, specifying a sampling factor. Sampled log events
1133 * will be emitted with a 1 in N random chance.
1135 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1136 * @since 1.25 support for additional context data
1137 * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
1139 * @param string $logGroup
1140 * @param string $text
1141 * @param string|bool $dest Destination of the message:
1142 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1143 * - 'log': only to the log and not in HTML
1144 * - 'private': only to the specific log if set in $wgDebugLogGroups and
1145 * discarded otherwise
1146 * For backward compatibility, it can also take a boolean:
1147 * - true: same as 'all'
1148 * - false: same as 'private'
1149 * @param array $context Additional logging context data
1151 function wfDebugLog(
1152 $logGroup, $text, $dest = 'all', array $context = array()
1154 // Turn $dest into a string if it's a boolean (for b/c)
1155 if ( $dest === true ) {
1157 } elseif ( $dest === false ) {
1161 $text = trim( $text );
1163 $logger = LoggerFactory
::getInstance( $logGroup );
1164 $context['private'] = ( $dest === 'private' );
1165 $logger->info( $text, $context );
1169 * Log for database errors
1171 * @since 1.25 support for additional context data
1173 * @param string $text Database error message.
1174 * @param array $context Additional logging context data
1176 function wfLogDBError( $text, array $context = array() ) {
1177 $logger = LoggerFactory
::getInstance( 'wfLogDBError' );
1178 $logger->error( trim( $text ), $context );
1182 * Throws a warning that $function is deprecated
1184 * @param string $function
1185 * @param string|bool $version Version of MediaWiki that the function
1186 * was deprecated in (Added in 1.19).
1187 * @param string|bool $component Added in 1.19.
1188 * @param int $callerOffset How far up the call stack is the original
1189 * caller. 2 = function that called the function that called
1190 * wfDeprecated (Added in 1.20)
1194 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1195 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1199 * Send a warning either to the debug log or in a PHP error depending on
1200 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1202 * @param string $msg Message to send
1203 * @param int $callerOffset Number of items to go back in the backtrace to
1204 * find the correct caller (1 = function calling wfWarn, ...)
1205 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1206 * only used when $wgDevelopmentWarnings is true
1208 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1209 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1213 * Send a warning as a PHP error and the debug log. This is intended for logging
1214 * warnings in production. For logging development warnings, use WfWarn instead.
1216 * @param string $msg Message to send
1217 * @param int $callerOffset Number of items to go back in the backtrace to
1218 * find the correct caller (1 = function calling wfLogWarning, ...)
1219 * @param int $level PHP error level; defaults to E_USER_WARNING
1221 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1222 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1226 * Log to a file without getting "file size exceeded" signals.
1228 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1229 * send lines to the specified port, prefixed by the specified prefix and a space.
1230 * @since 1.25 support for additional context data
1232 * @param string $text
1233 * @param string $file Filename
1234 * @param array $context Additional logging context data
1235 * @throws MWException
1236 * @deprecated since 1.25 Use MediaWiki\Logger\LegacyLogger::emit or UDPTransport
1238 function wfErrorLog( $text, $file, array $context = array() ) {
1239 wfDeprecated( __METHOD__
, '1.25' );
1240 $logger = LoggerFactory
::getInstance( 'wfErrorLog' );
1241 $context['destination'] = $file;
1242 $logger->info( trim( $text ), $context );
1248 function wfLogProfilingData() {
1249 global $wgDebugLogGroups, $wgDebugRawPage;
1251 $context = RequestContext
::getMain();
1252 $request = $context->getRequest();
1254 $profiler = Profiler
::instance();
1255 $profiler->setContext( $context );
1256 $profiler->logData();
1258 $config = $context->getConfig();
1259 if ( $config->get( 'StatsdServer' ) ) {
1261 $statsdServer = explode( ':', $config->get( 'StatsdServer' ) );
1262 $statsdHost = $statsdServer[0];
1263 $statsdPort = isset( $statsdServer[1] ) ?
$statsdServer[1] : 8125;
1264 $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1265 $statsdClient = new SamplingStatsdClient( $statsdSender, true, false );
1266 $statsdClient->send( $context->getStats()->getBuffer() );
1267 } catch ( Exception
$ex ) {
1268 MWExceptionHandler
::logException( $ex );
1272 # Profiling must actually be enabled...
1273 if ( $profiler instanceof ProfilerStub
) {
1277 if ( isset( $wgDebugLogGroups['profileoutput'] )
1278 && $wgDebugLogGroups['profileoutput'] === false
1280 // Explicitly disabled
1283 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1287 $ctx = array( 'elapsed' => $request->getElapsedTime() );
1288 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1289 $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
1291 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1292 $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP'];
1294 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1295 $ctx['from'] = $_SERVER['HTTP_FROM'];
1297 if ( isset( $ctx['forwarded_for'] ) ||
1298 isset( $ctx['client_ip'] ) ||
1299 isset( $ctx['from'] ) ) {
1300 $ctx['proxy'] = $_SERVER['REMOTE_ADDR'];
1303 // Don't load $wgUser at this late stage just for statistics purposes
1304 // @todo FIXME: We can detect some anons even if it is not loaded.
1305 // See User::getId()
1306 $user = $context->getUser();
1307 $ctx['anon'] = $user->isItemLoaded( 'id' ) && $user->isAnon();
1309 // Command line script uses a FauxRequest object which does not have
1310 // any knowledge about an URL and throw an exception instead.
1312 $ctx['url'] = urldecode( $request->getRequestURL() );
1313 } catch ( Exception
$ignored ) {
1317 $ctx['output'] = $profiler->getOutput();
1319 $log = LoggerFactory
::getInstance( 'profileoutput' );
1320 $log->info( "Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx );
1324 * Increment a statistics counter
1326 * @param string $key
1330 function wfIncrStats( $key, $count = 1 ) {
1331 $stats = RequestContext
::getMain()->getStats();
1332 $stats->updateCount( $key, $count );
1336 * Check whether the wiki is in read-only mode.
1340 function wfReadOnly() {
1341 return wfReadOnlyReason() !== false;
1345 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1347 * @return string|bool String when in read-only mode; false otherwise
1349 function wfReadOnlyReason() {
1350 global $wgReadOnly, $wgReadOnlyFile;
1352 if ( $wgReadOnly === null ) {
1353 // Set $wgReadOnly for faster access next time
1354 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1355 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1357 $wgReadOnly = false;
1359 // Callers use this method to be aware that data presented to a user
1360 // may be very stale and thus allowing submissions can be problematic.
1362 if ( $wgReadOnly === false && wfGetLB()->getLaggedSlaveMode() ) {
1363 $wgReadOnly = 'The database has been automatically locked ' .
1364 'while the slave database servers catch up to the master';
1366 } catch ( DBConnectionError
$e ) {
1367 $wgReadOnly = 'The database has been automatically locked ' .
1368 'until the slave database servers become available';
1376 * Return a Language object from $langcode
1378 * @param Language|string|bool $langcode Either:
1379 * - a Language object
1380 * - code of the language to get the message for, if it is
1381 * a valid code create a language for that language, if
1382 * it is a string but not a valid code then make a basic
1384 * - a boolean: if it's false then use the global object for
1385 * the current user's language (as a fallback for the old parameter
1386 * functionality), or if it is true then use global object
1387 * for the wiki's content language.
1390 function wfGetLangObj( $langcode = false ) {
1391 # Identify which language to get or create a language object for.
1392 # Using is_object here due to Stub objects.
1393 if ( is_object( $langcode ) ) {
1394 # Great, we already have the object (hopefully)!
1398 global $wgContLang, $wgLanguageCode;
1399 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1400 # $langcode is the language code of the wikis content language object.
1401 # or it is a boolean and value is true
1406 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1407 # $langcode is the language code of user language object.
1408 # or it was a boolean and value is false
1412 $validCodes = array_keys( Language
::fetchLanguageNames() );
1413 if ( in_array( $langcode, $validCodes ) ) {
1414 # $langcode corresponds to a valid language.
1415 return Language
::factory( $langcode );
1418 # $langcode is a string, but not a valid language code; use content language.
1419 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1424 * This is the function for getting translated interface messages.
1426 * @see Message class for documentation how to use them.
1427 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1429 * This function replaces all old wfMsg* functions.
1431 * @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier
1432 * @param mixed $params,... Normal message parameters
1437 * @see Message::__construct
1439 function wfMessage( $key /*...*/ ) {
1440 $params = func_get_args();
1441 array_shift( $params );
1442 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1443 $params = $params[0];
1445 return new Message( $key, $params );
1449 * This function accepts multiple message keys and returns a message instance
1450 * for the first message which is non-empty. If all messages are empty then an
1451 * instance of the first message key is returned.
1453 * @param string|string[] $keys,... Message keys
1458 * @see Message::newFallbackSequence
1460 function wfMessageFallback( /*...*/ ) {
1461 $args = func_get_args();
1462 return call_user_func_array( 'Message::newFallbackSequence', $args );
1466 * Get a message from anywhere, for the current user language.
1468 * Use wfMsgForContent() instead if the message should NOT
1469 * change depending on the user preferences.
1471 * @deprecated since 1.18
1473 * @param string $key Lookup key for the message, usually
1474 * defined in languages/Language.php
1476 * Parameters to the message, which can be used to insert variable text into
1477 * it, can be passed to this function in the following formats:
1478 * - One per argument, starting at the second parameter
1479 * - As an array in the second parameter
1480 * These are not shown in the function definition.
1484 function wfMsg( $key ) {
1485 wfDeprecated( __METHOD__
, '1.21' );
1487 $args = func_get_args();
1488 array_shift( $args );
1489 return wfMsgReal( $key, $args );
1493 * Same as above except doesn't transform the message
1495 * @deprecated since 1.18
1497 * @param string $key
1500 function wfMsgNoTrans( $key ) {
1501 wfDeprecated( __METHOD__
, '1.21' );
1503 $args = func_get_args();
1504 array_shift( $args );
1505 return wfMsgReal( $key, $args, true, false, false );
1509 * Get a message from anywhere, for the current global language
1510 * set with $wgLanguageCode.
1512 * Use this if the message should NOT change dependent on the
1513 * language set in the user's preferences. This is the case for
1514 * most text written into logs, as well as link targets (such as
1515 * the name of the copyright policy page). Link titles, on the
1516 * other hand, should be shown in the UI language.
1518 * Note that MediaWiki allows users to change the user interface
1519 * language in their preferences, but a single installation
1520 * typically only contains content in one language.
1522 * Be wary of this distinction: If you use wfMsg() where you should
1523 * use wfMsgForContent(), a user of the software may have to
1524 * customize potentially hundreds of messages in
1525 * order to, e.g., fix a link in every possible language.
1527 * @deprecated since 1.18
1529 * @param string $key Lookup key for the message, usually
1530 * defined in languages/Language.php
1533 function wfMsgForContent( $key ) {
1534 wfDeprecated( __METHOD__
, '1.21' );
1536 global $wgForceUIMsgAsContentMsg;
1537 $args = func_get_args();
1538 array_shift( $args );
1540 if ( is_array( $wgForceUIMsgAsContentMsg )
1541 && in_array( $key, $wgForceUIMsgAsContentMsg )
1543 $forcontent = false;
1545 return wfMsgReal( $key, $args, true, $forcontent );
1549 * Same as above except doesn't transform the message
1551 * @deprecated since 1.18
1553 * @param string $key
1556 function wfMsgForContentNoTrans( $key ) {
1557 wfDeprecated( __METHOD__
, '1.21' );
1559 global $wgForceUIMsgAsContentMsg;
1560 $args = func_get_args();
1561 array_shift( $args );
1563 if ( is_array( $wgForceUIMsgAsContentMsg )
1564 && in_array( $key, $wgForceUIMsgAsContentMsg )
1566 $forcontent = false;
1568 return wfMsgReal( $key, $args, true, $forcontent, false );
1572 * Really get a message
1574 * @deprecated since 1.18
1576 * @param string $key Key to get.
1577 * @param array $args
1578 * @param bool $useDB
1579 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1580 * @param bool $transform Whether or not to transform the message.
1581 * @return string The requested message.
1583 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1584 wfDeprecated( __METHOD__
, '1.21' );
1586 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1587 $message = wfMsgReplaceArgs( $message, $args );
1592 * Fetch a message string value, but don't replace any keys yet.
1594 * @deprecated since 1.18
1596 * @param string $key
1597 * @param bool $useDB
1598 * @param string|bool $langCode Code of the language to get the message for, or
1599 * behaves as a content language switch if it is a boolean.
1600 * @param bool $transform Whether to parse magic words, etc.
1603 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1604 wfDeprecated( __METHOD__
, '1.21' );
1606 Hooks
::run( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1608 $cache = MessageCache
::singleton();
1609 $message = $cache->get( $key, $useDB, $langCode );
1610 if ( $message === false ) {
1611 $message = '<' . htmlspecialchars( $key ) . '>';
1612 } elseif ( $transform ) {
1613 $message = $cache->transform( $message );
1619 * Replace message parameter keys on the given formatted output.
1621 * @param string $message
1622 * @param array $args
1626 function wfMsgReplaceArgs( $message, $args ) {
1627 # Fix windows line-endings
1628 # Some messages are split with explode("\n", $msg)
1629 $message = str_replace( "\r", '', $message );
1631 // Replace arguments
1632 if ( count( $args ) ) {
1633 if ( is_array( $args[0] ) ) {
1634 $args = array_values( $args[0] );
1636 $replacementKeys = array();
1637 foreach ( $args as $n => $param ) {
1638 $replacementKeys['$' . ( $n +
1 )] = $param;
1640 $message = strtr( $message, $replacementKeys );
1647 * Return an HTML-escaped version of a message.
1648 * Parameter replacements, if any, are done *after* the HTML-escaping,
1649 * so parameters may contain HTML (eg links or form controls). Be sure
1650 * to pre-escape them if you really do want plaintext, or just wrap
1651 * the whole thing in htmlspecialchars().
1653 * @deprecated since 1.18
1655 * @param string $key
1656 * @param string $args,... Parameters
1659 function wfMsgHtml( $key ) {
1660 wfDeprecated( __METHOD__
, '1.21' );
1662 $args = func_get_args();
1663 array_shift( $args );
1664 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1668 * Return an HTML version of message
1669 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1670 * so parameters may contain HTML (eg links or form controls). Be sure
1671 * to pre-escape them if you really do want plaintext, or just wrap
1672 * the whole thing in htmlspecialchars().
1674 * @deprecated since 1.18
1676 * @param string $key
1677 * @param string $args,... Parameters
1680 function wfMsgWikiHtml( $key ) {
1681 wfDeprecated( __METHOD__
, '1.21' );
1683 $args = func_get_args();
1684 array_shift( $args );
1685 return wfMsgReplaceArgs(
1686 MessageCache
::singleton()->parse( wfMsgGetKey( $key ), null,
1687 /* can't be set to false */ true, /* interface */ true )->getText(),
1692 * Returns message in the requested format
1694 * @deprecated since 1.18
1696 * @param string $key Key of the message
1697 * @param array $options Processing rules.
1698 * Can take the following options:
1699 * parse: parses wikitext to HTML
1700 * parseinline: parses wikitext to HTML and removes the surrounding
1701 * p's added by parser or tidy
1702 * escape: filters message through htmlspecialchars
1703 * escapenoentities: same, but allows entity references like   through
1704 * replaceafter: parameters are substituted after parsing or escaping
1705 * parsemag: transform the message using magic phrases
1706 * content: fetch message for content language instead of interface
1707 * Also can accept a single associative argument, of the form 'language' => 'xx':
1708 * language: Language object or language code to fetch message for
1709 * (overridden by content).
1710 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1714 function wfMsgExt( $key, $options ) {
1715 wfDeprecated( __METHOD__
, '1.21' );
1717 $args = func_get_args();
1718 array_shift( $args );
1719 array_shift( $args );
1720 $options = (array)$options;
1721 $validOptions = array( 'parse', 'parseinline', 'escape', 'escapenoentities', 'replaceafter',
1722 'parsemag', 'content' );
1724 foreach ( $options as $arrayKey => $option ) {
1725 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1726 // An unknown index, neither numeric nor "language"
1727 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
1728 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option, $validOptions ) ) {
1729 // A numeric index with unknown value
1730 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
1734 if ( in_array( 'content', $options, true ) ) {
1737 $langCodeObj = null;
1738 } elseif ( array_key_exists( 'language', $options ) ) {
1739 $forContent = false;
1740 $langCode = wfGetLangObj( $options['language'] );
1741 $langCodeObj = $langCode;
1743 $forContent = false;
1745 $langCodeObj = null;
1748 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1750 if ( !in_array( 'replaceafter', $options, true ) ) {
1751 $string = wfMsgReplaceArgs( $string, $args );
1754 $messageCache = MessageCache
::singleton();
1755 $parseInline = in_array( 'parseinline', $options, true );
1756 if ( in_array( 'parse', $options, true ) ||
$parseInline ) {
1757 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1758 if ( $string instanceof ParserOutput
) {
1759 $string = $string->getText();
1762 if ( $parseInline ) {
1763 $string = Parser
::stripOuterParagraph( $string );
1765 } elseif ( in_array( 'parsemag', $options, true ) ) {
1766 $string = $messageCache->transform( $string,
1767 !$forContent, $langCodeObj );
1770 if ( in_array( 'escape', $options, true ) ) {
1771 $string = htmlspecialchars( $string );
1772 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1773 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
1776 if ( in_array( 'replaceafter', $options, true ) ) {
1777 $string = wfMsgReplaceArgs( $string, $args );
1784 * Since wfMsg() and co suck, they don't return false if the message key they
1785 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1786 * nonexistence of messages by checking the MessageCache::get() result directly.
1788 * @deprecated since 1.18. Use Message::isDisabled().
1790 * @param string $key The message key looked up
1791 * @return bool True if the message *doesn't* exist.
1793 function wfEmptyMsg( $key ) {
1794 wfDeprecated( __METHOD__
, '1.21' );
1796 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1800 * Fetch server name for use in error reporting etc.
1801 * Use real server name if available, so we know which machine
1802 * in a server farm generated the current page.
1806 function wfHostname() {
1808 if ( is_null( $host ) ) {
1810 # Hostname overriding
1811 global $wgOverrideHostname;
1812 if ( $wgOverrideHostname !== false ) {
1813 # Set static and skip any detection
1814 $host = $wgOverrideHostname;
1818 if ( function_exists( 'posix_uname' ) ) {
1819 // This function not present on Windows
1820 $uname = posix_uname();
1824 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1825 $host = $uname['nodename'];
1826 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1827 # Windows computer name
1828 $host = getenv( 'COMPUTERNAME' );
1830 # This may be a virtual server.
1831 $host = $_SERVER['SERVER_NAME'];
1838 * Returns a script tag that stores the amount of time it took MediaWiki to
1839 * handle the request in milliseconds as 'wgBackendResponseTime'.
1841 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1842 * hostname of the server handling the request.
1846 function wfReportTime() {
1847 global $wgRequestTime, $wgShowHostnames;
1849 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1850 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1851 if ( $wgShowHostnames ) {
1852 $reportVars['wgHostname'] = wfHostname();
1854 return Skin
::makeVariablesScript( $reportVars );
1858 * Safety wrapper for debug_backtrace().
1860 * Will return an empty array if debug_backtrace is disabled, otherwise
1861 * the output from debug_backtrace() (trimmed).
1863 * @param int $limit This parameter can be used to limit the number of stack frames returned
1865 * @return array Array of backtrace information
1867 function wfDebugBacktrace( $limit = 0 ) {
1868 static $disabled = null;
1870 if ( is_null( $disabled ) ) {
1871 $disabled = !function_exists( 'debug_backtrace' );
1873 wfDebug( "debug_backtrace() is disabled\n" );
1880 if ( $limit && version_compare( PHP_VERSION
, '5.4.0', '>=' ) ) {
1881 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1883 return array_slice( debug_backtrace(), 1 );
1888 * Get a debug backtrace as a string
1890 * @param bool|null $raw If true, the return value is plain text. If false, HTML.
1891 * Defaults to $wgCommandLineMode if unset.
1893 * @since 1.25 Supports $raw parameter.
1895 function wfBacktrace( $raw = null ) {
1896 global $wgCommandLineMode;
1898 if ( $raw === null ) {
1899 $raw = $wgCommandLineMode;
1903 $frameFormat = "%s line %s calls %s()\n";
1904 $traceFormat = "%s";
1906 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1907 $traceFormat = "<ul>\n%s</ul>\n";
1910 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1911 $file = !empty( $frame['file'] ) ?
basename( $frame['file'] ) : '-';
1912 $line = isset( $frame['line'] ) ?
$frame['line'] : '-';
1913 $call = $frame['function'];
1914 if ( !empty( $frame['class'] ) ) {
1915 $call = $frame['class'] . $frame['type'] . $call;
1917 return sprintf( $frameFormat, $file, $line, $call );
1918 }, wfDebugBacktrace() );
1920 return sprintf( $traceFormat, implode( '', $frames ) );
1924 * Get the name of the function which called this function
1925 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1926 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1927 * wfGetCaller( 3 ) is the parent of that.
1932 function wfGetCaller( $level = 2 ) {
1933 $backtrace = wfDebugBacktrace( $level +
1 );
1934 if ( isset( $backtrace[$level] ) ) {
1935 return wfFormatStackFrame( $backtrace[$level] );
1942 * Return a string consisting of callers in the stack. Useful sometimes
1943 * for profiling specific points.
1945 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1948 function wfGetAllCallers( $limit = 3 ) {
1949 $trace = array_reverse( wfDebugBacktrace() );
1950 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1951 $limit = count( $trace ) - 1;
1953 $trace = array_slice( $trace, -$limit - 1, $limit );
1954 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1958 * Return a string representation of frame
1960 * @param array $frame
1963 function wfFormatStackFrame( $frame ) {
1964 return isset( $frame['class'] ) ?
1965 $frame['class'] . '::' . $frame['function'] :
1969 /* Some generic result counters, pulled out of SearchEngine */
1974 * @param int $offset
1978 function wfShowingResults( $offset, $limit ) {
1979 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
1984 * @todo FIXME: We may want to blacklist some broken browsers
1986 * @param bool $force
1987 * @return bool Whereas client accept gzip compression
1989 function wfClientAcceptsGzip( $force = false ) {
1990 static $result = null;
1991 if ( $result === null ||
$force ) {
1993 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1994 # @todo FIXME: We may want to blacklist some broken browsers
1997 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1998 $_SERVER['HTTP_ACCEPT_ENCODING'],
2002 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2006 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2015 * Obtain the offset and limit values from the request string;
2016 * used in special pages
2018 * @param int $deflimit Default limit if none supplied
2019 * @param string $optionname Name of a user preference to check against
2021 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2023 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2025 wfDeprecated( __METHOD__
, '1.24' );
2026 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2030 * Escapes the given text so that it may be output using addWikiText()
2031 * without any linking, formatting, etc. making its way through. This
2032 * is achieved by substituting certain characters with HTML entities.
2033 * As required by the callers, "<nowiki>" is not used.
2035 * @param string $text Text to be escaped
2038 function wfEscapeWikiText( $text ) {
2039 static $repl = null, $repl2 = null;
2040 if ( $repl === null ) {
2042 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
2043 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
2044 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
2045 "\n#" => "\n#", "\r#" => "\r#",
2046 "\n*" => "\n*", "\r*" => "\r*",
2047 "\n:" => "\n:", "\r:" => "\r:",
2048 "\n " => "\n ", "\r " => "\r ",
2049 "\n\n" => "\n ", "\r\n" => " \n",
2050 "\n\r" => "\n ", "\r\r" => "\r ",
2051 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
2052 "\n----" => "\n----", "\r----" => "\r----",
2053 '__' => '__', '://' => '://',
2056 // We have to catch everything "\s" matches in PCRE
2057 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2058 $repl["$magic "] = "$magic ";
2059 $repl["$magic\t"] = "$magic	";
2060 $repl["$magic\r"] = "$magic ";
2061 $repl["$magic\n"] = "$magic ";
2062 $repl["$magic\f"] = "$magic";
2065 // And handle protocols that don't use "://"
2066 global $wgUrlProtocols;
2068 foreach ( $wgUrlProtocols as $prot ) {
2069 if ( substr( $prot, -1 ) === ':' ) {
2070 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2073 $repl2 = $repl2 ?
'/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2075 $text = substr( strtr( "\n$text", $repl ), 1 );
2076 $text = preg_replace( $repl2, '$1:', $text );
2081 * Sets dest to source and returns the original value of dest
2082 * If source is NULL, it just returns the value, it doesn't set the variable
2083 * If force is true, it will set the value even if source is NULL
2085 * @param mixed $dest
2086 * @param mixed $source
2087 * @param bool $force
2090 function wfSetVar( &$dest, $source, $force = false ) {
2092 if ( !is_null( $source ) ||
$force ) {
2099 * As for wfSetVar except setting a bit
2103 * @param bool $state
2107 function wfSetBit( &$dest, $bit, $state = true ) {
2108 $temp = (bool)( $dest & $bit );
2109 if ( !is_null( $state ) ) {
2120 * A wrapper around the PHP function var_export().
2121 * Either print it or add it to the regular output ($wgOut).
2123 * @param mixed $var A PHP variable to dump.
2125 function wfVarDump( $var ) {
2127 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2128 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
2131 $wgOut->addHTML( $s );
2136 * Provide a simple HTTP error.
2138 * @param int|string $code
2139 * @param string $label
2140 * @param string $desc
2142 function wfHttpError( $code, $label, $desc ) {
2144 HttpStatus
::header( $code );
2147 $wgOut->sendCacheControl();
2150 header( 'Content-type: text/html; charset=utf-8' );
2151 print '<!DOCTYPE html>' .
2152 '<html><head><title>' .
2153 htmlspecialchars( $label ) .
2154 '</title></head><body><h1>' .
2155 htmlspecialchars( $label ) .
2157 nl2br( htmlspecialchars( $desc ) ) .
2158 "</p></body></html>\n";
2162 * Clear away any user-level output buffers, discarding contents.
2164 * Suitable for 'starting afresh', for instance when streaming
2165 * relatively large amounts of data without buffering, or wanting to
2166 * output image files without ob_gzhandler's compression.
2168 * The optional $resetGzipEncoding parameter controls suppression of
2169 * the Content-Encoding header sent by ob_gzhandler; by default it
2170 * is left. See comments for wfClearOutputBuffers() for why it would
2173 * Note that some PHP configuration options may add output buffer
2174 * layers which cannot be removed; these are left in place.
2176 * @param bool $resetGzipEncoding
2178 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2179 if ( $resetGzipEncoding ) {
2180 // Suppress Content-Encoding and Content-Length
2181 // headers from 1.10+s wfOutputHandler
2182 global $wgDisableOutputCompression;
2183 $wgDisableOutputCompression = true;
2185 while ( $status = ob_get_status() ) {
2186 if ( isset( $status['flags'] ) ) {
2187 $flags = PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_REMOVABLE
;
2188 $deleteable = ( $status['flags'] & $flags ) === $flags;
2189 } elseif ( isset( $status['del'] ) ) {
2190 $deleteable = $status['del'];
2192 // Guess that any PHP-internal setting can't be removed.
2193 $deleteable = $status['type'] !== 0; /* PHP_OUTPUT_HANDLER_INTERNAL */
2195 if ( !$deleteable ) {
2196 // Give up, and hope the result doesn't break
2200 if ( $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ) {
2201 // Unit testing barrier to prevent this function from breaking PHPUnit.
2204 if ( !ob_end_clean() ) {
2205 // Could not remove output buffer handler; abort now
2206 // to avoid getting in some kind of infinite loop.
2209 if ( $resetGzipEncoding ) {
2210 if ( $status['name'] == 'ob_gzhandler' ) {
2211 // Reset the 'Content-Encoding' field set by this handler
2212 // so we can start fresh.
2213 header_remove( 'Content-Encoding' );
2221 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2223 * Clear away output buffers, but keep the Content-Encoding header
2224 * produced by ob_gzhandler, if any.
2226 * This should be used for HTTP 304 responses, where you need to
2227 * preserve the Content-Encoding header of the real result, but
2228 * also need to suppress the output of ob_gzhandler to keep to spec
2229 * and avoid breaking Firefox in rare cases where the headers and
2230 * body are broken over two packets.
2232 function wfClearOutputBuffers() {
2233 wfResetOutputBuffers( false );
2237 * Converts an Accept-* header into an array mapping string values to quality
2240 * @param string $accept
2241 * @param string $def Default
2242 * @return float[] Associative array of string => float pairs
2244 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2245 # No arg means accept anything (per HTTP spec)
2247 return array( $def => 1.0 );
2252 $parts = explode( ',', $accept );
2254 foreach ( $parts as $part ) {
2255 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2256 $values = explode( ';', trim( $part ) );
2258 if ( count( $values ) == 1 ) {
2259 $prefs[$values[0]] = 1.0;
2260 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2261 $prefs[$values[0]] = floatval( $match[1] );
2269 * Checks if a given MIME type matches any of the keys in the given
2270 * array. Basic wildcards are accepted in the array keys.
2272 * Returns the matching MIME type (or wildcard) if a match, otherwise
2275 * @param string $type
2276 * @param array $avail
2280 function mimeTypeMatch( $type, $avail ) {
2281 if ( array_key_exists( $type, $avail ) ) {
2284 $parts = explode( '/', $type );
2285 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2286 return $parts[0] . '/*';
2287 } elseif ( array_key_exists( '*/*', $avail ) ) {
2296 * Returns the 'best' match between a client's requested internet media types
2297 * and the server's list of available types. Each list should be an associative
2298 * array of type to preference (preference is a float between 0.0 and 1.0).
2299 * Wildcards in the types are acceptable.
2301 * @param array $cprefs Client's acceptable type list
2302 * @param array $sprefs Server's offered types
2305 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2306 * XXX: generalize to negotiate other stuff
2308 function wfNegotiateType( $cprefs, $sprefs ) {
2311 foreach ( array_keys( $sprefs ) as $type ) {
2312 $parts = explode( '/', $type );
2313 if ( $parts[1] != '*' ) {
2314 $ckey = mimeTypeMatch( $type, $cprefs );
2316 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2321 foreach ( array_keys( $cprefs ) as $type ) {
2322 $parts = explode( '/', $type );
2323 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2324 $skey = mimeTypeMatch( $type, $sprefs );
2326 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2334 foreach ( array_keys( $combine ) as $type ) {
2335 if ( $combine[$type] > $bestq ) {
2337 $bestq = $combine[$type];
2345 * Reference-counted warning suppression
2347 * @deprecated since 1.26, use MediaWiki\suppressWarnings() directly
2350 function wfSuppressWarnings( $end = false ) {
2351 MediaWiki\
suppressWarnings( $end );
2355 * @deprecated since 1.26, use MediaWiki\restoreWarnings() directly
2356 * Restore error level to previous value
2358 function wfRestoreWarnings() {
2359 MediaWiki\
suppressWarnings( true );
2362 # Autodetect, convert and provide timestamps of various types
2365 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2367 define( 'TS_UNIX', 0 );
2370 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2372 define( 'TS_MW', 1 );
2375 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2377 define( 'TS_DB', 2 );
2380 * RFC 2822 format, for E-mail and HTTP headers
2382 define( 'TS_RFC2822', 3 );
2385 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2387 * This is used by Special:Export
2389 define( 'TS_ISO_8601', 4 );
2392 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2394 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2395 * DateTime tag and page 36 for the DateTimeOriginal and
2396 * DateTimeDigitized tags.
2398 define( 'TS_EXIF', 5 );
2401 * Oracle format time.
2403 define( 'TS_ORACLE', 6 );
2406 * Postgres format time.
2408 define( 'TS_POSTGRES', 7 );
2411 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2413 define( 'TS_ISO_8601_BASIC', 9 );
2416 * Get a timestamp string in one of various formats
2418 * @param mixed $outputtype A timestamp in one of the supported formats, the
2419 * function will autodetect which format is supplied and act accordingly.
2420 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2421 * @return string|bool String / false The same date in the format specified in $outputtype or false
2423 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2425 $timestamp = new MWTimestamp( $ts );
2426 return $timestamp->getTimestamp( $outputtype );
2427 } catch ( TimestampException
$e ) {
2428 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2434 * Return a formatted timestamp, or null if input is null.
2435 * For dealing with nullable timestamp columns in the database.
2437 * @param int $outputtype
2441 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2442 if ( is_null( $ts ) ) {
2445 return wfTimestamp( $outputtype, $ts );
2450 * Convenience function; returns MediaWiki timestamp for the present time.
2454 function wfTimestampNow() {
2456 return wfTimestamp( TS_MW
, time() );
2460 * Check if the operating system is Windows
2462 * @return bool True if it's Windows, false otherwise.
2464 function wfIsWindows() {
2465 static $isWindows = null;
2466 if ( $isWindows === null ) {
2467 $isWindows = strtoupper( substr( PHP_OS
, 0, 3 ) ) === 'WIN';
2473 * Check if we are running under HHVM
2477 function wfIsHHVM() {
2478 return defined( 'HHVM_VERSION' );
2482 * Tries to get the system directory for temporary files. First
2483 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2484 * environment variables are then checked in sequence, and if none are
2485 * set try sys_get_temp_dir().
2487 * NOTE: When possible, use instead the tmpfile() function to create
2488 * temporary files to avoid race conditions on file creation, etc.
2492 function wfTempDir() {
2493 global $wgTmpDirectory;
2495 if ( $wgTmpDirectory !== false ) {
2496 return $wgTmpDirectory;
2499 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2501 foreach ( $tmpDir as $tmp ) {
2502 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2506 return sys_get_temp_dir();
2510 * Make directory, and make all parent directories if they don't exist
2512 * @param string $dir Full path to directory to create
2513 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2514 * @param string $caller Optional caller param for debugging.
2515 * @throws MWException
2518 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2519 global $wgDirectoryMode;
2521 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2522 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2525 if ( !is_null( $caller ) ) {
2526 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2529 if ( strval( $dir ) === '' ||
is_dir( $dir ) ) {
2533 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2535 if ( is_null( $mode ) ) {
2536 $mode = $wgDirectoryMode;
2539 // Turn off the normal warning, we're doing our own below
2540 MediaWiki\
suppressWarnings();
2541 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2542 MediaWiki\restoreWarnings
();
2545 //directory may have been created on another request since we last checked
2546 if ( is_dir( $dir ) ) {
2550 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2551 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2557 * Remove a directory and all its content.
2558 * Does not hide error.
2559 * @param string $dir
2561 function wfRecursiveRemoveDir( $dir ) {
2562 wfDebug( __FUNCTION__
. "( $dir )\n" );
2563 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2564 if ( is_dir( $dir ) ) {
2565 $objects = scandir( $dir );
2566 foreach ( $objects as $object ) {
2567 if ( $object != "." && $object != ".." ) {
2568 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2569 wfRecursiveRemoveDir( $dir . '/' . $object );
2571 unlink( $dir . '/' . $object );
2581 * @param int $nr The number to format
2582 * @param int $acc The number of digits after the decimal point, default 2
2583 * @param bool $round Whether or not to round the value, default true
2586 function wfPercent( $nr, $acc = 2, $round = true ) {
2587 $ret = sprintf( "%.${acc}f", $nr );
2588 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2592 * Safety wrapper around ini_get() for boolean settings.
2593 * The values returned from ini_get() are pre-normalized for settings
2594 * set via php.ini or php_flag/php_admin_flag... but *not*
2595 * for those set via php_value/php_admin_value.
2597 * It's fairly common for people to use php_value instead of php_flag,
2598 * which can leave you with an 'off' setting giving a false positive
2599 * for code that just takes the ini_get() return value as a boolean.
2601 * To make things extra interesting, setting via php_value accepts
2602 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2603 * Unrecognized values go false... again opposite PHP's own coercion
2604 * from string to bool.
2606 * Luckily, 'properly' set settings will always come back as '0' or '1',
2607 * so we only have to worry about them and the 'improper' settings.
2609 * I frickin' hate PHP... :P
2611 * @param string $setting
2614 function wfIniGetBool( $setting ) {
2615 $val = strtolower( ini_get( $setting ) );
2616 // 'on' and 'true' can't have whitespace around them, but '1' can.
2620 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2624 * Windows-compatible version of escapeshellarg()
2625 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2626 * function puts single quotes in regardless of OS.
2628 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2629 * earlier distro releases of PHP)
2631 * @param string ... strings to escape and glue together, or a single array of strings parameter
2634 function wfEscapeShellArg( /*...*/ ) {
2635 wfInitShellLocale();
2637 $args = func_get_args();
2638 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
2639 // If only one argument has been passed, and that argument is an array,
2640 // treat it as a list of arguments
2641 $args = reset( $args );
2646 foreach ( $args as $arg ) {
2653 if ( wfIsWindows() ) {
2654 // Escaping for an MSVC-style command line parser and CMD.EXE
2655 // @codingStandardsIgnoreStart For long URLs
2657 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2658 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2661 // Double the backslashes before any double quotes. Escape the double quotes.
2662 // @codingStandardsIgnoreEnd
2663 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2666 foreach ( $tokens as $token ) {
2667 if ( $iteration %
2 == 1 ) {
2668 // Delimiter, a double quote preceded by zero or more slashes
2669 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2670 } elseif ( $iteration %
4 == 2 ) {
2671 // ^ in $token will be outside quotes, need to be escaped
2672 $arg .= str_replace( '^', '^^', $token );
2673 } else { // $iteration % 4 == 0
2674 // ^ in $token will appear inside double quotes, so leave as is
2679 // Double the backslashes before the end of the string, because
2680 // we will soon add a quote
2682 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2683 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2686 // Add surrounding quotes
2687 $retVal .= '"' . $arg . '"';
2689 $retVal .= escapeshellarg( $arg );
2696 * Check if wfShellExec() is effectively disabled via php.ini config
2698 * @return bool|string False or one of (safemode,disabled)
2701 function wfShellExecDisabled() {
2702 static $disabled = null;
2703 if ( is_null( $disabled ) ) {
2704 if ( wfIniGetBool( 'safe_mode' ) ) {
2705 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2706 $disabled = 'safemode';
2707 } elseif ( !function_exists( 'proc_open' ) ) {
2708 wfDebug( "proc_open() is disabled\n" );
2709 $disabled = 'disabled';
2718 * Execute a shell command, with time and memory limits mirrored from the PHP
2719 * configuration if supported.
2721 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2722 * or an array of unescaped arguments, in which case each value will be escaped
2723 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2724 * @param null|mixed &$retval Optional, will receive the program's exit code.
2725 * (non-zero is usually failure). If there is an error from
2726 * read, select, or proc_open(), this will be set to -1.
2727 * @param array $environ Optional environment variables which should be
2728 * added to the executed command environment.
2729 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2730 * this overwrites the global wgMaxShell* limits.
2731 * @param array $options Array of options:
2732 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2733 * including errors from limit.sh
2734 * - profileMethod: By default this function will profile based on the calling
2735 * method. Set this to a string for an alternative method to profile from
2737 * @return string Collected stdout as a string
2739 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2740 $limits = array(), $options = array()
2742 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2743 $wgMaxShellWallClockTime, $wgShellCgroup;
2745 $disabled = wfShellExecDisabled();
2748 return $disabled == 'safemode' ?
2749 'Unable to run external programs in safe mode.' :
2750 'Unable to run external programs, proc_open() is disabled.';
2753 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2754 $profileMethod = isset( $options['profileMethod'] ) ?
$options['profileMethod'] : wfGetCaller();
2756 wfInitShellLocale();
2759 foreach ( $environ as $k => $v ) {
2760 if ( wfIsWindows() ) {
2761 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2762 * appear in the environment variable, so we must use carat escaping as documented in
2763 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2764 * Note however that the quote isn't listed there, but is needed, and the parentheses
2765 * are listed there but doesn't appear to need it.
2767 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2769 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2770 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2772 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2775 if ( is_array( $cmd ) ) {
2776 $cmd = wfEscapeShellArg( $cmd );
2779 $cmd = $envcmd . $cmd;
2781 $useLogPipe = false;
2782 if ( is_executable( '/bin/bash' ) ) {
2783 $time = intval( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2784 if ( isset( $limits['walltime'] ) ) {
2785 $wallTime = intval( $limits['walltime'] );
2786 } elseif ( isset( $limits['time'] ) ) {
2789 $wallTime = intval( $wgMaxShellWallClockTime );
2791 $mem = intval( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2792 $filesize = intval( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2794 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2795 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2796 escapeshellarg( $cmd ) . ' ' .
2798 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2799 "MW_CPU_LIMIT=$time; " .
2800 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2801 "MW_MEM_LIMIT=$mem; " .
2802 "MW_FILE_SIZE_LIMIT=$filesize; " .
2803 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2804 "MW_USE_LOG_PIPE=yes"
2807 } elseif ( $includeStderr ) {
2810 } elseif ( $includeStderr ) {
2813 wfDebug( "wfShellExec: $cmd\n" );
2816 0 => array( 'file', 'php://stdin', 'r' ),
2817 1 => array( 'pipe', 'w' ),
2818 2 => array( 'file', 'php://stderr', 'w' ) );
2819 if ( $useLogPipe ) {
2820 $desc[3] = array( 'pipe', 'w' );
2823 $scoped = Profiler
::instance()->scopedProfileIn( __FUNCTION__
. '-' . $profileMethod );
2824 $proc = proc_open( $cmd, $desc, $pipes );
2826 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2830 $outBuffer = $logBuffer = '';
2831 $emptyArray = array();
2835 // According to the documentation, it is possible for stream_select()
2836 // to fail due to EINTR. I haven't managed to induce this in testing
2837 // despite sending various signals. If it did happen, the error
2838 // message would take the form:
2840 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2842 // where [4] is the value of the macro EINTR and "Interrupted system
2843 // call" is string which according to the Linux manual is "possibly"
2844 // localised according to LC_MESSAGES.
2845 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2846 $eintrMessage = "stream_select(): unable to select [$eintr]";
2848 // Build a table mapping resource IDs to pipe FDs to work around a
2849 // PHP 5.3 issue in which stream_select() does not preserve array keys
2850 // <https://bugs.php.net/bug.php?id=53427>.
2852 foreach ( $pipes as $fd => $pipe ) {
2853 $fds[(int)$pipe] = $fd;
2860 while ( $running === true ||
$numReadyPipes !== 0 ) {
2862 $status = proc_get_status( $proc );
2863 // If the process has terminated, switch to nonblocking selects
2864 // for getting any data still waiting to be read.
2865 if ( !$status['running'] ) {
2871 $readyPipes = $pipes;
2874 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2875 @trigger_error
( '' );
2876 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
2877 if ( $numReadyPipes === false ) {
2878 // @codingStandardsIgnoreEnd
2879 $error = error_get_last();
2880 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2883 trigger_error( $error['message'], E_USER_WARNING
);
2884 $logMsg = $error['message'];
2888 foreach ( $readyPipes as $pipe ) {
2889 $block = fread( $pipe, 65536 );
2890 $fd = $fds[(int)$pipe];
2891 if ( $block === '' ) {
2893 fclose( $pipes[$fd] );
2894 unset( $pipes[$fd] );
2898 } elseif ( $block === false ) {
2900 $logMsg = "Error reading from pipe";
2902 } elseif ( $fd == 1 ) {
2904 $outBuffer .= $block;
2905 } elseif ( $fd == 3 ) {
2907 $logBuffer .= $block;
2908 if ( strpos( $block, "\n" ) !== false ) {
2909 $lines = explode( "\n", $logBuffer );
2910 $logBuffer = array_pop( $lines );
2911 foreach ( $lines as $line ) {
2912 wfDebugLog( 'exec', $line );
2919 foreach ( $pipes as $pipe ) {
2923 // Use the status previously collected if possible, since proc_get_status()
2924 // just calls waitpid() which will not return anything useful the second time.
2926 $status = proc_get_status( $proc );
2929 if ( $logMsg !== false ) {
2930 // Read/select error
2932 proc_close( $proc );
2933 } elseif ( $status['signaled'] ) {
2934 $logMsg = "Exited with signal {$status['termsig']}";
2935 $retval = 128 +
$status['termsig'];
2936 proc_close( $proc );
2938 if ( $status['running'] ) {
2939 $retval = proc_close( $proc );
2941 $retval = $status['exitcode'];
2942 proc_close( $proc );
2944 if ( $retval == 127 ) {
2945 $logMsg = "Possibly missing executable file";
2946 } elseif ( $retval >= 129 && $retval <= 192 ) {
2947 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2951 if ( $logMsg !== false ) {
2952 wfDebugLog( 'exec', "$logMsg: $cmd" );
2959 * Execute a shell command, returning both stdout and stderr. Convenience
2960 * function, as all the arguments to wfShellExec can become unwieldy.
2962 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2963 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2964 * or an array of unescaped arguments, in which case each value will be escaped
2965 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2966 * @param null|mixed &$retval Optional, will receive the program's exit code.
2967 * (non-zero is usually failure)
2968 * @param array $environ Optional environment variables which should be
2969 * added to the executed command environment.
2970 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2971 * this overwrites the global wgMaxShell* limits.
2972 * @return string Collected stdout and stderr as a string
2974 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2975 return wfShellExec( $cmd, $retval, $environ, $limits,
2976 array( 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ) );
2980 * Workaround for http://bugs.php.net/bug.php?id=45132
2981 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2983 function wfInitShellLocale() {
2984 static $done = false;
2989 global $wgShellLocale;
2990 if ( !wfIniGetBool( 'safe_mode' ) ) {
2991 putenv( "LC_CTYPE=$wgShellLocale" );
2992 setlocale( LC_CTYPE
, $wgShellLocale );
2997 * Generate a shell-escaped command line string to run a MediaWiki cli script.
2998 * Note that $parameters should be a flat array and an option with an argument
2999 * should consist of two consecutive items in the array (do not use "--option value").
3001 * @param string $script MediaWiki cli script path
3002 * @param array $parameters Arguments and options to the script
3003 * @param array $options Associative array of options:
3004 * 'php': The path to the php executable
3005 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3008 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3010 // Give site config file a chance to run the script in a wrapper.
3011 // The caller may likely want to call wfBasename() on $script.
3012 Hooks
::run( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3013 $cmd = isset( $options['php'] ) ?
array( $options['php'] ) : array( $wgPhpCli );
3014 if ( isset( $options['wrapper'] ) ) {
3015 $cmd[] = $options['wrapper'];
3018 // Escape each parameter for shell
3019 return wfEscapeShellArg( array_merge( $cmd, $parameters ) );
3023 * wfMerge attempts to merge differences between three texts.
3024 * Returns true for a clean merge and false for failure or a conflict.
3026 * @param string $old
3027 * @param string $mine
3028 * @param string $yours
3029 * @param string $result
3032 function wfMerge( $old, $mine, $yours, &$result ) {
3035 # This check may also protect against code injection in
3036 # case of broken installations.
3037 MediaWiki\
suppressWarnings();
3038 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3039 MediaWiki\restoreWarnings
();
3041 if ( !$haveDiff3 ) {
3042 wfDebug( "diff3 not found\n" );
3046 # Make temporary files
3048 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3049 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3050 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3052 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3053 # a newline character. To avoid this, we normalize the trailing whitespace before
3054 # creating the diff.
3056 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3057 fclose( $oldtextFile );
3058 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3059 fclose( $mytextFile );
3060 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3061 fclose( $yourtextFile );
3063 # Check for a conflict
3064 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '--overlap-only', $mytextName,
3065 $oldtextName, $yourtextName );
3066 $handle = popen( $cmd, 'r' );
3068 if ( fgets( $handle, 1024 ) ) {
3076 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '-e', '--merge', $mytextName,
3077 $oldtextName, $yourtextName );
3078 $handle = popen( $cmd, 'r' );
3081 $data = fread( $handle, 8192 );
3082 if ( strlen( $data ) == 0 ) {
3088 unlink( $mytextName );
3089 unlink( $oldtextName );
3090 unlink( $yourtextName );
3092 if ( $result === '' && $old !== '' && !$conflict ) {
3093 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3100 * Returns unified plain-text diff of two texts.
3101 * "Useful" for machine processing of diffs.
3103 * @deprecated since 1.25, use DiffEngine/UnifiedDiffFormatter directly
3105 * @param string $before The text before the changes.
3106 * @param string $after The text after the changes.
3107 * @param string $params Command-line options for the diff command.
3108 * @return string Unified diff of $before and $after
3110 function wfDiff( $before, $after, $params = '-u' ) {
3111 if ( $before == $after ) {
3116 MediaWiki\
suppressWarnings();
3117 $haveDiff = $wgDiff && file_exists( $wgDiff );
3118 MediaWiki\restoreWarnings
();
3120 # This check may also protect against code injection in
3121 # case of broken installations.
3123 wfDebug( "diff executable not found\n" );
3124 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3125 $format = new UnifiedDiffFormatter();
3126 return $format->format( $diffs );
3129 # Make temporary files
3131 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3132 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3134 fwrite( $oldtextFile, $before );
3135 fclose( $oldtextFile );
3136 fwrite( $newtextFile, $after );
3137 fclose( $newtextFile );
3139 // Get the diff of the two files
3140 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3142 $h = popen( $cmd, 'r' );
3144 unlink( $oldtextName );
3145 unlink( $newtextName );
3146 throw new Exception( __METHOD__
. '(): popen() failed' );
3152 $data = fread( $h, 8192 );
3153 if ( strlen( $data ) == 0 ) {
3161 unlink( $oldtextName );
3162 unlink( $newtextName );
3164 // Kill the --- and +++ lines. They're not useful.
3165 $diff_lines = explode( "\n", $diff );
3166 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
3167 unset( $diff_lines[0] );
3169 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
3170 unset( $diff_lines[1] );
3173 $diff = implode( "\n", $diff_lines );
3179 * This function works like "use VERSION" in Perl, the program will die with a
3180 * backtrace if the current version of PHP is less than the version provided
3182 * This is useful for extensions which due to their nature are not kept in sync
3183 * with releases, and might depend on other versions of PHP than the main code
3185 * Note: PHP might die due to parsing errors in some cases before it ever
3186 * manages to call this function, such is life
3188 * @see perldoc -f use
3190 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3191 * @throws MWException
3193 function wfUsePHP( $req_ver ) {
3194 $php_ver = PHP_VERSION
;
3196 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3197 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3202 * This function works like "use VERSION" in Perl except it checks the version
3203 * of MediaWiki, the program will die with a backtrace if the current version
3204 * of MediaWiki is less than the version provided.
3206 * This is useful for extensions which due to their nature are not kept in sync
3209 * Note: Due to the behavior of PHP's version_compare() which is used in this
3210 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3211 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3212 * targeted version number. For example if you wanted to allow any variation
3213 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3214 * not result in the same comparison due to the internal logic of
3215 * version_compare().
3217 * @see perldoc -f use
3219 * @deprecated since 1.26, use the "requires' property of extension.json
3220 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3221 * @throws MWException
3223 function wfUseMW( $req_ver ) {
3226 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3227 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3232 * Return the final portion of a pathname.
3233 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3234 * http://bugs.php.net/bug.php?id=33898
3236 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3237 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3239 * @param string $path
3240 * @param string $suffix String to remove if present
3243 function wfBaseName( $path, $suffix = '' ) {
3244 if ( $suffix == '' ) {
3247 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3251 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3259 * Generate a relative path name to the given file.
3260 * May explode on non-matching case-insensitive paths,
3261 * funky symlinks, etc.
3263 * @param string $path Absolute destination path including target filename
3264 * @param string $from Absolute source path, directory only
3267 function wfRelativePath( $path, $from ) {
3268 // Normalize mixed input on Windows...
3269 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
3270 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
3272 // Trim trailing slashes -- fix for drive root
3273 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
3274 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
3276 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
3277 $against = explode( DIRECTORY_SEPARATOR
, $from );
3279 if ( $pieces[0] !== $against[0] ) {
3280 // Non-matching Windows drive letters?
3281 // Return a full path.
3285 // Trim off common prefix
3286 while ( count( $pieces ) && count( $against )
3287 && $pieces[0] == $against[0] ) {
3288 array_shift( $pieces );
3289 array_shift( $against );
3292 // relative dots to bump us to the parent
3293 while ( count( $against ) ) {
3294 array_unshift( $pieces, '..' );
3295 array_shift( $against );
3298 array_push( $pieces, wfBaseName( $path ) );
3300 return implode( DIRECTORY_SEPARATOR
, $pieces );
3304 * Convert an arbitrarily-long digit string from one numeric base
3305 * to another, optionally zero-padding to a minimum column width.
3307 * Supports base 2 through 36; digit values 10-36 are represented
3308 * as lowercase letters a-z. Input is case-insensitive.
3310 * @param string $input Input number
3311 * @param int $sourceBase Base of the input number
3312 * @param int $destBase Desired base of the output
3313 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3314 * @param bool $lowercase Whether to output in lowercase or uppercase
3315 * @param string $engine Either "gmp", "bcmath", or "php"
3316 * @return string|bool The output number as a string, or false on error
3318 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3319 $lowercase = true, $engine = 'auto'
3321 $input = (string)$input;
3327 $sourceBase != (int)$sourceBase ||
3328 $destBase != (int)$destBase ||
3329 $pad != (int)$pad ||
3331 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3338 static $baseChars = array(
3339 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3340 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3341 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3342 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3343 34 => 'y', 35 => 'z',
3345 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3346 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3347 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3348 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3349 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3350 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3353 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' ||
$engine == 'gmp' ) ) {
3354 // Removing leading zeros works around broken base detection code in
3355 // some PHP versions (see <https://bugs.php.net/bug.php?id=50175> and
3356 // <https://bugs.php.net/bug.php?id=55398>).
3357 $result = gmp_strval( gmp_init( ltrim( $input, '0' ) ?
: '0', $sourceBase ), $destBase );
3358 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' ||
$engine == 'bcmath' ) ) {
3360 foreach ( str_split( strtolower( $input ) ) as $char ) {
3361 $decimal = bcmul( $decimal, $sourceBase );
3362 $decimal = bcadd( $decimal, $baseChars[$char] );
3365 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3366 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3367 $result .= $baseChars[bcmod( $decimal, $destBase )];
3369 // @codingStandardsIgnoreEnd
3371 $result = strrev( $result );
3373 $inDigits = array();
3374 foreach ( str_split( strtolower( $input ) ) as $char ) {
3375 $inDigits[] = $baseChars[$char];
3378 // Iterate over the input, modulo-ing out an output digit
3379 // at a time until input is gone.
3381 while ( $inDigits ) {
3383 $workDigits = array();
3386 foreach ( $inDigits as $digit ) {
3387 $work *= $sourceBase;
3390 if ( $workDigits ||
$work >= $destBase ) {
3391 $workDigits[] = (int)( $work / $destBase );
3396 // All that division leaves us with a remainder,
3397 // which is conveniently our next output digit.
3398 $result .= $baseChars[$work];
3401 $inDigits = $workDigits;
3404 $result = strrev( $result );
3407 if ( !$lowercase ) {
3408 $result = strtoupper( $result );
3411 return str_pad( $result, $pad, '0', STR_PAD_LEFT
);
3415 * Check if there is sufficient entropy in php's built-in session generation
3417 * @return bool True = there is sufficient entropy
3419 function wfCheckEntropy() {
3421 ( wfIsWindows() && version_compare( PHP_VERSION
, '5.3.3', '>=' ) )
3422 ||
ini_get( 'session.entropy_file' )
3424 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3428 * Override session_id before session startup if php's built-in
3429 * session generation code is not secure.
3431 function wfFixSessionID() {
3432 // If the cookie or session id is already set we already have a session and should abort
3433 if ( isset( $_COOKIE[session_name()] ) ||
session_id() ) {
3437 // PHP's built-in session entropy is enabled if:
3438 // - entropy_file is set or you're on Windows with php 5.3.3+
3439 // - AND entropy_length is > 0
3440 // We treat it as disabled if it doesn't have an entropy length of at least 32
3441 $entropyEnabled = wfCheckEntropy();
3443 // If built-in entropy is not enabled or not sufficient override PHP's
3444 // built in session id generation code
3445 if ( !$entropyEnabled ) {
3446 wfDebug( __METHOD__
. ": PHP's built in entropy is disabled or not sufficient, " .
3447 "overriding session id generation using our cryptrand source.\n" );
3448 session_id( MWCryptRand
::generateHex( 32 ) );
3453 * Reset the session_id
3457 function wfResetSessionID() {
3458 global $wgCookieSecure;
3459 $oldSessionId = session_id();
3460 $cookieParams = session_get_cookie_params();
3461 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3462 session_regenerate_id( false );
3466 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
3469 $newSessionId = session_id();
3473 * Initialise php session
3475 * @param bool $sessionId
3477 function wfSetupSession( $sessionId = false ) {
3478 global $wgSessionsInObjectCache, $wgSessionHandler;
3479 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
3481 if ( $wgSessionsInObjectCache ) {
3482 ObjectCacheSessionHandler
::install();
3483 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3484 # Only set this if $wgSessionHandler isn't null and session.save_handler
3485 # hasn't already been set to the desired value (that causes errors)
3486 ini_set( 'session.save_handler', $wgSessionHandler );
3489 session_set_cookie_params(
3490 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3491 session_cache_limiter( 'private, must-revalidate' );
3493 session_id( $sessionId );
3498 MediaWiki\
suppressWarnings();
3500 MediaWiki\restoreWarnings
();
3502 if ( $wgSessionsInObjectCache ) {
3503 ObjectCacheSessionHandler
::renewCurrentSession();
3508 * Get an object from the precompiled serialized directory
3510 * @param string $name
3511 * @return mixed The variable on success, false on failure
3513 function wfGetPrecompiledData( $name ) {
3516 $file = "$IP/serialized/$name";
3517 if ( file_exists( $file ) ) {
3518 $blob = file_get_contents( $file );
3520 return unserialize( $blob );
3527 * Make a cache key for the local wiki.
3529 * @param string $args,...
3532 function wfMemcKey( /*...*/ ) {
3533 global $wgCachePrefix;
3534 $prefix = $wgCachePrefix === false ?
wfWikiID() : $wgCachePrefix;
3535 $args = func_get_args();
3536 $key = $prefix . ':' . implode( ':', $args );
3537 return strtr( $key, ' ', '_' );
3541 * Make a cache key for a foreign DB.
3543 * Must match what wfMemcKey() would produce in context of the foreign wiki.
3546 * @param string $prefix
3547 * @param string $args,...
3550 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3551 $args = array_slice( func_get_args(), 2 );
3553 // Match wfWikiID() logic
3554 $key = "$db-$prefix:" . implode( ':', $args );
3556 $key = $db . ':' . implode( ':', $args );
3558 return strtr( $key, ' ', '_' );
3562 * Make a cache key with database-agnostic prefix.
3564 * Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix
3565 * instead. Must have a prefix as otherwise keys that use a database name
3566 * in the first segment will clash with wfMemcKey/wfForeignMemcKey.
3569 * @param string $args,...
3572 function wfGlobalCacheKey( /*...*/ ) {
3573 $args = func_get_args();
3574 $key = 'global:' . implode( ':', $args );
3575 return strtr( $key, ' ', '_' );
3579 * Get an ASCII string identifying this wiki
3580 * This is used as a prefix in memcached keys
3584 function wfWikiID() {
3585 global $wgDBprefix, $wgDBname;
3586 if ( $wgDBprefix ) {
3587 return "$wgDBname-$wgDBprefix";
3594 * Split a wiki ID into DB name and table prefix
3596 * @param string $wiki
3600 function wfSplitWikiID( $wiki ) {
3601 $bits = explode( '-', $wiki, 2 );
3602 if ( count( $bits ) < 2 ) {
3609 * Get a Database object.
3611 * @param int $db Index of the connection to get. May be DB_MASTER for the
3612 * master (for write queries), DB_SLAVE for potentially lagged read
3613 * queries, or an integer >= 0 for a particular server.
3615 * @param string|string[] $groups Query groups. An array of group names that this query
3616 * belongs to. May contain a single string if the query is only
3619 * @param string|bool $wiki The wiki ID, or false for the current wiki
3621 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3622 * will always return the same object, unless the underlying connection or load
3623 * balancer is manually destroyed.
3625 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3626 * updater to ensure that a proper database is being updated.
3628 * @return DatabaseBase
3630 function wfGetDB( $db, $groups = array(), $wiki = false ) {
3631 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3635 * Get a load balancer object.
3637 * @param string|bool $wiki Wiki ID, or false for the current wiki
3638 * @return LoadBalancer
3640 function wfGetLB( $wiki = false ) {
3641 return wfGetLBFactory()->getMainLB( $wiki );
3645 * Get the load balancer factory object
3649 function wfGetLBFactory() {
3650 return LBFactory
::singleton();
3655 * Shortcut for RepoGroup::singleton()->findFile()
3657 * @param string $title String or Title object
3658 * @param array $options Associative array of options (see RepoGroup::findFile)
3659 * @return File|bool File, or false if the file does not exist
3661 function wfFindFile( $title, $options = array() ) {
3662 return RepoGroup
::singleton()->findFile( $title, $options );
3666 * Get an object referring to a locally registered file.
3667 * Returns a valid placeholder object if the file does not exist.
3669 * @param Title|string $title
3670 * @return LocalFile|null A File, or null if passed an invalid Title
3672 function wfLocalFile( $title ) {
3673 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3677 * Should low-performance queries be disabled?
3680 * @codeCoverageIgnore
3682 function wfQueriesMustScale() {
3683 global $wgMiserMode;
3685 ||
( SiteStats
::pages() > 100000
3686 && SiteStats
::edits() > 1000000
3687 && SiteStats
::users() > 10000 );
3691 * Get the path to a specified script file, respecting file
3692 * extensions; this is a wrapper around $wgScriptExtension etc.
3693 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3695 * @param string $script Script filename, sans extension
3698 function wfScript( $script = 'index' ) {
3699 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3700 if ( $script === 'index' ) {
3702 } elseif ( $script === 'load' ) {
3703 return $wgLoadScript;
3705 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3710 * Get the script URL.
3712 * @return string Script URL
3714 function wfGetScriptUrl() {
3715 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3717 # as it was called, minus the query string.
3719 # Some sites use Apache rewrite rules to handle subdomains,
3720 # and have PHP set up in a weird way that causes PHP_SELF
3721 # to contain the rewritten URL instead of the one that the
3722 # outside world sees.
3724 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3725 # provides containing the "before" URL.
3726 return $_SERVER['SCRIPT_NAME'];
3728 return $_SERVER['URL'];
3733 * Convenience function converts boolean values into "true"
3734 * or "false" (string) values
3736 * @param bool $value
3739 function wfBoolToStr( $value ) {
3740 return $value ?
'true' : 'false';
3744 * Get a platform-independent path to the null file, e.g. /dev/null
3748 function wfGetNull() {
3749 return wfIsWindows() ?
'NUL' : '/dev/null';
3753 * Waits for the slaves to catch up to the master position
3755 * Use this when updating very large numbers of rows, as in maintenance scripts,
3756 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
3758 * By default this waits on the main DB cluster of the current wiki.
3759 * If $cluster is set to "*" it will wait on all DB clusters, including
3760 * external ones. If the lag being waiting on is caused by the code that
3761 * does this check, it makes since to use $ifWritesSince, particularly if
3762 * cluster is "*", to avoid excess overhead.
3764 * Never call this function after a big DB write that is still in a transaction.
3765 * This only makes sense after the possible lag inducing changes were committed.
3767 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3768 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3769 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3770 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3771 * @return bool Success (able to connect and no timeouts reached)
3773 function wfWaitForSlaves(
3774 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3776 // B/C: first argument used to be "max seconds of lag"; ignore such values
3777 $ifWritesSince = ( $ifWritesSince > 1e9
) ?
$ifWritesSince : null;
3779 if ( $timeout === null ) {
3780 $timeout = ( PHP_SAPI
=== 'cli' ) ?
86400 : 10;
3783 // Figure out which clusters need to be checked
3784 /** @var LoadBalancer[] $lbs */
3786 if ( $cluster === '*' ) {
3787 wfGetLBFactory()->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
3790 } elseif ( $cluster !== false ) {
3791 $lbs[] = wfGetLBFactory()->getExternalLB( $cluster );
3793 $lbs[] = wfGetLB( $wiki );
3796 // Get all the master positions of applicable DBs right now.
3797 // This can be faster since waiting on one cluster reduces the
3798 // time needed to wait on the next clusters.
3799 $masterPositions = array_fill( 0, count( $lbs ), false );
3800 foreach ( $lbs as $i => $lb ) {
3801 if ( $lb->getServerCount() <= 1 ) {
3802 // Bug 27975 - Don't try to wait for slaves if there are none
3803 // Prevents permission error when getting master position
3805 } elseif ( $ifWritesSince && $lb->lastMasterChangeTimestamp() < $ifWritesSince ) {
3806 continue; // no writes since the last wait
3808 $masterPositions[$i] = $lb->getMasterPos();
3812 foreach ( $lbs as $i => $lb ) {
3813 if ( $masterPositions[$i] ) {
3814 // The DBMS may not support getMasterPos() or the whole
3815 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3816 $ok = $lb->waitForAll( $masterPositions[$i], $timeout ) && $ok;
3824 * Count down from $seconds to zero on the terminal, with a one-second pause
3825 * between showing each number. For use in command-line scripts.
3827 * @codeCoverageIgnore
3828 * @param int $seconds
3830 function wfCountDown( $seconds ) {
3831 for ( $i = $seconds; $i >= 0; $i-- ) {
3832 if ( $i != $seconds ) {
3833 echo str_repeat( "\x08", strlen( $i +
1 ) );
3845 * Replace all invalid characters with -
3846 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3847 * By default, $wgIllegalFileChars = ':'
3849 * @param string $name Filename to process
3852 function wfStripIllegalFilenameChars( $name ) {
3853 global $wgIllegalFileChars;
3854 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3855 $name = wfBaseName( $name );
3856 $name = preg_replace(
3857 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3865 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit
3867 * @return int Resulting value of the memory limit.
3869 function wfMemoryLimit() {
3870 global $wgMemoryLimit;
3871 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3872 if ( $memlimit != -1 ) {
3873 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3874 if ( $conflimit == -1 ) {
3875 wfDebug( "Removing PHP's memory limit\n" );
3876 MediaWiki\
suppressWarnings();
3877 ini_set( 'memory_limit', $conflimit );
3878 MediaWiki\restoreWarnings
();
3880 } elseif ( $conflimit > $memlimit ) {
3881 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3882 MediaWiki\
suppressWarnings();
3883 ini_set( 'memory_limit', $conflimit );
3884 MediaWiki\restoreWarnings
();
3892 * Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit
3894 * @return int Prior time limit
3897 function wfTransactionalTimeLimit() {
3898 global $wgTransactionalTimeLimit;
3900 $timeLimit = ini_get( 'max_execution_time' );
3901 // Note that CLI scripts use 0
3902 if ( $timeLimit > 0 && $wgTransactionalTimeLimit > $timeLimit ) {
3903 set_time_limit( $wgTransactionalTimeLimit );
3906 ignore_user_abort( true ); // ignore client disconnects
3912 * Converts shorthand byte notation to integer form
3914 * @param string $string
3917 function wfShorthandToInteger( $string = '' ) {
3918 $string = trim( $string );
3919 if ( $string === '' ) {
3922 $last = $string[strlen( $string ) - 1];
3923 $val = intval( $string );
3928 // break intentionally missing
3932 // break intentionally missing
3942 * Get the normalised IETF language tag
3943 * See unit test for examples.
3945 * @param string $code The language code.
3946 * @return string The language code which complying with BCP 47 standards.
3948 function wfBCP47( $code ) {
3949 $codeSegment = explode( '-', $code );
3951 foreach ( $codeSegment as $segNo => $seg ) {
3952 // when previous segment is x, it is a private segment and should be lc
3953 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3954 $codeBCP[$segNo] = strtolower( $seg );
3955 // ISO 3166 country code
3956 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3957 $codeBCP[$segNo] = strtoupper( $seg );
3958 // ISO 15924 script code
3959 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3960 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3961 // Use lowercase for other cases
3963 $codeBCP[$segNo] = strtolower( $seg );
3966 $langCode = implode( '-', $codeBCP );
3971 * Get a specific cache object.
3973 * @param int|string $cacheType A CACHE_* constants, or other key in $wgObjectCaches
3976 function wfGetCache( $cacheType ) {
3977 return ObjectCache
::getInstance( $cacheType );
3981 * Get the main cache object
3985 function wfGetMainCache() {
3986 global $wgMainCacheType;
3987 return ObjectCache
::getInstance( $wgMainCacheType );
3991 * Get the cache object used by the message cache
3995 function wfGetMessageCacheStorage() {
3996 global $wgMessageCacheType;
3997 return ObjectCache
::getInstance( $wgMessageCacheType );
4001 * Get the cache object used by the parser cache
4005 function wfGetParserCacheStorage() {
4006 global $wgParserCacheType;
4007 return ObjectCache
::getInstance( $wgParserCacheType );
4011 * Call hook functions defined in $wgHooks
4013 * @param string $event Event name
4014 * @param array $args Parameters passed to hook functions
4015 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
4017 * @return bool True if no handler aborted the hook
4018 * @deprecated 1.25 - use Hooks::run
4020 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
4021 return Hooks
::run( $event, $args, $deprecatedVersion );
4025 * Wrapper around php's unpack.
4027 * @param string $format The format string (See php's docs)
4028 * @param string $data A binary string of binary data
4029 * @param int|bool $length The minimum length of $data or false. This is to
4030 * prevent reading beyond the end of $data. false to disable the check.
4032 * Also be careful when using this function to read unsigned 32 bit integer
4033 * because php might make it negative.
4035 * @throws MWException If $data not long enough, or if unpack fails
4036 * @return array Associative array of the extracted data
4038 function wfUnpack( $format, $data, $length = false ) {
4039 if ( $length !== false ) {
4040 $realLen = strlen( $data );
4041 if ( $realLen < $length ) {
4042 throw new MWException( "Tried to use wfUnpack on a "
4043 . "string of length $realLen, but needed one "
4044 . "of at least length $length."
4049 MediaWiki\
suppressWarnings();
4050 $result = unpack( $format, $data );
4051 MediaWiki\restoreWarnings
();
4053 if ( $result === false ) {
4054 // If it cannot extract the packed data.
4055 throw new MWException( "unpack could not unpack binary data" );
4061 * Determine if an image exists on the 'bad image list'.
4063 * The format of MediaWiki:Bad_image_list is as follows:
4064 * * Only list items (lines starting with "*") are considered
4065 * * The first link on a line must be a link to a bad image
4066 * * Any subsequent links on the same line are considered to be exceptions,
4067 * i.e. articles where the image may occur inline.
4069 * @param string $name The image name to check
4070 * @param Title|bool $contextTitle The page on which the image occurs, if known
4071 * @param string $blacklist Wikitext of a file blacklist
4074 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4076 $redirectTitle = RepoGroup
::singleton()->checkRedirect( Title
::makeTitle( NS_FILE
, $name ) );
4077 if ( $redirectTitle ) {
4078 $name = $redirectTitle->getDBkey();
4081 # Run the extension hook
4083 if ( !Hooks
::run( 'BadImage', array( $name, &$bad ) ) ) {
4087 $cache = ObjectCache
::newAccelerator( 'hash' );
4088 $key = wfMemcKey( 'bad-image-list', ( $blacklist === null ) ?
'default' : md5( $blacklist ) );
4089 $badImages = $cache->get( $key );
4091 if ( $badImages === false ) { // cache miss
4092 if ( $blacklist === null ) {
4093 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4095 # Build the list now
4096 $badImages = array();
4097 $lines = explode( "\n", $blacklist );
4098 foreach ( $lines as $line ) {
4100 if ( substr( $line, 0, 1 ) !== '*' ) {
4106 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4110 $exceptions = array();
4111 $imageDBkey = false;
4112 foreach ( $m[1] as $i => $titleText ) {
4113 $title = Title
::newFromText( $titleText );
4114 if ( !is_null( $title ) ) {
4116 $imageDBkey = $title->getDBkey();
4118 $exceptions[$title->getPrefixedDBkey()] = true;
4123 if ( $imageDBkey !== false ) {
4124 $badImages[$imageDBkey] = $exceptions;
4127 $cache->set( $key, $badImages, 60 );
4130 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
4131 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4137 * Determine whether the client at a given source IP is likely to be able to
4138 * access the wiki via HTTPS.
4140 * @param string $ip The IPv4/6 address in the normal human-readable form
4143 function wfCanIPUseHTTPS( $ip ) {
4145 Hooks
::run( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4150 * Determine input string is represents as infinity
4152 * @param string $str The string to determine
4156 function wfIsInfinity( $str ) {
4157 $infinityValues = array( 'infinite', 'indefinite', 'infinity', 'never' );
4158 return in_array( $str, $infinityValues );
4162 * Work out the IP address based on various globals
4163 * For trusted proxies, use the XFF client IP (first of the chain)
4165 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4168 function wfGetIP() {
4169 wfDeprecated( __METHOD__
, '1.19' );
4171 return $wgRequest->getIP();
4175 * Checks if an IP is a trusted proxy provider.
4176 * Useful to tell if X-Forwarded-For data is possibly bogus.
4177 * Squid cache servers for the site are whitelisted.
4178 * @deprecated Since 1.24, use IP::isTrustedProxy()
4183 function wfIsTrustedProxy( $ip ) {
4184 wfDeprecated( __METHOD__
, '1.24' );
4185 return IP
::isTrustedProxy( $ip );
4189 * Checks if an IP matches a proxy we've configured.
4190 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4194 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4196 function wfIsConfiguredProxy( $ip ) {
4197 wfDeprecated( __METHOD__
, '1.24' );
4198 return IP
::isConfiguredProxy( $ip );
4202 * Returns true if these thumbnail parameters match one that MediaWiki
4203 * requests from file description pages and/or parser output.
4205 * $params is considered non-standard if they involve a non-standard
4206 * width or any non-default parameters aside from width and page number.
4207 * The number of possible files with standard parameters is far less than
4208 * that of all combinations; rate-limiting for them can thus be more generious.
4211 * @param array $params
4213 * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25
4215 function wfThumbIsStandard( File
$file, array $params ) {
4216 global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages;
4218 $multipliers = array( 1 );
4219 if ( $wgResponsiveImages ) {
4220 // These available sizes are hardcoded currently elsewhere in MediaWiki.
4221 // @see Linker::processResponsiveImages
4222 $multipliers[] = 1.5;
4226 $handler = $file->getHandler();
4227 if ( !$handler ||
!isset( $params['width'] ) ) {
4231 $basicParams = array();
4232 if ( isset( $params['page'] ) ) {
4233 $basicParams['page'] = $params['page'];
4236 $thumbLimits = array();
4237 $imageLimits = array();
4238 // Expand limits to account for multipliers
4239 foreach ( $multipliers as $multiplier ) {
4240 $thumbLimits = array_merge( $thumbLimits, array_map(
4241 function ( $width ) use ( $multiplier ) {
4242 return round( $width * $multiplier );
4245 $imageLimits = array_merge( $imageLimits, array_map(
4246 function ( $pair ) use ( $multiplier ) {
4248 round( $pair[0] * $multiplier ),
4249 round( $pair[1] * $multiplier ),
4255 // Check if the width matches one of $wgThumbLimits
4256 if ( in_array( $params['width'], $thumbLimits ) ) {
4257 $normalParams = $basicParams +
array( 'width' => $params['width'] );
4258 // Append any default values to the map (e.g. "lossy", "lossless", ...)
4259 $handler->normaliseParams( $file, $normalParams );
4261 // If not, then check if the width matchs one of $wgImageLimits
4263 foreach ( $imageLimits as $pair ) {
4264 $normalParams = $basicParams +
array( 'width' => $pair[0], 'height' => $pair[1] );
4265 // Decide whether the thumbnail should be scaled on width or height.
4266 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
4267 $handler->normaliseParams( $file, $normalParams );
4268 // Check if this standard thumbnail size maps to the given width
4269 if ( $normalParams['width'] == $params['width'] ) {
4275 return false; // not standard for description pages
4279 // Check that the given values for non-page, non-width, params are just defaults
4280 foreach ( $params as $key => $value ) {
4281 if ( !isset( $normalParams[$key] ) ||
$normalParams[$key] != $value ) {
4290 * Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
4292 * Values that exist in both values will be combined with += (all values of the array
4293 * of $newValues will be added to the values of the array of $baseArray, while values,
4294 * that exists in both, the value of $baseArray will be used).
4296 * @param array $baseArray The array where you want to add the values of $newValues to
4297 * @param array $newValues An array with new values
4298 * @return array The combined array
4301 function wfArrayPlus2d( array $baseArray, array $newValues ) {
4302 // First merge items that are in both arrays
4303 foreach ( $baseArray as $name => &$groupVal ) {
4304 if ( isset( $newValues[$name] ) ) {
4305 $groupVal +
= $newValues[$name];
4308 // Now add items that didn't exist yet
4309 $baseArray +
= $newValues;