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( 'iconv' ) ) {
43 function iconv( $from, $to, $string ) {
44 return Fallback
::iconv( $from, $to, $string );
48 if ( !function_exists( 'mb_substr' ) ) {
53 function mb_substr( $str, $start, $count = 'end' ) {
54 return Fallback
::mb_substr( $str, $start, $count );
61 function mb_substr_split_unicode( $str, $splitPos ) {
62 return Fallback
::mb_substr_split_unicode( $str, $splitPos );
66 if ( !function_exists( 'mb_strlen' ) ) {
71 function mb_strlen( $str, $enc = '' ) {
72 return Fallback
::mb_strlen( $str, $enc );
76 if ( !function_exists( 'mb_strpos' ) ) {
81 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
82 return Fallback
::mb_strpos( $haystack, $needle, $offset, $encoding );
86 if ( !function_exists( 'mb_strrpos' ) ) {
91 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
92 return Fallback
::mb_strrpos( $haystack, $needle, $offset, $encoding );
96 // gzdecode function only exists in PHP >= 5.4.0
97 // http://php.net/gzdecode
98 if ( !function_exists( 'gzdecode' ) ) {
100 * @codeCoverageIgnore
103 function gzdecode( $data ) {
104 return gzinflate( substr( $data, 10, -8 ) );
108 // hash_equals function only exists in PHP >= 5.6.0
109 if ( !function_exists( 'hash_equals' ) ) {
111 * Check whether a user-provided string is equal to a fixed-length secret without
112 * revealing bytes of the secret through timing differences.
114 * This timing guarantee -- that a partial match takes the same time as a complete
115 * mismatch -- is why this function is used in some security-sensitive parts of the code.
116 * For example, it shouldn't be possible to guess an HMAC signature one byte at a time.
118 * Longer explanation: http://www.emerose.com/timing-attacks-explained
120 * @codeCoverageIgnore
121 * @param string $known_string Fixed-length secret to compare against
122 * @param string $user_string User-provided string
123 * @return bool True if the strings are the same, false otherwise
125 function hash_equals( $known_string, $user_string ) {
126 // Strict type checking as in PHP's native implementation
127 if ( !is_string( $known_string ) ) {
128 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
129 gettype( $known_string ) . ' given', E_USER_WARNING
);
134 if ( !is_string( $user_string ) ) {
135 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
136 gettype( $user_string ) . ' given', E_USER_WARNING
);
141 // Note that we do one thing PHP doesn't: try to avoid leaking information about
142 // relative lengths of $known_string and $user_string, and of multiple $known_strings.
143 // However, lengths may still inevitably leak through, for example, CPU cache misses.
144 $known_string_len = strlen( $known_string );
145 $user_string_len = strlen( $user_string );
146 $result = $known_string_len ^
$user_string_len;
147 for ( $i = 0; $i < $user_string_len; $i++
) {
148 $result |
= ord( $known_string[$i %
$known_string_len] ) ^
ord( $user_string[$i] );
151 return ( $result === 0 );
157 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
162 function wfArrayDiff2( $a, $b ) {
163 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
167 * @param array|string $a
168 * @param array|string $b
171 function wfArrayDiff2_cmp( $a, $b ) {
172 if ( is_string( $a ) && is_string( $b ) ) {
173 return strcmp( $a, $b );
174 } elseif ( count( $a ) !== count( $b ) ) {
175 return count( $a ) < count( $b ) ?
-1 : 1;
179 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
180 $cmp = strcmp( $valueA, $valueB );
191 * Returns an array where the values in array $b are replaced by the
192 * values in array $a with the corresponding keys
194 * @deprecated since 1.22; use array_intersect_key()
199 function wfArrayLookup( $a, $b ) {
200 wfDeprecated( __FUNCTION__
, '1.22' );
201 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
205 * Appends to second array if $value differs from that in $default
207 * @param string|int $key
208 * @param mixed $value
209 * @param mixed $default
210 * @param array $changed Array to alter
211 * @throws MWException
213 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
214 if ( is_null( $changed ) ) {
215 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
217 if ( $default[$key] !== $value ) {
218 $changed[$key] = $value;
223 * Backwards array plus for people who haven't bothered to read the PHP manual
224 * XXX: will not darn your socks for you.
226 * @deprecated since 1.22; use array_replace()
228 * @param array $array1 Initial array to merge.
229 * @param array [$array2,...] Variable list of arrays to merge.
232 function wfArrayMerge( $array1 /*...*/ ) {
233 wfDeprecated( __FUNCTION__
, '1.22' );
234 $args = func_get_args();
235 $args = array_reverse( $args, true );
237 foreach ( $args as $arg ) {
244 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
246 * wfMergeErrorArrays(
247 * array( array( 'x' ) ),
248 * array( array( 'x', '2' ) ),
249 * array( array( 'x' ) ),
250 * array( array( 'y' ) )
259 * @param array [$array1,...]
262 function wfMergeErrorArrays( /*...*/ ) {
263 $args = func_get_args();
265 foreach ( $args as $errors ) {
266 foreach ( $errors as $params ) {
267 # @todo FIXME: Sometimes get nested arrays for $params,
268 # which leads to E_NOTICEs
269 $spec = implode( "\t", $params );
270 $out[$spec] = $params;
273 return array_values( $out );
277 * Insert array into another array after the specified *KEY*
279 * @param array $array The array.
280 * @param array $insert The array to insert.
281 * @param mixed $after The key to insert after
284 function wfArrayInsertAfter( array $array, array $insert, $after ) {
285 // Find the offset of the element to insert after.
286 $keys = array_keys( $array );
287 $offsetByKey = array_flip( $keys );
289 $offset = $offsetByKey[$after];
291 // Insert at the specified offset
292 $before = array_slice( $array, 0, $offset +
1, true );
293 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
295 $output = $before +
$insert +
$after;
301 * Recursively converts the parameter (an object) to an array with the same data
303 * @param object|array $objOrArray
304 * @param bool $recursive
307 function wfObjectToArray( $objOrArray, $recursive = true ) {
309 if ( is_object( $objOrArray ) ) {
310 $objOrArray = get_object_vars( $objOrArray );
312 foreach ( $objOrArray as $key => $value ) {
313 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
314 $value = wfObjectToArray( $value );
317 $array[$key] = $value;
324 * Get a random decimal value between 0 and 1, in a way
325 * not likely to give duplicate values for any realistic
326 * number of articles.
330 function wfRandom() {
331 # The maximum random value is "only" 2^31-1, so get two random
332 # values to reduce the chance of dupes
333 $max = mt_getrandmax() +
1;
334 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
340 * Get a random string containing a number of pseudo-random hex
342 * @note This is not secure, if you are trying to generate some sort
343 * of token please use MWCryptRand instead.
345 * @param int $length The length of the string to generate
349 function wfRandomString( $length = 32 ) {
351 for ( $n = 0; $n < $length; $n +
= 7 ) {
352 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
354 return substr( $str, 0, $length );
358 * We want some things to be included as literal characters in our title URLs
359 * for prettiness, which urlencode encodes by default. According to RFC 1738,
360 * all of the following should be safe:
364 * But + is not safe because it's used to indicate a space; &= are only safe in
365 * paths and not in queries (and we don't distinguish here); ' seems kind of
366 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
367 * is reserved, we don't care. So the list we unescape is:
371 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
372 * so no fancy : for IIS7.
374 * %2F in the page titles seems to fatally break for some reason.
379 function wfUrlencode( $s ) {
382 if ( is_null( $s ) ) {
387 if ( is_null( $needle ) ) {
388 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
389 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
390 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
396 $s = urlencode( $s );
399 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
407 * This function takes two arrays as input, and returns a CGI-style string, e.g.
408 * "days=7&limit=100". Options in the first array override options in the second.
409 * Options set to null or false will not be output.
411 * @param array $array1 ( String|Array )
412 * @param array $array2 ( String|Array )
413 * @param string $prefix
416 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
417 if ( !is_null( $array2 ) ) {
418 $array1 = $array1 +
$array2;
422 foreach ( $array1 as $key => $value ) {
423 if ( !is_null( $value ) && $value !== false ) {
427 if ( $prefix !== '' ) {
428 $key = $prefix . "[$key]";
430 if ( is_array( $value ) ) {
432 foreach ( $value as $k => $v ) {
433 $cgi .= $firstTime ?
'' : '&';
434 if ( is_array( $v ) ) {
435 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
437 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
442 if ( is_object( $value ) ) {
443 $value = $value->__toString();
445 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
453 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
454 * its argument and returns the same string in array form. This allows compatibility
455 * with legacy functions that accept raw query strings instead of nice
456 * arrays. Of course, keys and values are urldecode()d.
458 * @param string $query Query string
459 * @return string[] Array version of input
461 function wfCgiToArray( $query ) {
462 if ( isset( $query[0] ) && $query[0] == '?' ) {
463 $query = substr( $query, 1 );
465 $bits = explode( '&', $query );
467 foreach ( $bits as $bit ) {
471 if ( strpos( $bit, '=' ) === false ) {
472 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
476 list( $key, $value ) = explode( '=', $bit );
478 $key = urldecode( $key );
479 $value = urldecode( $value );
480 if ( strpos( $key, '[' ) !== false ) {
481 $keys = array_reverse( explode( '[', $key ) );
482 $key = array_pop( $keys );
484 foreach ( $keys as $k ) {
485 $k = substr( $k, 0, -1 );
486 $temp = array( $k => $temp );
488 if ( isset( $ret[$key] ) ) {
489 $ret[$key] = array_merge( $ret[$key], $temp );
501 * Append a query string to an existing URL, which may or may not already
502 * have query string parameters already. If so, they will be combined.
505 * @param string|string[] $query String or associative array
508 function wfAppendQuery( $url, $query ) {
509 if ( is_array( $query ) ) {
510 $query = wfArrayToCgi( $query );
512 if ( $query != '' ) {
513 if ( false === strpos( $url, '?' ) ) {
524 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
527 * The meaning of the PROTO_* constants is as follows:
528 * PROTO_HTTP: Output a URL starting with http://
529 * PROTO_HTTPS: Output a URL starting with https://
530 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
531 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
532 * on which protocol was used for the current incoming request
533 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
534 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
535 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
537 * @todo this won't work with current-path-relative URLs
538 * like "subdir/foo.html", etc.
540 * @param string $url Either fully-qualified or a local path + query
541 * @param string $defaultProto One of the PROTO_* constants. Determines the
542 * protocol to use if $url or $wgServer is protocol-relative
543 * @return string Fully-qualified URL, current-path-relative URL or false if
544 * no valid URL can be constructed
546 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
547 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
549 if ( $defaultProto === PROTO_CANONICAL
) {
550 $serverUrl = $wgCanonicalServer;
551 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
552 // Make $wgInternalServer fall back to $wgServer if not set
553 $serverUrl = $wgInternalServer;
555 $serverUrl = $wgServer;
556 if ( $defaultProto === PROTO_CURRENT
) {
557 $defaultProto = $wgRequest->getProtocol() . '://';
561 // Analyze $serverUrl to obtain its protocol
562 $bits = wfParseUrl( $serverUrl );
563 $serverHasProto = $bits && $bits['scheme'] != '';
565 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
566 if ( $serverHasProto ) {
567 $defaultProto = $bits['scheme'] . '://';
569 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
570 // This really isn't supposed to happen. Fall back to HTTP in this
572 $defaultProto = PROTO_HTTP
;
576 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
578 if ( substr( $url, 0, 2 ) == '//' ) {
579 $url = $defaultProtoWithoutSlashes . $url;
580 } elseif ( substr( $url, 0, 1 ) == '/' ) {
581 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
582 // otherwise leave it alone.
583 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
586 $bits = wfParseUrl( $url );
588 // ensure proper port for HTTPS arrives in URL
589 // https://bugzilla.wikimedia.org/show_bug.cgi?id=65184
590 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
591 $bits['port'] = $wgHttpsPort;
594 if ( $bits && isset( $bits['path'] ) ) {
595 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
596 return wfAssembleUrl( $bits );
600 } elseif ( substr( $url, 0, 1 ) != '/' ) {
601 # URL is a relative path
602 return wfRemoveDotSegments( $url );
605 # Expanded URL is not valid.
610 * This function will reassemble a URL parsed with wfParseURL. This is useful
611 * if you need to edit part of a URL and put it back together.
613 * This is the basic structure used (brackets contain keys for $urlParts):
614 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
616 * @todo Need to integrate this into wfExpandUrl (bug 32168)
619 * @param array $urlParts URL parts, as output from wfParseUrl
620 * @return string URL assembled from its component parts
622 function wfAssembleUrl( $urlParts ) {
625 if ( isset( $urlParts['delimiter'] ) ) {
626 if ( isset( $urlParts['scheme'] ) ) {
627 $result .= $urlParts['scheme'];
630 $result .= $urlParts['delimiter'];
633 if ( isset( $urlParts['host'] ) ) {
634 if ( isset( $urlParts['user'] ) ) {
635 $result .= $urlParts['user'];
636 if ( isset( $urlParts['pass'] ) ) {
637 $result .= ':' . $urlParts['pass'];
642 $result .= $urlParts['host'];
644 if ( isset( $urlParts['port'] ) ) {
645 $result .= ':' . $urlParts['port'];
649 if ( isset( $urlParts['path'] ) ) {
650 $result .= $urlParts['path'];
653 if ( isset( $urlParts['query'] ) ) {
654 $result .= '?' . $urlParts['query'];
657 if ( isset( $urlParts['fragment'] ) ) {
658 $result .= '#' . $urlParts['fragment'];
665 * Remove all dot-segments in the provided URL path. For example,
666 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
667 * RFC3986 section 5.2.4.
669 * @todo Need to integrate this into wfExpandUrl (bug 32168)
671 * @param string $urlPath URL path, potentially containing dot-segments
672 * @return string URL path with all dot-segments removed
674 function wfRemoveDotSegments( $urlPath ) {
677 $inputLength = strlen( $urlPath );
679 while ( $inputOffset < $inputLength ) {
680 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
681 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
682 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
683 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
686 if ( $prefixLengthTwo == './' ) {
687 # Step A, remove leading "./"
689 } elseif ( $prefixLengthThree == '../' ) {
690 # Step A, remove leading "../"
692 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
693 # Step B, replace leading "/.$" with "/"
695 $urlPath[$inputOffset] = '/';
696 } elseif ( $prefixLengthThree == '/./' ) {
697 # Step B, replace leading "/./" with "/"
699 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
700 # Step C, replace leading "/..$" with "/" and
701 # remove last path component in output
703 $urlPath[$inputOffset] = '/';
705 } elseif ( $prefixLengthFour == '/../' ) {
706 # Step C, replace leading "/../" with "/" and
707 # remove last path component in output
710 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
711 # Step D, remove "^.$"
713 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
714 # Step D, remove "^..$"
717 # Step E, move leading path segment to output
718 if ( $prefixLengthOne == '/' ) {
719 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
721 $slashPos = strpos( $urlPath, '/', $inputOffset );
723 if ( $slashPos === false ) {
724 $output .= substr( $urlPath, $inputOffset );
725 $inputOffset = $inputLength;
727 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
728 $inputOffset +
= $slashPos - $inputOffset;
733 $slashPos = strrpos( $output, '/' );
734 if ( $slashPos === false ) {
737 $output = substr( $output, 0, $slashPos );
746 * Returns a regular expression of url protocols
748 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
749 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
752 function wfUrlProtocols( $includeProtocolRelative = true ) {
753 global $wgUrlProtocols;
755 // Cache return values separately based on $includeProtocolRelative
756 static $withProtRel = null, $withoutProtRel = null;
757 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
758 if ( !is_null( $cachedValue ) ) {
762 // Support old-style $wgUrlProtocols strings, for backwards compatibility
763 // with LocalSettings files from 1.5
764 if ( is_array( $wgUrlProtocols ) ) {
765 $protocols = array();
766 foreach ( $wgUrlProtocols as $protocol ) {
767 // Filter out '//' if !$includeProtocolRelative
768 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
769 $protocols[] = preg_quote( $protocol, '/' );
773 $retval = implode( '|', $protocols );
775 // Ignore $includeProtocolRelative in this case
776 // This case exists for pre-1.6 compatibility, and we can safely assume
777 // that '//' won't appear in a pre-1.6 config because protocol-relative
778 // URLs weren't supported until 1.18
779 $retval = $wgUrlProtocols;
782 // Cache return value
783 if ( $includeProtocolRelative ) {
784 $withProtRel = $retval;
786 $withoutProtRel = $retval;
792 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
793 * you need a regex that matches all URL protocols but does not match protocol-
797 function wfUrlProtocolsWithoutProtRel() {
798 return wfUrlProtocols( false );
802 * parse_url() work-alike, but non-broken. Differences:
804 * 1) Does not raise warnings on bad URLs (just returns false).
805 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
806 * protocol-relative URLs) correctly.
807 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
809 * @param string $url A URL to parse
810 * @return string[] Bits of the URL in an associative array, per PHP docs
812 function wfParseUrl( $url ) {
813 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
815 // Protocol-relative URLs are handled really badly by parse_url(). It's so
816 // bad that the easiest way to handle them is to just prepend 'http:' and
817 // strip the protocol out later.
818 $wasRelative = substr( $url, 0, 2 ) == '//';
819 if ( $wasRelative ) {
822 wfSuppressWarnings();
823 $bits = parse_url( $url );
825 // parse_url() returns an array without scheme for some invalid URLs, e.g.
826 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
827 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
831 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
832 $bits['scheme'] = strtolower( $bits['scheme'] );
834 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
835 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
836 $bits['delimiter'] = '://';
837 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
838 $bits['delimiter'] = ':';
839 // parse_url detects for news: and mailto: the host part of an url as path
840 // We have to correct this wrong detection
841 if ( isset( $bits['path'] ) ) {
842 $bits['host'] = $bits['path'];
849 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
850 if ( !isset( $bits['host'] ) ) {
854 if ( isset( $bits['path'] ) ) {
855 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
856 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
857 $bits['path'] = '/' . $bits['path'];
864 // If the URL was protocol-relative, fix scheme and delimiter
865 if ( $wasRelative ) {
866 $bits['scheme'] = '';
867 $bits['delimiter'] = '//';
873 * Take a URL, make sure it's expanded to fully qualified, and replace any
874 * encoded non-ASCII Unicode characters with their UTF-8 original forms
875 * for more compact display and legibility for local audiences.
877 * @todo handle punycode domains too
882 function wfExpandIRI( $url ) {
883 return preg_replace_callback(
884 '/((?:%[89A-F][0-9A-F])+)/i',
885 'wfExpandIRI_callback',
891 * Private callback for wfExpandIRI
892 * @param array $matches
895 function wfExpandIRI_callback( $matches ) {
896 return urldecode( $matches[1] );
900 * Make URL indexes, appropriate for the el_index field of externallinks.
905 function wfMakeUrlIndexes( $url ) {
906 $bits = wfParseUrl( $url );
908 // Reverse the labels in the hostname, convert to lower case
909 // For emails reverse domainpart only
910 if ( $bits['scheme'] == 'mailto' ) {
911 $mailparts = explode( '@', $bits['host'], 2 );
912 if ( count( $mailparts ) === 2 ) {
913 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
915 // No domain specified, don't mangle it
918 $reversedHost = $domainpart . '@' . $mailparts[0];
920 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
922 // Add an extra dot to the end
923 // Why? Is it in wrong place in mailto links?
924 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
925 $reversedHost .= '.';
927 // Reconstruct the pseudo-URL
928 $prot = $bits['scheme'];
929 $index = $prot . $bits['delimiter'] . $reversedHost;
930 // Leave out user and password. Add the port, path, query and fragment
931 if ( isset( $bits['port'] ) ) {
932 $index .= ':' . $bits['port'];
934 if ( isset( $bits['path'] ) ) {
935 $index .= $bits['path'];
939 if ( isset( $bits['query'] ) ) {
940 $index .= '?' . $bits['query'];
942 if ( isset( $bits['fragment'] ) ) {
943 $index .= '#' . $bits['fragment'];
947 return array( "http:$index", "https:$index" );
949 return array( $index );
954 * Check whether a given URL has a domain that occurs in a given set of domains
955 * @param string $url URL
956 * @param array $domains Array of domains (strings)
957 * @return bool True if the host part of $url ends in one of the strings in $domains
959 function wfMatchesDomainList( $url, $domains ) {
960 $bits = wfParseUrl( $url );
961 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
962 $host = '.' . $bits['host'];
963 foreach ( (array)$domains as $domain ) {
964 $domain = '.' . $domain;
965 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
974 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
975 * In normal operation this is a NOP.
977 * Controlling globals:
978 * $wgDebugLogFile - points to the log file
979 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
980 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
982 * @param string $text
983 * @param string|bool $dest Destination of the message:
984 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
985 * - 'log': only to the log and not in HTML
986 * For backward compatibility, it can also take a boolean:
987 * - true: same as 'all'
988 * - false: same as 'log'
990 function wfDebug( $text, $dest = 'all' ) {
991 global $wgDebugLogFile, $wgDebugRawPage, $wgDebugLogPrefix;
993 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
997 // Turn $dest into a string if it's a boolean (for b/c)
998 if ( $dest === true ) {
1000 } elseif ( $dest === false ) {
1004 $timer = wfDebugTimer();
1005 if ( $timer !== '' ) {
1006 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
1009 if ( $dest === 'all' ) {
1010 MWDebug
::debugMsg( $text );
1013 if ( $wgDebugLogFile != '' ) {
1014 # Strip unprintables; they can switch terminal modes when binary data
1015 # gets dumped, which is pretty annoying.
1016 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
1017 $text = $wgDebugLogPrefix . $text;
1018 wfErrorLog( $text, $wgDebugLogFile );
1023 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1026 function wfIsDebugRawPage() {
1028 if ( $cache !== null ) {
1031 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1032 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1034 isset( $_SERVER['SCRIPT_NAME'] )
1035 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1046 * Get microsecond timestamps for debug logs
1050 function wfDebugTimer() {
1051 global $wgDebugTimestamps, $wgRequestTime;
1053 if ( !$wgDebugTimestamps ) {
1057 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1058 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1059 return "$prefix $mem ";
1063 * Send a line giving PHP memory usage.
1065 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1067 function wfDebugMem( $exact = false ) {
1068 $mem = memory_get_usage();
1070 $mem = floor( $mem / 1024 ) . ' KiB';
1074 wfDebug( "Memory usage: $mem\n" );
1078 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
1079 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string
1080 * filename or an associative array mapping 'destination' to the desired filename. The
1081 * associative array may also contain a 'sample' key with an integer value, specifying
1082 * a sampling factor.
1084 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1086 * @param string $logGroup
1087 * @param string $text
1088 * @param string|bool $dest Destination of the message:
1089 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1090 * - 'log': only to the log and not in HTML
1091 * - 'private': only to the specifc log if set in $wgDebugLogGroups and
1092 * discarded otherwise
1093 * For backward compatibility, it can also take a boolean:
1094 * - true: same as 'all'
1095 * - false: same as 'private'
1097 function wfDebugLog( $logGroup, $text, $dest = 'all' ) {
1098 global $wgDebugLogGroups;
1100 $text = trim( $text ) . "\n";
1102 // Turn $dest into a string if it's a boolean (for b/c)
1103 if ( $dest === true ) {
1105 } elseif ( $dest === false ) {
1109 if ( !isset( $wgDebugLogGroups[$logGroup] ) ) {
1110 if ( $dest !== 'private' ) {
1111 wfDebug( "[$logGroup] $text", $dest );
1116 if ( $dest === 'all' ) {
1117 MWDebug
::debugMsg( "[$logGroup] $text" );
1120 $logConfig = $wgDebugLogGroups[$logGroup];
1121 if ( $logConfig === false ) {
1124 if ( is_array( $logConfig ) ) {
1125 if ( isset( $logConfig['sample'] ) && mt_rand( 1, $logConfig['sample'] ) !== 1 ) {
1128 $destination = $logConfig['destination'];
1130 $destination = strval( $logConfig );
1133 $time = wfTimestamp( TS_DB
);
1135 $host = wfHostname();
1136 wfErrorLog( "$time $host $wiki: $text", $destination );
1140 * Log for database errors
1142 * @param string $text Database error message.
1144 function wfLogDBError( $text ) {
1145 global $wgDBerrorLog, $wgDBerrorLogTZ;
1146 static $logDBErrorTimeZoneObject = null;
1148 if ( $wgDBerrorLog ) {
1149 $host = wfHostname();
1152 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
1153 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
1156 // Workaround for https://bugs.php.net/bug.php?id=52063
1157 // Can be removed when min PHP > 5.3.2
1158 if ( $logDBErrorTimeZoneObject === null ) {
1159 $d = date_create( "now" );
1161 $d = date_create( "now", $logDBErrorTimeZoneObject );
1164 $date = $d->format( 'D M j G:i:s T Y' );
1166 $text = "$date\t$host\t$wiki\t" . trim( $text ) . "\n";
1167 wfErrorLog( $text, $wgDBerrorLog );
1172 * Throws a warning that $function is deprecated
1174 * @param string $function
1175 * @param string|bool $version Version of MediaWiki that the function
1176 * was deprecated in (Added in 1.19).
1177 * @param string|bool $component Added in 1.19.
1178 * @param int $callerOffset How far up the call stack is the original
1179 * caller. 2 = function that called the function that called
1180 * wfDeprecated (Added in 1.20)
1184 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1185 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1189 * Send a warning either to the debug log or in a PHP error depending on
1190 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1192 * @param string $msg message to send
1193 * @param int $callerOffset Number of items to go back in the backtrace to
1194 * find the correct caller (1 = function calling wfWarn, ...)
1195 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1196 * only used when $wgDevelopmentWarnings is true
1198 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1199 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1203 * Send a warning as a PHP error and the debug log. This is intended for logging
1204 * warnings in production. For logging development warnings, use WfWarn instead.
1206 * @param string $msg Message to send
1207 * @param int $callerOffset Number of items to go back in the backtrace to
1208 * find the correct caller (1 = function calling wfLogWarning, ...)
1209 * @param int $level PHP error level; defaults to E_USER_WARNING
1211 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1212 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1216 * Log to a file without getting "file size exceeded" signals.
1218 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1219 * send lines to the specified port, prefixed by the specified prefix and a space.
1221 * @param string $text
1222 * @param string $file Filename
1223 * @throws MWException
1225 function wfErrorLog( $text, $file ) {
1226 if ( substr( $file, 0, 4 ) == 'udp:' ) {
1227 # Needs the sockets extension
1228 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
1229 // IPv6 bracketed host
1231 $port = intval( $m[3] );
1232 $prefix = isset( $m[4] ) ?
$m[4] : false;
1234 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
1236 if ( !IP
::isIPv4( $host ) ) {
1237 $host = gethostbyname( $host );
1239 $port = intval( $m[3] );
1240 $prefix = isset( $m[4] ) ?
$m[4] : false;
1243 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
1246 // Clean it up for the multiplexer
1247 if ( strval( $prefix ) !== '' ) {
1248 $text = preg_replace( '/^/m', $prefix . ' ', $text );
1251 if ( strlen( $text ) > 65506 ) {
1252 $text = substr( $text, 0, 65506 );
1255 if ( substr( $text, -1 ) != "\n" ) {
1258 } elseif ( strlen( $text ) > 65507 ) {
1259 $text = substr( $text, 0, 65507 );
1262 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
1267 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
1268 socket_close( $sock );
1270 wfSuppressWarnings();
1271 $exists = file_exists( $file );
1272 $size = $exists ?
filesize( $file ) : false;
1273 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
1274 file_put_contents( $file, $text, FILE_APPEND
);
1276 wfRestoreWarnings();
1283 function wfLogProfilingData() {
1284 global $wgRequestTime, $wgDebugLogFile, $wgDebugLogGroups, $wgDebugRawPage;
1285 global $wgProfileLimit, $wgUser, $wgRequest;
1287 StatCounter
::singleton()->flush();
1289 $profiler = Profiler
::instance();
1291 # Profiling must actually be enabled...
1292 if ( $profiler->isStub() ) {
1296 // Get total page request time and only show pages that longer than
1297 // $wgProfileLimit time (default is 0)
1298 $elapsed = microtime( true ) - $wgRequestTime;
1299 if ( $elapsed <= $wgProfileLimit ) {
1303 $profiler->logData();
1305 // Check whether this should be logged in the debug file.
1306 if ( isset( $wgDebugLogGroups['profileoutput'] )
1307 && $wgDebugLogGroups['profileoutput'] === false
1309 // Explicitely disabled
1312 if ( !isset( $wgDebugLogGroups['profileoutput'] ) && $wgDebugLogFile == '' ) {
1313 // Logging not enabled; no point going further
1316 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1321 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1322 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
1324 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1325 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
1327 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1328 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
1331 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
1333 // Don't load $wgUser at this late stage just for statistics purposes
1334 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
1335 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1336 $forward .= ' anon';
1339 // Command line script uses a FauxRequest object which does not have
1340 // any knowledge about an URL and throw an exception instead.
1342 $requestUrl = $wgRequest->getRequestURL();
1343 } catch ( MWException
$e ) {
1344 $requestUrl = 'n/a';
1347 $log = sprintf( "%s\t%04.3f\t%s\n",
1348 gmdate( 'YmdHis' ), $elapsed,
1349 urldecode( $requestUrl . $forward ) );
1351 wfDebugLog( 'profileoutput', $log . $profiler->getOutput() );
1355 * Increment a statistics counter
1357 * @param string $key
1361 function wfIncrStats( $key, $count = 1 ) {
1362 StatCounter
::singleton()->incr( $key, $count );
1366 * Check whether the wiki is in read-only mode.
1370 function wfReadOnly() {
1371 return wfReadOnlyReason() !== false;
1375 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1377 * @return string|bool String when in read-only mode; false otherwise
1379 function wfReadOnlyReason() {
1380 global $wgReadOnly, $wgReadOnlyFile;
1382 if ( $wgReadOnly === null ) {
1383 // Set $wgReadOnly for faster access next time
1384 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1385 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1387 $wgReadOnly = false;
1395 * Return a Language object from $langcode
1397 * @param Language|string|bool $langcode Either:
1398 * - a Language object
1399 * - code of the language to get the message for, if it is
1400 * a valid code create a language for that language, if
1401 * it is a string but not a valid code then make a basic
1403 * - a boolean: if it's false then use the global object for
1404 * the current user's language (as a fallback for the old parameter
1405 * functionality), or if it is true then use global object
1406 * for the wiki's content language.
1409 function wfGetLangObj( $langcode = false ) {
1410 # Identify which language to get or create a language object for.
1411 # Using is_object here due to Stub objects.
1412 if ( is_object( $langcode ) ) {
1413 # Great, we already have the object (hopefully)!
1417 global $wgContLang, $wgLanguageCode;
1418 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1419 # $langcode is the language code of the wikis content language object.
1420 # or it is a boolean and value is true
1425 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1426 # $langcode is the language code of user language object.
1427 # or it was a boolean and value is false
1431 $validCodes = array_keys( Language
::fetchLanguageNames() );
1432 if ( in_array( $langcode, $validCodes ) ) {
1433 # $langcode corresponds to a valid language.
1434 return Language
::factory( $langcode );
1437 # $langcode is a string, but not a valid language code; use content language.
1438 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1443 * This is the function for getting translated interface messages.
1445 * @see Message class for documentation how to use them.
1446 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1448 * This function replaces all old wfMsg* functions.
1450 * @param string $key Message key
1451 * @param mixed [$params,...] Normal message parameters
1456 * @see Message::__construct
1458 function wfMessage( $key /*...*/ ) {
1459 $params = func_get_args();
1460 array_shift( $params );
1461 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1462 $params = $params[0];
1464 return new Message( $key, $params );
1468 * This function accepts multiple message keys and returns a message instance
1469 * for the first message which is non-empty. If all messages are empty then an
1470 * instance of the first message key is returned.
1472 * @param string|string[] [$keys,...] Message keys
1477 * @see Message::newFallbackSequence
1479 function wfMessageFallback( /*...*/ ) {
1480 $args = func_get_args();
1481 return call_user_func_array( 'Message::newFallbackSequence', $args );
1485 * Get a message from anywhere, for the current user language.
1487 * Use wfMsgForContent() instead if the message should NOT
1488 * change depending on the user preferences.
1490 * @deprecated since 1.18
1492 * @param string $key lookup key for the message, usually
1493 * defined in languages/Language.php
1495 * Parameters to the message, which can be used to insert variable text into
1496 * it, can be passed to this function in the following formats:
1497 * - One per argument, starting at the second parameter
1498 * - As an array in the second parameter
1499 * These are not shown in the function definition.
1503 function wfMsg( $key ) {
1504 wfDeprecated( __METHOD__
, '1.21' );
1506 $args = func_get_args();
1507 array_shift( $args );
1508 return wfMsgReal( $key, $args );
1512 * Same as above except doesn't transform the message
1514 * @deprecated since 1.18
1516 * @param string $key
1519 function wfMsgNoTrans( $key ) {
1520 wfDeprecated( __METHOD__
, '1.21' );
1522 $args = func_get_args();
1523 array_shift( $args );
1524 return wfMsgReal( $key, $args, true, false, false );
1528 * Get a message from anywhere, for the current global language
1529 * set with $wgLanguageCode.
1531 * Use this if the message should NOT change dependent on the
1532 * language set in the user's preferences. This is the case for
1533 * most text written into logs, as well as link targets (such as
1534 * the name of the copyright policy page). Link titles, on the
1535 * other hand, should be shown in the UI language.
1537 * Note that MediaWiki allows users to change the user interface
1538 * language in their preferences, but a single installation
1539 * typically only contains content in one language.
1541 * Be wary of this distinction: If you use wfMsg() where you should
1542 * use wfMsgForContent(), a user of the software may have to
1543 * customize potentially hundreds of messages in
1544 * order to, e.g., fix a link in every possible language.
1546 * @deprecated since 1.18
1548 * @param string $key Lookup key for the message, usually
1549 * defined in languages/Language.php
1552 function wfMsgForContent( $key ) {
1553 wfDeprecated( __METHOD__
, '1.21' );
1555 global $wgForceUIMsgAsContentMsg;
1556 $args = func_get_args();
1557 array_shift( $args );
1559 if ( is_array( $wgForceUIMsgAsContentMsg )
1560 && in_array( $key, $wgForceUIMsgAsContentMsg )
1562 $forcontent = false;
1564 return wfMsgReal( $key, $args, true, $forcontent );
1568 * Same as above except doesn't transform the message
1570 * @deprecated since 1.18
1572 * @param string $key
1575 function wfMsgForContentNoTrans( $key ) {
1576 wfDeprecated( __METHOD__
, '1.21' );
1578 global $wgForceUIMsgAsContentMsg;
1579 $args = func_get_args();
1580 array_shift( $args );
1582 if ( is_array( $wgForceUIMsgAsContentMsg )
1583 && in_array( $key, $wgForceUIMsgAsContentMsg )
1585 $forcontent = false;
1587 return wfMsgReal( $key, $args, true, $forcontent, false );
1591 * Really get a message
1593 * @deprecated since 1.18
1595 * @param string $key Key to get.
1596 * @param array $args
1597 * @param bool $useDB
1598 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1599 * @param bool $transform Whether or not to transform the message.
1600 * @return string The requested message.
1602 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1603 wfDeprecated( __METHOD__
, '1.21' );
1605 wfProfileIn( __METHOD__
);
1606 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1607 $message = wfMsgReplaceArgs( $message, $args );
1608 wfProfileOut( __METHOD__
);
1613 * Fetch a message string value, but don't replace any keys yet.
1615 * @deprecated since 1.18
1617 * @param string $key
1618 * @param bool $useDB
1619 * @param string|bool $langCode Code of the language to get the message for, or
1620 * behaves as a content language switch if it is a boolean.
1621 * @param bool $transform Whether to parse magic words, etc.
1624 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1625 wfDeprecated( __METHOD__
, '1.21' );
1627 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1629 $cache = MessageCache
::singleton();
1630 $message = $cache->get( $key, $useDB, $langCode );
1631 if ( $message === false ) {
1632 $message = '<' . htmlspecialchars( $key ) . '>';
1633 } elseif ( $transform ) {
1634 $message = $cache->transform( $message );
1640 * Replace message parameter keys on the given formatted output.
1642 * @param string $message
1643 * @param array $args
1647 function wfMsgReplaceArgs( $message, $args ) {
1648 # Fix windows line-endings
1649 # Some messages are split with explode("\n", $msg)
1650 $message = str_replace( "\r", '', $message );
1652 // Replace arguments
1653 if ( count( $args ) ) {
1654 if ( is_array( $args[0] ) ) {
1655 $args = array_values( $args[0] );
1657 $replacementKeys = array();
1658 foreach ( $args as $n => $param ) {
1659 $replacementKeys['$' . ( $n +
1 )] = $param;
1661 $message = strtr( $message, $replacementKeys );
1668 * Return an HTML-escaped version of a message.
1669 * Parameter replacements, if any, are done *after* the HTML-escaping,
1670 * so parameters may contain HTML (eg links or form controls). Be sure
1671 * to pre-escape them if you really do want plaintext, or just wrap
1672 * the whole thing in htmlspecialchars().
1674 * @deprecated since 1.18
1676 * @param string $key
1677 * @param string [$args,...] Parameters
1680 function wfMsgHtml( $key ) {
1681 wfDeprecated( __METHOD__
, '1.21' );
1683 $args = func_get_args();
1684 array_shift( $args );
1685 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1689 * Return an HTML version of message
1690 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1691 * so parameters may contain HTML (eg links or form controls). Be sure
1692 * to pre-escape them if you really do want plaintext, or just wrap
1693 * the whole thing in htmlspecialchars().
1695 * @deprecated since 1.18
1697 * @param string $key
1698 * @param string [$args,...] Parameters
1701 function wfMsgWikiHtml( $key ) {
1702 wfDeprecated( __METHOD__
, '1.21' );
1704 $args = func_get_args();
1705 array_shift( $args );
1706 return wfMsgReplaceArgs(
1707 MessageCache
::singleton()->parse( wfMsgGetKey( $key ), null,
1708 /* can't be set to false */ true, /* interface */ true )->getText(),
1713 * Returns message in the requested format
1715 * @deprecated since 1.18
1717 * @param string $key Key of the message
1718 * @param array $options Processing rules.
1719 * Can take the following options:
1720 * parse: parses wikitext to HTML
1721 * parseinline: parses wikitext to HTML and removes the surrounding
1722 * p's added by parser or tidy
1723 * escape: filters message through htmlspecialchars
1724 * escapenoentities: same, but allows entity references like   through
1725 * replaceafter: parameters are substituted after parsing or escaping
1726 * parsemag: transform the message using magic phrases
1727 * content: fetch message for content language instead of interface
1728 * Also can accept a single associative argument, of the form 'language' => 'xx':
1729 * language: Language object or language code to fetch message for
1730 * (overridden by content).
1731 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1735 function wfMsgExt( $key, $options ) {
1736 wfDeprecated( __METHOD__
, '1.21' );
1738 $args = func_get_args();
1739 array_shift( $args );
1740 array_shift( $args );
1741 $options = (array)$options;
1743 foreach ( $options as $arrayKey => $option ) {
1744 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1745 # An unknown index, neither numeric nor "language"
1746 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
1747 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1748 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1749 'replaceafter', 'parsemag', 'content' ) ) ) {
1750 # A numeric index with unknown value
1751 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
1755 if ( in_array( 'content', $options, true ) ) {
1758 $langCodeObj = null;
1759 } elseif ( array_key_exists( 'language', $options ) ) {
1760 $forContent = false;
1761 $langCode = wfGetLangObj( $options['language'] );
1762 $langCodeObj = $langCode;
1764 $forContent = false;
1766 $langCodeObj = null;
1769 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1771 if ( !in_array( 'replaceafter', $options, true ) ) {
1772 $string = wfMsgReplaceArgs( $string, $args );
1775 $messageCache = MessageCache
::singleton();
1776 $parseInline = in_array( 'parseinline', $options, true );
1777 if ( in_array( 'parse', $options, true ) ||
$parseInline ) {
1778 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1779 if ( $string instanceof ParserOutput
) {
1780 $string = $string->getText();
1783 if ( $parseInline ) {
1784 $string = Parser
::stripOuterParagraph( $string );
1786 } elseif ( in_array( 'parsemag', $options, true ) ) {
1787 $string = $messageCache->transform( $string,
1788 !$forContent, $langCodeObj );
1791 if ( in_array( 'escape', $options, true ) ) {
1792 $string = htmlspecialchars ( $string );
1793 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1794 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
1797 if ( in_array( 'replaceafter', $options, true ) ) {
1798 $string = wfMsgReplaceArgs( $string, $args );
1805 * Since wfMsg() and co suck, they don't return false if the message key they
1806 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1807 * nonexistence of messages by checking the MessageCache::get() result directly.
1809 * @deprecated since 1.18. Use Message::isDisabled().
1811 * @param string $key The message key looked up
1812 * @return bool True if the message *doesn't* exist.
1814 function wfEmptyMsg( $key ) {
1815 wfDeprecated( __METHOD__
, '1.21' );
1817 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1821 * Throw a debugging exception. This function previously once exited the process,
1822 * but now throws an exception instead, with similar results.
1824 * @deprecated since 1.22; just throw an MWException yourself
1825 * @param string $msg Message shown when dying.
1826 * @throws MWException
1828 function wfDebugDieBacktrace( $msg = '' ) {
1829 wfDeprecated( __FUNCTION__
, '1.22' );
1830 throw new MWException( $msg );
1834 * Fetch server name for use in error reporting etc.
1835 * Use real server name if available, so we know which machine
1836 * in a server farm generated the current page.
1840 function wfHostname() {
1842 if ( is_null( $host ) ) {
1844 # Hostname overriding
1845 global $wgOverrideHostname;
1846 if ( $wgOverrideHostname !== false ) {
1847 # Set static and skip any detection
1848 $host = $wgOverrideHostname;
1852 if ( function_exists( 'posix_uname' ) ) {
1853 // This function not present on Windows
1854 $uname = posix_uname();
1858 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1859 $host = $uname['nodename'];
1860 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1861 # Windows computer name
1862 $host = getenv( 'COMPUTERNAME' );
1864 # This may be a virtual server.
1865 $host = $_SERVER['SERVER_NAME'];
1872 * Returns a script tag that stores the amount of time it took MediaWiki to
1873 * handle the request in milliseconds as 'wgBackendResponseTime'.
1875 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1876 * hostname of the server handling the request.
1880 function wfReportTime() {
1881 global $wgRequestTime, $wgShowHostnames;
1883 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1884 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1885 if ( $wgShowHostnames ) {
1886 $reportVars[ 'wgHostname' ] = wfHostname();
1888 return Skin
::makeVariablesScript( $reportVars );
1892 * Safety wrapper for debug_backtrace().
1894 * Will return an empty array if debug_backtrace is disabled, otherwise
1895 * the output from debug_backtrace() (trimmed).
1897 * @param int $limit This parameter can be used to limit the number of stack frames returned
1899 * @return array Array of backtrace information
1901 function wfDebugBacktrace( $limit = 0 ) {
1902 static $disabled = null;
1904 if ( is_null( $disabled ) ) {
1905 $disabled = !function_exists( 'debug_backtrace' );
1907 wfDebug( "debug_backtrace() is disabled\n" );
1914 if ( $limit && version_compare( PHP_VERSION
, '5.4.0', '>=' ) ) {
1915 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1917 return array_slice( debug_backtrace(), 1 );
1922 * Get a debug backtrace as a string
1926 function wfBacktrace() {
1927 global $wgCommandLineMode;
1929 if ( $wgCommandLineMode ) {
1934 $backtrace = wfDebugBacktrace();
1935 foreach ( $backtrace as $call ) {
1936 if ( isset( $call['file'] ) ) {
1937 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1938 $file = $f[count( $f ) - 1];
1942 if ( isset( $call['line'] ) ) {
1943 $line = $call['line'];
1947 if ( $wgCommandLineMode ) {
1948 $msg .= "$file line $line calls ";
1950 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1952 if ( !empty( $call['class'] ) ) {
1953 $msg .= $call['class'] . $call['type'];
1955 $msg .= $call['function'] . '()';
1957 if ( $wgCommandLineMode ) {
1963 if ( $wgCommandLineMode ) {
1973 * Get the name of the function which called this function
1974 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1975 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1976 * wfGetCaller( 3 ) is the parent of that.
1981 function wfGetCaller( $level = 2 ) {
1982 $backtrace = wfDebugBacktrace( $level +
1 );
1983 if ( isset( $backtrace[$level] ) ) {
1984 return wfFormatStackFrame( $backtrace[$level] );
1991 * Return a string consisting of callers in the stack. Useful sometimes
1992 * for profiling specific points.
1994 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1997 function wfGetAllCallers( $limit = 3 ) {
1998 $trace = array_reverse( wfDebugBacktrace() );
1999 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
2000 $limit = count( $trace ) - 1;
2002 $trace = array_slice( $trace, -$limit - 1, $limit );
2003 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
2007 * Return a string representation of frame
2009 * @param array $frame
2012 function wfFormatStackFrame( $frame ) {
2013 return isset( $frame['class'] ) ?
2014 $frame['class'] . '::' . $frame['function'] :
2018 /* Some generic result counters, pulled out of SearchEngine */
2023 * @param int $offset
2027 function wfShowingResults( $offset, $limit ) {
2028 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
2033 * @todo FIXME: We may want to blacklist some broken browsers
2035 * @param bool $force
2036 * @return bool Whereas client accept gzip compression
2038 function wfClientAcceptsGzip( $force = false ) {
2039 static $result = null;
2040 if ( $result === null ||
$force ) {
2042 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
2043 # @todo FIXME: We may want to blacklist some broken browsers
2046 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
2047 $_SERVER['HTTP_ACCEPT_ENCODING'],
2051 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2055 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2064 * Obtain the offset and limit values from the request string;
2065 * used in special pages
2067 * @param int $deflimit Default limit if none supplied
2068 * @param string $optionname Name of a user preference to check against
2070 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2072 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2074 wfDeprecated( __METHOD__
, '1.24' );
2075 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2079 * Escapes the given text so that it may be output using addWikiText()
2080 * without any linking, formatting, etc. making its way through. This
2081 * is achieved by substituting certain characters with HTML entities.
2082 * As required by the callers, "<nowiki>" is not used.
2084 * @param string $text Text to be escaped
2087 function wfEscapeWikiText( $text ) {
2088 static $repl = null, $repl2 = null;
2089 if ( $repl === null ) {
2091 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
2092 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
2093 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
2094 "\n#" => "\n#", "\r#" => "\r#",
2095 "\n*" => "\n*", "\r*" => "\r*",
2096 "\n:" => "\n:", "\r:" => "\r:",
2097 "\n " => "\n ", "\r " => "\r ",
2098 "\n\n" => "\n ", "\r\n" => " \n",
2099 "\n\r" => "\n ", "\r\r" => "\r ",
2100 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
2101 "\n----" => "\n----", "\r----" => "\r----",
2102 '__' => '__', '://' => '://',
2105 // We have to catch everything "\s" matches in PCRE
2106 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2107 $repl["$magic "] = "$magic ";
2108 $repl["$magic\t"] = "$magic	";
2109 $repl["$magic\r"] = "$magic ";
2110 $repl["$magic\n"] = "$magic ";
2111 $repl["$magic\f"] = "$magic";
2114 // And handle protocols that don't use "://"
2115 global $wgUrlProtocols;
2117 foreach ( $wgUrlProtocols as $prot ) {
2118 if ( substr( $prot, -1 ) === ':' ) {
2119 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2122 $repl2 = $repl2 ?
'/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2124 $text = substr( strtr( "\n$text", $repl ), 1 );
2125 $text = preg_replace( $repl2, '$1:', $text );
2130 * Get the current unix timestamp with microseconds. Useful for profiling
2131 * @deprecated since 1.22; call microtime() directly
2135 wfDeprecated( __FUNCTION__
, '1.22' );
2136 return microtime( true );
2140 * Sets dest to source and returns the original value of dest
2141 * If source is NULL, it just returns the value, it doesn't set the variable
2142 * If force is true, it will set the value even if source is NULL
2144 * @param mixed $dest
2145 * @param mixed $source
2146 * @param bool $force
2149 function wfSetVar( &$dest, $source, $force = false ) {
2151 if ( !is_null( $source ) ||
$force ) {
2158 * As for wfSetVar except setting a bit
2162 * @param bool $state
2166 function wfSetBit( &$dest, $bit, $state = true ) {
2167 $temp = (bool)( $dest & $bit );
2168 if ( !is_null( $state ) ) {
2179 * A wrapper around the PHP function var_export().
2180 * Either print it or add it to the regular output ($wgOut).
2182 * @param mixed $var A PHP variable to dump.
2184 function wfVarDump( $var ) {
2186 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2187 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
2190 $wgOut->addHTML( $s );
2195 * Provide a simple HTTP error.
2197 * @param int|string $code
2198 * @param string $label
2199 * @param string $desc
2201 function wfHttpError( $code, $label, $desc ) {
2204 header( "HTTP/1.0 $code $label" );
2205 header( "Status: $code $label" );
2206 $wgOut->sendCacheControl();
2208 header( 'Content-type: text/html; charset=utf-8' );
2209 print "<!doctype html>" .
2210 '<html><head><title>' .
2211 htmlspecialchars( $label ) .
2212 '</title></head><body><h1>' .
2213 htmlspecialchars( $label ) .
2215 nl2br( htmlspecialchars( $desc ) ) .
2216 "</p></body></html>\n";
2220 * Clear away any user-level output buffers, discarding contents.
2222 * Suitable for 'starting afresh', for instance when streaming
2223 * relatively large amounts of data without buffering, or wanting to
2224 * output image files without ob_gzhandler's compression.
2226 * The optional $resetGzipEncoding parameter controls suppression of
2227 * the Content-Encoding header sent by ob_gzhandler; by default it
2228 * is left. See comments for wfClearOutputBuffers() for why it would
2231 * Note that some PHP configuration options may add output buffer
2232 * layers which cannot be removed; these are left in place.
2234 * @param bool $resetGzipEncoding
2236 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2237 if ( $resetGzipEncoding ) {
2238 // Suppress Content-Encoding and Content-Length
2239 // headers from 1.10+s wfOutputHandler
2240 global $wgDisableOutputCompression;
2241 $wgDisableOutputCompression = true;
2243 while ( $status = ob_get_status() ) {
2244 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2245 // Probably from zlib.output_compression or other
2246 // PHP-internal setting which can't be removed.
2248 // Give up, and hope the result doesn't break
2252 if ( !ob_end_clean() ) {
2253 // Could not remove output buffer handler; abort now
2254 // to avoid getting in some kind of infinite loop.
2257 if ( $resetGzipEncoding ) {
2258 if ( $status['name'] == 'ob_gzhandler' ) {
2259 // Reset the 'Content-Encoding' field set by this handler
2260 // so we can start fresh.
2261 header_remove( 'Content-Encoding' );
2269 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2271 * Clear away output buffers, but keep the Content-Encoding header
2272 * produced by ob_gzhandler, if any.
2274 * This should be used for HTTP 304 responses, where you need to
2275 * preserve the Content-Encoding header of the real result, but
2276 * also need to suppress the output of ob_gzhandler to keep to spec
2277 * and avoid breaking Firefox in rare cases where the headers and
2278 * body are broken over two packets.
2280 function wfClearOutputBuffers() {
2281 wfResetOutputBuffers( false );
2285 * Converts an Accept-* header into an array mapping string values to quality
2288 * @param string $accept
2289 * @param string $def default
2290 * @return float[] Associative array of string => float pairs
2292 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2293 # No arg means accept anything (per HTTP spec)
2295 return array( $def => 1.0 );
2300 $parts = explode( ',', $accept );
2302 foreach ( $parts as $part ) {
2303 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2304 $values = explode( ';', trim( $part ) );
2306 if ( count( $values ) == 1 ) {
2307 $prefs[$values[0]] = 1.0;
2308 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2309 $prefs[$values[0]] = floatval( $match[1] );
2317 * Checks if a given MIME type matches any of the keys in the given
2318 * array. Basic wildcards are accepted in the array keys.
2320 * Returns the matching MIME type (or wildcard) if a match, otherwise
2323 * @param string $type
2324 * @param array $avail
2328 function mimeTypeMatch( $type, $avail ) {
2329 if ( array_key_exists( $type, $avail ) ) {
2332 $parts = explode( '/', $type );
2333 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2334 return $parts[0] . '/*';
2335 } elseif ( array_key_exists( '*/*', $avail ) ) {
2344 * Returns the 'best' match between a client's requested internet media types
2345 * and the server's list of available types. Each list should be an associative
2346 * array of type to preference (preference is a float between 0.0 and 1.0).
2347 * Wildcards in the types are acceptable.
2349 * @param array $cprefs Client's acceptable type list
2350 * @param array $sprefs Server's offered types
2353 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2354 * XXX: generalize to negotiate other stuff
2356 function wfNegotiateType( $cprefs, $sprefs ) {
2359 foreach ( array_keys( $sprefs ) as $type ) {
2360 $parts = explode( '/', $type );
2361 if ( $parts[1] != '*' ) {
2362 $ckey = mimeTypeMatch( $type, $cprefs );
2364 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2369 foreach ( array_keys( $cprefs ) as $type ) {
2370 $parts = explode( '/', $type );
2371 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2372 $skey = mimeTypeMatch( $type, $sprefs );
2374 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2382 foreach ( array_keys( $combine ) as $type ) {
2383 if ( $combine[$type] > $bestq ) {
2385 $bestq = $combine[$type];
2393 * Reference-counted warning suppression
2397 function wfSuppressWarnings( $end = false ) {
2398 static $suppressCount = 0;
2399 static $originalLevel = false;
2402 if ( $suppressCount ) {
2404 if ( !$suppressCount ) {
2405 error_reporting( $originalLevel );
2409 if ( !$suppressCount ) {
2410 $originalLevel = error_reporting( E_ALL
& ~
(
2425 * Restore error level to previous value
2427 function wfRestoreWarnings() {
2428 wfSuppressWarnings( true );
2431 # Autodetect, convert and provide timestamps of various types
2434 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2436 define( 'TS_UNIX', 0 );
2439 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2441 define( 'TS_MW', 1 );
2444 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2446 define( 'TS_DB', 2 );
2449 * RFC 2822 format, for E-mail and HTTP headers
2451 define( 'TS_RFC2822', 3 );
2454 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2456 * This is used by Special:Export
2458 define( 'TS_ISO_8601', 4 );
2461 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2463 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2464 * DateTime tag and page 36 for the DateTimeOriginal and
2465 * DateTimeDigitized tags.
2467 define( 'TS_EXIF', 5 );
2470 * Oracle format time.
2472 define( 'TS_ORACLE', 6 );
2475 * Postgres format time.
2477 define( 'TS_POSTGRES', 7 );
2480 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2482 define( 'TS_ISO_8601_BASIC', 9 );
2485 * Get a timestamp string in one of various formats
2487 * @param mixed $outputtype A timestamp in one of the supported formats, the
2488 * function will autodetect which format is supplied and act accordingly.
2489 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2490 * @return string|bool String / false The same date in the format specified in $outputtype or false
2492 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2494 $timestamp = new MWTimestamp( $ts );
2495 return $timestamp->getTimestamp( $outputtype );
2496 } catch ( TimestampException
$e ) {
2497 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2503 * Return a formatted timestamp, or null if input is null.
2504 * For dealing with nullable timestamp columns in the database.
2506 * @param int $outputtype
2510 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2511 if ( is_null( $ts ) ) {
2514 return wfTimestamp( $outputtype, $ts );
2519 * Convenience function; returns MediaWiki timestamp for the present time.
2523 function wfTimestampNow() {
2525 return wfTimestamp( TS_MW
, time() );
2529 * Check if the operating system is Windows
2531 * @return bool True if it's Windows, false otherwise.
2533 function wfIsWindows() {
2534 static $isWindows = null;
2535 if ( $isWindows === null ) {
2536 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2542 * Check if we are running under HHVM
2546 function wfIsHHVM() {
2547 return defined( 'HHVM_VERSION' );
2551 * Swap two variables
2553 * @deprecated since 1.24
2557 function swap( &$x, &$y ) {
2558 wfDeprecated( __FUNCTION__
, '1.24' );
2565 * Tries to get the system directory for temporary files. First
2566 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2567 * environment variables are then checked in sequence, and if none are
2568 * set try sys_get_temp_dir().
2570 * NOTE: When possible, use instead the tmpfile() function to create
2571 * temporary files to avoid race conditions on file creation, etc.
2575 function wfTempDir() {
2576 global $wgTmpDirectory;
2578 if ( $wgTmpDirectory !== false ) {
2579 return $wgTmpDirectory;
2582 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2584 foreach ( $tmpDir as $tmp ) {
2585 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2589 return sys_get_temp_dir();
2593 * Make directory, and make all parent directories if they don't exist
2595 * @param string $dir Full path to directory to create
2596 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2597 * @param string $caller Optional caller param for debugging.
2598 * @throws MWException
2601 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2602 global $wgDirectoryMode;
2604 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2605 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2608 if ( !is_null( $caller ) ) {
2609 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2612 if ( strval( $dir ) === '' ||
( file_exists( $dir ) && is_dir( $dir ) ) ) {
2616 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2618 if ( is_null( $mode ) ) {
2619 $mode = $wgDirectoryMode;
2622 // Turn off the normal warning, we're doing our own below
2623 wfSuppressWarnings();
2624 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2625 wfRestoreWarnings();
2628 //directory may have been created on another request since we last checked
2629 if ( is_dir( $dir ) ) {
2633 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2634 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2640 * Remove a directory and all its content.
2641 * Does not hide error.
2642 * @param string $dir
2644 function wfRecursiveRemoveDir( $dir ) {
2645 wfDebug( __FUNCTION__
. "( $dir )\n" );
2646 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2647 if ( is_dir( $dir ) ) {
2648 $objects = scandir( $dir );
2649 foreach ( $objects as $object ) {
2650 if ( $object != "." && $object != ".." ) {
2651 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2652 wfRecursiveRemoveDir( $dir . '/' . $object );
2654 unlink( $dir . '/' . $object );
2664 * @param int $nr The number to format
2665 * @param int $acc The number of digits after the decimal point, default 2
2666 * @param bool $round Whether or not to round the value, default true
2669 function wfPercent( $nr, $acc = 2, $round = true ) {
2670 $ret = sprintf( "%.${acc}f", $nr );
2671 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2675 * Safety wrapper around ini_get() for boolean settings.
2676 * The values returned from ini_get() are pre-normalized for settings
2677 * set via php.ini or php_flag/php_admin_flag... but *not*
2678 * for those set via php_value/php_admin_value.
2680 * It's fairly common for people to use php_value instead of php_flag,
2681 * which can leave you with an 'off' setting giving a false positive
2682 * for code that just takes the ini_get() return value as a boolean.
2684 * To make things extra interesting, setting via php_value accepts
2685 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2686 * Unrecognized values go false... again opposite PHP's own coercion
2687 * from string to bool.
2689 * Luckily, 'properly' set settings will always come back as '0' or '1',
2690 * so we only have to worry about them and the 'improper' settings.
2692 * I frickin' hate PHP... :P
2694 * @param string $setting
2697 function wfIniGetBool( $setting ) {
2698 $val = strtolower( ini_get( $setting ) );
2699 // 'on' and 'true' can't have whitespace around them, but '1' can.
2703 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2707 * Windows-compatible version of escapeshellarg()
2708 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2709 * function puts single quotes in regardless of OS.
2711 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2712 * earlier distro releases of PHP)
2714 * @param string [$args,...]
2717 function wfEscapeShellArg( /*...*/ ) {
2718 wfInitShellLocale();
2720 $args = func_get_args();
2723 foreach ( $args as $arg ) {
2730 if ( wfIsWindows() ) {
2731 // Escaping for an MSVC-style command line parser and CMD.EXE
2732 // @codingStandardsIgnoreStart For long URLs
2734 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2735 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2738 // Double the backslashes before any double quotes. Escape the double quotes.
2739 // @codingStandardsIgnoreEnd
2740 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2743 foreach ( $tokens as $token ) {
2744 if ( $iteration %
2 == 1 ) {
2745 // Delimiter, a double quote preceded by zero or more slashes
2746 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2747 } elseif ( $iteration %
4 == 2 ) {
2748 // ^ in $token will be outside quotes, need to be escaped
2749 $arg .= str_replace( '^', '^^', $token );
2750 } else { // $iteration % 4 == 0
2751 // ^ in $token will appear inside double quotes, so leave as is
2756 // Double the backslashes before the end of the string, because
2757 // we will soon add a quote
2759 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2760 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2763 // Add surrounding quotes
2764 $retVal .= '"' . $arg . '"';
2766 $retVal .= escapeshellarg( $arg );
2773 * Check if wfShellExec() is effectively disabled via php.ini config
2775 * @return bool|string False or one of (safemode,disabled)
2778 function wfShellExecDisabled() {
2779 static $disabled = null;
2780 if ( is_null( $disabled ) ) {
2781 if ( wfIniGetBool( 'safe_mode' ) ) {
2782 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2783 $disabled = 'safemode';
2784 } elseif ( !function_exists( 'proc_open' ) ) {
2785 wfDebug( "proc_open() is disabled\n" );
2786 $disabled = 'disabled';
2795 * Execute a shell command, with time and memory limits mirrored from the PHP
2796 * configuration if supported.
2798 * @param string $cmd Command line, properly escaped for shell.
2799 * @param null|mixed &$retval Optional, will receive the program's exit code.
2800 * (non-zero is usually failure). If there is an error from
2801 * read, select, or proc_open(), this will be set to -1.
2802 * @param array $environ Optional environment variables which should be
2803 * added to the executed command environment.
2804 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2805 * this overwrites the global wgMaxShell* limits.
2806 * @param array $options Array of options:
2807 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2808 * including errors from limit.sh
2810 * @return string Collected stdout as a string
2812 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2813 $limits = array(), $options = array()
2815 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2816 $wgMaxShellWallClockTime, $wgShellCgroup;
2818 $disabled = wfShellExecDisabled();
2821 return $disabled == 'safemode' ?
2822 'Unable to run external programs in safe mode.' :
2823 'Unable to run external programs, proc_open() is disabled.';
2826 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2828 wfInitShellLocale();
2831 foreach ( $environ as $k => $v ) {
2832 if ( wfIsWindows() ) {
2833 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2834 * appear in the environment variable, so we must use carat escaping as documented in
2835 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2836 * Note however that the quote isn't listed there, but is needed, and the parentheses
2837 * are listed there but doesn't appear to need it.
2839 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2841 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2842 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2844 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2847 $cmd = $envcmd . $cmd;
2849 $useLogPipe = false;
2850 if ( is_executable( '/bin/bash' ) ) {
2851 $time = intval ( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2852 if ( isset( $limits['walltime'] ) ) {
2853 $wallTime = intval( $limits['walltime'] );
2854 } elseif ( isset( $limits['time'] ) ) {
2857 $wallTime = intval( $wgMaxShellWallClockTime );
2859 $mem = intval ( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2860 $filesize = intval ( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2862 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2863 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2864 escapeshellarg( $cmd ) . ' ' .
2866 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2867 "MW_CPU_LIMIT=$time; " .
2868 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2869 "MW_MEM_LIMIT=$mem; " .
2870 "MW_FILE_SIZE_LIMIT=$filesize; " .
2871 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2872 "MW_USE_LOG_PIPE=yes"
2875 } elseif ( $includeStderr ) {
2878 } elseif ( $includeStderr ) {
2881 wfDebug( "wfShellExec: $cmd\n" );
2884 0 => array( 'file', 'php://stdin', 'r' ),
2885 1 => array( 'pipe', 'w' ),
2886 2 => array( 'file', 'php://stderr', 'w' ) );
2887 if ( $useLogPipe ) {
2888 $desc[3] = array( 'pipe', 'w' );
2891 $proc = proc_open( $cmd, $desc, $pipes );
2893 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2897 $outBuffer = $logBuffer = '';
2898 $emptyArray = array();
2902 // According to the documentation, it is possible for stream_select()
2903 // to fail due to EINTR. I haven't managed to induce this in testing
2904 // despite sending various signals. If it did happen, the error
2905 // message would take the form:
2907 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2909 // where [4] is the value of the macro EINTR and "Interrupted system
2910 // call" is string which according to the Linux manual is "possibly"
2911 // localised according to LC_MESSAGES.
2912 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2913 $eintrMessage = "stream_select(): unable to select [$eintr]";
2915 // Build a table mapping resource IDs to pipe FDs to work around a
2916 // PHP 5.3 issue in which stream_select() does not preserve array keys
2917 // <https://bugs.php.net/bug.php?id=53427>.
2919 foreach ( $pipes as $fd => $pipe ) {
2920 $fds[(int)$pipe] = $fd;
2924 $status = proc_get_status( $proc );
2925 if ( !$status['running'] ) {
2930 $readyPipes = $pipes;
2933 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2934 @trigger_error
( '' );
2935 if ( @stream_select
( $readyPipes, $emptyArray, $emptyArray, null ) === false ) {
2936 // @codingStandardsIgnoreEnd
2937 $error = error_get_last();
2938 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2941 trigger_error( $error['message'], E_USER_WARNING
);
2942 $logMsg = $error['message'];
2946 foreach ( $readyPipes as $pipe ) {
2947 $block = fread( $pipe, 65536 );
2948 $fd = $fds[(int)$pipe];
2949 if ( $block === '' ) {
2951 fclose( $pipes[$fd] );
2952 unset( $pipes[$fd] );
2956 } elseif ( $block === false ) {
2958 $logMsg = "Error reading from pipe";
2960 } elseif ( $fd == 1 ) {
2962 $outBuffer .= $block;
2963 } elseif ( $fd == 3 ) {
2965 $logBuffer .= $block;
2966 if ( strpos( $block, "\n" ) !== false ) {
2967 $lines = explode( "\n", $logBuffer );
2968 $logBuffer = array_pop( $lines );
2969 foreach ( $lines as $line ) {
2970 wfDebugLog( 'exec', $line );
2977 foreach ( $pipes as $pipe ) {
2981 // Use the status previously collected if possible, since proc_get_status()
2982 // just calls waitpid() which will not return anything useful the second time.
2983 if ( $status === false ) {
2984 $status = proc_get_status( $proc );
2987 if ( $logMsg !== false ) {
2988 // Read/select error
2990 proc_close( $proc );
2991 } elseif ( $status['signaled'] ) {
2992 $logMsg = "Exited with signal {$status['termsig']}";
2993 $retval = 128 +
$status['termsig'];
2994 proc_close( $proc );
2996 if ( $status['running'] ) {
2997 $retval = proc_close( $proc );
2999 $retval = $status['exitcode'];
3000 proc_close( $proc );
3002 if ( $retval == 127 ) {
3003 $logMsg = "Possibly missing executable file";
3004 } elseif ( $retval >= 129 && $retval <= 192 ) {
3005 $logMsg = "Probably exited with signal " . ( $retval - 128 );
3009 if ( $logMsg !== false ) {
3010 wfDebugLog( 'exec', "$logMsg: $cmd" );
3017 * Execute a shell command, returning both stdout and stderr. Convenience
3018 * function, as all the arguments to wfShellExec can become unwieldy.
3020 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
3021 * @param string $cmd Command line, properly escaped for shell.
3022 * @param null|mixed &$retval Optional, will receive the program's exit code.
3023 * (non-zero is usually failure)
3024 * @param array $environ optional environment variables which should be
3025 * added to the executed command environment.
3026 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
3027 * this overwrites the global wgMaxShell* limits.
3028 * @return string Collected stdout and stderr as a string
3030 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
3031 return wfShellExec( $cmd, $retval, $environ, $limits, array( 'duplicateStderr' => true ) );
3035 * Workaround for http://bugs.php.net/bug.php?id=45132
3036 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
3038 function wfInitShellLocale() {
3039 static $done = false;
3044 global $wgShellLocale;
3045 if ( !wfIniGetBool( 'safe_mode' ) ) {
3046 putenv( "LC_CTYPE=$wgShellLocale" );
3047 setlocale( LC_CTYPE
, $wgShellLocale );
3052 * Alias to wfShellWikiCmd()
3054 * @see wfShellWikiCmd()
3056 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
3057 return wfShellWikiCmd( $script, $parameters, $options );
3061 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3062 * Note that $parameters should be a flat array and an option with an argument
3063 * should consist of two consecutive items in the array (do not use "--option value").
3065 * @param string $script MediaWiki cli script path
3066 * @param array $parameters Arguments and options to the script
3067 * @param array $options Associative array of options:
3068 * 'php': The path to the php executable
3069 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3072 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3074 // Give site config file a chance to run the script in a wrapper.
3075 // The caller may likely want to call wfBasename() on $script.
3076 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3077 $cmd = isset( $options['php'] ) ?
array( $options['php'] ) : array( $wgPhpCli );
3078 if ( isset( $options['wrapper'] ) ) {
3079 $cmd[] = $options['wrapper'];
3082 // Escape each parameter for shell
3083 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
3087 * wfMerge attempts to merge differences between three texts.
3088 * Returns true for a clean merge and false for failure or a conflict.
3090 * @param string $old
3091 * @param string $mine
3092 * @param string $yours
3093 * @param string $result
3096 function wfMerge( $old, $mine, $yours, &$result ) {
3099 # This check may also protect against code injection in
3100 # case of broken installations.
3101 wfSuppressWarnings();
3102 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3103 wfRestoreWarnings();
3105 if ( !$haveDiff3 ) {
3106 wfDebug( "diff3 not found\n" );
3110 # Make temporary files
3112 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3113 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3114 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3116 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3117 # a newline character. To avoid this, we normalize the trailing whitespace before
3118 # creating the diff.
3120 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3121 fclose( $oldtextFile );
3122 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3123 fclose( $mytextFile );
3124 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3125 fclose( $yourtextFile );
3127 # Check for a conflict
3128 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
3129 wfEscapeShellArg( $mytextName ) . ' ' .
3130 wfEscapeShellArg( $oldtextName ) . ' ' .
3131 wfEscapeShellArg( $yourtextName );
3132 $handle = popen( $cmd, 'r' );
3134 if ( fgets( $handle, 1024 ) ) {
3142 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
3143 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
3144 $handle = popen( $cmd, 'r' );
3147 $data = fread( $handle, 8192 );
3148 if ( strlen( $data ) == 0 ) {
3154 unlink( $mytextName );
3155 unlink( $oldtextName );
3156 unlink( $yourtextName );
3158 if ( $result === '' && $old !== '' && !$conflict ) {
3159 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3166 * Returns unified plain-text diff of two texts.
3167 * Useful for machine processing of diffs.
3169 * @param string $before The text before the changes.
3170 * @param string $after The text after the changes.
3171 * @param string $params Command-line options for the diff command.
3172 * @return string Unified diff of $before and $after
3174 function wfDiff( $before, $after, $params = '-u' ) {
3175 if ( $before == $after ) {
3180 wfSuppressWarnings();
3181 $haveDiff = $wgDiff && file_exists( $wgDiff );
3182 wfRestoreWarnings();
3184 # This check may also protect against code injection in
3185 # case of broken installations.
3187 wfDebug( "diff executable not found\n" );
3188 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3189 $format = new UnifiedDiffFormatter();
3190 return $format->format( $diffs );
3193 # Make temporary files
3195 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3196 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3198 fwrite( $oldtextFile, $before );
3199 fclose( $oldtextFile );
3200 fwrite( $newtextFile, $after );
3201 fclose( $newtextFile );
3203 // Get the diff of the two files
3204 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3206 $h = popen( $cmd, 'r' );
3211 $data = fread( $h, 8192 );
3212 if ( strlen( $data ) == 0 ) {
3220 unlink( $oldtextName );
3221 unlink( $newtextName );
3223 // Kill the --- and +++ lines. They're not useful.
3224 $diff_lines = explode( "\n", $diff );
3225 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
3226 unset( $diff_lines[0] );
3228 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
3229 unset( $diff_lines[1] );
3232 $diff = implode( "\n", $diff_lines );
3238 * This function works like "use VERSION" in Perl, the program will die with a
3239 * backtrace if the current version of PHP is less than the version provided
3241 * This is useful for extensions which due to their nature are not kept in sync
3242 * with releases, and might depend on other versions of PHP than the main code
3244 * Note: PHP might die due to parsing errors in some cases before it ever
3245 * manages to call this function, such is life
3247 * @see perldoc -f use
3249 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3250 * @throws MWException
3252 function wfUsePHP( $req_ver ) {
3253 $php_ver = PHP_VERSION
;
3255 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3256 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3261 * This function works like "use VERSION" in Perl except it checks the version
3262 * of MediaWiki, the program will die with a backtrace if the current version
3263 * of MediaWiki is less than the version provided.
3265 * This is useful for extensions which due to their nature are not kept in sync
3268 * Note: Due to the behavior of PHP's version_compare() which is used in this
3269 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3270 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3271 * targeted version number. For example if you wanted to allow any variation
3272 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3273 * not result in the same comparison due to the internal logic of
3274 * version_compare().
3276 * @see perldoc -f use
3278 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3279 * @throws MWException
3281 function wfUseMW( $req_ver ) {
3284 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3285 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3290 * Return the final portion of a pathname.
3291 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3292 * http://bugs.php.net/bug.php?id=33898
3294 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3295 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3297 * @param string $path
3298 * @param string $suffix String to remove if present
3301 function wfBaseName( $path, $suffix = '' ) {
3302 if ( $suffix == '' ) {
3305 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3309 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3317 * Generate a relative path name to the given file.
3318 * May explode on non-matching case-insensitive paths,
3319 * funky symlinks, etc.
3321 * @param string $path Absolute destination path including target filename
3322 * @param string $from Absolute source path, directory only
3325 function wfRelativePath( $path, $from ) {
3326 // Normalize mixed input on Windows...
3327 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
3328 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
3330 // Trim trailing slashes -- fix for drive root
3331 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
3332 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
3334 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
3335 $against = explode( DIRECTORY_SEPARATOR
, $from );
3337 if ( $pieces[0] !== $against[0] ) {
3338 // Non-matching Windows drive letters?
3339 // Return a full path.
3343 // Trim off common prefix
3344 while ( count( $pieces ) && count( $against )
3345 && $pieces[0] == $against[0] ) {
3346 array_shift( $pieces );
3347 array_shift( $against );
3350 // relative dots to bump us to the parent
3351 while ( count( $against ) ) {
3352 array_unshift( $pieces, '..' );
3353 array_shift( $against );
3356 array_push( $pieces, wfBaseName( $path ) );
3358 return implode( DIRECTORY_SEPARATOR
, $pieces );
3362 * Convert an arbitrarily-long digit string from one numeric base
3363 * to another, optionally zero-padding to a minimum column width.
3365 * Supports base 2 through 36; digit values 10-36 are represented
3366 * as lowercase letters a-z. Input is case-insensitive.
3368 * @param string $input Input number
3369 * @param int $sourceBase Base of the input number
3370 * @param int $destBase Desired base of the output
3371 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3372 * @param bool $lowercase Whether to output in lowercase or uppercase
3373 * @param string $engine Either "gmp", "bcmath", or "php"
3374 * @return string|bool The output number as a string, or false on error
3376 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3377 $lowercase = true, $engine = 'auto'
3379 $input = (string)$input;
3385 $sourceBase != (int)$sourceBase ||
3386 $destBase != (int)$destBase ||
3387 $pad != (int)$pad ||
3389 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3396 static $baseChars = array(
3397 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3398 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3399 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3400 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3401 34 => 'y', 35 => 'z',
3403 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3404 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3405 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3406 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3407 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3408 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3411 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' ||
$engine == 'gmp' ) ) {
3412 $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
3413 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' ||
$engine == 'bcmath' ) ) {
3415 foreach ( str_split( strtolower( $input ) ) as $char ) {
3416 $decimal = bcmul( $decimal, $sourceBase );
3417 $decimal = bcadd( $decimal, $baseChars[$char] );
3420 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3421 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3422 $result .= $baseChars[bcmod( $decimal, $destBase )];
3424 // @codingStandardsIgnoreEnd
3426 $result = strrev( $result );
3428 $inDigits = array();
3429 foreach ( str_split( strtolower( $input ) ) as $char ) {
3430 $inDigits[] = $baseChars[$char];
3433 // Iterate over the input, modulo-ing out an output digit
3434 // at a time until input is gone.
3436 while ( $inDigits ) {
3438 $workDigits = array();
3441 foreach ( $inDigits as $digit ) {
3442 $work *= $sourceBase;
3445 if ( $workDigits ||
$work >= $destBase ) {
3446 $workDigits[] = (int)( $work / $destBase );
3451 // All that division leaves us with a remainder,
3452 // which is conveniently our next output digit.
3453 $result .= $baseChars[$work];
3456 $inDigits = $workDigits;
3459 $result = strrev( $result );
3462 if ( !$lowercase ) {
3463 $result = strtoupper( $result );
3466 return str_pad( $result, $pad, '0', STR_PAD_LEFT
);
3470 * Check if there is sufficient entropy in php's built-in session generation
3472 * @return bool true = there is sufficient entropy
3474 function wfCheckEntropy() {
3476 ( wfIsWindows() && version_compare( PHP_VERSION
, '5.3.3', '>=' ) )
3477 ||
ini_get( 'session.entropy_file' )
3479 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3483 * Override session_id before session startup if php's built-in
3484 * session generation code is not secure.
3486 function wfFixSessionID() {
3487 // If the cookie or session id is already set we already have a session and should abort
3488 if ( isset( $_COOKIE[session_name()] ) ||
session_id() ) {
3492 // PHP's built-in session entropy is enabled if:
3493 // - entropy_file is set or you're on Windows with php 5.3.3+
3494 // - AND entropy_length is > 0
3495 // We treat it as disabled if it doesn't have an entropy length of at least 32
3496 $entropyEnabled = wfCheckEntropy();
3498 // If built-in entropy is not enabled or not sufficient override PHP's
3499 // built in session id generation code
3500 if ( !$entropyEnabled ) {
3501 wfDebug( __METHOD__
. ": PHP's built in entropy is disabled or not sufficient, " .
3502 "overriding session id generation using our cryptrand source.\n" );
3503 session_id( MWCryptRand
::generateHex( 32 ) );
3508 * Reset the session_id
3512 function wfResetSessionID() {
3513 global $wgCookieSecure;
3514 $oldSessionId = session_id();
3515 $cookieParams = session_get_cookie_params();
3516 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3517 session_regenerate_id( false );
3521 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
3524 $newSessionId = session_id();
3525 wfRunHooks( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3529 * Initialise php session
3531 * @param bool $sessionId
3533 function wfSetupSession( $sessionId = false ) {
3534 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3535 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3536 if ( $wgSessionsInObjectCache ||
$wgSessionsInMemcached ) {
3537 ObjectCacheSessionHandler
::install();
3538 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3539 # Only set this if $wgSessionHandler isn't null and session.save_handler
3540 # hasn't already been set to the desired value (that causes errors)
3541 ini_set( 'session.save_handler', $wgSessionHandler );
3543 session_set_cookie_params(
3544 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3545 session_cache_limiter( 'private, must-revalidate' );
3547 session_id( $sessionId );
3551 wfSuppressWarnings();
3553 wfRestoreWarnings();
3557 * Get an object from the precompiled serialized directory
3559 * @param string $name
3560 * @return mixed The variable on success, false on failure
3562 function wfGetPrecompiledData( $name ) {
3565 $file = "$IP/serialized/$name";
3566 if ( file_exists( $file ) ) {
3567 $blob = file_get_contents( $file );
3569 return unserialize( $blob );
3578 * @param string [$args,...]
3581 function wfMemcKey( /*...*/ ) {
3582 global $wgCachePrefix;
3583 $prefix = $wgCachePrefix === false ?
wfWikiID() : $wgCachePrefix;
3584 $args = func_get_args();
3585 $key = $prefix . ':' . implode( ':', $args );
3586 $key = str_replace( ' ', '_', $key );
3591 * Get a cache key for a foreign DB
3594 * @param string $prefix
3595 * @param string [$args,...]
3598 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3599 $args = array_slice( func_get_args(), 2 );
3601 $key = "$db-$prefix:" . implode( ':', $args );
3603 $key = $db . ':' . implode( ':', $args );
3605 return str_replace( ' ', '_', $key );
3609 * Get an ASCII string identifying this wiki
3610 * This is used as a prefix in memcached keys
3614 function wfWikiID() {
3615 global $wgDBprefix, $wgDBname;
3616 if ( $wgDBprefix ) {
3617 return "$wgDBname-$wgDBprefix";
3624 * Split a wiki ID into DB name and table prefix
3626 * @param string $wiki
3630 function wfSplitWikiID( $wiki ) {
3631 $bits = explode( '-', $wiki, 2 );
3632 if ( count( $bits ) < 2 ) {
3639 * Get a Database object.
3641 * @param int $db Index of the connection to get. May be DB_MASTER for the
3642 * master (for write queries), DB_SLAVE for potentially lagged read
3643 * queries, or an integer >= 0 for a particular server.
3645 * @param string|string[] $groups Query groups. An array of group names that this query
3646 * belongs to. May contain a single string if the query is only
3649 * @param string|bool $wiki The wiki ID, or false for the current wiki
3651 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3652 * will always return the same object, unless the underlying connection or load
3653 * balancer is manually destroyed.
3655 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3656 * updater to ensure that a proper database is being updated.
3658 * @return DatabaseBase
3660 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3661 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3665 * Get a load balancer object.
3667 * @param string|bool $wiki wiki ID, or false for the current wiki
3668 * @return LoadBalancer
3670 function wfGetLB( $wiki = false ) {
3671 return wfGetLBFactory()->getMainLB( $wiki );
3675 * Get the load balancer factory object
3679 function &wfGetLBFactory() {
3680 return LBFactory
::singleton();
3685 * Shortcut for RepoGroup::singleton()->findFile()
3687 * @param string $title or Title object
3688 * @param array $options Associative array of options:
3689 * time: requested time for an archived image, or false for the
3690 * current version. An image object will be returned which was
3691 * created at the specified time.
3693 * ignoreRedirect: If true, do not follow file redirects
3695 * private: If true, return restricted (deleted) files if the current
3696 * user is allowed to view them. Otherwise, such files will not
3699 * bypassCache: If true, do not use the process-local cache of File objects
3701 * @return File|bool File, or false if the file does not exist
3703 function wfFindFile( $title, $options = array() ) {
3704 return RepoGroup
::singleton()->findFile( $title, $options );
3708 * Get an object referring to a locally registered file.
3709 * Returns a valid placeholder object if the file does not exist.
3711 * @param Title|string $title
3712 * @return LocalFile|null A File, or null if passed an invalid Title
3714 function wfLocalFile( $title ) {
3715 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3719 * Should low-performance queries be disabled?
3722 * @codeCoverageIgnore
3724 function wfQueriesMustScale() {
3725 global $wgMiserMode;
3727 ||
( SiteStats
::pages() > 100000
3728 && SiteStats
::edits() > 1000000
3729 && SiteStats
::users() > 10000 );
3733 * Get the path to a specified script file, respecting file
3734 * extensions; this is a wrapper around $wgScriptExtension etc.
3735 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3737 * @param string $script Script filename, sans extension
3740 function wfScript( $script = 'index' ) {
3741 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3742 if ( $script === 'index' ) {
3744 } elseif ( $script === 'load' ) {
3745 return $wgLoadScript;
3747 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3752 * Get the script URL.
3754 * @return string script URL
3756 function wfGetScriptUrl() {
3757 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3759 # as it was called, minus the query string.
3761 # Some sites use Apache rewrite rules to handle subdomains,
3762 # and have PHP set up in a weird way that causes PHP_SELF
3763 # to contain the rewritten URL instead of the one that the
3764 # outside world sees.
3766 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3767 # provides containing the "before" URL.
3768 return $_SERVER['SCRIPT_NAME'];
3770 return $_SERVER['URL'];
3775 * Convenience function converts boolean values into "true"
3776 * or "false" (string) values
3778 * @param bool $value
3781 function wfBoolToStr( $value ) {
3782 return $value ?
'true' : 'false';
3786 * Get a platform-independent path to the null file, e.g. /dev/null
3790 function wfGetNull() {
3791 return wfIsWindows() ?
'NUL' : '/dev/null';
3795 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3796 * and waiting for it to go down, this waits for the slaves to catch up to the
3797 * master position. Use this when updating very large numbers of rows, as
3798 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3799 * a no-op if there are no slaves.
3801 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3802 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3803 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3805 function wfWaitForSlaves( $ifWritesSince = false, $wiki = false, $cluster = false ) {
3806 // B/C: first argument used to be "max seconds of lag"; ignore such values
3807 $ifWritesSince = ( $ifWritesSince > 1e9
) ?
$ifWritesSince : false;
3809 if ( $cluster !== false ) {
3810 $lb = wfGetLBFactory()->getExternalLB( $cluster );
3812 $lb = wfGetLB( $wiki );
3815 // bug 27975 - Don't try to wait for slaves if there are none
3816 // Prevents permission error when getting master position
3817 if ( $lb->getServerCount() > 1 ) {
3818 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3819 return; // assume no writes done
3821 $dbw = $lb->getConnection( DB_MASTER
, array(), $wiki );
3822 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3823 return; // no writes since the last wait
3825 $pos = $dbw->getMasterPos();
3826 // The DBMS may not support getMasterPos() or the whole
3827 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3828 if ( $pos !== false ) {
3829 $lb->waitForAll( $pos );
3835 * Count down from $seconds to zero on the terminal, with a one-second pause
3836 * between showing each number. For use in command-line scripts.
3838 * @codeCoverageIgnore
3839 * @param int $seconds
3841 function wfCountDown( $seconds ) {
3842 for ( $i = $seconds; $i >= 0; $i-- ) {
3843 if ( $i != $seconds ) {
3844 echo str_repeat( "\x08", strlen( $i +
1 ) );
3856 * Replace all invalid characters with -
3857 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3858 * By default, $wgIllegalFileChars = ':'
3860 * @param string $name Filename to process
3863 function wfStripIllegalFilenameChars( $name ) {
3864 global $wgIllegalFileChars;
3865 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3866 $name = wfBaseName( $name );
3867 $name = preg_replace(
3868 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3876 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3878 * @return int Value the memory limit was set to.
3880 function wfMemoryLimit() {
3881 global $wgMemoryLimit;
3882 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3883 if ( $memlimit != -1 ) {
3884 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3885 if ( $conflimit == -1 ) {
3886 wfDebug( "Removing PHP's memory limit\n" );
3887 wfSuppressWarnings();
3888 ini_set( 'memory_limit', $conflimit );
3889 wfRestoreWarnings();
3891 } elseif ( $conflimit > $memlimit ) {
3892 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3893 wfSuppressWarnings();
3894 ini_set( 'memory_limit', $conflimit );
3895 wfRestoreWarnings();
3903 * Converts shorthand byte notation to integer form
3905 * @param string $string
3908 function wfShorthandToInteger( $string = '' ) {
3909 $string = trim( $string );
3910 if ( $string === '' ) {
3913 $last = $string[strlen( $string ) - 1];
3914 $val = intval( $string );
3919 // break intentionally missing
3923 // break intentionally missing
3933 * Get the normalised IETF language tag
3934 * See unit test for examples.
3936 * @param string $code The language code.
3937 * @return string The language code which complying with BCP 47 standards.
3939 function wfBCP47( $code ) {
3940 $codeSegment = explode( '-', $code );
3942 foreach ( $codeSegment as $segNo => $seg ) {
3943 // when previous segment is x, it is a private segment and should be lc
3944 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3945 $codeBCP[$segNo] = strtolower( $seg );
3946 // ISO 3166 country code
3947 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3948 $codeBCP[$segNo] = strtoupper( $seg );
3949 // ISO 15924 script code
3950 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3951 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3952 // Use lowercase for other cases
3954 $codeBCP[$segNo] = strtolower( $seg );
3957 $langCode = implode( '-', $codeBCP );
3962 * Get a cache object.
3964 * @param int $inputType Cache type, one the the CACHE_* constants.
3967 function wfGetCache( $inputType ) {
3968 return ObjectCache
::getInstance( $inputType );
3972 * Get the main cache object
3976 function wfGetMainCache() {
3977 global $wgMainCacheType;
3978 return ObjectCache
::getInstance( $wgMainCacheType );
3982 * Get the cache object used by the message cache
3986 function wfGetMessageCacheStorage() {
3987 global $wgMessageCacheType;
3988 return ObjectCache
::getInstance( $wgMessageCacheType );
3992 * Get the cache object used by the parser cache
3996 function wfGetParserCacheStorage() {
3997 global $wgParserCacheType;
3998 return ObjectCache
::getInstance( $wgParserCacheType );
4002 * Get the cache object used by the language converter
4006 function wfGetLangConverterCacheStorage() {
4007 global $wgLanguageConverterCacheType;
4008 return ObjectCache
::getInstance( $wgLanguageConverterCacheType );
4012 * Call hook functions defined in $wgHooks
4014 * @param string $event Event name
4015 * @param array $args Parameters passed to hook functions
4016 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
4018 * @return bool True if no handler aborted the hook
4020 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
4021 return Hooks
::run( $event, $args, $deprecatedVersion );
4025 * Wrapper around php's unpack.
4027 * @param string $format The format string (See php's docs)
4028 * @param string $data A binary string of binary data
4029 * @param int|bool $length The minimum length of $data or false. This is to
4030 * prevent reading beyond the end of $data. false to disable the check.
4032 * Also be careful when using this function to read unsigned 32 bit integer
4033 * because php might make it negative.
4035 * @throws MWException if $data not long enough, or if unpack fails
4036 * @return array Associative array of the extracted data
4038 function wfUnpack( $format, $data, $length = false ) {
4039 if ( $length !== false ) {
4040 $realLen = strlen( $data );
4041 if ( $realLen < $length ) {
4042 throw new MWException( "Tried to use wfUnpack on a "
4043 . "string of length $realLen, but needed one "
4044 . "of at least length $length."
4049 wfSuppressWarnings();
4050 $result = unpack( $format, $data );
4051 wfRestoreWarnings();
4053 if ( $result === false ) {
4054 // If it cannot extract the packed data.
4055 throw new MWException( "unpack could not unpack binary data" );
4061 * Determine if an image exists on the 'bad image list'.
4063 * The format of MediaWiki:Bad_image_list is as follows:
4064 * * Only list items (lines starting with "*") are considered
4065 * * The first link on a line must be a link to a bad image
4066 * * Any subsequent links on the same line are considered to be exceptions,
4067 * i.e. articles where the image may occur inline.
4069 * @param string $name The image name to check
4070 * @param Title|bool $contextTitle The page on which the image occurs, if known
4071 * @param string $blacklist Wikitext of a file blacklist
4074 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4075 static $badImageCache = null; // based on bad_image_list msg
4076 wfProfileIn( __METHOD__
);
4079 $redirectTitle = RepoGroup
::singleton()->checkRedirect( Title
::makeTitle( NS_FILE
, $name ) );
4080 if ( $redirectTitle ) {
4081 $name = $redirectTitle->getDBkey();
4084 # Run the extension hook
4086 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
4087 wfProfileOut( __METHOD__
);
4091 $cacheable = ( $blacklist === null );
4092 if ( $cacheable && $badImageCache !== null ) {
4093 $badImages = $badImageCache;
4094 } else { // cache miss
4095 if ( $blacklist === null ) {
4096 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4098 # Build the list now
4099 $badImages = array();
4100 $lines = explode( "\n", $blacklist );
4101 foreach ( $lines as $line ) {
4103 if ( substr( $line, 0, 1 ) !== '*' ) {
4109 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4113 $exceptions = array();
4114 $imageDBkey = false;
4115 foreach ( $m[1] as $i => $titleText ) {
4116 $title = Title
::newFromText( $titleText );
4117 if ( !is_null( $title ) ) {
4119 $imageDBkey = $title->getDBkey();
4121 $exceptions[$title->getPrefixedDBkey()] = true;
4126 if ( $imageDBkey !== false ) {
4127 $badImages[$imageDBkey] = $exceptions;
4131 $badImageCache = $badImages;
4135 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
4136 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4137 wfProfileOut( __METHOD__
);
4142 * Determine whether the client at a given source IP is likely to be able to
4143 * access the wiki via HTTPS.
4145 * @param string $ip The IPv4/6 address in the normal human-readable form
4148 function wfCanIPUseHTTPS( $ip ) {
4150 wfRunHooks( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4155 * Work out the IP address based on various globals
4156 * For trusted proxies, use the XFF client IP (first of the chain)
4158 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4161 function wfGetIP() {
4162 wfDeprecated( __METHOD__
, '1.19' );
4164 return $wgRequest->getIP();
4168 * Checks if an IP is a trusted proxy provider.
4169 * Useful to tell if X-Forwarded-For data is possibly bogus.
4170 * Squid cache servers for the site are whitelisted.
4171 * @deprecated Since 1.24, use IP::isTrustedProxy()
4176 function wfIsTrustedProxy( $ip ) {
4177 return IP
::isTrustedProxy( $ip );
4181 * Checks if an IP matches a proxy we've configured.
4182 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4186 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4188 function wfIsConfiguredProxy( $ip ) {
4189 return IP
::isConfiguredProxy( $ip );