3 * Global functions used everywhere.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 if ( !defined( 'MEDIAWIKI' ) ) {
24 die( "This file is part of MediaWiki, it is not a valid entry point" );
27 // Hide compatibility functions from Doxygen
31 * Compatibility functions
33 * We support PHP 5.3.2 and up.
34 * Re-implementations of newer functions or functions in non-standard
35 * PHP extensions may be included here.
38 if ( !function_exists( 'mb_substr' ) ) {
43 function mb_substr( $str, $start, $count = 'end' ) {
44 return Fallback
::mb_substr( $str, $start, $count );
51 function mb_substr_split_unicode( $str, $splitPos ) {
52 return Fallback
::mb_substr_split_unicode( $str, $splitPos );
56 if ( !function_exists( 'mb_strlen' ) ) {
61 function mb_strlen( $str, $enc = '' ) {
62 return Fallback
::mb_strlen( $str, $enc );
66 if ( !function_exists( 'mb_strpos' ) ) {
71 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
72 return Fallback
::mb_strpos( $haystack, $needle, $offset, $encoding );
76 if ( !function_exists( 'mb_strrpos' ) ) {
81 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
82 return Fallback
::mb_strrpos( $haystack, $needle, $offset, $encoding );
86 // gzdecode function only exists in PHP >= 5.4.0
87 // http://php.net/gzdecode
88 if ( !function_exists( 'gzdecode' ) ) {
93 function gzdecode( $data ) {
94 return gzinflate( substr( $data, 10, -8 ) );
98 // hash_equals function only exists in PHP >= 5.6.0
99 if ( !function_exists( 'hash_equals' ) ) {
101 * Check whether a user-provided string is equal to a fixed-length secret without
102 * revealing bytes of the secret through timing differences.
104 * This timing guarantee -- that a partial match takes the same time as a complete
105 * mismatch -- is why this function is used in some security-sensitive parts of the code.
106 * For example, it shouldn't be possible to guess an HMAC signature one byte at a time.
108 * Longer explanation: http://www.emerose.com/timing-attacks-explained
110 * @codeCoverageIgnore
111 * @param string $known_string Fixed-length secret to compare against
112 * @param string $user_string User-provided string
113 * @return bool True if the strings are the same, false otherwise
115 function hash_equals( $known_string, $user_string ) {
116 // Strict type checking as in PHP's native implementation
117 if ( !is_string( $known_string ) ) {
118 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
119 gettype( $known_string ) . ' given', E_USER_WARNING
);
124 if ( !is_string( $user_string ) ) {
125 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
126 gettype( $user_string ) . ' given', E_USER_WARNING
);
131 // Note that we do one thing PHP doesn't: try to avoid leaking information about
132 // relative lengths of $known_string and $user_string, and of multiple $known_strings.
133 // However, lengths may still inevitably leak through, for example, CPU cache misses.
134 $known_string_len = strlen( $known_string );
135 $user_string_len = strlen( $user_string );
136 $result = $known_string_len ^
$user_string_len;
137 for ( $i = 0; $i < $user_string_len; $i++
) {
138 $result |
= ord( $known_string[$i %
$known_string_len] ) ^
ord( $user_string[$i] );
141 return ( $result === 0 );
147 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
152 function wfArrayDiff2( $a, $b ) {
153 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
157 * @param array|string $a
158 * @param array|string $b
161 function wfArrayDiff2_cmp( $a, $b ) {
162 if ( is_string( $a ) && is_string( $b ) ) {
163 return strcmp( $a, $b );
164 } elseif ( count( $a ) !== count( $b ) ) {
165 return count( $a ) < count( $b ) ?
-1 : 1;
169 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
170 $cmp = strcmp( $valueA, $valueB );
181 * Returns an array where the values in array $b are replaced by the
182 * values in array $a with the corresponding keys
184 * @deprecated since 1.22; use array_intersect_key()
189 function wfArrayLookup( $a, $b ) {
190 wfDeprecated( __FUNCTION__
, '1.22' );
191 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
195 * Appends to second array if $value differs from that in $default
197 * @param string|int $key
198 * @param mixed $value
199 * @param mixed $default
200 * @param array $changed Array to alter
201 * @throws MWException
203 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
204 if ( is_null( $changed ) ) {
205 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
207 if ( $default[$key] !== $value ) {
208 $changed[$key] = $value;
213 * Backwards array plus for people who haven't bothered to read the PHP manual
214 * XXX: will not darn your socks for you.
216 * @deprecated since 1.22; use array_replace()
218 * @param array $array1 Initial array to merge.
219 * @param array $array2,... Variable list of arrays to merge.
222 function wfArrayMerge( $array1 /*...*/ ) {
223 wfDeprecated( __FUNCTION__
, '1.22' );
224 $args = func_get_args();
225 $args = array_reverse( $args, true );
227 foreach ( $args as $arg ) {
234 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
236 * wfMergeErrorArrays(
237 * array( array( 'x' ) ),
238 * array( array( 'x', '2' ) ),
239 * array( array( 'x' ) ),
240 * array( array( 'y' ) )
249 * @param array $array1,...
252 function wfMergeErrorArrays( /*...*/ ) {
253 $args = func_get_args();
255 foreach ( $args as $errors ) {
256 foreach ( $errors as $params ) {
257 # @todo FIXME: Sometimes get nested arrays for $params,
258 # which leads to E_NOTICEs
259 $spec = implode( "\t", $params );
260 $out[$spec] = $params;
263 return array_values( $out );
267 * Insert array into another array after the specified *KEY*
269 * @param array $array The array.
270 * @param array $insert The array to insert.
271 * @param mixed $after The key to insert after
274 function wfArrayInsertAfter( array $array, array $insert, $after ) {
275 // Find the offset of the element to insert after.
276 $keys = array_keys( $array );
277 $offsetByKey = array_flip( $keys );
279 $offset = $offsetByKey[$after];
281 // Insert at the specified offset
282 $before = array_slice( $array, 0, $offset +
1, true );
283 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
285 $output = $before +
$insert +
$after;
291 * Recursively converts the parameter (an object) to an array with the same data
293 * @param object|array $objOrArray
294 * @param bool $recursive
297 function wfObjectToArray( $objOrArray, $recursive = true ) {
299 if ( is_object( $objOrArray ) ) {
300 $objOrArray = get_object_vars( $objOrArray );
302 foreach ( $objOrArray as $key => $value ) {
303 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
304 $value = wfObjectToArray( $value );
307 $array[$key] = $value;
314 * Get a random decimal value between 0 and 1, in a way
315 * not likely to give duplicate values for any realistic
316 * number of articles.
320 function wfRandom() {
321 # The maximum random value is "only" 2^31-1, so get two random
322 # values to reduce the chance of dupes
323 $max = mt_getrandmax() +
1;
324 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
330 * Get a random string containing a number of pseudo-random hex
332 * @note This is not secure, if you are trying to generate some sort
333 * of token please use MWCryptRand instead.
335 * @param int $length The length of the string to generate
339 function wfRandomString( $length = 32 ) {
341 for ( $n = 0; $n < $length; $n +
= 7 ) {
342 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
344 return substr( $str, 0, $length );
348 * We want some things to be included as literal characters in our title URLs
349 * for prettiness, which urlencode encodes by default. According to RFC 1738,
350 * all of the following should be safe:
354 * But + is not safe because it's used to indicate a space; &= are only safe in
355 * paths and not in queries (and we don't distinguish here); ' seems kind of
356 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
357 * is reserved, we don't care. So the list we unescape is:
361 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
362 * so no fancy : for IIS7.
364 * %2F in the page titles seems to fatally break for some reason.
369 function wfUrlencode( $s ) {
372 if ( is_null( $s ) ) {
377 if ( is_null( $needle ) ) {
378 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
379 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
380 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
386 $s = urlencode( $s );
389 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
397 * This function takes two arrays as input, and returns a CGI-style string, e.g.
398 * "days=7&limit=100". Options in the first array override options in the second.
399 * Options set to null or false will not be output.
401 * @param array $array1 ( String|Array )
402 * @param array $array2 ( String|Array )
403 * @param string $prefix
406 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
407 if ( !is_null( $array2 ) ) {
408 $array1 = $array1 +
$array2;
412 foreach ( $array1 as $key => $value ) {
413 if ( !is_null( $value ) && $value !== false ) {
417 if ( $prefix !== '' ) {
418 $key = $prefix . "[$key]";
420 if ( is_array( $value ) ) {
422 foreach ( $value as $k => $v ) {
423 $cgi .= $firstTime ?
'' : '&';
424 if ( is_array( $v ) ) {
425 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
427 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
432 if ( is_object( $value ) ) {
433 $value = $value->__toString();
435 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
443 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
444 * its argument and returns the same string in array form. This allows compatibility
445 * with legacy functions that accept raw query strings instead of nice
446 * arrays. Of course, keys and values are urldecode()d.
448 * @param string $query Query string
449 * @return string[] Array version of input
451 function wfCgiToArray( $query ) {
452 if ( isset( $query[0] ) && $query[0] == '?' ) {
453 $query = substr( $query, 1 );
455 $bits = explode( '&', $query );
457 foreach ( $bits as $bit ) {
461 if ( strpos( $bit, '=' ) === false ) {
462 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
466 list( $key, $value ) = explode( '=', $bit );
468 $key = urldecode( $key );
469 $value = urldecode( $value );
470 if ( strpos( $key, '[' ) !== false ) {
471 $keys = array_reverse( explode( '[', $key ) );
472 $key = array_pop( $keys );
474 foreach ( $keys as $k ) {
475 $k = substr( $k, 0, -1 );
476 $temp = array( $k => $temp );
478 if ( isset( $ret[$key] ) ) {
479 $ret[$key] = array_merge( $ret[$key], $temp );
491 * Append a query string to an existing URL, which may or may not already
492 * have query string parameters already. If so, they will be combined.
495 * @param string|string[] $query String or associative array
498 function wfAppendQuery( $url, $query ) {
499 if ( is_array( $query ) ) {
500 $query = wfArrayToCgi( $query );
502 if ( $query != '' ) {
503 if ( false === strpos( $url, '?' ) ) {
514 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
517 * The meaning of the PROTO_* constants is as follows:
518 * PROTO_HTTP: Output a URL starting with http://
519 * PROTO_HTTPS: Output a URL starting with https://
520 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
521 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
522 * on which protocol was used for the current incoming request
523 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
524 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
525 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
527 * @todo this won't work with current-path-relative URLs
528 * like "subdir/foo.html", etc.
530 * @param string $url Either fully-qualified or a local path + query
531 * @param string $defaultProto One of the PROTO_* constants. Determines the
532 * protocol to use if $url or $wgServer is protocol-relative
533 * @return string Fully-qualified URL, current-path-relative URL or false if
534 * no valid URL can be constructed
536 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
537 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
539 if ( $defaultProto === PROTO_CANONICAL
) {
540 $serverUrl = $wgCanonicalServer;
541 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
542 // Make $wgInternalServer fall back to $wgServer if not set
543 $serverUrl = $wgInternalServer;
545 $serverUrl = $wgServer;
546 if ( $defaultProto === PROTO_CURRENT
) {
547 $defaultProto = $wgRequest->getProtocol() . '://';
551 // Analyze $serverUrl to obtain its protocol
552 $bits = wfParseUrl( $serverUrl );
553 $serverHasProto = $bits && $bits['scheme'] != '';
555 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
556 if ( $serverHasProto ) {
557 $defaultProto = $bits['scheme'] . '://';
559 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
560 // This really isn't supposed to happen. Fall back to HTTP in this
562 $defaultProto = PROTO_HTTP
;
566 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
568 if ( substr( $url, 0, 2 ) == '//' ) {
569 $url = $defaultProtoWithoutSlashes . $url;
570 } elseif ( substr( $url, 0, 1 ) == '/' ) {
571 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
572 // otherwise leave it alone.
573 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
576 $bits = wfParseUrl( $url );
578 // ensure proper port for HTTPS arrives in URL
579 // https://bugzilla.wikimedia.org/show_bug.cgi?id=65184
580 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
581 $bits['port'] = $wgHttpsPort;
584 if ( $bits && isset( $bits['path'] ) ) {
585 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
586 return wfAssembleUrl( $bits );
590 } elseif ( substr( $url, 0, 1 ) != '/' ) {
591 # URL is a relative path
592 return wfRemoveDotSegments( $url );
595 # Expanded URL is not valid.
600 * This function will reassemble a URL parsed with wfParseURL. This is useful
601 * if you need to edit part of a URL and put it back together.
603 * This is the basic structure used (brackets contain keys for $urlParts):
604 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
606 * @todo Need to integrate this into wfExpandUrl (bug 32168)
609 * @param array $urlParts URL parts, as output from wfParseUrl
610 * @return string URL assembled from its component parts
612 function wfAssembleUrl( $urlParts ) {
615 if ( isset( $urlParts['delimiter'] ) ) {
616 if ( isset( $urlParts['scheme'] ) ) {
617 $result .= $urlParts['scheme'];
620 $result .= $urlParts['delimiter'];
623 if ( isset( $urlParts['host'] ) ) {
624 if ( isset( $urlParts['user'] ) ) {
625 $result .= $urlParts['user'];
626 if ( isset( $urlParts['pass'] ) ) {
627 $result .= ':' . $urlParts['pass'];
632 $result .= $urlParts['host'];
634 if ( isset( $urlParts['port'] ) ) {
635 $result .= ':' . $urlParts['port'];
639 if ( isset( $urlParts['path'] ) ) {
640 $result .= $urlParts['path'];
643 if ( isset( $urlParts['query'] ) ) {
644 $result .= '?' . $urlParts['query'];
647 if ( isset( $urlParts['fragment'] ) ) {
648 $result .= '#' . $urlParts['fragment'];
655 * Remove all dot-segments in the provided URL path. For example,
656 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
657 * RFC3986 section 5.2.4.
659 * @todo Need to integrate this into wfExpandUrl (bug 32168)
661 * @param string $urlPath URL path, potentially containing dot-segments
662 * @return string URL path with all dot-segments removed
664 function wfRemoveDotSegments( $urlPath ) {
667 $inputLength = strlen( $urlPath );
669 while ( $inputOffset < $inputLength ) {
670 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
671 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
672 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
673 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
676 if ( $prefixLengthTwo == './' ) {
677 # Step A, remove leading "./"
679 } elseif ( $prefixLengthThree == '../' ) {
680 # Step A, remove leading "../"
682 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
683 # Step B, replace leading "/.$" with "/"
685 $urlPath[$inputOffset] = '/';
686 } elseif ( $prefixLengthThree == '/./' ) {
687 # Step B, replace leading "/./" with "/"
689 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
690 # Step C, replace leading "/..$" with "/" and
691 # remove last path component in output
693 $urlPath[$inputOffset] = '/';
695 } elseif ( $prefixLengthFour == '/../' ) {
696 # Step C, replace leading "/../" with "/" and
697 # remove last path component in output
700 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
701 # Step D, remove "^.$"
703 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
704 # Step D, remove "^..$"
707 # Step E, move leading path segment to output
708 if ( $prefixLengthOne == '/' ) {
709 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
711 $slashPos = strpos( $urlPath, '/', $inputOffset );
713 if ( $slashPos === false ) {
714 $output .= substr( $urlPath, $inputOffset );
715 $inputOffset = $inputLength;
717 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
718 $inputOffset +
= $slashPos - $inputOffset;
723 $slashPos = strrpos( $output, '/' );
724 if ( $slashPos === false ) {
727 $output = substr( $output, 0, $slashPos );
736 * Returns a regular expression of url protocols
738 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
739 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
742 function wfUrlProtocols( $includeProtocolRelative = true ) {
743 global $wgUrlProtocols;
745 // Cache return values separately based on $includeProtocolRelative
746 static $withProtRel = null, $withoutProtRel = null;
747 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
748 if ( !is_null( $cachedValue ) ) {
752 // Support old-style $wgUrlProtocols strings, for backwards compatibility
753 // with LocalSettings files from 1.5
754 if ( is_array( $wgUrlProtocols ) ) {
755 $protocols = array();
756 foreach ( $wgUrlProtocols as $protocol ) {
757 // Filter out '//' if !$includeProtocolRelative
758 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
759 $protocols[] = preg_quote( $protocol, '/' );
763 $retval = implode( '|', $protocols );
765 // Ignore $includeProtocolRelative in this case
766 // This case exists for pre-1.6 compatibility, and we can safely assume
767 // that '//' won't appear in a pre-1.6 config because protocol-relative
768 // URLs weren't supported until 1.18
769 $retval = $wgUrlProtocols;
772 // Cache return value
773 if ( $includeProtocolRelative ) {
774 $withProtRel = $retval;
776 $withoutProtRel = $retval;
782 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
783 * you need a regex that matches all URL protocols but does not match protocol-
787 function wfUrlProtocolsWithoutProtRel() {
788 return wfUrlProtocols( false );
792 * parse_url() work-alike, but non-broken. Differences:
794 * 1) Does not raise warnings on bad URLs (just returns false).
795 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
796 * protocol-relative URLs) correctly.
797 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
799 * @param string $url A URL to parse
800 * @return string[] Bits of the URL in an associative array, per PHP docs
802 function wfParseUrl( $url ) {
803 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
805 // Protocol-relative URLs are handled really badly by parse_url(). It's so
806 // bad that the easiest way to handle them is to just prepend 'http:' and
807 // strip the protocol out later.
808 $wasRelative = substr( $url, 0, 2 ) == '//';
809 if ( $wasRelative ) {
812 wfSuppressWarnings();
813 $bits = parse_url( $url );
815 // parse_url() returns an array without scheme for some invalid URLs, e.g.
816 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
817 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
821 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
822 $bits['scheme'] = strtolower( $bits['scheme'] );
824 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
825 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
826 $bits['delimiter'] = '://';
827 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
828 $bits['delimiter'] = ':';
829 // parse_url detects for news: and mailto: the host part of an url as path
830 // We have to correct this wrong detection
831 if ( isset( $bits['path'] ) ) {
832 $bits['host'] = $bits['path'];
839 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
840 if ( !isset( $bits['host'] ) ) {
844 if ( isset( $bits['path'] ) ) {
845 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
846 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
847 $bits['path'] = '/' . $bits['path'];
854 // If the URL was protocol-relative, fix scheme and delimiter
855 if ( $wasRelative ) {
856 $bits['scheme'] = '';
857 $bits['delimiter'] = '//';
863 * Take a URL, make sure it's expanded to fully qualified, and replace any
864 * encoded non-ASCII Unicode characters with their UTF-8 original forms
865 * for more compact display and legibility for local audiences.
867 * @todo handle punycode domains too
872 function wfExpandIRI( $url ) {
873 return preg_replace_callback(
874 '/((?:%[89A-F][0-9A-F])+)/i',
875 'wfExpandIRI_callback',
881 * Private callback for wfExpandIRI
882 * @param array $matches
885 function wfExpandIRI_callback( $matches ) {
886 return urldecode( $matches[1] );
890 * Make URL indexes, appropriate for the el_index field of externallinks.
895 function wfMakeUrlIndexes( $url ) {
896 $bits = wfParseUrl( $url );
898 // Reverse the labels in the hostname, convert to lower case
899 // For emails reverse domainpart only
900 if ( $bits['scheme'] == 'mailto' ) {
901 $mailparts = explode( '@', $bits['host'], 2 );
902 if ( count( $mailparts ) === 2 ) {
903 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
905 // No domain specified, don't mangle it
908 $reversedHost = $domainpart . '@' . $mailparts[0];
910 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
912 // Add an extra dot to the end
913 // Why? Is it in wrong place in mailto links?
914 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
915 $reversedHost .= '.';
917 // Reconstruct the pseudo-URL
918 $prot = $bits['scheme'];
919 $index = $prot . $bits['delimiter'] . $reversedHost;
920 // Leave out user and password. Add the port, path, query and fragment
921 if ( isset( $bits['port'] ) ) {
922 $index .= ':' . $bits['port'];
924 if ( isset( $bits['path'] ) ) {
925 $index .= $bits['path'];
929 if ( isset( $bits['query'] ) ) {
930 $index .= '?' . $bits['query'];
932 if ( isset( $bits['fragment'] ) ) {
933 $index .= '#' . $bits['fragment'];
937 return array( "http:$index", "https:$index" );
939 return array( $index );
944 * Check whether a given URL has a domain that occurs in a given set of domains
945 * @param string $url URL
946 * @param array $domains Array of domains (strings)
947 * @return bool True if the host part of $url ends in one of the strings in $domains
949 function wfMatchesDomainList( $url, $domains ) {
950 $bits = wfParseUrl( $url );
951 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
952 $host = '.' . $bits['host'];
953 foreach ( (array)$domains as $domain ) {
954 $domain = '.' . $domain;
955 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
964 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
965 * In normal operation this is a NOP.
967 * Controlling globals:
968 * $wgDebugLogFile - points to the log file
969 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
970 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
972 * @param string $text
973 * @param string|bool $dest Destination of the message:
974 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
975 * - 'log': only to the log and not in HTML
976 * For backward compatibility, it can also take a boolean:
977 * - true: same as 'all'
978 * - false: same as 'log'
980 function wfDebug( $text, $dest = 'all' ) {
981 global $wgDebugLogFile, $wgDebugRawPage, $wgDebugLogPrefix;
983 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
987 // Turn $dest into a string if it's a boolean (for b/c)
988 if ( $dest === true ) {
990 } elseif ( $dest === false ) {
994 $timer = wfDebugTimer();
995 if ( $timer !== '' ) {
996 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
999 if ( $dest === 'all' ) {
1000 MWDebug
::debugMsg( $text );
1003 if ( $wgDebugLogFile != '' ) {
1004 # Strip unprintables; they can switch terminal modes when binary data
1005 # gets dumped, which is pretty annoying.
1006 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
1007 $text = $wgDebugLogPrefix . $text;
1008 wfErrorLog( $text, $wgDebugLogFile );
1013 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1016 function wfIsDebugRawPage() {
1018 if ( $cache !== null ) {
1021 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1022 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1024 isset( $_SERVER['SCRIPT_NAME'] )
1025 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1036 * Get microsecond timestamps for debug logs
1040 function wfDebugTimer() {
1041 global $wgDebugTimestamps, $wgRequestTime;
1043 if ( !$wgDebugTimestamps ) {
1047 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1048 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1049 return "$prefix $mem ";
1053 * Send a line giving PHP memory usage.
1055 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1057 function wfDebugMem( $exact = false ) {
1058 $mem = memory_get_usage();
1060 $mem = floor( $mem / 1024 ) . ' KiB';
1064 wfDebug( "Memory usage: $mem\n" );
1068 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
1069 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string
1070 * filename or an associative array mapping 'destination' to the desired filename. The
1071 * associative array may also contain a 'sample' key with an integer value, specifying
1072 * a sampling factor.
1074 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1076 * @param string $logGroup
1077 * @param string $text
1078 * @param string|bool $dest Destination of the message:
1079 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1080 * - 'log': only to the log and not in HTML
1081 * - 'private': only to the specifc log if set in $wgDebugLogGroups and
1082 * discarded otherwise
1083 * For backward compatibility, it can also take a boolean:
1084 * - true: same as 'all'
1085 * - false: same as 'private'
1087 function wfDebugLog( $logGroup, $text, $dest = 'all' ) {
1088 global $wgDebugLogGroups;
1090 $text = trim( $text ) . "\n";
1092 // Turn $dest into a string if it's a boolean (for b/c)
1093 if ( $dest === true ) {
1095 } elseif ( $dest === false ) {
1099 if ( !isset( $wgDebugLogGroups[$logGroup] ) ) {
1100 if ( $dest !== 'private' ) {
1101 wfDebug( "[$logGroup] $text", $dest );
1106 if ( $dest === 'all' ) {
1107 MWDebug
::debugMsg( "[$logGroup] $text" );
1110 $logConfig = $wgDebugLogGroups[$logGroup];
1111 if ( $logConfig === false ) {
1114 if ( is_array( $logConfig ) ) {
1115 if ( isset( $logConfig['sample'] ) && mt_rand( 1, $logConfig['sample'] ) !== 1 ) {
1118 $destination = $logConfig['destination'];
1120 $destination = strval( $logConfig );
1123 $time = wfTimestamp( TS_DB
);
1125 $host = wfHostname();
1126 wfErrorLog( "$time $host $wiki: $text", $destination );
1130 * Log for database errors
1132 * @param string $text Database error message.
1134 function wfLogDBError( $text ) {
1135 global $wgDBerrorLog, $wgDBerrorLogTZ;
1136 static $logDBErrorTimeZoneObject = null;
1138 if ( $wgDBerrorLog ) {
1139 $host = wfHostname();
1142 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
1143 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
1146 // Workaround for https://bugs.php.net/bug.php?id=52063
1147 // Can be removed when min PHP > 5.3.2
1148 if ( $logDBErrorTimeZoneObject === null ) {
1149 $d = date_create( "now" );
1151 $d = date_create( "now", $logDBErrorTimeZoneObject );
1154 $date = $d->format( 'D M j G:i:s T Y' );
1156 $text = "$date\t$host\t$wiki\t" . trim( $text ) . "\n";
1157 wfErrorLog( $text, $wgDBerrorLog );
1162 * Throws a warning that $function is deprecated
1164 * @param string $function
1165 * @param string|bool $version Version of MediaWiki that the function
1166 * was deprecated in (Added in 1.19).
1167 * @param string|bool $component Added in 1.19.
1168 * @param int $callerOffset How far up the call stack is the original
1169 * caller. 2 = function that called the function that called
1170 * wfDeprecated (Added in 1.20)
1174 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1175 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1179 * Send a warning either to the debug log or in a PHP error depending on
1180 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1182 * @param string $msg Message to send
1183 * @param int $callerOffset Number of items to go back in the backtrace to
1184 * find the correct caller (1 = function calling wfWarn, ...)
1185 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1186 * only used when $wgDevelopmentWarnings is true
1188 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1189 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1193 * Send a warning as a PHP error and the debug log. This is intended for logging
1194 * warnings in production. For logging development warnings, use WfWarn instead.
1196 * @param string $msg Message to send
1197 * @param int $callerOffset Number of items to go back in the backtrace to
1198 * find the correct caller (1 = function calling wfLogWarning, ...)
1199 * @param int $level PHP error level; defaults to E_USER_WARNING
1201 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1202 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1206 * Log to a file without getting "file size exceeded" signals.
1208 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1209 * send lines to the specified port, prefixed by the specified prefix and a space.
1211 * @param string $text
1212 * @param string $file Filename
1213 * @throws MWException
1215 function wfErrorLog( $text, $file ) {
1216 if ( substr( $file, 0, 4 ) == 'udp:' ) {
1217 # Needs the sockets extension
1218 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
1219 // IPv6 bracketed host
1221 $port = intval( $m[3] );
1222 $prefix = isset( $m[4] ) ?
$m[4] : false;
1224 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
1226 if ( !IP
::isIPv4( $host ) ) {
1227 $host = gethostbyname( $host );
1229 $port = intval( $m[3] );
1230 $prefix = isset( $m[4] ) ?
$m[4] : false;
1233 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
1236 // Clean it up for the multiplexer
1237 if ( strval( $prefix ) !== '' ) {
1238 $text = preg_replace( '/^/m', $prefix . ' ', $text );
1241 if ( strlen( $text ) > 65506 ) {
1242 $text = substr( $text, 0, 65506 );
1245 if ( substr( $text, -1 ) != "\n" ) {
1248 } elseif ( strlen( $text ) > 65507 ) {
1249 $text = substr( $text, 0, 65507 );
1252 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
1257 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
1258 socket_close( $sock );
1260 wfSuppressWarnings();
1261 $exists = file_exists( $file );
1262 $size = $exists ?
filesize( $file ) : false;
1263 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
1264 file_put_contents( $file, $text, FILE_APPEND
);
1266 wfRestoreWarnings();
1273 function wfLogProfilingData() {
1274 global $wgRequestTime, $wgDebugLogFile, $wgDebugLogGroups, $wgDebugRawPage;
1275 global $wgProfileLimit, $wgUser, $wgRequest;
1277 StatCounter
::singleton()->flush();
1279 $profiler = Profiler
::instance();
1281 # Profiling must actually be enabled...
1282 if ( $profiler->isStub() ) {
1286 // Get total page request time and only show pages that longer than
1287 // $wgProfileLimit time (default is 0)
1288 $elapsed = microtime( true ) - $wgRequestTime;
1289 if ( $elapsed <= $wgProfileLimit ) {
1293 $profiler->logData();
1295 // Check whether this should be logged in the debug file.
1296 if ( isset( $wgDebugLogGroups['profileoutput'] )
1297 && $wgDebugLogGroups['profileoutput'] === false
1299 // Explicitely disabled
1302 if ( !isset( $wgDebugLogGroups['profileoutput'] ) && $wgDebugLogFile == '' ) {
1303 // Logging not enabled; no point going further
1306 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1311 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1312 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
1314 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1315 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
1317 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1318 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
1321 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
1323 // Don't load $wgUser at this late stage just for statistics purposes
1324 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
1325 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1326 $forward .= ' anon';
1329 // Command line script uses a FauxRequest object which does not have
1330 // any knowledge about an URL and throw an exception instead.
1332 $requestUrl = $wgRequest->getRequestURL();
1333 } catch ( MWException
$e ) {
1334 $requestUrl = 'n/a';
1337 $log = sprintf( "%s\t%04.3f\t%s\n",
1338 gmdate( 'YmdHis' ), $elapsed,
1339 urldecode( $requestUrl . $forward ) );
1341 wfDebugLog( 'profileoutput', $log . $profiler->getOutput() );
1345 * Increment a statistics counter
1347 * @param string $key
1351 function wfIncrStats( $key, $count = 1 ) {
1352 StatCounter
::singleton()->incr( $key, $count );
1356 * Check whether the wiki is in read-only mode.
1360 function wfReadOnly() {
1361 return wfReadOnlyReason() !== false;
1365 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1367 * @return string|bool String when in read-only mode; false otherwise
1369 function wfReadOnlyReason() {
1370 global $wgReadOnly, $wgReadOnlyFile;
1372 if ( $wgReadOnly === null ) {
1373 // Set $wgReadOnly for faster access next time
1374 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1375 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1377 $wgReadOnly = false;
1385 * Return a Language object from $langcode
1387 * @param Language|string|bool $langcode Either:
1388 * - a Language object
1389 * - code of the language to get the message for, if it is
1390 * a valid code create a language for that language, if
1391 * it is a string but not a valid code then make a basic
1393 * - a boolean: if it's false then use the global object for
1394 * the current user's language (as a fallback for the old parameter
1395 * functionality), or if it is true then use global object
1396 * for the wiki's content language.
1399 function wfGetLangObj( $langcode = false ) {
1400 # Identify which language to get or create a language object for.
1401 # Using is_object here due to Stub objects.
1402 if ( is_object( $langcode ) ) {
1403 # Great, we already have the object (hopefully)!
1407 global $wgContLang, $wgLanguageCode;
1408 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1409 # $langcode is the language code of the wikis content language object.
1410 # or it is a boolean and value is true
1415 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1416 # $langcode is the language code of user language object.
1417 # or it was a boolean and value is false
1421 $validCodes = array_keys( Language
::fetchLanguageNames() );
1422 if ( in_array( $langcode, $validCodes ) ) {
1423 # $langcode corresponds to a valid language.
1424 return Language
::factory( $langcode );
1427 # $langcode is a string, but not a valid language code; use content language.
1428 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1433 * This is the function for getting translated interface messages.
1435 * @see Message class for documentation how to use them.
1436 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1438 * This function replaces all old wfMsg* functions.
1440 * @param string $key Message key
1441 * @param mixed $params,... Normal message parameters
1446 * @see Message::__construct
1448 function wfMessage( $key /*...*/ ) {
1449 $params = func_get_args();
1450 array_shift( $params );
1451 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1452 $params = $params[0];
1454 return new Message( $key, $params );
1458 * This function accepts multiple message keys and returns a message instance
1459 * for the first message which is non-empty. If all messages are empty then an
1460 * instance of the first message key is returned.
1462 * @param string|string[] $keys,... Message keys
1467 * @see Message::newFallbackSequence
1469 function wfMessageFallback( /*...*/ ) {
1470 $args = func_get_args();
1471 return call_user_func_array( 'Message::newFallbackSequence', $args );
1475 * Get a message from anywhere, for the current user language.
1477 * Use wfMsgForContent() instead if the message should NOT
1478 * change depending on the user preferences.
1480 * @deprecated since 1.18
1482 * @param string $key Lookup key for the message, usually
1483 * defined in languages/Language.php
1485 * Parameters to the message, which can be used to insert variable text into
1486 * it, can be passed to this function in the following formats:
1487 * - One per argument, starting at the second parameter
1488 * - As an array in the second parameter
1489 * These are not shown in the function definition.
1493 function wfMsg( $key ) {
1494 wfDeprecated( __METHOD__
, '1.21' );
1496 $args = func_get_args();
1497 array_shift( $args );
1498 return wfMsgReal( $key, $args );
1502 * Same as above except doesn't transform the message
1504 * @deprecated since 1.18
1506 * @param string $key
1509 function wfMsgNoTrans( $key ) {
1510 wfDeprecated( __METHOD__
, '1.21' );
1512 $args = func_get_args();
1513 array_shift( $args );
1514 return wfMsgReal( $key, $args, true, false, false );
1518 * Get a message from anywhere, for the current global language
1519 * set with $wgLanguageCode.
1521 * Use this if the message should NOT change dependent on the
1522 * language set in the user's preferences. This is the case for
1523 * most text written into logs, as well as link targets (such as
1524 * the name of the copyright policy page). Link titles, on the
1525 * other hand, should be shown in the UI language.
1527 * Note that MediaWiki allows users to change the user interface
1528 * language in their preferences, but a single installation
1529 * typically only contains content in one language.
1531 * Be wary of this distinction: If you use wfMsg() where you should
1532 * use wfMsgForContent(), a user of the software may have to
1533 * customize potentially hundreds of messages in
1534 * order to, e.g., fix a link in every possible language.
1536 * @deprecated since 1.18
1538 * @param string $key Lookup key for the message, usually
1539 * defined in languages/Language.php
1542 function wfMsgForContent( $key ) {
1543 wfDeprecated( __METHOD__
, '1.21' );
1545 global $wgForceUIMsgAsContentMsg;
1546 $args = func_get_args();
1547 array_shift( $args );
1549 if ( is_array( $wgForceUIMsgAsContentMsg )
1550 && in_array( $key, $wgForceUIMsgAsContentMsg )
1552 $forcontent = false;
1554 return wfMsgReal( $key, $args, true, $forcontent );
1558 * Same as above except doesn't transform the message
1560 * @deprecated since 1.18
1562 * @param string $key
1565 function wfMsgForContentNoTrans( $key ) {
1566 wfDeprecated( __METHOD__
, '1.21' );
1568 global $wgForceUIMsgAsContentMsg;
1569 $args = func_get_args();
1570 array_shift( $args );
1572 if ( is_array( $wgForceUIMsgAsContentMsg )
1573 && in_array( $key, $wgForceUIMsgAsContentMsg )
1575 $forcontent = false;
1577 return wfMsgReal( $key, $args, true, $forcontent, false );
1581 * Really get a message
1583 * @deprecated since 1.18
1585 * @param string $key Key to get.
1586 * @param array $args
1587 * @param bool $useDB
1588 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1589 * @param bool $transform Whether or not to transform the message.
1590 * @return string The requested message.
1592 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1593 wfDeprecated( __METHOD__
, '1.21' );
1595 wfProfileIn( __METHOD__
);
1596 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1597 $message = wfMsgReplaceArgs( $message, $args );
1598 wfProfileOut( __METHOD__
);
1603 * Fetch a message string value, but don't replace any keys yet.
1605 * @deprecated since 1.18
1607 * @param string $key
1608 * @param bool $useDB
1609 * @param string|bool $langCode Code of the language to get the message for, or
1610 * behaves as a content language switch if it is a boolean.
1611 * @param bool $transform Whether to parse magic words, etc.
1614 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1615 wfDeprecated( __METHOD__
, '1.21' );
1617 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1619 $cache = MessageCache
::singleton();
1620 $message = $cache->get( $key, $useDB, $langCode );
1621 if ( $message === false ) {
1622 $message = '<' . htmlspecialchars( $key ) . '>';
1623 } elseif ( $transform ) {
1624 $message = $cache->transform( $message );
1630 * Replace message parameter keys on the given formatted output.
1632 * @param string $message
1633 * @param array $args
1637 function wfMsgReplaceArgs( $message, $args ) {
1638 # Fix windows line-endings
1639 # Some messages are split with explode("\n", $msg)
1640 $message = str_replace( "\r", '', $message );
1642 // Replace arguments
1643 if ( count( $args ) ) {
1644 if ( is_array( $args[0] ) ) {
1645 $args = array_values( $args[0] );
1647 $replacementKeys = array();
1648 foreach ( $args as $n => $param ) {
1649 $replacementKeys['$' . ( $n +
1 )] = $param;
1651 $message = strtr( $message, $replacementKeys );
1658 * Return an HTML-escaped version of a message.
1659 * Parameter replacements, if any, are done *after* the HTML-escaping,
1660 * so parameters may contain HTML (eg links or form controls). Be sure
1661 * to pre-escape them if you really do want plaintext, or just wrap
1662 * the whole thing in htmlspecialchars().
1664 * @deprecated since 1.18
1666 * @param string $key
1667 * @param string $args,... Parameters
1670 function wfMsgHtml( $key ) {
1671 wfDeprecated( __METHOD__
, '1.21' );
1673 $args = func_get_args();
1674 array_shift( $args );
1675 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1679 * Return an HTML version of message
1680 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1681 * so parameters may contain HTML (eg links or form controls). Be sure
1682 * to pre-escape them if you really do want plaintext, or just wrap
1683 * the whole thing in htmlspecialchars().
1685 * @deprecated since 1.18
1687 * @param string $key
1688 * @param string $args,... Parameters
1691 function wfMsgWikiHtml( $key ) {
1692 wfDeprecated( __METHOD__
, '1.21' );
1694 $args = func_get_args();
1695 array_shift( $args );
1696 return wfMsgReplaceArgs(
1697 MessageCache
::singleton()->parse( wfMsgGetKey( $key ), null,
1698 /* can't be set to false */ true, /* interface */ true )->getText(),
1703 * Returns message in the requested format
1705 * @deprecated since 1.18
1707 * @param string $key Key of the message
1708 * @param array $options Processing rules.
1709 * Can take the following options:
1710 * parse: parses wikitext to HTML
1711 * parseinline: parses wikitext to HTML and removes the surrounding
1712 * p's added by parser or tidy
1713 * escape: filters message through htmlspecialchars
1714 * escapenoentities: same, but allows entity references like   through
1715 * replaceafter: parameters are substituted after parsing or escaping
1716 * parsemag: transform the message using magic phrases
1717 * content: fetch message for content language instead of interface
1718 * Also can accept a single associative argument, of the form 'language' => 'xx':
1719 * language: Language object or language code to fetch message for
1720 * (overridden by content).
1721 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1725 function wfMsgExt( $key, $options ) {
1726 wfDeprecated( __METHOD__
, '1.21' );
1728 $args = func_get_args();
1729 array_shift( $args );
1730 array_shift( $args );
1731 $options = (array)$options;
1733 foreach ( $options as $arrayKey => $option ) {
1734 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1735 # An unknown index, neither numeric nor "language"
1736 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
1737 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1738 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1739 'replaceafter', 'parsemag', 'content' ) ) ) {
1740 # A numeric index with unknown value
1741 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
1745 if ( in_array( 'content', $options, true ) ) {
1748 $langCodeObj = null;
1749 } elseif ( array_key_exists( 'language', $options ) ) {
1750 $forContent = false;
1751 $langCode = wfGetLangObj( $options['language'] );
1752 $langCodeObj = $langCode;
1754 $forContent = false;
1756 $langCodeObj = null;
1759 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1761 if ( !in_array( 'replaceafter', $options, true ) ) {
1762 $string = wfMsgReplaceArgs( $string, $args );
1765 $messageCache = MessageCache
::singleton();
1766 $parseInline = in_array( 'parseinline', $options, true );
1767 if ( in_array( 'parse', $options, true ) ||
$parseInline ) {
1768 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1769 if ( $string instanceof ParserOutput
) {
1770 $string = $string->getText();
1773 if ( $parseInline ) {
1774 $string = Parser
::stripOuterParagraph( $string );
1776 } elseif ( in_array( 'parsemag', $options, true ) ) {
1777 $string = $messageCache->transform( $string,
1778 !$forContent, $langCodeObj );
1781 if ( in_array( 'escape', $options, true ) ) {
1782 $string = htmlspecialchars ( $string );
1783 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1784 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
1787 if ( in_array( 'replaceafter', $options, true ) ) {
1788 $string = wfMsgReplaceArgs( $string, $args );
1795 * Since wfMsg() and co suck, they don't return false if the message key they
1796 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1797 * nonexistence of messages by checking the MessageCache::get() result directly.
1799 * @deprecated since 1.18. Use Message::isDisabled().
1801 * @param string $key The message key looked up
1802 * @return bool True if the message *doesn't* exist.
1804 function wfEmptyMsg( $key ) {
1805 wfDeprecated( __METHOD__
, '1.21' );
1807 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1811 * Throw a debugging exception. This function previously once exited the process,
1812 * but now throws an exception instead, with similar results.
1814 * @deprecated since 1.22; just throw an MWException yourself
1815 * @param string $msg Message shown when dying.
1816 * @throws MWException
1818 function wfDebugDieBacktrace( $msg = '' ) {
1819 wfDeprecated( __FUNCTION__
, '1.22' );
1820 throw new MWException( $msg );
1824 * Fetch server name for use in error reporting etc.
1825 * Use real server name if available, so we know which machine
1826 * in a server farm generated the current page.
1830 function wfHostname() {
1832 if ( is_null( $host ) ) {
1834 # Hostname overriding
1835 global $wgOverrideHostname;
1836 if ( $wgOverrideHostname !== false ) {
1837 # Set static and skip any detection
1838 $host = $wgOverrideHostname;
1842 if ( function_exists( 'posix_uname' ) ) {
1843 // This function not present on Windows
1844 $uname = posix_uname();
1848 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1849 $host = $uname['nodename'];
1850 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1851 # Windows computer name
1852 $host = getenv( 'COMPUTERNAME' );
1854 # This may be a virtual server.
1855 $host = $_SERVER['SERVER_NAME'];
1862 * Returns a script tag that stores the amount of time it took MediaWiki to
1863 * handle the request in milliseconds as 'wgBackendResponseTime'.
1865 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1866 * hostname of the server handling the request.
1870 function wfReportTime() {
1871 global $wgRequestTime, $wgShowHostnames;
1873 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1874 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1875 if ( $wgShowHostnames ) {
1876 $reportVars['wgHostname'] = wfHostname();
1878 return Skin
::makeVariablesScript( $reportVars );
1882 * Safety wrapper for debug_backtrace().
1884 * Will return an empty array if debug_backtrace is disabled, otherwise
1885 * the output from debug_backtrace() (trimmed).
1887 * @param int $limit This parameter can be used to limit the number of stack frames returned
1889 * @return array Array of backtrace information
1891 function wfDebugBacktrace( $limit = 0 ) {
1892 static $disabled = null;
1894 if ( is_null( $disabled ) ) {
1895 $disabled = !function_exists( 'debug_backtrace' );
1897 wfDebug( "debug_backtrace() is disabled\n" );
1904 if ( $limit && version_compare( PHP_VERSION
, '5.4.0', '>=' ) ) {
1905 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1907 return array_slice( debug_backtrace(), 1 );
1912 * Get a debug backtrace as a string
1916 function wfBacktrace() {
1917 global $wgCommandLineMode;
1919 if ( $wgCommandLineMode ) {
1924 $backtrace = wfDebugBacktrace();
1925 foreach ( $backtrace as $call ) {
1926 if ( isset( $call['file'] ) ) {
1927 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1928 $file = $f[count( $f ) - 1];
1932 if ( isset( $call['line'] ) ) {
1933 $line = $call['line'];
1937 if ( $wgCommandLineMode ) {
1938 $msg .= "$file line $line calls ";
1940 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1942 if ( !empty( $call['class'] ) ) {
1943 $msg .= $call['class'] . $call['type'];
1945 $msg .= $call['function'] . '()';
1947 if ( $wgCommandLineMode ) {
1953 if ( $wgCommandLineMode ) {
1963 * Get the name of the function which called this function
1964 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1965 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1966 * wfGetCaller( 3 ) is the parent of that.
1971 function wfGetCaller( $level = 2 ) {
1972 $backtrace = wfDebugBacktrace( $level +
1 );
1973 if ( isset( $backtrace[$level] ) ) {
1974 return wfFormatStackFrame( $backtrace[$level] );
1981 * Return a string consisting of callers in the stack. Useful sometimes
1982 * for profiling specific points.
1984 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1987 function wfGetAllCallers( $limit = 3 ) {
1988 $trace = array_reverse( wfDebugBacktrace() );
1989 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1990 $limit = count( $trace ) - 1;
1992 $trace = array_slice( $trace, -$limit - 1, $limit );
1993 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1997 * Return a string representation of frame
1999 * @param array $frame
2002 function wfFormatStackFrame( $frame ) {
2003 return isset( $frame['class'] ) ?
2004 $frame['class'] . '::' . $frame['function'] :
2008 /* Some generic result counters, pulled out of SearchEngine */
2013 * @param int $offset
2017 function wfShowingResults( $offset, $limit ) {
2018 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
2023 * @todo FIXME: We may want to blacklist some broken browsers
2025 * @param bool $force
2026 * @return bool Whereas client accept gzip compression
2028 function wfClientAcceptsGzip( $force = false ) {
2029 static $result = null;
2030 if ( $result === null ||
$force ) {
2032 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
2033 # @todo FIXME: We may want to blacklist some broken browsers
2036 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
2037 $_SERVER['HTTP_ACCEPT_ENCODING'],
2041 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2045 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2054 * Obtain the offset and limit values from the request string;
2055 * used in special pages
2057 * @param int $deflimit Default limit if none supplied
2058 * @param string $optionname Name of a user preference to check against
2060 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2062 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2064 wfDeprecated( __METHOD__
, '1.24' );
2065 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2069 * Escapes the given text so that it may be output using addWikiText()
2070 * without any linking, formatting, etc. making its way through. This
2071 * is achieved by substituting certain characters with HTML entities.
2072 * As required by the callers, "<nowiki>" is not used.
2074 * @param string $text Text to be escaped
2077 function wfEscapeWikiText( $text ) {
2078 static $repl = null, $repl2 = null;
2079 if ( $repl === null ) {
2081 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
2082 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
2083 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
2084 "\n#" => "\n#", "\r#" => "\r#",
2085 "\n*" => "\n*", "\r*" => "\r*",
2086 "\n:" => "\n:", "\r:" => "\r:",
2087 "\n " => "\n ", "\r " => "\r ",
2088 "\n\n" => "\n ", "\r\n" => " \n",
2089 "\n\r" => "\n ", "\r\r" => "\r ",
2090 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
2091 "\n----" => "\n----", "\r----" => "\r----",
2092 '__' => '__', '://' => '://',
2095 // We have to catch everything "\s" matches in PCRE
2096 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2097 $repl["$magic "] = "$magic ";
2098 $repl["$magic\t"] = "$magic	";
2099 $repl["$magic\r"] = "$magic ";
2100 $repl["$magic\n"] = "$magic ";
2101 $repl["$magic\f"] = "$magic";
2104 // And handle protocols that don't use "://"
2105 global $wgUrlProtocols;
2107 foreach ( $wgUrlProtocols as $prot ) {
2108 if ( substr( $prot, -1 ) === ':' ) {
2109 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2112 $repl2 = $repl2 ?
'/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2114 $text = substr( strtr( "\n$text", $repl ), 1 );
2115 $text = preg_replace( $repl2, '$1:', $text );
2120 * Get the current unix timestamp with microseconds. Useful for profiling
2121 * @deprecated since 1.22; call microtime() directly
2125 wfDeprecated( __FUNCTION__
, '1.22' );
2126 return microtime( true );
2130 * Sets dest to source and returns the original value of dest
2131 * If source is NULL, it just returns the value, it doesn't set the variable
2132 * If force is true, it will set the value even if source is NULL
2134 * @param mixed $dest
2135 * @param mixed $source
2136 * @param bool $force
2139 function wfSetVar( &$dest, $source, $force = false ) {
2141 if ( !is_null( $source ) ||
$force ) {
2148 * As for wfSetVar except setting a bit
2152 * @param bool $state
2156 function wfSetBit( &$dest, $bit, $state = true ) {
2157 $temp = (bool)( $dest & $bit );
2158 if ( !is_null( $state ) ) {
2169 * A wrapper around the PHP function var_export().
2170 * Either print it or add it to the regular output ($wgOut).
2172 * @param mixed $var A PHP variable to dump.
2174 function wfVarDump( $var ) {
2176 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2177 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
2180 $wgOut->addHTML( $s );
2185 * Provide a simple HTTP error.
2187 * @param int|string $code
2188 * @param string $label
2189 * @param string $desc
2191 function wfHttpError( $code, $label, $desc ) {
2194 header( "HTTP/1.0 $code $label" );
2195 header( "Status: $code $label" );
2196 $wgOut->sendCacheControl();
2198 header( 'Content-type: text/html; charset=utf-8' );
2199 print "<!doctype html>" .
2200 '<html><head><title>' .
2201 htmlspecialchars( $label ) .
2202 '</title></head><body><h1>' .
2203 htmlspecialchars( $label ) .
2205 nl2br( htmlspecialchars( $desc ) ) .
2206 "</p></body></html>\n";
2210 * Clear away any user-level output buffers, discarding contents.
2212 * Suitable for 'starting afresh', for instance when streaming
2213 * relatively large amounts of data without buffering, or wanting to
2214 * output image files without ob_gzhandler's compression.
2216 * The optional $resetGzipEncoding parameter controls suppression of
2217 * the Content-Encoding header sent by ob_gzhandler; by default it
2218 * is left. See comments for wfClearOutputBuffers() for why it would
2221 * Note that some PHP configuration options may add output buffer
2222 * layers which cannot be removed; these are left in place.
2224 * @param bool $resetGzipEncoding
2226 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2227 if ( $resetGzipEncoding ) {
2228 // Suppress Content-Encoding and Content-Length
2229 // headers from 1.10+s wfOutputHandler
2230 global $wgDisableOutputCompression;
2231 $wgDisableOutputCompression = true;
2233 while ( $status = ob_get_status() ) {
2234 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2235 // Probably from zlib.output_compression or other
2236 // PHP-internal setting which can't be removed.
2238 // Give up, and hope the result doesn't break
2242 if ( !ob_end_clean() ) {
2243 // Could not remove output buffer handler; abort now
2244 // to avoid getting in some kind of infinite loop.
2247 if ( $resetGzipEncoding ) {
2248 if ( $status['name'] == 'ob_gzhandler' ) {
2249 // Reset the 'Content-Encoding' field set by this handler
2250 // so we can start fresh.
2251 header_remove( 'Content-Encoding' );
2259 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2261 * Clear away output buffers, but keep the Content-Encoding header
2262 * produced by ob_gzhandler, if any.
2264 * This should be used for HTTP 304 responses, where you need to
2265 * preserve the Content-Encoding header of the real result, but
2266 * also need to suppress the output of ob_gzhandler to keep to spec
2267 * and avoid breaking Firefox in rare cases where the headers and
2268 * body are broken over two packets.
2270 function wfClearOutputBuffers() {
2271 wfResetOutputBuffers( false );
2275 * Converts an Accept-* header into an array mapping string values to quality
2278 * @param string $accept
2279 * @param string $def Default
2280 * @return float[] Associative array of string => float pairs
2282 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2283 # No arg means accept anything (per HTTP spec)
2285 return array( $def => 1.0 );
2290 $parts = explode( ',', $accept );
2292 foreach ( $parts as $part ) {
2293 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2294 $values = explode( ';', trim( $part ) );
2296 if ( count( $values ) == 1 ) {
2297 $prefs[$values[0]] = 1.0;
2298 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2299 $prefs[$values[0]] = floatval( $match[1] );
2307 * Checks if a given MIME type matches any of the keys in the given
2308 * array. Basic wildcards are accepted in the array keys.
2310 * Returns the matching MIME type (or wildcard) if a match, otherwise
2313 * @param string $type
2314 * @param array $avail
2318 function mimeTypeMatch( $type, $avail ) {
2319 if ( array_key_exists( $type, $avail ) ) {
2322 $parts = explode( '/', $type );
2323 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2324 return $parts[0] . '/*';
2325 } elseif ( array_key_exists( '*/*', $avail ) ) {
2334 * Returns the 'best' match between a client's requested internet media types
2335 * and the server's list of available types. Each list should be an associative
2336 * array of type to preference (preference is a float between 0.0 and 1.0).
2337 * Wildcards in the types are acceptable.
2339 * @param array $cprefs Client's acceptable type list
2340 * @param array $sprefs Server's offered types
2343 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2344 * XXX: generalize to negotiate other stuff
2346 function wfNegotiateType( $cprefs, $sprefs ) {
2349 foreach ( array_keys( $sprefs ) as $type ) {
2350 $parts = explode( '/', $type );
2351 if ( $parts[1] != '*' ) {
2352 $ckey = mimeTypeMatch( $type, $cprefs );
2354 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2359 foreach ( array_keys( $cprefs ) as $type ) {
2360 $parts = explode( '/', $type );
2361 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2362 $skey = mimeTypeMatch( $type, $sprefs );
2364 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2372 foreach ( array_keys( $combine ) as $type ) {
2373 if ( $combine[$type] > $bestq ) {
2375 $bestq = $combine[$type];
2383 * Reference-counted warning suppression
2387 function wfSuppressWarnings( $end = false ) {
2388 static $suppressCount = 0;
2389 static $originalLevel = false;
2392 if ( $suppressCount ) {
2394 if ( !$suppressCount ) {
2395 error_reporting( $originalLevel );
2399 if ( !$suppressCount ) {
2400 $originalLevel = error_reporting( E_ALL
& ~
(
2415 * Restore error level to previous value
2417 function wfRestoreWarnings() {
2418 wfSuppressWarnings( true );
2421 # Autodetect, convert and provide timestamps of various types
2424 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2426 define( 'TS_UNIX', 0 );
2429 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2431 define( 'TS_MW', 1 );
2434 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2436 define( 'TS_DB', 2 );
2439 * RFC 2822 format, for E-mail and HTTP headers
2441 define( 'TS_RFC2822', 3 );
2444 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2446 * This is used by Special:Export
2448 define( 'TS_ISO_8601', 4 );
2451 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2453 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2454 * DateTime tag and page 36 for the DateTimeOriginal and
2455 * DateTimeDigitized tags.
2457 define( 'TS_EXIF', 5 );
2460 * Oracle format time.
2462 define( 'TS_ORACLE', 6 );
2465 * Postgres format time.
2467 define( 'TS_POSTGRES', 7 );
2470 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2472 define( 'TS_ISO_8601_BASIC', 9 );
2475 * Get a timestamp string in one of various formats
2477 * @param mixed $outputtype A timestamp in one of the supported formats, the
2478 * function will autodetect which format is supplied and act accordingly.
2479 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2480 * @return string|bool String / false The same date in the format specified in $outputtype or false
2482 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2484 $timestamp = new MWTimestamp( $ts );
2485 return $timestamp->getTimestamp( $outputtype );
2486 } catch ( TimestampException
$e ) {
2487 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2493 * Return a formatted timestamp, or null if input is null.
2494 * For dealing with nullable timestamp columns in the database.
2496 * @param int $outputtype
2500 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2501 if ( is_null( $ts ) ) {
2504 return wfTimestamp( $outputtype, $ts );
2509 * Convenience function; returns MediaWiki timestamp for the present time.
2513 function wfTimestampNow() {
2515 return wfTimestamp( TS_MW
, time() );
2519 * Check if the operating system is Windows
2521 * @return bool True if it's Windows, false otherwise.
2523 function wfIsWindows() {
2524 static $isWindows = null;
2525 if ( $isWindows === null ) {
2526 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2532 * Check if we are running under HHVM
2536 function wfIsHHVM() {
2537 return defined( 'HHVM_VERSION' );
2541 * Swap two variables
2543 * @deprecated since 1.24
2547 function swap( &$x, &$y ) {
2548 wfDeprecated( __FUNCTION__
, '1.24' );
2555 * Tries to get the system directory for temporary files. First
2556 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2557 * environment variables are then checked in sequence, and if none are
2558 * set try sys_get_temp_dir().
2560 * NOTE: When possible, use instead the tmpfile() function to create
2561 * temporary files to avoid race conditions on file creation, etc.
2565 function wfTempDir() {
2566 global $wgTmpDirectory;
2568 if ( $wgTmpDirectory !== false ) {
2569 return $wgTmpDirectory;
2572 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2574 foreach ( $tmpDir as $tmp ) {
2575 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2579 return sys_get_temp_dir();
2583 * Make directory, and make all parent directories if they don't exist
2585 * @param string $dir Full path to directory to create
2586 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2587 * @param string $caller Optional caller param for debugging.
2588 * @throws MWException
2591 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2592 global $wgDirectoryMode;
2594 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2595 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2598 if ( !is_null( $caller ) ) {
2599 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2602 if ( strval( $dir ) === '' ||
( file_exists( $dir ) && is_dir( $dir ) ) ) {
2606 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2608 if ( is_null( $mode ) ) {
2609 $mode = $wgDirectoryMode;
2612 // Turn off the normal warning, we're doing our own below
2613 wfSuppressWarnings();
2614 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2615 wfRestoreWarnings();
2618 //directory may have been created on another request since we last checked
2619 if ( is_dir( $dir ) ) {
2623 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2624 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2630 * Remove a directory and all its content.
2631 * Does not hide error.
2632 * @param string $dir
2634 function wfRecursiveRemoveDir( $dir ) {
2635 wfDebug( __FUNCTION__
. "( $dir )\n" );
2636 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2637 if ( is_dir( $dir ) ) {
2638 $objects = scandir( $dir );
2639 foreach ( $objects as $object ) {
2640 if ( $object != "." && $object != ".." ) {
2641 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2642 wfRecursiveRemoveDir( $dir . '/' . $object );
2644 unlink( $dir . '/' . $object );
2654 * @param int $nr The number to format
2655 * @param int $acc The number of digits after the decimal point, default 2
2656 * @param bool $round Whether or not to round the value, default true
2659 function wfPercent( $nr, $acc = 2, $round = true ) {
2660 $ret = sprintf( "%.${acc}f", $nr );
2661 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2665 * Safety wrapper around ini_get() for boolean settings.
2666 * The values returned from ini_get() are pre-normalized for settings
2667 * set via php.ini or php_flag/php_admin_flag... but *not*
2668 * for those set via php_value/php_admin_value.
2670 * It's fairly common for people to use php_value instead of php_flag,
2671 * which can leave you with an 'off' setting giving a false positive
2672 * for code that just takes the ini_get() return value as a boolean.
2674 * To make things extra interesting, setting via php_value accepts
2675 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2676 * Unrecognized values go false... again opposite PHP's own coercion
2677 * from string to bool.
2679 * Luckily, 'properly' set settings will always come back as '0' or '1',
2680 * so we only have to worry about them and the 'improper' settings.
2682 * I frickin' hate PHP... :P
2684 * @param string $setting
2687 function wfIniGetBool( $setting ) {
2688 $val = strtolower( ini_get( $setting ) );
2689 // 'on' and 'true' can't have whitespace around them, but '1' can.
2693 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2697 * Windows-compatible version of escapeshellarg()
2698 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2699 * function puts single quotes in regardless of OS.
2701 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2702 * earlier distro releases of PHP)
2704 * @param string $args,...
2707 function wfEscapeShellArg( /*...*/ ) {
2708 wfInitShellLocale();
2710 $args = func_get_args();
2713 foreach ( $args as $arg ) {
2720 if ( wfIsWindows() ) {
2721 // Escaping for an MSVC-style command line parser and CMD.EXE
2722 // @codingStandardsIgnoreStart For long URLs
2724 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2725 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2728 // Double the backslashes before any double quotes. Escape the double quotes.
2729 // @codingStandardsIgnoreEnd
2730 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2733 foreach ( $tokens as $token ) {
2734 if ( $iteration %
2 == 1 ) {
2735 // Delimiter, a double quote preceded by zero or more slashes
2736 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2737 } elseif ( $iteration %
4 == 2 ) {
2738 // ^ in $token will be outside quotes, need to be escaped
2739 $arg .= str_replace( '^', '^^', $token );
2740 } else { // $iteration % 4 == 0
2741 // ^ in $token will appear inside double quotes, so leave as is
2746 // Double the backslashes before the end of the string, because
2747 // we will soon add a quote
2749 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2750 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2753 // Add surrounding quotes
2754 $retVal .= '"' . $arg . '"';
2756 $retVal .= escapeshellarg( $arg );
2763 * Check if wfShellExec() is effectively disabled via php.ini config
2765 * @return bool|string False or one of (safemode,disabled)
2768 function wfShellExecDisabled() {
2769 static $disabled = null;
2770 if ( is_null( $disabled ) ) {
2771 if ( wfIniGetBool( 'safe_mode' ) ) {
2772 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2773 $disabled = 'safemode';
2774 } elseif ( !function_exists( 'proc_open' ) ) {
2775 wfDebug( "proc_open() is disabled\n" );
2776 $disabled = 'disabled';
2785 * Execute a shell command, with time and memory limits mirrored from the PHP
2786 * configuration if supported.
2788 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2789 * or an array of unescaped arguments, in which case each value will be escaped
2790 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2791 * @param null|mixed &$retval Optional, will receive the program's exit code.
2792 * (non-zero is usually failure). If there is an error from
2793 * read, select, or proc_open(), this will be set to -1.
2794 * @param array $environ Optional environment variables which should be
2795 * added to the executed command environment.
2796 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2797 * this overwrites the global wgMaxShell* limits.
2798 * @param array $options Array of options:
2799 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2800 * including errors from limit.sh
2802 * @return string Collected stdout as a string
2804 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2805 $limits = array(), $options = array()
2807 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2808 $wgMaxShellWallClockTime, $wgShellCgroup;
2810 $disabled = wfShellExecDisabled();
2813 return $disabled == 'safemode' ?
2814 'Unable to run external programs in safe mode.' :
2815 'Unable to run external programs, proc_open() is disabled.';
2818 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2820 wfInitShellLocale();
2823 foreach ( $environ as $k => $v ) {
2824 if ( wfIsWindows() ) {
2825 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2826 * appear in the environment variable, so we must use carat escaping as documented in
2827 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2828 * Note however that the quote isn't listed there, but is needed, and the parentheses
2829 * are listed there but doesn't appear to need it.
2831 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2833 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2834 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2836 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2839 if ( is_array( $cmd ) ) {
2840 // Command line may be given as an array, escape each value and glue them together with a space
2842 foreach ( $cmd as $val ) {
2843 $cmdVals[] = wfEscapeShellArg( $val );
2845 $cmd = implode( ' ', $cmdVals );
2848 $cmd = $envcmd . $cmd;
2850 $useLogPipe = false;
2851 if ( is_executable( '/bin/bash' ) ) {
2852 $time = intval ( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2853 if ( isset( $limits['walltime'] ) ) {
2854 $wallTime = intval( $limits['walltime'] );
2855 } elseif ( isset( $limits['time'] ) ) {
2858 $wallTime = intval( $wgMaxShellWallClockTime );
2860 $mem = intval ( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2861 $filesize = intval ( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2863 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2864 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2865 escapeshellarg( $cmd ) . ' ' .
2867 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2868 "MW_CPU_LIMIT=$time; " .
2869 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2870 "MW_MEM_LIMIT=$mem; " .
2871 "MW_FILE_SIZE_LIMIT=$filesize; " .
2872 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2873 "MW_USE_LOG_PIPE=yes"
2876 } elseif ( $includeStderr ) {
2879 } elseif ( $includeStderr ) {
2882 wfDebug( "wfShellExec: $cmd\n" );
2885 0 => array( 'file', 'php://stdin', 'r' ),
2886 1 => array( 'pipe', 'w' ),
2887 2 => array( 'file', 'php://stderr', 'w' ) );
2888 if ( $useLogPipe ) {
2889 $desc[3] = array( 'pipe', 'w' );
2892 $proc = proc_open( $cmd, $desc, $pipes );
2894 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2898 $outBuffer = $logBuffer = '';
2899 $emptyArray = array();
2903 // According to the documentation, it is possible for stream_select()
2904 // to fail due to EINTR. I haven't managed to induce this in testing
2905 // despite sending various signals. If it did happen, the error
2906 // message would take the form:
2908 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2910 // where [4] is the value of the macro EINTR and "Interrupted system
2911 // call" is string which according to the Linux manual is "possibly"
2912 // localised according to LC_MESSAGES.
2913 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2914 $eintrMessage = "stream_select(): unable to select [$eintr]";
2916 // Build a table mapping resource IDs to pipe FDs to work around a
2917 // PHP 5.3 issue in which stream_select() does not preserve array keys
2918 // <https://bugs.php.net/bug.php?id=53427>.
2920 foreach ( $pipes as $fd => $pipe ) {
2921 $fds[(int)$pipe] = $fd;
2928 while ( $running === true ||
$numReadyPipes !== 0 ) {
2930 $status = proc_get_status( $proc );
2931 // If the process has terminated, switch to nonblocking selects
2932 // for getting any data still waiting to be read.
2933 if ( !$status['running'] ) {
2939 $readyPipes = $pipes;
2942 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2943 @trigger_error
( '' );
2944 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
2945 if ( $numReadyPipes === false ) {
2946 // @codingStandardsIgnoreEnd
2947 $error = error_get_last();
2948 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2951 trigger_error( $error['message'], E_USER_WARNING
);
2952 $logMsg = $error['message'];
2956 foreach ( $readyPipes as $pipe ) {
2957 $block = fread( $pipe, 65536 );
2958 $fd = $fds[(int)$pipe];
2959 if ( $block === '' ) {
2961 fclose( $pipes[$fd] );
2962 unset( $pipes[$fd] );
2966 } elseif ( $block === false ) {
2968 $logMsg = "Error reading from pipe";
2970 } elseif ( $fd == 1 ) {
2972 $outBuffer .= $block;
2973 } elseif ( $fd == 3 ) {
2975 $logBuffer .= $block;
2976 if ( strpos( $block, "\n" ) !== false ) {
2977 $lines = explode( "\n", $logBuffer );
2978 $logBuffer = array_pop( $lines );
2979 foreach ( $lines as $line ) {
2980 wfDebugLog( 'exec', $line );
2987 foreach ( $pipes as $pipe ) {
2991 // Use the status previously collected if possible, since proc_get_status()
2992 // just calls waitpid() which will not return anything useful the second time.
2994 $status = proc_get_status( $proc );
2997 if ( $logMsg !== false ) {
2998 // Read/select error
3000 proc_close( $proc );
3001 } elseif ( $status['signaled'] ) {
3002 $logMsg = "Exited with signal {$status['termsig']}";
3003 $retval = 128 +
$status['termsig'];
3004 proc_close( $proc );
3006 if ( $status['running'] ) {
3007 $retval = proc_close( $proc );
3009 $retval = $status['exitcode'];
3010 proc_close( $proc );
3012 if ( $retval == 127 ) {
3013 $logMsg = "Possibly missing executable file";
3014 } elseif ( $retval >= 129 && $retval <= 192 ) {
3015 $logMsg = "Probably exited with signal " . ( $retval - 128 );
3019 if ( $logMsg !== false ) {
3020 wfDebugLog( 'exec', "$logMsg: $cmd" );
3027 * Execute a shell command, returning both stdout and stderr. Convenience
3028 * function, as all the arguments to wfShellExec can become unwieldy.
3030 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
3031 * @param string $cmd Command line, properly escaped for shell.
3032 * @param null|mixed &$retval Optional, will receive the program's exit code.
3033 * (non-zero is usually failure)
3034 * @param array $environ Optional environment variables which should be
3035 * added to the executed command environment.
3036 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
3037 * this overwrites the global wgMaxShell* limits.
3038 * @return string Collected stdout and stderr as a string
3040 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
3041 return wfShellExec( $cmd, $retval, $environ, $limits, array( 'duplicateStderr' => true ) );
3045 * Workaround for http://bugs.php.net/bug.php?id=45132
3046 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
3048 function wfInitShellLocale() {
3049 static $done = false;
3054 global $wgShellLocale;
3055 if ( !wfIniGetBool( 'safe_mode' ) ) {
3056 putenv( "LC_CTYPE=$wgShellLocale" );
3057 setlocale( LC_CTYPE
, $wgShellLocale );
3062 * Alias to wfShellWikiCmd()
3064 * @see wfShellWikiCmd()
3066 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
3067 return wfShellWikiCmd( $script, $parameters, $options );
3071 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3072 * Note that $parameters should be a flat array and an option with an argument
3073 * should consist of two consecutive items in the array (do not use "--option value").
3075 * @param string $script MediaWiki cli script path
3076 * @param array $parameters Arguments and options to the script
3077 * @param array $options Associative array of options:
3078 * 'php': The path to the php executable
3079 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3082 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3084 // Give site config file a chance to run the script in a wrapper.
3085 // The caller may likely want to call wfBasename() on $script.
3086 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3087 $cmd = isset( $options['php'] ) ?
array( $options['php'] ) : array( $wgPhpCli );
3088 if ( isset( $options['wrapper'] ) ) {
3089 $cmd[] = $options['wrapper'];
3092 // Escape each parameter for shell
3093 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
3097 * wfMerge attempts to merge differences between three texts.
3098 * Returns true for a clean merge and false for failure or a conflict.
3100 * @param string $old
3101 * @param string $mine
3102 * @param string $yours
3103 * @param string $result
3106 function wfMerge( $old, $mine, $yours, &$result ) {
3109 # This check may also protect against code injection in
3110 # case of broken installations.
3111 wfSuppressWarnings();
3112 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3113 wfRestoreWarnings();
3115 if ( !$haveDiff3 ) {
3116 wfDebug( "diff3 not found\n" );
3120 # Make temporary files
3122 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3123 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3124 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3126 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3127 # a newline character. To avoid this, we normalize the trailing whitespace before
3128 # creating the diff.
3130 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3131 fclose( $oldtextFile );
3132 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3133 fclose( $mytextFile );
3134 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3135 fclose( $yourtextFile );
3137 # Check for a conflict
3138 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
3139 wfEscapeShellArg( $mytextName ) . ' ' .
3140 wfEscapeShellArg( $oldtextName ) . ' ' .
3141 wfEscapeShellArg( $yourtextName );
3142 $handle = popen( $cmd, 'r' );
3144 if ( fgets( $handle, 1024 ) ) {
3152 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
3153 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
3154 $handle = popen( $cmd, 'r' );
3157 $data = fread( $handle, 8192 );
3158 if ( strlen( $data ) == 0 ) {
3164 unlink( $mytextName );
3165 unlink( $oldtextName );
3166 unlink( $yourtextName );
3168 if ( $result === '' && $old !== '' && !$conflict ) {
3169 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3176 * Returns unified plain-text diff of two texts.
3177 * Useful for machine processing of diffs.
3179 * @param string $before The text before the changes.
3180 * @param string $after The text after the changes.
3181 * @param string $params Command-line options for the diff command.
3182 * @return string Unified diff of $before and $after
3184 function wfDiff( $before, $after, $params = '-u' ) {
3185 if ( $before == $after ) {
3190 wfSuppressWarnings();
3191 $haveDiff = $wgDiff && file_exists( $wgDiff );
3192 wfRestoreWarnings();
3194 # This check may also protect against code injection in
3195 # case of broken installations.
3197 wfDebug( "diff executable not found\n" );
3198 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3199 $format = new UnifiedDiffFormatter();
3200 return $format->format( $diffs );
3203 # Make temporary files
3205 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3206 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3208 fwrite( $oldtextFile, $before );
3209 fclose( $oldtextFile );
3210 fwrite( $newtextFile, $after );
3211 fclose( $newtextFile );
3213 // Get the diff of the two files
3214 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3216 $h = popen( $cmd, 'r' );
3221 $data = fread( $h, 8192 );
3222 if ( strlen( $data ) == 0 ) {
3230 unlink( $oldtextName );
3231 unlink( $newtextName );
3233 // Kill the --- and +++ lines. They're not useful.
3234 $diff_lines = explode( "\n", $diff );
3235 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
3236 unset( $diff_lines[0] );
3238 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
3239 unset( $diff_lines[1] );
3242 $diff = implode( "\n", $diff_lines );
3248 * This function works like "use VERSION" in Perl, the program will die with a
3249 * backtrace if the current version of PHP is less than the version provided
3251 * This is useful for extensions which due to their nature are not kept in sync
3252 * with releases, and might depend on other versions of PHP than the main code
3254 * Note: PHP might die due to parsing errors in some cases before it ever
3255 * manages to call this function, such is life
3257 * @see perldoc -f use
3259 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3260 * @throws MWException
3262 function wfUsePHP( $req_ver ) {
3263 $php_ver = PHP_VERSION
;
3265 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3266 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3271 * This function works like "use VERSION" in Perl except it checks the version
3272 * of MediaWiki, the program will die with a backtrace if the current version
3273 * of MediaWiki is less than the version provided.
3275 * This is useful for extensions which due to their nature are not kept in sync
3278 * Note: Due to the behavior of PHP's version_compare() which is used in this
3279 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3280 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3281 * targeted version number. For example if you wanted to allow any variation
3282 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3283 * not result in the same comparison due to the internal logic of
3284 * version_compare().
3286 * @see perldoc -f use
3288 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3289 * @throws MWException
3291 function wfUseMW( $req_ver ) {
3294 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3295 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3300 * Return the final portion of a pathname.
3301 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3302 * http://bugs.php.net/bug.php?id=33898
3304 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3305 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3307 * @param string $path
3308 * @param string $suffix String to remove if present
3311 function wfBaseName( $path, $suffix = '' ) {
3312 if ( $suffix == '' ) {
3315 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3319 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3327 * Generate a relative path name to the given file.
3328 * May explode on non-matching case-insensitive paths,
3329 * funky symlinks, etc.
3331 * @param string $path Absolute destination path including target filename
3332 * @param string $from Absolute source path, directory only
3335 function wfRelativePath( $path, $from ) {
3336 // Normalize mixed input on Windows...
3337 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
3338 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
3340 // Trim trailing slashes -- fix for drive root
3341 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
3342 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
3344 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
3345 $against = explode( DIRECTORY_SEPARATOR
, $from );
3347 if ( $pieces[0] !== $against[0] ) {
3348 // Non-matching Windows drive letters?
3349 // Return a full path.
3353 // Trim off common prefix
3354 while ( count( $pieces ) && count( $against )
3355 && $pieces[0] == $against[0] ) {
3356 array_shift( $pieces );
3357 array_shift( $against );
3360 // relative dots to bump us to the parent
3361 while ( count( $against ) ) {
3362 array_unshift( $pieces, '..' );
3363 array_shift( $against );
3366 array_push( $pieces, wfBaseName( $path ) );
3368 return implode( DIRECTORY_SEPARATOR
, $pieces );
3372 * Convert an arbitrarily-long digit string from one numeric base
3373 * to another, optionally zero-padding to a minimum column width.
3375 * Supports base 2 through 36; digit values 10-36 are represented
3376 * as lowercase letters a-z. Input is case-insensitive.
3378 * @param string $input Input number
3379 * @param int $sourceBase Base of the input number
3380 * @param int $destBase Desired base of the output
3381 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3382 * @param bool $lowercase Whether to output in lowercase or uppercase
3383 * @param string $engine Either "gmp", "bcmath", or "php"
3384 * @return string|bool The output number as a string, or false on error
3386 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3387 $lowercase = true, $engine = 'auto'
3389 $input = (string)$input;
3395 $sourceBase != (int)$sourceBase ||
3396 $destBase != (int)$destBase ||
3397 $pad != (int)$pad ||
3399 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3406 static $baseChars = array(
3407 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3408 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3409 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3410 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3411 34 => 'y', 35 => 'z',
3413 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3414 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3415 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3416 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3417 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3418 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3421 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' ||
$engine == 'gmp' ) ) {
3422 $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
3423 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' ||
$engine == 'bcmath' ) ) {
3425 foreach ( str_split( strtolower( $input ) ) as $char ) {
3426 $decimal = bcmul( $decimal, $sourceBase );
3427 $decimal = bcadd( $decimal, $baseChars[$char] );
3430 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3431 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3432 $result .= $baseChars[bcmod( $decimal, $destBase )];
3434 // @codingStandardsIgnoreEnd
3436 $result = strrev( $result );
3438 $inDigits = array();
3439 foreach ( str_split( strtolower( $input ) ) as $char ) {
3440 $inDigits[] = $baseChars[$char];
3443 // Iterate over the input, modulo-ing out an output digit
3444 // at a time until input is gone.
3446 while ( $inDigits ) {
3448 $workDigits = array();
3451 foreach ( $inDigits as $digit ) {
3452 $work *= $sourceBase;
3455 if ( $workDigits ||
$work >= $destBase ) {
3456 $workDigits[] = (int)( $work / $destBase );
3461 // All that division leaves us with a remainder,
3462 // which is conveniently our next output digit.
3463 $result .= $baseChars[$work];
3466 $inDigits = $workDigits;
3469 $result = strrev( $result );
3472 if ( !$lowercase ) {
3473 $result = strtoupper( $result );
3476 return str_pad( $result, $pad, '0', STR_PAD_LEFT
);
3480 * Check if there is sufficient entropy in php's built-in session generation
3482 * @return bool True = there is sufficient entropy
3484 function wfCheckEntropy() {
3486 ( wfIsWindows() && version_compare( PHP_VERSION
, '5.3.3', '>=' ) )
3487 ||
ini_get( 'session.entropy_file' )
3489 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3493 * Override session_id before session startup if php's built-in
3494 * session generation code is not secure.
3496 function wfFixSessionID() {
3497 // If the cookie or session id is already set we already have a session and should abort
3498 if ( isset( $_COOKIE[session_name()] ) ||
session_id() ) {
3502 // PHP's built-in session entropy is enabled if:
3503 // - entropy_file is set or you're on Windows with php 5.3.3+
3504 // - AND entropy_length is > 0
3505 // We treat it as disabled if it doesn't have an entropy length of at least 32
3506 $entropyEnabled = wfCheckEntropy();
3508 // If built-in entropy is not enabled or not sufficient override PHP's
3509 // built in session id generation code
3510 if ( !$entropyEnabled ) {
3511 wfDebug( __METHOD__
. ": PHP's built in entropy is disabled or not sufficient, " .
3512 "overriding session id generation using our cryptrand source.\n" );
3513 session_id( MWCryptRand
::generateHex( 32 ) );
3518 * Reset the session_id
3522 function wfResetSessionID() {
3523 global $wgCookieSecure;
3524 $oldSessionId = session_id();
3525 $cookieParams = session_get_cookie_params();
3526 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3527 session_regenerate_id( false );
3531 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
3534 $newSessionId = session_id();
3535 wfRunHooks( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3539 * Initialise php session
3541 * @param bool $sessionId
3543 function wfSetupSession( $sessionId = false ) {
3544 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3545 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3546 if ( $wgSessionsInObjectCache ||
$wgSessionsInMemcached ) {
3547 ObjectCacheSessionHandler
::install();
3548 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3549 # Only set this if $wgSessionHandler isn't null and session.save_handler
3550 # hasn't already been set to the desired value (that causes errors)
3551 ini_set( 'session.save_handler', $wgSessionHandler );
3553 session_set_cookie_params(
3554 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3555 session_cache_limiter( 'private, must-revalidate' );
3557 session_id( $sessionId );
3561 wfSuppressWarnings();
3563 wfRestoreWarnings();
3567 * Get an object from the precompiled serialized directory
3569 * @param string $name
3570 * @return mixed The variable on success, false on failure
3572 function wfGetPrecompiledData( $name ) {
3575 $file = "$IP/serialized/$name";
3576 if ( file_exists( $file ) ) {
3577 $blob = file_get_contents( $file );
3579 return unserialize( $blob );
3588 * @param string $args,...
3591 function wfMemcKey( /*...*/ ) {
3592 global $wgCachePrefix;
3593 $prefix = $wgCachePrefix === false ?
wfWikiID() : $wgCachePrefix;
3594 $args = func_get_args();
3595 $key = $prefix . ':' . implode( ':', $args );
3596 $key = str_replace( ' ', '_', $key );
3601 * Get a cache key for a foreign DB
3604 * @param string $prefix
3605 * @param string $args,...
3608 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3609 $args = array_slice( func_get_args(), 2 );
3611 $key = "$db-$prefix:" . implode( ':', $args );
3613 $key = $db . ':' . implode( ':', $args );
3615 return str_replace( ' ', '_', $key );
3619 * Get an ASCII string identifying this wiki
3620 * This is used as a prefix in memcached keys
3624 function wfWikiID() {
3625 global $wgDBprefix, $wgDBname;
3626 if ( $wgDBprefix ) {
3627 return "$wgDBname-$wgDBprefix";
3634 * Split a wiki ID into DB name and table prefix
3636 * @param string $wiki
3640 function wfSplitWikiID( $wiki ) {
3641 $bits = explode( '-', $wiki, 2 );
3642 if ( count( $bits ) < 2 ) {
3649 * Get a Database object.
3651 * @param int $db Index of the connection to get. May be DB_MASTER for the
3652 * master (for write queries), DB_SLAVE for potentially lagged read
3653 * queries, or an integer >= 0 for a particular server.
3655 * @param string|string[] $groups Query groups. An array of group names that this query
3656 * belongs to. May contain a single string if the query is only
3659 * @param string|bool $wiki The wiki ID, or false for the current wiki
3661 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3662 * will always return the same object, unless the underlying connection or load
3663 * balancer is manually destroyed.
3665 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3666 * updater to ensure that a proper database is being updated.
3668 * @return DatabaseBase
3670 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3671 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3675 * Get a load balancer object.
3677 * @param string|bool $wiki Wiki ID, or false for the current wiki
3678 * @return LoadBalancer
3680 function wfGetLB( $wiki = false ) {
3681 return wfGetLBFactory()->getMainLB( $wiki );
3685 * Get the load balancer factory object
3689 function &wfGetLBFactory() {
3690 return LBFactory
::singleton();
3695 * Shortcut for RepoGroup::singleton()->findFile()
3697 * @param string $title String or Title object
3698 * @param array $options Associative array of options:
3699 * time: requested time for an archived image, or false for the
3700 * current version. An image object will be returned which was
3701 * created at the specified time.
3703 * ignoreRedirect: If true, do not follow file redirects
3705 * private: If true, return restricted (deleted) files if the current
3706 * user is allowed to view them. Otherwise, such files will not
3709 * bypassCache: If true, do not use the process-local cache of File objects
3711 * @return File|bool File, or false if the file does not exist
3713 function wfFindFile( $title, $options = array() ) {
3714 return RepoGroup
::singleton()->findFile( $title, $options );
3718 * Get an object referring to a locally registered file.
3719 * Returns a valid placeholder object if the file does not exist.
3721 * @param Title|string $title
3722 * @return LocalFile|null A File, or null if passed an invalid Title
3724 function wfLocalFile( $title ) {
3725 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3729 * Should low-performance queries be disabled?
3732 * @codeCoverageIgnore
3734 function wfQueriesMustScale() {
3735 global $wgMiserMode;
3737 ||
( SiteStats
::pages() > 100000
3738 && SiteStats
::edits() > 1000000
3739 && SiteStats
::users() > 10000 );
3743 * Get the path to a specified script file, respecting file
3744 * extensions; this is a wrapper around $wgScriptExtension etc.
3745 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3747 * @param string $script Script filename, sans extension
3750 function wfScript( $script = 'index' ) {
3751 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3752 if ( $script === 'index' ) {
3754 } elseif ( $script === 'load' ) {
3755 return $wgLoadScript;
3757 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3762 * Get the script URL.
3764 * @return string Script URL
3766 function wfGetScriptUrl() {
3767 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3769 # as it was called, minus the query string.
3771 # Some sites use Apache rewrite rules to handle subdomains,
3772 # and have PHP set up in a weird way that causes PHP_SELF
3773 # to contain the rewritten URL instead of the one that the
3774 # outside world sees.
3776 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3777 # provides containing the "before" URL.
3778 return $_SERVER['SCRIPT_NAME'];
3780 return $_SERVER['URL'];
3785 * Convenience function converts boolean values into "true"
3786 * or "false" (string) values
3788 * @param bool $value
3791 function wfBoolToStr( $value ) {
3792 return $value ?
'true' : 'false';
3796 * Get a platform-independent path to the null file, e.g. /dev/null
3800 function wfGetNull() {
3801 return wfIsWindows() ?
'NUL' : '/dev/null';
3805 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3806 * and waiting for it to go down, this waits for the slaves to catch up to the
3807 * master position. Use this when updating very large numbers of rows, as
3808 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3809 * a no-op if there are no slaves.
3811 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3812 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3813 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3815 function wfWaitForSlaves( $ifWritesSince = false, $wiki = false, $cluster = false ) {
3816 // B/C: first argument used to be "max seconds of lag"; ignore such values
3817 $ifWritesSince = ( $ifWritesSince > 1e9
) ?
$ifWritesSince : false;
3819 if ( $cluster !== false ) {
3820 $lb = wfGetLBFactory()->getExternalLB( $cluster );
3822 $lb = wfGetLB( $wiki );
3825 // bug 27975 - Don't try to wait for slaves if there are none
3826 // Prevents permission error when getting master position
3827 if ( $lb->getServerCount() > 1 ) {
3828 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3829 return; // assume no writes done
3831 $dbw = $lb->getConnection( DB_MASTER
, array(), $wiki );
3832 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3833 return; // no writes since the last wait
3835 $pos = $dbw->getMasterPos();
3836 // The DBMS may not support getMasterPos() or the whole
3837 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3838 if ( $pos !== false ) {
3839 $lb->waitForAll( $pos );
3845 * Count down from $seconds to zero on the terminal, with a one-second pause
3846 * between showing each number. For use in command-line scripts.
3848 * @codeCoverageIgnore
3849 * @param int $seconds
3851 function wfCountDown( $seconds ) {
3852 for ( $i = $seconds; $i >= 0; $i-- ) {
3853 if ( $i != $seconds ) {
3854 echo str_repeat( "\x08", strlen( $i +
1 ) );
3866 * Replace all invalid characters with -
3867 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3868 * By default, $wgIllegalFileChars = ':'
3870 * @param string $name Filename to process
3873 function wfStripIllegalFilenameChars( $name ) {
3874 global $wgIllegalFileChars;
3875 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3876 $name = wfBaseName( $name );
3877 $name = preg_replace(
3878 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3886 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3888 * @return int Value the memory limit was set to.
3890 function wfMemoryLimit() {
3891 global $wgMemoryLimit;
3892 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3893 if ( $memlimit != -1 ) {
3894 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3895 if ( $conflimit == -1 ) {
3896 wfDebug( "Removing PHP's memory limit\n" );
3897 wfSuppressWarnings();
3898 ini_set( 'memory_limit', $conflimit );
3899 wfRestoreWarnings();
3901 } elseif ( $conflimit > $memlimit ) {
3902 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3903 wfSuppressWarnings();
3904 ini_set( 'memory_limit', $conflimit );
3905 wfRestoreWarnings();
3913 * Converts shorthand byte notation to integer form
3915 * @param string $string
3918 function wfShorthandToInteger( $string = '' ) {
3919 $string = trim( $string );
3920 if ( $string === '' ) {
3923 $last = $string[strlen( $string ) - 1];
3924 $val = intval( $string );
3929 // break intentionally missing
3933 // break intentionally missing
3943 * Get the normalised IETF language tag
3944 * See unit test for examples.
3946 * @param string $code The language code.
3947 * @return string The language code which complying with BCP 47 standards.
3949 function wfBCP47( $code ) {
3950 $codeSegment = explode( '-', $code );
3952 foreach ( $codeSegment as $segNo => $seg ) {
3953 // when previous segment is x, it is a private segment and should be lc
3954 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3955 $codeBCP[$segNo] = strtolower( $seg );
3956 // ISO 3166 country code
3957 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3958 $codeBCP[$segNo] = strtoupper( $seg );
3959 // ISO 15924 script code
3960 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3961 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3962 // Use lowercase for other cases
3964 $codeBCP[$segNo] = strtolower( $seg );
3967 $langCode = implode( '-', $codeBCP );
3972 * Get a cache object.
3974 * @param int $inputType Cache type, one the the CACHE_* constants.
3977 function wfGetCache( $inputType ) {
3978 return ObjectCache
::getInstance( $inputType );
3982 * Get the main cache object
3986 function wfGetMainCache() {
3987 global $wgMainCacheType;
3988 return ObjectCache
::getInstance( $wgMainCacheType );
3992 * Get the cache object used by the message cache
3996 function wfGetMessageCacheStorage() {
3997 global $wgMessageCacheType;
3998 return ObjectCache
::getInstance( $wgMessageCacheType );
4002 * Get the cache object used by the parser cache
4006 function wfGetParserCacheStorage() {
4007 global $wgParserCacheType;
4008 return ObjectCache
::getInstance( $wgParserCacheType );
4012 * Get the cache object used by the language converter
4016 function wfGetLangConverterCacheStorage() {
4017 global $wgLanguageConverterCacheType;
4018 return ObjectCache
::getInstance( $wgLanguageConverterCacheType );
4022 * Call hook functions defined in $wgHooks
4024 * @param string $event Event name
4025 * @param array $args Parameters passed to hook functions
4026 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
4028 * @return bool True if no handler aborted the hook
4030 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
4031 return Hooks
::run( $event, $args, $deprecatedVersion );
4035 * Wrapper around php's unpack.
4037 * @param string $format The format string (See php's docs)
4038 * @param string $data A binary string of binary data
4039 * @param int|bool $length The minimum length of $data or false. This is to
4040 * prevent reading beyond the end of $data. false to disable the check.
4042 * Also be careful when using this function to read unsigned 32 bit integer
4043 * because php might make it negative.
4045 * @throws MWException If $data not long enough, or if unpack fails
4046 * @return array Associative array of the extracted data
4048 function wfUnpack( $format, $data, $length = false ) {
4049 if ( $length !== false ) {
4050 $realLen = strlen( $data );
4051 if ( $realLen < $length ) {
4052 throw new MWException( "Tried to use wfUnpack on a "
4053 . "string of length $realLen, but needed one "
4054 . "of at least length $length."
4059 wfSuppressWarnings();
4060 $result = unpack( $format, $data );
4061 wfRestoreWarnings();
4063 if ( $result === false ) {
4064 // If it cannot extract the packed data.
4065 throw new MWException( "unpack could not unpack binary data" );
4071 * Determine if an image exists on the 'bad image list'.
4073 * The format of MediaWiki:Bad_image_list is as follows:
4074 * * Only list items (lines starting with "*") are considered
4075 * * The first link on a line must be a link to a bad image
4076 * * Any subsequent links on the same line are considered to be exceptions,
4077 * i.e. articles where the image may occur inline.
4079 * @param string $name The image name to check
4080 * @param Title|bool $contextTitle The page on which the image occurs, if known
4081 * @param string $blacklist Wikitext of a file blacklist
4084 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4085 static $badImageCache = null; // based on bad_image_list msg
4086 wfProfileIn( __METHOD__
);
4089 $redirectTitle = RepoGroup
::singleton()->checkRedirect( Title
::makeTitle( NS_FILE
, $name ) );
4090 if ( $redirectTitle ) {
4091 $name = $redirectTitle->getDBkey();
4094 # Run the extension hook
4096 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
4097 wfProfileOut( __METHOD__
);
4101 $cacheable = ( $blacklist === null );
4102 if ( $cacheable && $badImageCache !== null ) {
4103 $badImages = $badImageCache;
4104 } else { // cache miss
4105 if ( $blacklist === null ) {
4106 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4108 # Build the list now
4109 $badImages = array();
4110 $lines = explode( "\n", $blacklist );
4111 foreach ( $lines as $line ) {
4113 if ( substr( $line, 0, 1 ) !== '*' ) {
4119 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4123 $exceptions = array();
4124 $imageDBkey = false;
4125 foreach ( $m[1] as $i => $titleText ) {
4126 $title = Title
::newFromText( $titleText );
4127 if ( !is_null( $title ) ) {
4129 $imageDBkey = $title->getDBkey();
4131 $exceptions[$title->getPrefixedDBkey()] = true;
4136 if ( $imageDBkey !== false ) {
4137 $badImages[$imageDBkey] = $exceptions;
4141 $badImageCache = $badImages;
4145 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
4146 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4147 wfProfileOut( __METHOD__
);
4152 * Determine whether the client at a given source IP is likely to be able to
4153 * access the wiki via HTTPS.
4155 * @param string $ip The IPv4/6 address in the normal human-readable form
4158 function wfCanIPUseHTTPS( $ip ) {
4160 wfRunHooks( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4165 * Work out the IP address based on various globals
4166 * For trusted proxies, use the XFF client IP (first of the chain)
4168 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4171 function wfGetIP() {
4172 wfDeprecated( __METHOD__
, '1.19' );
4174 return $wgRequest->getIP();
4178 * Checks if an IP is a trusted proxy provider.
4179 * Useful to tell if X-Forwarded-For data is possibly bogus.
4180 * Squid cache servers for the site are whitelisted.
4181 * @deprecated Since 1.24, use IP::isTrustedProxy()
4186 function wfIsTrustedProxy( $ip ) {
4187 return IP
::isTrustedProxy( $ip );
4191 * Checks if an IP matches a proxy we've configured.
4192 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4196 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4198 function wfIsConfiguredProxy( $ip ) {
4199 return IP
::isConfiguredProxy( $ip );