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 // Hide compatibility functions from Doxygen
31 * Compatibility functions
33 * We support PHP 5.3.2 and up.
34 * Re-implementations of newer functions or functions in non-standard
35 * PHP extensions may be included here.
38 if ( !function_exists( 'mb_substr' ) ) {
41 * @see Fallback::mb_substr
44 function mb_substr( $str, $start, $count = 'end' ) {
45 return Fallback
::mb_substr( $str, $start, $count );
50 * @see Fallback::mb_substr_split_unicode
53 function mb_substr_split_unicode( $str, $splitPos ) {
54 return Fallback
::mb_substr_split_unicode( $str, $splitPos );
58 if ( !function_exists( 'mb_strlen' ) ) {
61 * @see Fallback::mb_strlen
64 function mb_strlen( $str, $enc = '' ) {
65 return Fallback
::mb_strlen( $str, $enc );
69 if ( !function_exists( 'mb_strpos' ) ) {
72 * @see Fallback::mb_strpos
75 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
76 return Fallback
::mb_strpos( $haystack, $needle, $offset, $encoding );
80 if ( !function_exists( 'mb_strrpos' ) ) {
83 * @see Fallback::mb_strrpos
86 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
87 return Fallback
::mb_strrpos( $haystack, $needle, $offset, $encoding );
91 // gzdecode function only exists in PHP >= 5.4.0
92 // http://php.net/gzdecode
93 if ( !function_exists( 'gzdecode' ) ) {
99 function gzdecode( $data ) {
100 return gzinflate( substr( $data, 10, -8 ) );
104 // hash_equals function only exists in PHP >= 5.6.0
105 if ( !function_exists( 'hash_equals' ) ) {
107 * Check whether a user-provided string is equal to a fixed-length secret without
108 * revealing bytes of the secret through timing differences.
110 * This timing guarantee -- that a partial match takes the same time as a complete
111 * mismatch -- is why this function is used in some security-sensitive parts of the code.
112 * For example, it shouldn't be possible to guess an HMAC signature one byte at a time.
114 * Longer explanation: http://www.emerose.com/timing-attacks-explained
116 * @codeCoverageIgnore
117 * @param string $known_string Fixed-length secret to compare against
118 * @param string $user_string User-provided string
119 * @return bool True if the strings are the same, false otherwise
121 function hash_equals( $known_string, $user_string ) {
122 // Strict type checking as in PHP's native implementation
123 if ( !is_string( $known_string ) ) {
124 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
125 gettype( $known_string ) . ' given', E_USER_WARNING
);
130 if ( !is_string( $user_string ) ) {
131 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
132 gettype( $user_string ) . ' given', E_USER_WARNING
);
137 // Note that we do one thing PHP doesn't: try to avoid leaking information about
138 // relative lengths of $known_string and $user_string, and of multiple $known_strings.
139 // However, lengths may still inevitably leak through, for example, CPU cache misses.
140 $known_string_len = strlen( $known_string );
141 $user_string_len = strlen( $user_string );
142 $result = $known_string_len ^
$user_string_len;
143 for ( $i = 0; $i < $user_string_len; $i++
) {
144 $result |
= ord( $known_string[$i %
$known_string_len] ) ^
ord( $user_string[$i] );
147 return ( $result === 0 );
153 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
158 function wfArrayDiff2( $a, $b ) {
159 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
163 * @param array|string $a
164 * @param array|string $b
167 function wfArrayDiff2_cmp( $a, $b ) {
168 if ( is_string( $a ) && is_string( $b ) ) {
169 return strcmp( $a, $b );
170 } elseif ( count( $a ) !== count( $b ) ) {
171 return count( $a ) < count( $b ) ?
-1 : 1;
175 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
176 $cmp = strcmp( $valueA, $valueB );
186 * Appends to second array if $value differs from that in $default
188 * @param string|int $key
189 * @param mixed $value
190 * @param mixed $default
191 * @param array $changed Array to alter
192 * @throws MWException
194 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
195 if ( is_null( $changed ) ) {
196 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
198 if ( $default[$key] !== $value ) {
199 $changed[$key] = $value;
204 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
206 * wfMergeErrorArrays(
207 * array( array( 'x' ) ),
208 * array( array( 'x', '2' ) ),
209 * array( array( 'x' ) ),
210 * array( array( 'y' ) )
219 * @param array $array1,...
222 function wfMergeErrorArrays( /*...*/ ) {
223 $args = func_get_args();
225 foreach ( $args as $errors ) {
226 foreach ( $errors as $params ) {
227 # @todo FIXME: Sometimes get nested arrays for $params,
228 # which leads to E_NOTICEs
229 $spec = implode( "\t", $params );
230 $out[$spec] = $params;
233 return array_values( $out );
237 * Insert array into another array after the specified *KEY*
239 * @param array $array The array.
240 * @param array $insert The array to insert.
241 * @param mixed $after The key to insert after
244 function wfArrayInsertAfter( array $array, array $insert, $after ) {
245 // Find the offset of the element to insert after.
246 $keys = array_keys( $array );
247 $offsetByKey = array_flip( $keys );
249 $offset = $offsetByKey[$after];
251 // Insert at the specified offset
252 $before = array_slice( $array, 0, $offset +
1, true );
253 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
255 $output = $before +
$insert +
$after;
261 * Recursively converts the parameter (an object) to an array with the same data
263 * @param object|array $objOrArray
264 * @param bool $recursive
267 function wfObjectToArray( $objOrArray, $recursive = true ) {
269 if ( is_object( $objOrArray ) ) {
270 $objOrArray = get_object_vars( $objOrArray );
272 foreach ( $objOrArray as $key => $value ) {
273 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
274 $value = wfObjectToArray( $value );
277 $array[$key] = $value;
284 * Get a random decimal value between 0 and 1, in a way
285 * not likely to give duplicate values for any realistic
286 * number of articles.
290 function wfRandom() {
291 # The maximum random value is "only" 2^31-1, so get two random
292 # values to reduce the chance of dupes
293 $max = mt_getrandmax() +
1;
294 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
300 * Get a random string containing a number of pseudo-random hex
302 * @note This is not secure, if you are trying to generate some sort
303 * of token please use MWCryptRand instead.
305 * @param int $length The length of the string to generate
309 function wfRandomString( $length = 32 ) {
311 for ( $n = 0; $n < $length; $n +
= 7 ) {
312 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
314 return substr( $str, 0, $length );
318 * We want some things to be included as literal characters in our title URLs
319 * for prettiness, which urlencode encodes by default. According to RFC 1738,
320 * all of the following should be safe:
324 * But + is not safe because it's used to indicate a space; &= are only safe in
325 * paths and not in queries (and we don't distinguish here); ' seems kind of
326 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
327 * is reserved, we don't care. So the list we unescape is:
331 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
332 * so no fancy : for IIS7.
334 * %2F in the page titles seems to fatally break for some reason.
339 function wfUrlencode( $s ) {
342 if ( is_null( $s ) ) {
347 if ( is_null( $needle ) ) {
348 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
349 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
350 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
356 $s = urlencode( $s );
359 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
367 * This function takes two arrays as input, and returns a CGI-style string, e.g.
368 * "days=7&limit=100". Options in the first array override options in the second.
369 * Options set to null or false will not be output.
371 * @param array $array1 ( String|Array )
372 * @param array $array2 ( String|Array )
373 * @param string $prefix
376 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
377 if ( !is_null( $array2 ) ) {
378 $array1 = $array1 +
$array2;
382 foreach ( $array1 as $key => $value ) {
383 if ( !is_null( $value ) && $value !== false ) {
387 if ( $prefix !== '' ) {
388 $key = $prefix . "[$key]";
390 if ( is_array( $value ) ) {
392 foreach ( $value as $k => $v ) {
393 $cgi .= $firstTime ?
'' : '&';
394 if ( is_array( $v ) ) {
395 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
397 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
402 if ( is_object( $value ) ) {
403 $value = $value->__toString();
405 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
413 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
414 * its argument and returns the same string in array form. This allows compatibility
415 * with legacy functions that accept raw query strings instead of nice
416 * arrays. Of course, keys and values are urldecode()d.
418 * @param string $query Query string
419 * @return string[] Array version of input
421 function wfCgiToArray( $query ) {
422 if ( isset( $query[0] ) && $query[0] == '?' ) {
423 $query = substr( $query, 1 );
425 $bits = explode( '&', $query );
427 foreach ( $bits as $bit ) {
431 if ( strpos( $bit, '=' ) === false ) {
432 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
436 list( $key, $value ) = explode( '=', $bit );
438 $key = urldecode( $key );
439 $value = urldecode( $value );
440 if ( strpos( $key, '[' ) !== false ) {
441 $keys = array_reverse( explode( '[', $key ) );
442 $key = array_pop( $keys );
444 foreach ( $keys as $k ) {
445 $k = substr( $k, 0, -1 );
446 $temp = array( $k => $temp );
448 if ( isset( $ret[$key] ) ) {
449 $ret[$key] = array_merge( $ret[$key], $temp );
461 * Append a query string to an existing URL, which may or may not already
462 * have query string parameters already. If so, they will be combined.
465 * @param string|string[] $query String or associative array
468 function wfAppendQuery( $url, $query ) {
469 if ( is_array( $query ) ) {
470 $query = wfArrayToCgi( $query );
472 if ( $query != '' ) {
473 if ( false === strpos( $url, '?' ) ) {
484 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
487 * The meaning of the PROTO_* constants is as follows:
488 * PROTO_HTTP: Output a URL starting with http://
489 * PROTO_HTTPS: Output a URL starting with https://
490 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
491 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
492 * on which protocol was used for the current incoming request
493 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
494 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
495 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
497 * @todo this won't work with current-path-relative URLs
498 * like "subdir/foo.html", etc.
500 * @param string $url Either fully-qualified or a local path + query
501 * @param string $defaultProto One of the PROTO_* constants. Determines the
502 * protocol to use if $url or $wgServer is protocol-relative
503 * @return string Fully-qualified URL, current-path-relative URL or false if
504 * no valid URL can be constructed
506 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
507 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
509 if ( $defaultProto === PROTO_CANONICAL
) {
510 $serverUrl = $wgCanonicalServer;
511 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
512 // Make $wgInternalServer fall back to $wgServer if not set
513 $serverUrl = $wgInternalServer;
515 $serverUrl = $wgServer;
516 if ( $defaultProto === PROTO_CURRENT
) {
517 $defaultProto = $wgRequest->getProtocol() . '://';
521 // Analyze $serverUrl to obtain its protocol
522 $bits = wfParseUrl( $serverUrl );
523 $serverHasProto = $bits && $bits['scheme'] != '';
525 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
526 if ( $serverHasProto ) {
527 $defaultProto = $bits['scheme'] . '://';
529 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
530 // This really isn't supposed to happen. Fall back to HTTP in this
532 $defaultProto = PROTO_HTTP
;
536 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
538 if ( substr( $url, 0, 2 ) == '//' ) {
539 $url = $defaultProtoWithoutSlashes . $url;
540 } elseif ( substr( $url, 0, 1 ) == '/' ) {
541 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
542 // otherwise leave it alone.
543 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
546 $bits = wfParseUrl( $url );
548 // ensure proper port for HTTPS arrives in URL
549 // https://bugzilla.wikimedia.org/show_bug.cgi?id=65184
550 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
551 $bits['port'] = $wgHttpsPort;
554 if ( $bits && isset( $bits['path'] ) ) {
555 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
556 return wfAssembleUrl( $bits );
560 } elseif ( substr( $url, 0, 1 ) != '/' ) {
561 # URL is a relative path
562 return wfRemoveDotSegments( $url );
565 # Expanded URL is not valid.
570 * This function will reassemble a URL parsed with wfParseURL. This is useful
571 * if you need to edit part of a URL and put it back together.
573 * This is the basic structure used (brackets contain keys for $urlParts):
574 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
576 * @todo Need to integrate this into wfExpandUrl (bug 32168)
579 * @param array $urlParts URL parts, as output from wfParseUrl
580 * @return string URL assembled from its component parts
582 function wfAssembleUrl( $urlParts ) {
585 if ( isset( $urlParts['delimiter'] ) ) {
586 if ( isset( $urlParts['scheme'] ) ) {
587 $result .= $urlParts['scheme'];
590 $result .= $urlParts['delimiter'];
593 if ( isset( $urlParts['host'] ) ) {
594 if ( isset( $urlParts['user'] ) ) {
595 $result .= $urlParts['user'];
596 if ( isset( $urlParts['pass'] ) ) {
597 $result .= ':' . $urlParts['pass'];
602 $result .= $urlParts['host'];
604 if ( isset( $urlParts['port'] ) ) {
605 $result .= ':' . $urlParts['port'];
609 if ( isset( $urlParts['path'] ) ) {
610 $result .= $urlParts['path'];
613 if ( isset( $urlParts['query'] ) ) {
614 $result .= '?' . $urlParts['query'];
617 if ( isset( $urlParts['fragment'] ) ) {
618 $result .= '#' . $urlParts['fragment'];
625 * Remove all dot-segments in the provided URL path. For example,
626 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
627 * RFC3986 section 5.2.4.
629 * @todo Need to integrate this into wfExpandUrl (bug 32168)
631 * @param string $urlPath URL path, potentially containing dot-segments
632 * @return string URL path with all dot-segments removed
634 function wfRemoveDotSegments( $urlPath ) {
637 $inputLength = strlen( $urlPath );
639 while ( $inputOffset < $inputLength ) {
640 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
641 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
642 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
643 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
646 if ( $prefixLengthTwo == './' ) {
647 # Step A, remove leading "./"
649 } elseif ( $prefixLengthThree == '../' ) {
650 # Step A, remove leading "../"
652 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
653 # Step B, replace leading "/.$" with "/"
655 $urlPath[$inputOffset] = '/';
656 } elseif ( $prefixLengthThree == '/./' ) {
657 # Step B, replace leading "/./" with "/"
659 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
660 # Step C, replace leading "/..$" with "/" and
661 # remove last path component in output
663 $urlPath[$inputOffset] = '/';
665 } elseif ( $prefixLengthFour == '/../' ) {
666 # Step C, replace leading "/../" with "/" and
667 # remove last path component in output
670 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
671 # Step D, remove "^.$"
673 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
674 # Step D, remove "^..$"
677 # Step E, move leading path segment to output
678 if ( $prefixLengthOne == '/' ) {
679 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
681 $slashPos = strpos( $urlPath, '/', $inputOffset );
683 if ( $slashPos === false ) {
684 $output .= substr( $urlPath, $inputOffset );
685 $inputOffset = $inputLength;
687 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
688 $inputOffset +
= $slashPos - $inputOffset;
693 $slashPos = strrpos( $output, '/' );
694 if ( $slashPos === false ) {
697 $output = substr( $output, 0, $slashPos );
706 * Returns a regular expression of url protocols
708 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
709 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
712 function wfUrlProtocols( $includeProtocolRelative = true ) {
713 global $wgUrlProtocols;
715 // Cache return values separately based on $includeProtocolRelative
716 static $withProtRel = null, $withoutProtRel = null;
717 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
718 if ( !is_null( $cachedValue ) ) {
722 // Support old-style $wgUrlProtocols strings, for backwards compatibility
723 // with LocalSettings files from 1.5
724 if ( is_array( $wgUrlProtocols ) ) {
725 $protocols = array();
726 foreach ( $wgUrlProtocols as $protocol ) {
727 // Filter out '//' if !$includeProtocolRelative
728 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
729 $protocols[] = preg_quote( $protocol, '/' );
733 $retval = implode( '|', $protocols );
735 // Ignore $includeProtocolRelative in this case
736 // This case exists for pre-1.6 compatibility, and we can safely assume
737 // that '//' won't appear in a pre-1.6 config because protocol-relative
738 // URLs weren't supported until 1.18
739 $retval = $wgUrlProtocols;
742 // Cache return value
743 if ( $includeProtocolRelative ) {
744 $withProtRel = $retval;
746 $withoutProtRel = $retval;
752 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
753 * you need a regex that matches all URL protocols but does not match protocol-
757 function wfUrlProtocolsWithoutProtRel() {
758 return wfUrlProtocols( false );
762 * parse_url() work-alike, but non-broken. Differences:
764 * 1) Does not raise warnings on bad URLs (just returns false).
765 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
766 * protocol-relative URLs) correctly.
767 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
769 * @param string $url A URL to parse
770 * @return string[] Bits of the URL in an associative array, per PHP docs
772 function wfParseUrl( $url ) {
773 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
775 // Protocol-relative URLs are handled really badly by parse_url(). It's so
776 // bad that the easiest way to handle them is to just prepend 'http:' and
777 // strip the protocol out later.
778 $wasRelative = substr( $url, 0, 2 ) == '//';
779 if ( $wasRelative ) {
782 wfSuppressWarnings();
783 $bits = parse_url( $url );
785 // parse_url() returns an array without scheme for some invalid URLs, e.g.
786 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
787 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
791 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
792 $bits['scheme'] = strtolower( $bits['scheme'] );
794 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
795 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
796 $bits['delimiter'] = '://';
797 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
798 $bits['delimiter'] = ':';
799 // parse_url detects for news: and mailto: the host part of an url as path
800 // We have to correct this wrong detection
801 if ( isset( $bits['path'] ) ) {
802 $bits['host'] = $bits['path'];
809 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
810 if ( !isset( $bits['host'] ) ) {
814 if ( isset( $bits['path'] ) ) {
815 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
816 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
817 $bits['path'] = '/' . $bits['path'];
824 // If the URL was protocol-relative, fix scheme and delimiter
825 if ( $wasRelative ) {
826 $bits['scheme'] = '';
827 $bits['delimiter'] = '//';
833 * Take a URL, make sure it's expanded to fully qualified, and replace any
834 * encoded non-ASCII Unicode characters with their UTF-8 original forms
835 * for more compact display and legibility for local audiences.
837 * @todo handle punycode domains too
842 function wfExpandIRI( $url ) {
843 return preg_replace_callback(
844 '/((?:%[89A-F][0-9A-F])+)/i',
845 'wfExpandIRI_callback',
851 * Private callback for wfExpandIRI
852 * @param array $matches
855 function wfExpandIRI_callback( $matches ) {
856 return urldecode( $matches[1] );
860 * Make URL indexes, appropriate for the el_index field of externallinks.
865 function wfMakeUrlIndexes( $url ) {
866 $bits = wfParseUrl( $url );
868 // Reverse the labels in the hostname, convert to lower case
869 // For emails reverse domainpart only
870 if ( $bits['scheme'] == 'mailto' ) {
871 $mailparts = explode( '@', $bits['host'], 2 );
872 if ( count( $mailparts ) === 2 ) {
873 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
875 // No domain specified, don't mangle it
878 $reversedHost = $domainpart . '@' . $mailparts[0];
880 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
882 // Add an extra dot to the end
883 // Why? Is it in wrong place in mailto links?
884 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
885 $reversedHost .= '.';
887 // Reconstruct the pseudo-URL
888 $prot = $bits['scheme'];
889 $index = $prot . $bits['delimiter'] . $reversedHost;
890 // Leave out user and password. Add the port, path, query and fragment
891 if ( isset( $bits['port'] ) ) {
892 $index .= ':' . $bits['port'];
894 if ( isset( $bits['path'] ) ) {
895 $index .= $bits['path'];
899 if ( isset( $bits['query'] ) ) {
900 $index .= '?' . $bits['query'];
902 if ( isset( $bits['fragment'] ) ) {
903 $index .= '#' . $bits['fragment'];
907 return array( "http:$index", "https:$index" );
909 return array( $index );
914 * Check whether a given URL has a domain that occurs in a given set of domains
915 * @param string $url URL
916 * @param array $domains Array of domains (strings)
917 * @return bool True if the host part of $url ends in one of the strings in $domains
919 function wfMatchesDomainList( $url, $domains ) {
920 $bits = wfParseUrl( $url );
921 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
922 $host = '.' . $bits['host'];
923 foreach ( (array)$domains as $domain ) {
924 $domain = '.' . $domain;
925 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
934 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
935 * In normal operation this is a NOP.
937 * Controlling globals:
938 * $wgDebugLogFile - points to the log file
939 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
940 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
942 * @param string $text
943 * @param string|bool $dest Destination of the message:
944 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
945 * - 'log': only to the log and not in HTML
946 * For backward compatibility, it can also take a boolean:
947 * - true: same as 'all'
948 * - false: same as 'log'
950 function wfDebug( $text, $dest = 'all' ) {
951 global $wgDebugLogFile, $wgDebugRawPage, $wgDebugLogPrefix;
953 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
957 // Turn $dest into a string if it's a boolean (for b/c)
958 if ( $dest === true ) {
960 } elseif ( $dest === false ) {
964 $timer = wfDebugTimer();
965 if ( $timer !== '' ) {
966 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
969 if ( $dest === 'all' ) {
970 MWDebug
::debugMsg( $text );
973 if ( $wgDebugLogFile != '' ) {
974 # Strip unprintables; they can switch terminal modes when binary data
975 # gets dumped, which is pretty annoying.
976 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
977 $text = $wgDebugLogPrefix . $text;
978 wfErrorLog( $text, $wgDebugLogFile );
983 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
986 function wfIsDebugRawPage() {
988 if ( $cache !== null ) {
991 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
992 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
994 isset( $_SERVER['SCRIPT_NAME'] )
995 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1006 * Get microsecond timestamps for debug logs
1010 function wfDebugTimer() {
1011 global $wgDebugTimestamps, $wgRequestTime;
1013 if ( !$wgDebugTimestamps ) {
1017 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1018 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1019 return "$prefix $mem ";
1023 * Send a line giving PHP memory usage.
1025 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1027 function wfDebugMem( $exact = false ) {
1028 $mem = memory_get_usage();
1030 $mem = floor( $mem / 1024 ) . ' KiB';
1034 wfDebug( "Memory usage: $mem\n" );
1038 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
1039 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string
1040 * filename or an associative array mapping 'destination' to the desired filename. The
1041 * associative array may also contain a 'sample' key with an integer value, specifying
1042 * a sampling factor.
1044 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1046 * @param string $logGroup
1047 * @param string $text
1048 * @param string|bool $dest Destination of the message:
1049 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1050 * - 'log': only to the log and not in HTML
1051 * - 'private': only to the specifc log if set in $wgDebugLogGroups and
1052 * discarded otherwise
1053 * For backward compatibility, it can also take a boolean:
1054 * - true: same as 'all'
1055 * - false: same as 'private'
1057 function wfDebugLog( $logGroup, $text, $dest = 'all' ) {
1058 global $wgDebugLogGroups;
1060 $text = trim( $text ) . "\n";
1062 // Turn $dest into a string if it's a boolean (for b/c)
1063 if ( $dest === true ) {
1065 } elseif ( $dest === false ) {
1069 if ( !isset( $wgDebugLogGroups[$logGroup] ) ) {
1070 if ( $dest !== 'private' ) {
1071 wfDebug( "[$logGroup] $text", $dest );
1076 if ( $dest === 'all' ) {
1077 MWDebug
::debugMsg( "[$logGroup] $text" );
1080 $logConfig = $wgDebugLogGroups[$logGroup];
1081 if ( $logConfig === false ) {
1084 if ( is_array( $logConfig ) ) {
1085 if ( isset( $logConfig['sample'] ) && mt_rand( 1, $logConfig['sample'] ) !== 1 ) {
1088 $destination = $logConfig['destination'];
1090 $destination = strval( $logConfig );
1093 $time = wfTimestamp( TS_DB
);
1095 $host = wfHostname();
1096 wfErrorLog( "$time $host $wiki: $text", $destination );
1100 * Log for database errors
1102 * @param string $text Database error message.
1104 function wfLogDBError( $text ) {
1105 global $wgDBerrorLog, $wgDBerrorLogTZ;
1106 static $logDBErrorTimeZoneObject = null;
1108 if ( $wgDBerrorLog ) {
1109 $host = wfHostname();
1112 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
1113 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
1116 // Workaround for https://bugs.php.net/bug.php?id=52063
1117 // Can be removed when min PHP > 5.3.2
1118 if ( $logDBErrorTimeZoneObject === null ) {
1119 $d = date_create( "now" );
1121 $d = date_create( "now", $logDBErrorTimeZoneObject );
1124 $date = $d->format( 'D M j G:i:s T Y' );
1126 $text = "$date\t$host\t$wiki\t" . trim( $text ) . "\n";
1127 wfErrorLog( $text, $wgDBerrorLog );
1132 * Throws a warning that $function is deprecated
1134 * @param string $function
1135 * @param string|bool $version Version of MediaWiki that the function
1136 * was deprecated in (Added in 1.19).
1137 * @param string|bool $component Added in 1.19.
1138 * @param int $callerOffset How far up the call stack is the original
1139 * caller. 2 = function that called the function that called
1140 * wfDeprecated (Added in 1.20)
1144 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1145 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1149 * Send a warning either to the debug log or in a PHP error depending on
1150 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1152 * @param string $msg Message to send
1153 * @param int $callerOffset Number of items to go back in the backtrace to
1154 * find the correct caller (1 = function calling wfWarn, ...)
1155 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1156 * only used when $wgDevelopmentWarnings is true
1158 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1159 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1163 * Send a warning as a PHP error and the debug log. This is intended for logging
1164 * warnings in production. For logging development warnings, use WfWarn instead.
1166 * @param string $msg Message to send
1167 * @param int $callerOffset Number of items to go back in the backtrace to
1168 * find the correct caller (1 = function calling wfLogWarning, ...)
1169 * @param int $level PHP error level; defaults to E_USER_WARNING
1171 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1172 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1176 * Log to a file without getting "file size exceeded" signals.
1178 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1179 * send lines to the specified port, prefixed by the specified prefix and a space.
1181 * @param string $text
1182 * @param string $file Filename
1183 * @throws MWException
1185 function wfErrorLog( $text, $file ) {
1186 if ( substr( $file, 0, 4 ) == 'udp:' ) {
1187 # Needs the sockets extension
1188 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
1189 // IPv6 bracketed host
1191 $port = intval( $m[3] );
1192 $prefix = isset( $m[4] ) ?
$m[4] : false;
1194 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
1196 if ( !IP
::isIPv4( $host ) ) {
1197 $host = gethostbyname( $host );
1199 $port = intval( $m[3] );
1200 $prefix = isset( $m[4] ) ?
$m[4] : false;
1203 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
1206 // Clean it up for the multiplexer
1207 if ( strval( $prefix ) !== '' ) {
1208 $text = preg_replace( '/^/m', $prefix . ' ', $text );
1211 if ( strlen( $text ) > 65506 ) {
1212 $text = substr( $text, 0, 65506 );
1215 if ( substr( $text, -1 ) != "\n" ) {
1218 } elseif ( strlen( $text ) > 65507 ) {
1219 $text = substr( $text, 0, 65507 );
1222 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
1227 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
1228 socket_close( $sock );
1230 wfSuppressWarnings();
1231 $exists = file_exists( $file );
1232 $size = $exists ?
filesize( $file ) : false;
1233 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
1234 file_put_contents( $file, $text, FILE_APPEND
);
1236 wfRestoreWarnings();
1243 function wfLogProfilingData() {
1244 global $wgRequestTime, $wgDebugLogFile, $wgDebugLogGroups, $wgDebugRawPage;
1245 global $wgProfileLimit, $wgUser, $wgRequest;
1247 StatCounter
::singleton()->flush();
1249 $profiler = Profiler
::instance();
1251 # Profiling must actually be enabled...
1252 if ( $profiler->isStub() ) {
1256 // Get total page request time and only show pages that longer than
1257 // $wgProfileLimit time (default is 0)
1258 $elapsed = microtime( true ) - $wgRequestTime;
1259 if ( $elapsed <= $wgProfileLimit ) {
1263 $profiler->logData();
1265 // Check whether this should be logged in the debug file.
1266 if ( isset( $wgDebugLogGroups['profileoutput'] )
1267 && $wgDebugLogGroups['profileoutput'] === false
1269 // Explicitely disabled
1272 if ( !isset( $wgDebugLogGroups['profileoutput'] ) && $wgDebugLogFile == '' ) {
1273 // Logging not enabled; no point going further
1276 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1281 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1282 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
1284 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1285 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
1287 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1288 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
1291 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
1293 // Don't load $wgUser at this late stage just for statistics purposes
1294 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
1295 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1296 $forward .= ' anon';
1299 // Command line script uses a FauxRequest object which does not have
1300 // any knowledge about an URL and throw an exception instead.
1302 $requestUrl = $wgRequest->getRequestURL();
1303 } catch ( MWException
$e ) {
1304 $requestUrl = 'n/a';
1307 $log = sprintf( "%s\t%04.3f\t%s\n",
1308 gmdate( 'YmdHis' ), $elapsed,
1309 urldecode( $requestUrl . $forward ) );
1311 wfDebugLog( 'profileoutput', $log . $profiler->getOutput() );
1315 * Increment a statistics counter
1317 * @param string $key
1321 function wfIncrStats( $key, $count = 1 ) {
1322 StatCounter
::singleton()->incr( $key, $count );
1326 * Check whether the wiki is in read-only mode.
1330 function wfReadOnly() {
1331 return wfReadOnlyReason() !== false;
1335 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1337 * @return string|bool String when in read-only mode; false otherwise
1339 function wfReadOnlyReason() {
1340 global $wgReadOnly, $wgReadOnlyFile;
1342 if ( $wgReadOnly === null ) {
1343 // Set $wgReadOnly for faster access next time
1344 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1345 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1347 $wgReadOnly = false;
1355 * Return a Language object from $langcode
1357 * @param Language|string|bool $langcode Either:
1358 * - a Language object
1359 * - code of the language to get the message for, if it is
1360 * a valid code create a language for that language, if
1361 * it is a string but not a valid code then make a basic
1363 * - a boolean: if it's false then use the global object for
1364 * the current user's language (as a fallback for the old parameter
1365 * functionality), or if it is true then use global object
1366 * for the wiki's content language.
1369 function wfGetLangObj( $langcode = false ) {
1370 # Identify which language to get or create a language object for.
1371 # Using is_object here due to Stub objects.
1372 if ( is_object( $langcode ) ) {
1373 # Great, we already have the object (hopefully)!
1377 global $wgContLang, $wgLanguageCode;
1378 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1379 # $langcode is the language code of the wikis content language object.
1380 # or it is a boolean and value is true
1385 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1386 # $langcode is the language code of user language object.
1387 # or it was a boolean and value is false
1391 $validCodes = array_keys( Language
::fetchLanguageNames() );
1392 if ( in_array( $langcode, $validCodes ) ) {
1393 # $langcode corresponds to a valid language.
1394 return Language
::factory( $langcode );
1397 # $langcode is a string, but not a valid language code; use content language.
1398 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1403 * This is the function for getting translated interface messages.
1405 * @see Message class for documentation how to use them.
1406 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1408 * This function replaces all old wfMsg* functions.
1410 * @param string|string[] $key Message key, or array of keys
1411 * @param mixed $params,... Normal message parameters
1416 * @see Message::__construct
1418 function wfMessage( $key /*...*/ ) {
1419 $params = func_get_args();
1420 array_shift( $params );
1421 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1422 $params = $params[0];
1424 return new Message( $key, $params );
1428 * This function accepts multiple message keys and returns a message instance
1429 * for the first message which is non-empty. If all messages are empty then an
1430 * instance of the first message key is returned.
1432 * @param string|string[] $keys,... Message keys
1437 * @see Message::newFallbackSequence
1439 function wfMessageFallback( /*...*/ ) {
1440 $args = func_get_args();
1441 return call_user_func_array( 'Message::newFallbackSequence', $args );
1445 * Get a message from anywhere, for the current user language.
1447 * Use wfMsgForContent() instead if the message should NOT
1448 * change depending on the user preferences.
1450 * @deprecated since 1.18
1452 * @param string $key Lookup key for the message, usually
1453 * defined in languages/Language.php
1455 * Parameters to the message, which can be used to insert variable text into
1456 * it, can be passed to this function in the following formats:
1457 * - One per argument, starting at the second parameter
1458 * - As an array in the second parameter
1459 * These are not shown in the function definition.
1463 function wfMsg( $key ) {
1464 wfDeprecated( __METHOD__
, '1.21' );
1466 $args = func_get_args();
1467 array_shift( $args );
1468 return wfMsgReal( $key, $args );
1472 * Same as above except doesn't transform the message
1474 * @deprecated since 1.18
1476 * @param string $key
1479 function wfMsgNoTrans( $key ) {
1480 wfDeprecated( __METHOD__
, '1.21' );
1482 $args = func_get_args();
1483 array_shift( $args );
1484 return wfMsgReal( $key, $args, true, false, false );
1488 * Get a message from anywhere, for the current global language
1489 * set with $wgLanguageCode.
1491 * Use this if the message should NOT change dependent on the
1492 * language set in the user's preferences. This is the case for
1493 * most text written into logs, as well as link targets (such as
1494 * the name of the copyright policy page). Link titles, on the
1495 * other hand, should be shown in the UI language.
1497 * Note that MediaWiki allows users to change the user interface
1498 * language in their preferences, but a single installation
1499 * typically only contains content in one language.
1501 * Be wary of this distinction: If you use wfMsg() where you should
1502 * use wfMsgForContent(), a user of the software may have to
1503 * customize potentially hundreds of messages in
1504 * order to, e.g., fix a link in every possible language.
1506 * @deprecated since 1.18
1508 * @param string $key Lookup key for the message, usually
1509 * defined in languages/Language.php
1512 function wfMsgForContent( $key ) {
1513 wfDeprecated( __METHOD__
, '1.21' );
1515 global $wgForceUIMsgAsContentMsg;
1516 $args = func_get_args();
1517 array_shift( $args );
1519 if ( is_array( $wgForceUIMsgAsContentMsg )
1520 && in_array( $key, $wgForceUIMsgAsContentMsg )
1522 $forcontent = false;
1524 return wfMsgReal( $key, $args, true, $forcontent );
1528 * Same as above except doesn't transform the message
1530 * @deprecated since 1.18
1532 * @param string $key
1535 function wfMsgForContentNoTrans( $key ) {
1536 wfDeprecated( __METHOD__
, '1.21' );
1538 global $wgForceUIMsgAsContentMsg;
1539 $args = func_get_args();
1540 array_shift( $args );
1542 if ( is_array( $wgForceUIMsgAsContentMsg )
1543 && in_array( $key, $wgForceUIMsgAsContentMsg )
1545 $forcontent = false;
1547 return wfMsgReal( $key, $args, true, $forcontent, false );
1551 * Really get a message
1553 * @deprecated since 1.18
1555 * @param string $key Key to get.
1556 * @param array $args
1557 * @param bool $useDB
1558 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1559 * @param bool $transform Whether or not to transform the message.
1560 * @return string The requested message.
1562 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1563 wfDeprecated( __METHOD__
, '1.21' );
1565 wfProfileIn( __METHOD__
);
1566 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1567 $message = wfMsgReplaceArgs( $message, $args );
1568 wfProfileOut( __METHOD__
);
1573 * Fetch a message string value, but don't replace any keys yet.
1575 * @deprecated since 1.18
1577 * @param string $key
1578 * @param bool $useDB
1579 * @param string|bool $langCode Code of the language to get the message for, or
1580 * behaves as a content language switch if it is a boolean.
1581 * @param bool $transform Whether to parse magic words, etc.
1584 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1585 wfDeprecated( __METHOD__
, '1.21' );
1587 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1589 $cache = MessageCache
::singleton();
1590 $message = $cache->get( $key, $useDB, $langCode );
1591 if ( $message === false ) {
1592 $message = '<' . htmlspecialchars( $key ) . '>';
1593 } elseif ( $transform ) {
1594 $message = $cache->transform( $message );
1600 * Replace message parameter keys on the given formatted output.
1602 * @param string $message
1603 * @param array $args
1605 * @deprecated since 1.25 Use the RawMessage class
1608 function wfMsgReplaceArgs( $message, $args ) {
1609 # Fix windows line-endings
1610 # Some messages are split with explode("\n", $msg)
1611 $message = str_replace( "\r", '', $message );
1613 // Replace arguments
1614 if ( count( $args ) ) {
1615 if ( is_array( $args[0] ) ) {
1616 $args = array_values( $args[0] );
1618 $replacementKeys = array();
1619 foreach ( $args as $n => $param ) {
1620 $replacementKeys['$' . ( $n +
1 )] = $param;
1622 $message = strtr( $message, $replacementKeys );
1629 * Return an HTML-escaped version of a message.
1630 * Parameter replacements, if any, are done *after* the HTML-escaping,
1631 * so parameters may contain HTML (eg links or form controls). Be sure
1632 * to pre-escape them if you really do want plaintext, or just wrap
1633 * the whole thing in htmlspecialchars().
1635 * @deprecated since 1.18
1637 * @param string $key
1638 * @param string $args,... Parameters
1641 function wfMsgHtml( $key ) {
1642 wfDeprecated( __METHOD__
, '1.21' );
1644 $args = func_get_args();
1645 array_shift( $args );
1646 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1650 * Return an HTML version of message
1651 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1652 * so parameters may contain HTML (eg links or form controls). Be sure
1653 * to pre-escape them if you really do want plaintext, or just wrap
1654 * the whole thing in htmlspecialchars().
1656 * @deprecated since 1.18
1658 * @param string $key
1659 * @param string $args,... Parameters
1662 function wfMsgWikiHtml( $key ) {
1663 wfDeprecated( __METHOD__
, '1.21' );
1665 $args = func_get_args();
1666 array_shift( $args );
1667 return wfMsgReplaceArgs(
1668 MessageCache
::singleton()->parse( wfMsgGetKey( $key ), null,
1669 /* can't be set to false */ true, /* interface */ true )->getText(),
1674 * Returns message in the requested format
1676 * @deprecated since 1.18
1678 * @param string $key Key of the message
1679 * @param array $options Processing rules.
1680 * Can take the following options:
1681 * parse: parses wikitext to HTML
1682 * parseinline: parses wikitext to HTML and removes the surrounding
1683 * p's added by parser or tidy
1684 * escape: filters message through htmlspecialchars
1685 * escapenoentities: same, but allows entity references like   through
1686 * replaceafter: parameters are substituted after parsing or escaping
1687 * parsemag: transform the message using magic phrases
1688 * content: fetch message for content language instead of interface
1689 * Also can accept a single associative argument, of the form 'language' => 'xx':
1690 * language: Language object or language code to fetch message for
1691 * (overridden by content).
1692 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1696 function wfMsgExt( $key, $options ) {
1697 wfDeprecated( __METHOD__
, '1.21' );
1699 $args = func_get_args();
1700 array_shift( $args );
1701 array_shift( $args );
1702 $options = (array)$options;
1704 foreach ( $options as $arrayKey => $option ) {
1705 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1706 # An unknown index, neither numeric nor "language"
1707 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
1708 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1709 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1710 'replaceafter', 'parsemag', 'content' ) ) ) {
1711 # A numeric index with unknown value
1712 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
1716 if ( in_array( 'content', $options, true ) ) {
1719 $langCodeObj = null;
1720 } elseif ( array_key_exists( 'language', $options ) ) {
1721 $forContent = false;
1722 $langCode = wfGetLangObj( $options['language'] );
1723 $langCodeObj = $langCode;
1725 $forContent = false;
1727 $langCodeObj = null;
1730 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1732 if ( !in_array( 'replaceafter', $options, true ) ) {
1733 $string = wfMsgReplaceArgs( $string, $args );
1736 $messageCache = MessageCache
::singleton();
1737 $parseInline = in_array( 'parseinline', $options, true );
1738 if ( in_array( 'parse', $options, true ) ||
$parseInline ) {
1739 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1740 if ( $string instanceof ParserOutput
) {
1741 $string = $string->getText();
1744 if ( $parseInline ) {
1745 $string = Parser
::stripOuterParagraph( $string );
1747 } elseif ( in_array( 'parsemag', $options, true ) ) {
1748 $string = $messageCache->transform( $string,
1749 !$forContent, $langCodeObj );
1752 if ( in_array( 'escape', $options, true ) ) {
1753 $string = htmlspecialchars ( $string );
1754 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1755 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
1758 if ( in_array( 'replaceafter', $options, true ) ) {
1759 $string = wfMsgReplaceArgs( $string, $args );
1766 * Since wfMsg() and co suck, they don't return false if the message key they
1767 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1768 * nonexistence of messages by checking the MessageCache::get() result directly.
1770 * @deprecated since 1.18. Use Message::isDisabled().
1772 * @param string $key The message key looked up
1773 * @return bool True if the message *doesn't* exist.
1775 function wfEmptyMsg( $key ) {
1776 wfDeprecated( __METHOD__
, '1.21' );
1778 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1782 * Fetch server name for use in error reporting etc.
1783 * Use real server name if available, so we know which machine
1784 * in a server farm generated the current page.
1788 function wfHostname() {
1790 if ( is_null( $host ) ) {
1792 # Hostname overriding
1793 global $wgOverrideHostname;
1794 if ( $wgOverrideHostname !== false ) {
1795 # Set static and skip any detection
1796 $host = $wgOverrideHostname;
1800 if ( function_exists( 'posix_uname' ) ) {
1801 // This function not present on Windows
1802 $uname = posix_uname();
1806 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1807 $host = $uname['nodename'];
1808 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1809 # Windows computer name
1810 $host = getenv( 'COMPUTERNAME' );
1812 # This may be a virtual server.
1813 $host = $_SERVER['SERVER_NAME'];
1820 * Returns a script tag that stores the amount of time it took MediaWiki to
1821 * handle the request in milliseconds as 'wgBackendResponseTime'.
1823 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1824 * hostname of the server handling the request.
1828 function wfReportTime() {
1829 global $wgRequestTime, $wgShowHostnames;
1831 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1832 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1833 if ( $wgShowHostnames ) {
1834 $reportVars['wgHostname'] = wfHostname();
1836 return Skin
::makeVariablesScript( $reportVars );
1840 * Safety wrapper for debug_backtrace().
1842 * Will return an empty array if debug_backtrace is disabled, otherwise
1843 * the output from debug_backtrace() (trimmed).
1845 * @param int $limit This parameter can be used to limit the number of stack frames returned
1847 * @return array Array of backtrace information
1849 function wfDebugBacktrace( $limit = 0 ) {
1850 static $disabled = null;
1852 if ( is_null( $disabled ) ) {
1853 $disabled = !function_exists( 'debug_backtrace' );
1855 wfDebug( "debug_backtrace() is disabled\n" );
1862 if ( $limit && version_compare( PHP_VERSION
, '5.4.0', '>=' ) ) {
1863 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1865 return array_slice( debug_backtrace(), 1 );
1870 * Get a debug backtrace as a string
1874 function wfBacktrace() {
1875 global $wgCommandLineMode;
1877 if ( $wgCommandLineMode ) {
1882 $backtrace = wfDebugBacktrace();
1883 foreach ( $backtrace as $call ) {
1884 if ( isset( $call['file'] ) ) {
1885 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1886 $file = $f[count( $f ) - 1];
1890 if ( isset( $call['line'] ) ) {
1891 $line = $call['line'];
1895 if ( $wgCommandLineMode ) {
1896 $msg .= "$file line $line calls ";
1898 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1900 if ( !empty( $call['class'] ) ) {
1901 $msg .= $call['class'] . $call['type'];
1903 $msg .= $call['function'] . '()';
1905 if ( $wgCommandLineMode ) {
1911 if ( $wgCommandLineMode ) {
1921 * Get the name of the function which called this function
1922 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1923 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1924 * wfGetCaller( 3 ) is the parent of that.
1929 function wfGetCaller( $level = 2 ) {
1930 $backtrace = wfDebugBacktrace( $level +
1 );
1931 if ( isset( $backtrace[$level] ) ) {
1932 return wfFormatStackFrame( $backtrace[$level] );
1939 * Return a string consisting of callers in the stack. Useful sometimes
1940 * for profiling specific points.
1942 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1945 function wfGetAllCallers( $limit = 3 ) {
1946 $trace = array_reverse( wfDebugBacktrace() );
1947 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1948 $limit = count( $trace ) - 1;
1950 $trace = array_slice( $trace, -$limit - 1, $limit );
1951 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1955 * Return a string representation of frame
1957 * @param array $frame
1960 function wfFormatStackFrame( $frame ) {
1961 return isset( $frame['class'] ) ?
1962 $frame['class'] . '::' . $frame['function'] :
1966 /* Some generic result counters, pulled out of SearchEngine */
1971 * @param int $offset
1975 function wfShowingResults( $offset, $limit ) {
1976 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
1981 * @todo FIXME: We may want to blacklist some broken browsers
1983 * @param bool $force
1984 * @return bool Whereas client accept gzip compression
1986 function wfClientAcceptsGzip( $force = false ) {
1987 static $result = null;
1988 if ( $result === null ||
$force ) {
1990 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1991 # @todo FIXME: We may want to blacklist some broken browsers
1994 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1995 $_SERVER['HTTP_ACCEPT_ENCODING'],
1999 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2003 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2012 * Obtain the offset and limit values from the request string;
2013 * used in special pages
2015 * @param int $deflimit Default limit if none supplied
2016 * @param string $optionname Name of a user preference to check against
2018 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2020 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2022 wfDeprecated( __METHOD__
, '1.24' );
2023 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2027 * Escapes the given text so that it may be output using addWikiText()
2028 * without any linking, formatting, etc. making its way through. This
2029 * is achieved by substituting certain characters with HTML entities.
2030 * As required by the callers, "<nowiki>" is not used.
2032 * @param string $text Text to be escaped
2035 function wfEscapeWikiText( $text ) {
2036 static $repl = null, $repl2 = null;
2037 if ( $repl === null ) {
2039 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
2040 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
2041 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
2042 "\n#" => "\n#", "\r#" => "\r#",
2043 "\n*" => "\n*", "\r*" => "\r*",
2044 "\n:" => "\n:", "\r:" => "\r:",
2045 "\n " => "\n ", "\r " => "\r ",
2046 "\n\n" => "\n ", "\r\n" => " \n",
2047 "\n\r" => "\n ", "\r\r" => "\r ",
2048 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
2049 "\n----" => "\n----", "\r----" => "\r----",
2050 '__' => '__', '://' => '://',
2053 // We have to catch everything "\s" matches in PCRE
2054 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2055 $repl["$magic "] = "$magic ";
2056 $repl["$magic\t"] = "$magic	";
2057 $repl["$magic\r"] = "$magic ";
2058 $repl["$magic\n"] = "$magic ";
2059 $repl["$magic\f"] = "$magic";
2062 // And handle protocols that don't use "://"
2063 global $wgUrlProtocols;
2065 foreach ( $wgUrlProtocols as $prot ) {
2066 if ( substr( $prot, -1 ) === ':' ) {
2067 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2070 $repl2 = $repl2 ?
'/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2072 $text = substr( strtr( "\n$text", $repl ), 1 );
2073 $text = preg_replace( $repl2, '$1:', $text );
2078 * Sets dest to source and returns the original value of dest
2079 * If source is NULL, it just returns the value, it doesn't set the variable
2080 * If force is true, it will set the value even if source is NULL
2082 * @param mixed $dest
2083 * @param mixed $source
2084 * @param bool $force
2087 function wfSetVar( &$dest, $source, $force = false ) {
2089 if ( !is_null( $source ) ||
$force ) {
2096 * As for wfSetVar except setting a bit
2100 * @param bool $state
2104 function wfSetBit( &$dest, $bit, $state = true ) {
2105 $temp = (bool)( $dest & $bit );
2106 if ( !is_null( $state ) ) {
2117 * A wrapper around the PHP function var_export().
2118 * Either print it or add it to the regular output ($wgOut).
2120 * @param mixed $var A PHP variable to dump.
2122 function wfVarDump( $var ) {
2124 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2125 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
2128 $wgOut->addHTML( $s );
2133 * Provide a simple HTTP error.
2135 * @param int|string $code
2136 * @param string $label
2137 * @param string $desc
2139 function wfHttpError( $code, $label, $desc ) {
2142 header( "HTTP/1.0 $code $label" );
2143 header( "Status: $code $label" );
2144 $wgOut->sendCacheControl();
2146 header( 'Content-type: text/html; charset=utf-8' );
2147 print "<!doctype html>" .
2148 '<html><head><title>' .
2149 htmlspecialchars( $label ) .
2150 '</title></head><body><h1>' .
2151 htmlspecialchars( $label ) .
2153 nl2br( htmlspecialchars( $desc ) ) .
2154 "</p></body></html>\n";
2158 * Clear away any user-level output buffers, discarding contents.
2160 * Suitable for 'starting afresh', for instance when streaming
2161 * relatively large amounts of data without buffering, or wanting to
2162 * output image files without ob_gzhandler's compression.
2164 * The optional $resetGzipEncoding parameter controls suppression of
2165 * the Content-Encoding header sent by ob_gzhandler; by default it
2166 * is left. See comments for wfClearOutputBuffers() for why it would
2169 * Note that some PHP configuration options may add output buffer
2170 * layers which cannot be removed; these are left in place.
2172 * @param bool $resetGzipEncoding
2174 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2175 if ( $resetGzipEncoding ) {
2176 // Suppress Content-Encoding and Content-Length
2177 // headers from 1.10+s wfOutputHandler
2178 global $wgDisableOutputCompression;
2179 $wgDisableOutputCompression = true;
2181 while ( $status = ob_get_status() ) {
2182 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2183 // Probably from zlib.output_compression or other
2184 // PHP-internal setting which can't be removed.
2186 // Give up, and hope the result doesn't break
2190 if ( !ob_end_clean() ) {
2191 // Could not remove output buffer handler; abort now
2192 // to avoid getting in some kind of infinite loop.
2195 if ( $resetGzipEncoding ) {
2196 if ( $status['name'] == 'ob_gzhandler' ) {
2197 // Reset the 'Content-Encoding' field set by this handler
2198 // so we can start fresh.
2199 header_remove( 'Content-Encoding' );
2207 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2209 * Clear away output buffers, but keep the Content-Encoding header
2210 * produced by ob_gzhandler, if any.
2212 * This should be used for HTTP 304 responses, where you need to
2213 * preserve the Content-Encoding header of the real result, but
2214 * also need to suppress the output of ob_gzhandler to keep to spec
2215 * and avoid breaking Firefox in rare cases where the headers and
2216 * body are broken over two packets.
2218 function wfClearOutputBuffers() {
2219 wfResetOutputBuffers( false );
2223 * Converts an Accept-* header into an array mapping string values to quality
2226 * @param string $accept
2227 * @param string $def Default
2228 * @return float[] Associative array of string => float pairs
2230 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2231 # No arg means accept anything (per HTTP spec)
2233 return array( $def => 1.0 );
2238 $parts = explode( ',', $accept );
2240 foreach ( $parts as $part ) {
2241 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2242 $values = explode( ';', trim( $part ) );
2244 if ( count( $values ) == 1 ) {
2245 $prefs[$values[0]] = 1.0;
2246 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2247 $prefs[$values[0]] = floatval( $match[1] );
2255 * Checks if a given MIME type matches any of the keys in the given
2256 * array. Basic wildcards are accepted in the array keys.
2258 * Returns the matching MIME type (or wildcard) if a match, otherwise
2261 * @param string $type
2262 * @param array $avail
2266 function mimeTypeMatch( $type, $avail ) {
2267 if ( array_key_exists( $type, $avail ) ) {
2270 $parts = explode( '/', $type );
2271 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2272 return $parts[0] . '/*';
2273 } elseif ( array_key_exists( '*/*', $avail ) ) {
2282 * Returns the 'best' match between a client's requested internet media types
2283 * and the server's list of available types. Each list should be an associative
2284 * array of type to preference (preference is a float between 0.0 and 1.0).
2285 * Wildcards in the types are acceptable.
2287 * @param array $cprefs Client's acceptable type list
2288 * @param array $sprefs Server's offered types
2291 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2292 * XXX: generalize to negotiate other stuff
2294 function wfNegotiateType( $cprefs, $sprefs ) {
2297 foreach ( array_keys( $sprefs ) as $type ) {
2298 $parts = explode( '/', $type );
2299 if ( $parts[1] != '*' ) {
2300 $ckey = mimeTypeMatch( $type, $cprefs );
2302 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2307 foreach ( array_keys( $cprefs ) as $type ) {
2308 $parts = explode( '/', $type );
2309 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2310 $skey = mimeTypeMatch( $type, $sprefs );
2312 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2320 foreach ( array_keys( $combine ) as $type ) {
2321 if ( $combine[$type] > $bestq ) {
2323 $bestq = $combine[$type];
2331 * Reference-counted warning suppression
2335 function wfSuppressWarnings( $end = false ) {
2336 static $suppressCount = 0;
2337 static $originalLevel = false;
2340 if ( $suppressCount ) {
2342 if ( !$suppressCount ) {
2343 error_reporting( $originalLevel );
2347 if ( !$suppressCount ) {
2348 $originalLevel = error_reporting( E_ALL
& ~
(
2363 * Restore error level to previous value
2365 function wfRestoreWarnings() {
2366 wfSuppressWarnings( true );
2369 # Autodetect, convert and provide timestamps of various types
2372 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2374 define( 'TS_UNIX', 0 );
2377 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2379 define( 'TS_MW', 1 );
2382 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2384 define( 'TS_DB', 2 );
2387 * RFC 2822 format, for E-mail and HTTP headers
2389 define( 'TS_RFC2822', 3 );
2392 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2394 * This is used by Special:Export
2396 define( 'TS_ISO_8601', 4 );
2399 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2401 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2402 * DateTime tag and page 36 for the DateTimeOriginal and
2403 * DateTimeDigitized tags.
2405 define( 'TS_EXIF', 5 );
2408 * Oracle format time.
2410 define( 'TS_ORACLE', 6 );
2413 * Postgres format time.
2415 define( 'TS_POSTGRES', 7 );
2418 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2420 define( 'TS_ISO_8601_BASIC', 9 );
2423 * Get a timestamp string in one of various formats
2425 * @param mixed $outputtype A timestamp in one of the supported formats, the
2426 * function will autodetect which format is supplied and act accordingly.
2427 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2428 * @return string|bool String / false The same date in the format specified in $outputtype or false
2430 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2432 $timestamp = new MWTimestamp( $ts );
2433 return $timestamp->getTimestamp( $outputtype );
2434 } catch ( TimestampException
$e ) {
2435 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2441 * Return a formatted timestamp, or null if input is null.
2442 * For dealing with nullable timestamp columns in the database.
2444 * @param int $outputtype
2448 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2449 if ( is_null( $ts ) ) {
2452 return wfTimestamp( $outputtype, $ts );
2457 * Convenience function; returns MediaWiki timestamp for the present time.
2461 function wfTimestampNow() {
2463 return wfTimestamp( TS_MW
, time() );
2467 * Check if the operating system is Windows
2469 * @return bool True if it's Windows, false otherwise.
2471 function wfIsWindows() {
2472 static $isWindows = null;
2473 if ( $isWindows === null ) {
2474 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2480 * Check if we are running under HHVM
2484 function wfIsHHVM() {
2485 return defined( 'HHVM_VERSION' );
2489 * Swap two variables
2491 * @deprecated since 1.24
2495 function swap( &$x, &$y ) {
2496 wfDeprecated( __FUNCTION__
, '1.24' );
2503 * Tries to get the system directory for temporary files. First
2504 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2505 * environment variables are then checked in sequence, and if none are
2506 * set try sys_get_temp_dir().
2508 * NOTE: When possible, use instead the tmpfile() function to create
2509 * temporary files to avoid race conditions on file creation, etc.
2513 function wfTempDir() {
2514 global $wgTmpDirectory;
2516 if ( $wgTmpDirectory !== false ) {
2517 return $wgTmpDirectory;
2520 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2522 foreach ( $tmpDir as $tmp ) {
2523 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2527 return sys_get_temp_dir();
2531 * Make directory, and make all parent directories if they don't exist
2533 * @param string $dir Full path to directory to create
2534 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2535 * @param string $caller Optional caller param for debugging.
2536 * @throws MWException
2539 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2540 global $wgDirectoryMode;
2542 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2543 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2546 if ( !is_null( $caller ) ) {
2547 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2550 if ( strval( $dir ) === '' ||
( file_exists( $dir ) && is_dir( $dir ) ) ) {
2554 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2556 if ( is_null( $mode ) ) {
2557 $mode = $wgDirectoryMode;
2560 // Turn off the normal warning, we're doing our own below
2561 wfSuppressWarnings();
2562 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2563 wfRestoreWarnings();
2566 //directory may have been created on another request since we last checked
2567 if ( is_dir( $dir ) ) {
2571 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2572 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2578 * Remove a directory and all its content.
2579 * Does not hide error.
2580 * @param string $dir
2582 function wfRecursiveRemoveDir( $dir ) {
2583 wfDebug( __FUNCTION__
. "( $dir )\n" );
2584 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2585 if ( is_dir( $dir ) ) {
2586 $objects = scandir( $dir );
2587 foreach ( $objects as $object ) {
2588 if ( $object != "." && $object != ".." ) {
2589 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2590 wfRecursiveRemoveDir( $dir . '/' . $object );
2592 unlink( $dir . '/' . $object );
2602 * @param int $nr The number to format
2603 * @param int $acc The number of digits after the decimal point, default 2
2604 * @param bool $round Whether or not to round the value, default true
2607 function wfPercent( $nr, $acc = 2, $round = true ) {
2608 $ret = sprintf( "%.${acc}f", $nr );
2609 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2613 * Safety wrapper around ini_get() for boolean settings.
2614 * The values returned from ini_get() are pre-normalized for settings
2615 * set via php.ini or php_flag/php_admin_flag... but *not*
2616 * for those set via php_value/php_admin_value.
2618 * It's fairly common for people to use php_value instead of php_flag,
2619 * which can leave you with an 'off' setting giving a false positive
2620 * for code that just takes the ini_get() return value as a boolean.
2622 * To make things extra interesting, setting via php_value accepts
2623 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2624 * Unrecognized values go false... again opposite PHP's own coercion
2625 * from string to bool.
2627 * Luckily, 'properly' set settings will always come back as '0' or '1',
2628 * so we only have to worry about them and the 'improper' settings.
2630 * I frickin' hate PHP... :P
2632 * @param string $setting
2635 function wfIniGetBool( $setting ) {
2636 $val = strtolower( ini_get( $setting ) );
2637 // 'on' and 'true' can't have whitespace around them, but '1' can.
2641 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2645 * Windows-compatible version of escapeshellarg()
2646 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2647 * function puts single quotes in regardless of OS.
2649 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2650 * earlier distro releases of PHP)
2652 * @param string $args,...
2655 function wfEscapeShellArg( /*...*/ ) {
2656 wfInitShellLocale();
2658 $args = func_get_args();
2661 foreach ( $args as $arg ) {
2668 if ( wfIsWindows() ) {
2669 // Escaping for an MSVC-style command line parser and CMD.EXE
2670 // @codingStandardsIgnoreStart For long URLs
2672 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2673 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2676 // Double the backslashes before any double quotes. Escape the double quotes.
2677 // @codingStandardsIgnoreEnd
2678 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2681 foreach ( $tokens as $token ) {
2682 if ( $iteration %
2 == 1 ) {
2683 // Delimiter, a double quote preceded by zero or more slashes
2684 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2685 } elseif ( $iteration %
4 == 2 ) {
2686 // ^ in $token will be outside quotes, need to be escaped
2687 $arg .= str_replace( '^', '^^', $token );
2688 } else { // $iteration % 4 == 0
2689 // ^ in $token will appear inside double quotes, so leave as is
2694 // Double the backslashes before the end of the string, because
2695 // we will soon add a quote
2697 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2698 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2701 // Add surrounding quotes
2702 $retVal .= '"' . $arg . '"';
2704 $retVal .= escapeshellarg( $arg );
2711 * Check if wfShellExec() is effectively disabled via php.ini config
2713 * @return bool|string False or one of (safemode,disabled)
2716 function wfShellExecDisabled() {
2717 static $disabled = null;
2718 if ( is_null( $disabled ) ) {
2719 if ( wfIniGetBool( 'safe_mode' ) ) {
2720 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2721 $disabled = 'safemode';
2722 } elseif ( !function_exists( 'proc_open' ) ) {
2723 wfDebug( "proc_open() is disabled\n" );
2724 $disabled = 'disabled';
2733 * Execute a shell command, with time and memory limits mirrored from the PHP
2734 * configuration if supported.
2736 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2737 * or an array of unescaped arguments, in which case each value will be escaped
2738 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2739 * @param null|mixed &$retval Optional, will receive the program's exit code.
2740 * (non-zero is usually failure). If there is an error from
2741 * read, select, or proc_open(), this will be set to -1.
2742 * @param array $environ Optional environment variables which should be
2743 * added to the executed command environment.
2744 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2745 * this overwrites the global wgMaxShell* limits.
2746 * @param array $options Array of options:
2747 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2748 * including errors from limit.sh
2750 * @return string Collected stdout as a string
2752 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2753 $limits = array(), $options = array()
2755 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2756 $wgMaxShellWallClockTime, $wgShellCgroup;
2758 $disabled = wfShellExecDisabled();
2761 return $disabled == 'safemode' ?
2762 'Unable to run external programs in safe mode.' :
2763 'Unable to run external programs, proc_open() is disabled.';
2766 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2768 wfInitShellLocale();
2771 foreach ( $environ as $k => $v ) {
2772 if ( wfIsWindows() ) {
2773 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2774 * appear in the environment variable, so we must use carat escaping as documented in
2775 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2776 * Note however that the quote isn't listed there, but is needed, and the parentheses
2777 * are listed there but doesn't appear to need it.
2779 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2781 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2782 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2784 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2787 if ( is_array( $cmd ) ) {
2788 // Command line may be given as an array, escape each value and glue them together with a space
2790 foreach ( $cmd as $val ) {
2791 $cmdVals[] = wfEscapeShellArg( $val );
2793 $cmd = implode( ' ', $cmdVals );
2796 $cmd = $envcmd . $cmd;
2798 $useLogPipe = false;
2799 if ( is_executable( '/bin/bash' ) ) {
2800 $time = intval ( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2801 if ( isset( $limits['walltime'] ) ) {
2802 $wallTime = intval( $limits['walltime'] );
2803 } elseif ( isset( $limits['time'] ) ) {
2806 $wallTime = intval( $wgMaxShellWallClockTime );
2808 $mem = intval ( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2809 $filesize = intval ( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2811 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2812 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2813 escapeshellarg( $cmd ) . ' ' .
2815 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2816 "MW_CPU_LIMIT=$time; " .
2817 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2818 "MW_MEM_LIMIT=$mem; " .
2819 "MW_FILE_SIZE_LIMIT=$filesize; " .
2820 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2821 "MW_USE_LOG_PIPE=yes"
2824 } elseif ( $includeStderr ) {
2827 } elseif ( $includeStderr ) {
2830 wfDebug( "wfShellExec: $cmd\n" );
2833 0 => array( 'file', 'php://stdin', 'r' ),
2834 1 => array( 'pipe', 'w' ),
2835 2 => array( 'file', 'php://stderr', 'w' ) );
2836 if ( $useLogPipe ) {
2837 $desc[3] = array( 'pipe', 'w' );
2840 $proc = proc_open( $cmd, $desc, $pipes );
2842 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2846 $outBuffer = $logBuffer = '';
2847 $emptyArray = array();
2851 // According to the documentation, it is possible for stream_select()
2852 // to fail due to EINTR. I haven't managed to induce this in testing
2853 // despite sending various signals. If it did happen, the error
2854 // message would take the form:
2856 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2858 // where [4] is the value of the macro EINTR and "Interrupted system
2859 // call" is string which according to the Linux manual is "possibly"
2860 // localised according to LC_MESSAGES.
2861 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2862 $eintrMessage = "stream_select(): unable to select [$eintr]";
2864 // Build a table mapping resource IDs to pipe FDs to work around a
2865 // PHP 5.3 issue in which stream_select() does not preserve array keys
2866 // <https://bugs.php.net/bug.php?id=53427>.
2868 foreach ( $pipes as $fd => $pipe ) {
2869 $fds[(int)$pipe] = $fd;
2876 while ( $running === true ||
$numReadyPipes !== 0 ) {
2878 $status = proc_get_status( $proc );
2879 // If the process has terminated, switch to nonblocking selects
2880 // for getting any data still waiting to be read.
2881 if ( !$status['running'] ) {
2887 $readyPipes = $pipes;
2890 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2891 @trigger_error
( '' );
2892 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
2893 if ( $numReadyPipes === false ) {
2894 // @codingStandardsIgnoreEnd
2895 $error = error_get_last();
2896 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2899 trigger_error( $error['message'], E_USER_WARNING
);
2900 $logMsg = $error['message'];
2904 foreach ( $readyPipes as $pipe ) {
2905 $block = fread( $pipe, 65536 );
2906 $fd = $fds[(int)$pipe];
2907 if ( $block === '' ) {
2909 fclose( $pipes[$fd] );
2910 unset( $pipes[$fd] );
2914 } elseif ( $block === false ) {
2916 $logMsg = "Error reading from pipe";
2918 } elseif ( $fd == 1 ) {
2920 $outBuffer .= $block;
2921 } elseif ( $fd == 3 ) {
2923 $logBuffer .= $block;
2924 if ( strpos( $block, "\n" ) !== false ) {
2925 $lines = explode( "\n", $logBuffer );
2926 $logBuffer = array_pop( $lines );
2927 foreach ( $lines as $line ) {
2928 wfDebugLog( 'exec', $line );
2935 foreach ( $pipes as $pipe ) {
2939 // Use the status previously collected if possible, since proc_get_status()
2940 // just calls waitpid() which will not return anything useful the second time.
2942 $status = proc_get_status( $proc );
2945 if ( $logMsg !== false ) {
2946 // Read/select error
2948 proc_close( $proc );
2949 } elseif ( $status['signaled'] ) {
2950 $logMsg = "Exited with signal {$status['termsig']}";
2951 $retval = 128 +
$status['termsig'];
2952 proc_close( $proc );
2954 if ( $status['running'] ) {
2955 $retval = proc_close( $proc );
2957 $retval = $status['exitcode'];
2958 proc_close( $proc );
2960 if ( $retval == 127 ) {
2961 $logMsg = "Possibly missing executable file";
2962 } elseif ( $retval >= 129 && $retval <= 192 ) {
2963 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2967 if ( $logMsg !== false ) {
2968 wfDebugLog( 'exec', "$logMsg: $cmd" );
2975 * Execute a shell command, returning both stdout and stderr. Convenience
2976 * function, as all the arguments to wfShellExec can become unwieldy.
2978 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2979 * @param string $cmd Command line, properly escaped for shell.
2980 * @param null|mixed &$retval Optional, will receive the program's exit code.
2981 * (non-zero is usually failure)
2982 * @param array $environ Optional environment variables which should be
2983 * added to the executed command environment.
2984 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2985 * this overwrites the global wgMaxShell* limits.
2986 * @return string Collected stdout and stderr as a string
2988 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2989 return wfShellExec( $cmd, $retval, $environ, $limits, array( 'duplicateStderr' => true ) );
2993 * Workaround for http://bugs.php.net/bug.php?id=45132
2994 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2996 function wfInitShellLocale() {
2997 static $done = false;
3002 global $wgShellLocale;
3003 if ( !wfIniGetBool( 'safe_mode' ) ) {
3004 putenv( "LC_CTYPE=$wgShellLocale" );
3005 setlocale( LC_CTYPE
, $wgShellLocale );
3010 * Alias to wfShellWikiCmd()
3012 * @see wfShellWikiCmd()
3014 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
3015 return wfShellWikiCmd( $script, $parameters, $options );
3019 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3020 * Note that $parameters should be a flat array and an option with an argument
3021 * should consist of two consecutive items in the array (do not use "--option value").
3023 * @param string $script MediaWiki cli script path
3024 * @param array $parameters Arguments and options to the script
3025 * @param array $options Associative array of options:
3026 * 'php': The path to the php executable
3027 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3030 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3032 // Give site config file a chance to run the script in a wrapper.
3033 // The caller may likely want to call wfBasename() on $script.
3034 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3035 $cmd = isset( $options['php'] ) ?
array( $options['php'] ) : array( $wgPhpCli );
3036 if ( isset( $options['wrapper'] ) ) {
3037 $cmd[] = $options['wrapper'];
3040 // Escape each parameter for shell
3041 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
3045 * wfMerge attempts to merge differences between three texts.
3046 * Returns true for a clean merge and false for failure or a conflict.
3048 * @param string $old
3049 * @param string $mine
3050 * @param string $yours
3051 * @param string $result
3054 function wfMerge( $old, $mine, $yours, &$result ) {
3057 # This check may also protect against code injection in
3058 # case of broken installations.
3059 wfSuppressWarnings();
3060 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3061 wfRestoreWarnings();
3063 if ( !$haveDiff3 ) {
3064 wfDebug( "diff3 not found\n" );
3068 # Make temporary files
3070 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3071 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3072 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3074 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3075 # a newline character. To avoid this, we normalize the trailing whitespace before
3076 # creating the diff.
3078 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3079 fclose( $oldtextFile );
3080 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3081 fclose( $mytextFile );
3082 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3083 fclose( $yourtextFile );
3085 # Check for a conflict
3086 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
3087 wfEscapeShellArg( $mytextName ) . ' ' .
3088 wfEscapeShellArg( $oldtextName ) . ' ' .
3089 wfEscapeShellArg( $yourtextName );
3090 $handle = popen( $cmd, 'r' );
3092 if ( fgets( $handle, 1024 ) ) {
3100 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
3101 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
3102 $handle = popen( $cmd, 'r' );
3105 $data = fread( $handle, 8192 );
3106 if ( strlen( $data ) == 0 ) {
3112 unlink( $mytextName );
3113 unlink( $oldtextName );
3114 unlink( $yourtextName );
3116 if ( $result === '' && $old !== '' && !$conflict ) {
3117 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3124 * Returns unified plain-text diff of two texts.
3125 * Useful for machine processing of diffs.
3127 * @param string $before The text before the changes.
3128 * @param string $after The text after the changes.
3129 * @param string $params Command-line options for the diff command.
3130 * @return string Unified diff of $before and $after
3132 function wfDiff( $before, $after, $params = '-u' ) {
3133 if ( $before == $after ) {
3138 wfSuppressWarnings();
3139 $haveDiff = $wgDiff && file_exists( $wgDiff );
3140 wfRestoreWarnings();
3142 # This check may also protect against code injection in
3143 # case of broken installations.
3145 wfDebug( "diff executable not found\n" );
3146 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3147 $format = new UnifiedDiffFormatter();
3148 return $format->format( $diffs );
3151 # Make temporary files
3153 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3154 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3156 fwrite( $oldtextFile, $before );
3157 fclose( $oldtextFile );
3158 fwrite( $newtextFile, $after );
3159 fclose( $newtextFile );
3161 // Get the diff of the two files
3162 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3164 $h = popen( $cmd, 'r' );
3169 $data = fread( $h, 8192 );
3170 if ( strlen( $data ) == 0 ) {
3178 unlink( $oldtextName );
3179 unlink( $newtextName );
3181 // Kill the --- and +++ lines. They're not useful.
3182 $diff_lines = explode( "\n", $diff );
3183 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
3184 unset( $diff_lines[0] );
3186 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
3187 unset( $diff_lines[1] );
3190 $diff = implode( "\n", $diff_lines );
3196 * This function works like "use VERSION" in Perl, the program will die with a
3197 * backtrace if the current version of PHP is less than the version provided
3199 * This is useful for extensions which due to their nature are not kept in sync
3200 * with releases, and might depend on other versions of PHP than the main code
3202 * Note: PHP might die due to parsing errors in some cases before it ever
3203 * manages to call this function, such is life
3205 * @see perldoc -f use
3207 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3208 * @throws MWException
3210 function wfUsePHP( $req_ver ) {
3211 $php_ver = PHP_VERSION
;
3213 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3214 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3219 * This function works like "use VERSION" in Perl except it checks the version
3220 * of MediaWiki, the program will die with a backtrace if the current version
3221 * of MediaWiki is less than the version provided.
3223 * This is useful for extensions which due to their nature are not kept in sync
3226 * Note: Due to the behavior of PHP's version_compare() which is used in this
3227 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3228 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3229 * targeted version number. For example if you wanted to allow any variation
3230 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3231 * not result in the same comparison due to the internal logic of
3232 * version_compare().
3234 * @see perldoc -f use
3236 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3237 * @throws MWException
3239 function wfUseMW( $req_ver ) {
3242 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3243 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3248 * Return the final portion of a pathname.
3249 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3250 * http://bugs.php.net/bug.php?id=33898
3252 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3253 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3255 * @param string $path
3256 * @param string $suffix String to remove if present
3259 function wfBaseName( $path, $suffix = '' ) {
3260 if ( $suffix == '' ) {
3263 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3267 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3275 * Generate a relative path name to the given file.
3276 * May explode on non-matching case-insensitive paths,
3277 * funky symlinks, etc.
3279 * @param string $path Absolute destination path including target filename
3280 * @param string $from Absolute source path, directory only
3283 function wfRelativePath( $path, $from ) {
3284 // Normalize mixed input on Windows...
3285 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
3286 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
3288 // Trim trailing slashes -- fix for drive root
3289 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
3290 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
3292 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
3293 $against = explode( DIRECTORY_SEPARATOR
, $from );
3295 if ( $pieces[0] !== $against[0] ) {
3296 // Non-matching Windows drive letters?
3297 // Return a full path.
3301 // Trim off common prefix
3302 while ( count( $pieces ) && count( $against )
3303 && $pieces[0] == $against[0] ) {
3304 array_shift( $pieces );
3305 array_shift( $against );
3308 // relative dots to bump us to the parent
3309 while ( count( $against ) ) {
3310 array_unshift( $pieces, '..' );
3311 array_shift( $against );
3314 array_push( $pieces, wfBaseName( $path ) );
3316 return implode( DIRECTORY_SEPARATOR
, $pieces );
3320 * Convert an arbitrarily-long digit string from one numeric base
3321 * to another, optionally zero-padding to a minimum column width.
3323 * Supports base 2 through 36; digit values 10-36 are represented
3324 * as lowercase letters a-z. Input is case-insensitive.
3326 * @param string $input Input number
3327 * @param int $sourceBase Base of the input number
3328 * @param int $destBase Desired base of the output
3329 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3330 * @param bool $lowercase Whether to output in lowercase or uppercase
3331 * @param string $engine Either "gmp", "bcmath", or "php"
3332 * @return string|bool The output number as a string, or false on error
3334 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3335 $lowercase = true, $engine = 'auto'
3337 $input = (string)$input;
3343 $sourceBase != (int)$sourceBase ||
3344 $destBase != (int)$destBase ||
3345 $pad != (int)$pad ||
3347 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3354 static $baseChars = array(
3355 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3356 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3357 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3358 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3359 34 => 'y', 35 => 'z',
3361 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3362 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3363 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3364 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3365 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3366 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3369 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' ||
$engine == 'gmp' ) ) {
3370 // Removing leading zeros works around broken base detection code in
3371 // some PHP versions (see <https://bugs.php.net/bug.php?id=50175> and
3372 // <https://bugs.php.net/bug.php?id=55398>).
3373 $result = gmp_strval( gmp_init( ltrim( $input, '0' ), $sourceBase ), $destBase );
3374 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' ||
$engine == 'bcmath' ) ) {
3376 foreach ( str_split( strtolower( $input ) ) as $char ) {
3377 $decimal = bcmul( $decimal, $sourceBase );
3378 $decimal = bcadd( $decimal, $baseChars[$char] );
3381 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3382 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3383 $result .= $baseChars[bcmod( $decimal, $destBase )];
3385 // @codingStandardsIgnoreEnd
3387 $result = strrev( $result );
3389 $inDigits = array();
3390 foreach ( str_split( strtolower( $input ) ) as $char ) {
3391 $inDigits[] = $baseChars[$char];
3394 // Iterate over the input, modulo-ing out an output digit
3395 // at a time until input is gone.
3397 while ( $inDigits ) {
3399 $workDigits = array();
3402 foreach ( $inDigits as $digit ) {
3403 $work *= $sourceBase;
3406 if ( $workDigits ||
$work >= $destBase ) {
3407 $workDigits[] = (int)( $work / $destBase );
3412 // All that division leaves us with a remainder,
3413 // which is conveniently our next output digit.
3414 $result .= $baseChars[$work];
3417 $inDigits = $workDigits;
3420 $result = strrev( $result );
3423 if ( !$lowercase ) {
3424 $result = strtoupper( $result );
3427 return str_pad( $result, $pad, '0', STR_PAD_LEFT
);
3431 * Check if there is sufficient entropy in php's built-in session generation
3433 * @return bool True = there is sufficient entropy
3435 function wfCheckEntropy() {
3437 ( wfIsWindows() && version_compare( PHP_VERSION
, '5.3.3', '>=' ) )
3438 ||
ini_get( 'session.entropy_file' )
3440 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3444 * Override session_id before session startup if php's built-in
3445 * session generation code is not secure.
3447 function wfFixSessionID() {
3448 // If the cookie or session id is already set we already have a session and should abort
3449 if ( isset( $_COOKIE[session_name()] ) ||
session_id() ) {
3453 // PHP's built-in session entropy is enabled if:
3454 // - entropy_file is set or you're on Windows with php 5.3.3+
3455 // - AND entropy_length is > 0
3456 // We treat it as disabled if it doesn't have an entropy length of at least 32
3457 $entropyEnabled = wfCheckEntropy();
3459 // If built-in entropy is not enabled or not sufficient override PHP's
3460 // built in session id generation code
3461 if ( !$entropyEnabled ) {
3462 wfDebug( __METHOD__
. ": PHP's built in entropy is disabled or not sufficient, " .
3463 "overriding session id generation using our cryptrand source.\n" );
3464 session_id( MWCryptRand
::generateHex( 32 ) );
3469 * Reset the session_id
3473 function wfResetSessionID() {
3474 global $wgCookieSecure;
3475 $oldSessionId = session_id();
3476 $cookieParams = session_get_cookie_params();
3477 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3478 session_regenerate_id( false );
3482 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
3485 $newSessionId = session_id();
3486 wfRunHooks( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3490 * Initialise php session
3492 * @param bool $sessionId
3494 function wfSetupSession( $sessionId = false ) {
3495 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3496 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3497 if ( $wgSessionsInObjectCache ||
$wgSessionsInMemcached ) {
3498 ObjectCacheSessionHandler
::install();
3499 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3500 # Only set this if $wgSessionHandler isn't null and session.save_handler
3501 # hasn't already been set to the desired value (that causes errors)
3502 ini_set( 'session.save_handler', $wgSessionHandler );
3504 session_set_cookie_params(
3505 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3506 session_cache_limiter( 'private, must-revalidate' );
3508 session_id( $sessionId );
3512 wfSuppressWarnings();
3514 wfRestoreWarnings();
3518 * Get an object from the precompiled serialized directory
3520 * @param string $name
3521 * @return mixed The variable on success, false on failure
3523 function wfGetPrecompiledData( $name ) {
3526 $file = "$IP/serialized/$name";
3527 if ( file_exists( $file ) ) {
3528 $blob = file_get_contents( $file );
3530 return unserialize( $blob );
3539 * @param string $args,...
3542 function wfMemcKey( /*...*/ ) {
3543 global $wgCachePrefix;
3544 $prefix = $wgCachePrefix === false ?
wfWikiID() : $wgCachePrefix;
3545 $args = func_get_args();
3546 $key = $prefix . ':' . implode( ':', $args );
3547 $key = str_replace( ' ', '_', $key );
3552 * Get a cache key for a foreign DB
3555 * @param string $prefix
3556 * @param string $args,...
3559 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3560 $args = array_slice( func_get_args(), 2 );
3562 $key = "$db-$prefix:" . implode( ':', $args );
3564 $key = $db . ':' . implode( ':', $args );
3566 return str_replace( ' ', '_', $key );
3570 * Get an ASCII string identifying this wiki
3571 * This is used as a prefix in memcached keys
3575 function wfWikiID() {
3576 global $wgDBprefix, $wgDBname;
3577 if ( $wgDBprefix ) {
3578 return "$wgDBname-$wgDBprefix";
3585 * Split a wiki ID into DB name and table prefix
3587 * @param string $wiki
3591 function wfSplitWikiID( $wiki ) {
3592 $bits = explode( '-', $wiki, 2 );
3593 if ( count( $bits ) < 2 ) {
3600 * Get a Database object.
3602 * @param int $db Index of the connection to get. May be DB_MASTER for the
3603 * master (for write queries), DB_SLAVE for potentially lagged read
3604 * queries, or an integer >= 0 for a particular server.
3606 * @param string|string[] $groups Query groups. An array of group names that this query
3607 * belongs to. May contain a single string if the query is only
3610 * @param string|bool $wiki The wiki ID, or false for the current wiki
3612 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3613 * will always return the same object, unless the underlying connection or load
3614 * balancer is manually destroyed.
3616 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3617 * updater to ensure that a proper database is being updated.
3619 * @return DatabaseBase
3621 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3622 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3626 * Get a load balancer object.
3628 * @param string|bool $wiki Wiki ID, or false for the current wiki
3629 * @return LoadBalancer
3631 function wfGetLB( $wiki = false ) {
3632 return wfGetLBFactory()->getMainLB( $wiki );
3636 * Get the load balancer factory object
3640 function &wfGetLBFactory() {
3641 return LBFactory
::singleton();
3646 * Shortcut for RepoGroup::singleton()->findFile()
3648 * @param string $title String or Title object
3649 * @param array $options Associative array of options:
3650 * time: requested time for an archived image, or false for the
3651 * current version. An image object will be returned which was
3652 * created at the specified time.
3654 * ignoreRedirect: If true, do not follow file redirects
3656 * private: If true, return restricted (deleted) files if the current
3657 * user is allowed to view them. Otherwise, such files will not
3660 * bypassCache: If true, do not use the process-local cache of File objects
3662 * @return File|bool File, or false if the file does not exist
3664 function wfFindFile( $title, $options = array() ) {
3665 return RepoGroup
::singleton()->findFile( $title, $options );
3669 * Get an object referring to a locally registered file.
3670 * Returns a valid placeholder object if the file does not exist.
3672 * @param Title|string $title
3673 * @return LocalFile|null A File, or null if passed an invalid Title
3675 function wfLocalFile( $title ) {
3676 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3680 * Should low-performance queries be disabled?
3683 * @codeCoverageIgnore
3685 function wfQueriesMustScale() {
3686 global $wgMiserMode;
3688 ||
( SiteStats
::pages() > 100000
3689 && SiteStats
::edits() > 1000000
3690 && SiteStats
::users() > 10000 );
3694 * Get the path to a specified script file, respecting file
3695 * extensions; this is a wrapper around $wgScriptExtension etc.
3696 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3698 * @param string $script Script filename, sans extension
3701 function wfScript( $script = 'index' ) {
3702 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3703 if ( $script === 'index' ) {
3705 } elseif ( $script === 'load' ) {
3706 return $wgLoadScript;
3708 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3713 * Get the script URL.
3715 * @return string Script URL
3717 function wfGetScriptUrl() {
3718 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3720 # as it was called, minus the query string.
3722 # Some sites use Apache rewrite rules to handle subdomains,
3723 # and have PHP set up in a weird way that causes PHP_SELF
3724 # to contain the rewritten URL instead of the one that the
3725 # outside world sees.
3727 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3728 # provides containing the "before" URL.
3729 return $_SERVER['SCRIPT_NAME'];
3731 return $_SERVER['URL'];
3736 * Convenience function converts boolean values into "true"
3737 * or "false" (string) values
3739 * @param bool $value
3742 function wfBoolToStr( $value ) {
3743 return $value ?
'true' : 'false';
3747 * Get a platform-independent path to the null file, e.g. /dev/null
3751 function wfGetNull() {
3752 return wfIsWindows() ?
'NUL' : '/dev/null';
3756 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3757 * and waiting for it to go down, this waits for the slaves to catch up to the
3758 * master position. Use this when updating very large numbers of rows, as
3759 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3760 * a no-op if there are no slaves.
3762 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3763 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3764 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3765 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3766 * @return bool Success (able to connect and no timeouts reached)
3768 function wfWaitForSlaves(
3769 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3771 // B/C: first argument used to be "max seconds of lag"; ignore such values
3772 $ifWritesSince = ( $ifWritesSince > 1e9
) ?
$ifWritesSince : null;
3774 if ( $timeout === null ) {
3775 $timeout = ( PHP_SAPI
=== 'cli' ) ?
86400 : 10;
3778 if ( $cluster !== false ) {
3779 $lb = wfGetLBFactory()->getExternalLB( $cluster );
3781 $lb = wfGetLB( $wiki );
3784 // bug 27975 - Don't try to wait for slaves if there are none
3785 // Prevents permission error when getting master position
3786 if ( $lb->getServerCount() > 1 ) {
3787 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3788 return true; // assume no writes done
3790 $dbw = $lb->getConnection( DB_MASTER
, array(), $wiki );
3791 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3792 return true; // no writes since the last wait
3794 $pos = $dbw->getMasterPos();
3795 // The DBMS may not support getMasterPos() or the whole
3796 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3797 if ( $pos !== false ) {
3798 return $lb->waitForAll( $pos, $timeout );
3806 * Count down from $seconds to zero on the terminal, with a one-second pause
3807 * between showing each number. For use in command-line scripts.
3809 * @codeCoverageIgnore
3810 * @param int $seconds
3812 function wfCountDown( $seconds ) {
3813 for ( $i = $seconds; $i >= 0; $i-- ) {
3814 if ( $i != $seconds ) {
3815 echo str_repeat( "\x08", strlen( $i +
1 ) );
3827 * Replace all invalid characters with -
3828 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3829 * By default, $wgIllegalFileChars = ':'
3831 * @param string $name Filename to process
3834 function wfStripIllegalFilenameChars( $name ) {
3835 global $wgIllegalFileChars;
3836 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3837 $name = wfBaseName( $name );
3838 $name = preg_replace(
3839 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3847 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3849 * @return int Value the memory limit was set to.
3851 function wfMemoryLimit() {
3852 global $wgMemoryLimit;
3853 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3854 if ( $memlimit != -1 ) {
3855 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3856 if ( $conflimit == -1 ) {
3857 wfDebug( "Removing PHP's memory limit\n" );
3858 wfSuppressWarnings();
3859 ini_set( 'memory_limit', $conflimit );
3860 wfRestoreWarnings();
3862 } elseif ( $conflimit > $memlimit ) {
3863 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3864 wfSuppressWarnings();
3865 ini_set( 'memory_limit', $conflimit );
3866 wfRestoreWarnings();
3874 * Converts shorthand byte notation to integer form
3876 * @param string $string
3879 function wfShorthandToInteger( $string = '' ) {
3880 $string = trim( $string );
3881 if ( $string === '' ) {
3884 $last = $string[strlen( $string ) - 1];
3885 $val = intval( $string );
3890 // break intentionally missing
3894 // break intentionally missing
3904 * Get the normalised IETF language tag
3905 * See unit test for examples.
3907 * @param string $code The language code.
3908 * @return string The language code which complying with BCP 47 standards.
3910 function wfBCP47( $code ) {
3911 $codeSegment = explode( '-', $code );
3913 foreach ( $codeSegment as $segNo => $seg ) {
3914 // when previous segment is x, it is a private segment and should be lc
3915 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3916 $codeBCP[$segNo] = strtolower( $seg );
3917 // ISO 3166 country code
3918 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3919 $codeBCP[$segNo] = strtoupper( $seg );
3920 // ISO 15924 script code
3921 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3922 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3923 // Use lowercase for other cases
3925 $codeBCP[$segNo] = strtolower( $seg );
3928 $langCode = implode( '-', $codeBCP );
3933 * Get a cache object.
3935 * @param int $inputType Cache type, one the the CACHE_* constants.
3938 function wfGetCache( $inputType ) {
3939 return ObjectCache
::getInstance( $inputType );
3943 * Get the main cache object
3947 function wfGetMainCache() {
3948 global $wgMainCacheType;
3949 return ObjectCache
::getInstance( $wgMainCacheType );
3953 * Get the cache object used by the message cache
3957 function wfGetMessageCacheStorage() {
3958 global $wgMessageCacheType;
3959 return ObjectCache
::getInstance( $wgMessageCacheType );
3963 * Get the cache object used by the parser cache
3967 function wfGetParserCacheStorage() {
3968 global $wgParserCacheType;
3969 return ObjectCache
::getInstance( $wgParserCacheType );
3973 * Get the cache object used by the language converter
3977 function wfGetLangConverterCacheStorage() {
3978 global $wgLanguageConverterCacheType;
3979 return ObjectCache
::getInstance( $wgLanguageConverterCacheType );
3983 * Call hook functions defined in $wgHooks
3985 * @param string $event Event name
3986 * @param array $args Parameters passed to hook functions
3987 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
3989 * @return bool True if no handler aborted the hook
3991 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
3992 return Hooks
::run( $event, $args, $deprecatedVersion );
3996 * Wrapper around php's unpack.
3998 * @param string $format The format string (See php's docs)
3999 * @param string $data A binary string of binary data
4000 * @param int|bool $length The minimum length of $data or false. This is to
4001 * prevent reading beyond the end of $data. false to disable the check.
4003 * Also be careful when using this function to read unsigned 32 bit integer
4004 * because php might make it negative.
4006 * @throws MWException If $data not long enough, or if unpack fails
4007 * @return array Associative array of the extracted data
4009 function wfUnpack( $format, $data, $length = false ) {
4010 if ( $length !== false ) {
4011 $realLen = strlen( $data );
4012 if ( $realLen < $length ) {
4013 throw new MWException( "Tried to use wfUnpack on a "
4014 . "string of length $realLen, but needed one "
4015 . "of at least length $length."
4020 wfSuppressWarnings();
4021 $result = unpack( $format, $data );
4022 wfRestoreWarnings();
4024 if ( $result === false ) {
4025 // If it cannot extract the packed data.
4026 throw new MWException( "unpack could not unpack binary data" );
4032 * Determine if an image exists on the 'bad image list'.
4034 * The format of MediaWiki:Bad_image_list is as follows:
4035 * * Only list items (lines starting with "*") are considered
4036 * * The first link on a line must be a link to a bad image
4037 * * Any subsequent links on the same line are considered to be exceptions,
4038 * i.e. articles where the image may occur inline.
4040 * @param string $name The image name to check
4041 * @param Title|bool $contextTitle The page on which the image occurs, if known
4042 * @param string $blacklist Wikitext of a file blacklist
4045 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4046 static $badImageCache = null; // based on bad_image_list msg
4047 wfProfileIn( __METHOD__
);
4050 $redirectTitle = RepoGroup
::singleton()->checkRedirect( Title
::makeTitle( NS_FILE
, $name ) );
4051 if ( $redirectTitle ) {
4052 $name = $redirectTitle->getDBkey();
4055 # Run the extension hook
4057 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
4058 wfProfileOut( __METHOD__
);
4062 $cacheable = ( $blacklist === null );
4063 if ( $cacheable && $badImageCache !== null ) {
4064 $badImages = $badImageCache;
4065 } else { // cache miss
4066 if ( $blacklist === null ) {
4067 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4069 # Build the list now
4070 $badImages = array();
4071 $lines = explode( "\n", $blacklist );
4072 foreach ( $lines as $line ) {
4074 if ( substr( $line, 0, 1 ) !== '*' ) {
4080 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4084 $exceptions = array();
4085 $imageDBkey = false;
4086 foreach ( $m[1] as $i => $titleText ) {
4087 $title = Title
::newFromText( $titleText );
4088 if ( !is_null( $title ) ) {
4090 $imageDBkey = $title->getDBkey();
4092 $exceptions[$title->getPrefixedDBkey()] = true;
4097 if ( $imageDBkey !== false ) {
4098 $badImages[$imageDBkey] = $exceptions;
4102 $badImageCache = $badImages;
4106 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
4107 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4108 wfProfileOut( __METHOD__
);
4113 * Determine whether the client at a given source IP is likely to be able to
4114 * access the wiki via HTTPS.
4116 * @param string $ip The IPv4/6 address in the normal human-readable form
4119 function wfCanIPUseHTTPS( $ip ) {
4121 wfRunHooks( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4126 * Work out the IP address based on various globals
4127 * For trusted proxies, use the XFF client IP (first of the chain)
4129 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4132 function wfGetIP() {
4133 wfDeprecated( __METHOD__
, '1.19' );
4135 return $wgRequest->getIP();
4139 * Checks if an IP is a trusted proxy provider.
4140 * Useful to tell if X-Forwarded-For data is possibly bogus.
4141 * Squid cache servers for the site are whitelisted.
4142 * @deprecated Since 1.24, use IP::isTrustedProxy()
4147 function wfIsTrustedProxy( $ip ) {
4148 return IP
::isTrustedProxy( $ip );
4152 * Checks if an IP matches a proxy we've configured.
4153 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4157 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4159 function wfIsConfiguredProxy( $ip ) {
4160 return IP
::isConfiguredProxy( $ip );