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 );
180 * Appends to second array if $value differs from that in $default
182 * @param string|int $key
183 * @param mixed $value
184 * @param mixed $default
185 * @param array $changed Array to alter
186 * @throws MWException
188 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
189 if ( is_null( $changed ) ) {
190 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
192 if ( $default[$key] !== $value ) {
193 $changed[$key] = $value;
198 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
200 * wfMergeErrorArrays(
201 * array( array( 'x' ) ),
202 * array( array( 'x', '2' ) ),
203 * array( array( 'x' ) ),
204 * array( array( 'y' ) )
213 * @param array $array1,...
216 function wfMergeErrorArrays( /*...*/ ) {
217 $args = func_get_args();
219 foreach ( $args as $errors ) {
220 foreach ( $errors as $params ) {
221 # @todo FIXME: Sometimes get nested arrays for $params,
222 # which leads to E_NOTICEs
223 $spec = implode( "\t", $params );
224 $out[$spec] = $params;
227 return array_values( $out );
231 * Insert array into another array after the specified *KEY*
233 * @param array $array The array.
234 * @param array $insert The array to insert.
235 * @param mixed $after The key to insert after
238 function wfArrayInsertAfter( array $array, array $insert, $after ) {
239 // Find the offset of the element to insert after.
240 $keys = array_keys( $array );
241 $offsetByKey = array_flip( $keys );
243 $offset = $offsetByKey[$after];
245 // Insert at the specified offset
246 $before = array_slice( $array, 0, $offset +
1, true );
247 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
249 $output = $before +
$insert +
$after;
255 * Recursively converts the parameter (an object) to an array with the same data
257 * @param object|array $objOrArray
258 * @param bool $recursive
261 function wfObjectToArray( $objOrArray, $recursive = true ) {
263 if ( is_object( $objOrArray ) ) {
264 $objOrArray = get_object_vars( $objOrArray );
266 foreach ( $objOrArray as $key => $value ) {
267 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
268 $value = wfObjectToArray( $value );
271 $array[$key] = $value;
278 * Get a random decimal value between 0 and 1, in a way
279 * not likely to give duplicate values for any realistic
280 * number of articles.
284 function wfRandom() {
285 # The maximum random value is "only" 2^31-1, so get two random
286 # values to reduce the chance of dupes
287 $max = mt_getrandmax() +
1;
288 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
294 * Get a random string containing a number of pseudo-random hex
296 * @note This is not secure, if you are trying to generate some sort
297 * of token please use MWCryptRand instead.
299 * @param int $length The length of the string to generate
303 function wfRandomString( $length = 32 ) {
305 for ( $n = 0; $n < $length; $n +
= 7 ) {
306 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
308 return substr( $str, 0, $length );
312 * We want some things to be included as literal characters in our title URLs
313 * for prettiness, which urlencode encodes by default. According to RFC 1738,
314 * all of the following should be safe:
318 * But + is not safe because it's used to indicate a space; &= are only safe in
319 * paths and not in queries (and we don't distinguish here); ' seems kind of
320 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
321 * is reserved, we don't care. So the list we unescape is:
325 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
326 * so no fancy : for IIS7.
328 * %2F in the page titles seems to fatally break for some reason.
333 function wfUrlencode( $s ) {
336 if ( is_null( $s ) ) {
341 if ( is_null( $needle ) ) {
342 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
343 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
344 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
350 $s = urlencode( $s );
353 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
361 * This function takes two arrays as input, and returns a CGI-style string, e.g.
362 * "days=7&limit=100". Options in the first array override options in the second.
363 * Options set to null or false will not be output.
365 * @param array $array1 ( String|Array )
366 * @param array $array2 ( String|Array )
367 * @param string $prefix
370 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
371 if ( !is_null( $array2 ) ) {
372 $array1 = $array1 +
$array2;
376 foreach ( $array1 as $key => $value ) {
377 if ( !is_null( $value ) && $value !== false ) {
381 if ( $prefix !== '' ) {
382 $key = $prefix . "[$key]";
384 if ( is_array( $value ) ) {
386 foreach ( $value as $k => $v ) {
387 $cgi .= $firstTime ?
'' : '&';
388 if ( is_array( $v ) ) {
389 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
391 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
396 if ( is_object( $value ) ) {
397 $value = $value->__toString();
399 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
407 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
408 * its argument and returns the same string in array form. This allows compatibility
409 * with legacy functions that accept raw query strings instead of nice
410 * arrays. Of course, keys and values are urldecode()d.
412 * @param string $query Query string
413 * @return string[] Array version of input
415 function wfCgiToArray( $query ) {
416 if ( isset( $query[0] ) && $query[0] == '?' ) {
417 $query = substr( $query, 1 );
419 $bits = explode( '&', $query );
421 foreach ( $bits as $bit ) {
425 if ( strpos( $bit, '=' ) === false ) {
426 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
430 list( $key, $value ) = explode( '=', $bit );
432 $key = urldecode( $key );
433 $value = urldecode( $value );
434 if ( strpos( $key, '[' ) !== false ) {
435 $keys = array_reverse( explode( '[', $key ) );
436 $key = array_pop( $keys );
438 foreach ( $keys as $k ) {
439 $k = substr( $k, 0, -1 );
440 $temp = array( $k => $temp );
442 if ( isset( $ret[$key] ) ) {
443 $ret[$key] = array_merge( $ret[$key], $temp );
455 * Append a query string to an existing URL, which may or may not already
456 * have query string parameters already. If so, they will be combined.
459 * @param string|string[] $query String or associative array
462 function wfAppendQuery( $url, $query ) {
463 if ( is_array( $query ) ) {
464 $query = wfArrayToCgi( $query );
466 if ( $query != '' ) {
467 if ( false === strpos( $url, '?' ) ) {
478 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
481 * The meaning of the PROTO_* constants is as follows:
482 * PROTO_HTTP: Output a URL starting with http://
483 * PROTO_HTTPS: Output a URL starting with https://
484 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
485 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
486 * on which protocol was used for the current incoming request
487 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
488 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
489 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
491 * @todo this won't work with current-path-relative URLs
492 * like "subdir/foo.html", etc.
494 * @param string $url Either fully-qualified or a local path + query
495 * @param string $defaultProto One of the PROTO_* constants. Determines the
496 * protocol to use if $url or $wgServer is protocol-relative
497 * @return string Fully-qualified URL, current-path-relative URL or false if
498 * no valid URL can be constructed
500 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
501 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
503 if ( $defaultProto === PROTO_CANONICAL
) {
504 $serverUrl = $wgCanonicalServer;
505 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
506 // Make $wgInternalServer fall back to $wgServer if not set
507 $serverUrl = $wgInternalServer;
509 $serverUrl = $wgServer;
510 if ( $defaultProto === PROTO_CURRENT
) {
511 $defaultProto = $wgRequest->getProtocol() . '://';
515 // Analyze $serverUrl to obtain its protocol
516 $bits = wfParseUrl( $serverUrl );
517 $serverHasProto = $bits && $bits['scheme'] != '';
519 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
520 if ( $serverHasProto ) {
521 $defaultProto = $bits['scheme'] . '://';
523 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
524 // This really isn't supposed to happen. Fall back to HTTP in this
526 $defaultProto = PROTO_HTTP
;
530 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
532 if ( substr( $url, 0, 2 ) == '//' ) {
533 $url = $defaultProtoWithoutSlashes . $url;
534 } elseif ( substr( $url, 0, 1 ) == '/' ) {
535 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
536 // otherwise leave it alone.
537 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
540 $bits = wfParseUrl( $url );
542 // ensure proper port for HTTPS arrives in URL
543 // https://bugzilla.wikimedia.org/show_bug.cgi?id=65184
544 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
545 $bits['port'] = $wgHttpsPort;
548 if ( $bits && isset( $bits['path'] ) ) {
549 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
550 return wfAssembleUrl( $bits );
554 } elseif ( substr( $url, 0, 1 ) != '/' ) {
555 # URL is a relative path
556 return wfRemoveDotSegments( $url );
559 # Expanded URL is not valid.
564 * This function will reassemble a URL parsed with wfParseURL. This is useful
565 * if you need to edit part of a URL and put it back together.
567 * This is the basic structure used (brackets contain keys for $urlParts):
568 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
570 * @todo Need to integrate this into wfExpandUrl (bug 32168)
573 * @param array $urlParts URL parts, as output from wfParseUrl
574 * @return string URL assembled from its component parts
576 function wfAssembleUrl( $urlParts ) {
579 if ( isset( $urlParts['delimiter'] ) ) {
580 if ( isset( $urlParts['scheme'] ) ) {
581 $result .= $urlParts['scheme'];
584 $result .= $urlParts['delimiter'];
587 if ( isset( $urlParts['host'] ) ) {
588 if ( isset( $urlParts['user'] ) ) {
589 $result .= $urlParts['user'];
590 if ( isset( $urlParts['pass'] ) ) {
591 $result .= ':' . $urlParts['pass'];
596 $result .= $urlParts['host'];
598 if ( isset( $urlParts['port'] ) ) {
599 $result .= ':' . $urlParts['port'];
603 if ( isset( $urlParts['path'] ) ) {
604 $result .= $urlParts['path'];
607 if ( isset( $urlParts['query'] ) ) {
608 $result .= '?' . $urlParts['query'];
611 if ( isset( $urlParts['fragment'] ) ) {
612 $result .= '#' . $urlParts['fragment'];
619 * Remove all dot-segments in the provided URL path. For example,
620 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
621 * RFC3986 section 5.2.4.
623 * @todo Need to integrate this into wfExpandUrl (bug 32168)
625 * @param string $urlPath URL path, potentially containing dot-segments
626 * @return string URL path with all dot-segments removed
628 function wfRemoveDotSegments( $urlPath ) {
631 $inputLength = strlen( $urlPath );
633 while ( $inputOffset < $inputLength ) {
634 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
635 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
636 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
637 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
640 if ( $prefixLengthTwo == './' ) {
641 # Step A, remove leading "./"
643 } elseif ( $prefixLengthThree == '../' ) {
644 # Step A, remove leading "../"
646 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
647 # Step B, replace leading "/.$" with "/"
649 $urlPath[$inputOffset] = '/';
650 } elseif ( $prefixLengthThree == '/./' ) {
651 # Step B, replace leading "/./" with "/"
653 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
654 # Step C, replace leading "/..$" with "/" and
655 # remove last path component in output
657 $urlPath[$inputOffset] = '/';
659 } elseif ( $prefixLengthFour == '/../' ) {
660 # Step C, replace leading "/../" with "/" and
661 # remove last path component in output
664 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
665 # Step D, remove "^.$"
667 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
668 # Step D, remove "^..$"
671 # Step E, move leading path segment to output
672 if ( $prefixLengthOne == '/' ) {
673 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
675 $slashPos = strpos( $urlPath, '/', $inputOffset );
677 if ( $slashPos === false ) {
678 $output .= substr( $urlPath, $inputOffset );
679 $inputOffset = $inputLength;
681 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
682 $inputOffset +
= $slashPos - $inputOffset;
687 $slashPos = strrpos( $output, '/' );
688 if ( $slashPos === false ) {
691 $output = substr( $output, 0, $slashPos );
700 * Returns a regular expression of url protocols
702 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
703 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
706 function wfUrlProtocols( $includeProtocolRelative = true ) {
707 global $wgUrlProtocols;
709 // Cache return values separately based on $includeProtocolRelative
710 static $withProtRel = null, $withoutProtRel = null;
711 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
712 if ( !is_null( $cachedValue ) ) {
716 // Support old-style $wgUrlProtocols strings, for backwards compatibility
717 // with LocalSettings files from 1.5
718 if ( is_array( $wgUrlProtocols ) ) {
719 $protocols = array();
720 foreach ( $wgUrlProtocols as $protocol ) {
721 // Filter out '//' if !$includeProtocolRelative
722 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
723 $protocols[] = preg_quote( $protocol, '/' );
727 $retval = implode( '|', $protocols );
729 // Ignore $includeProtocolRelative in this case
730 // This case exists for pre-1.6 compatibility, and we can safely assume
731 // that '//' won't appear in a pre-1.6 config because protocol-relative
732 // URLs weren't supported until 1.18
733 $retval = $wgUrlProtocols;
736 // Cache return value
737 if ( $includeProtocolRelative ) {
738 $withProtRel = $retval;
740 $withoutProtRel = $retval;
746 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
747 * you need a regex that matches all URL protocols but does not match protocol-
751 function wfUrlProtocolsWithoutProtRel() {
752 return wfUrlProtocols( false );
756 * parse_url() work-alike, but non-broken. Differences:
758 * 1) Does not raise warnings on bad URLs (just returns false).
759 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
760 * protocol-relative URLs) correctly.
761 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
763 * @param string $url A URL to parse
764 * @return string[] Bits of the URL in an associative array, per PHP docs
766 function wfParseUrl( $url ) {
767 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
769 // Protocol-relative URLs are handled really badly by parse_url(). It's so
770 // bad that the easiest way to handle them is to just prepend 'http:' and
771 // strip the protocol out later.
772 $wasRelative = substr( $url, 0, 2 ) == '//';
773 if ( $wasRelative ) {
776 wfSuppressWarnings();
777 $bits = parse_url( $url );
779 // parse_url() returns an array without scheme for some invalid URLs, e.g.
780 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
781 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
785 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
786 $bits['scheme'] = strtolower( $bits['scheme'] );
788 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
789 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
790 $bits['delimiter'] = '://';
791 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
792 $bits['delimiter'] = ':';
793 // parse_url detects for news: and mailto: the host part of an url as path
794 // We have to correct this wrong detection
795 if ( isset( $bits['path'] ) ) {
796 $bits['host'] = $bits['path'];
803 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
804 if ( !isset( $bits['host'] ) ) {
808 if ( isset( $bits['path'] ) ) {
809 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
810 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
811 $bits['path'] = '/' . $bits['path'];
818 // If the URL was protocol-relative, fix scheme and delimiter
819 if ( $wasRelative ) {
820 $bits['scheme'] = '';
821 $bits['delimiter'] = '//';
827 * Take a URL, make sure it's expanded to fully qualified, and replace any
828 * encoded non-ASCII Unicode characters with their UTF-8 original forms
829 * for more compact display and legibility for local audiences.
831 * @todo handle punycode domains too
836 function wfExpandIRI( $url ) {
837 return preg_replace_callback(
838 '/((?:%[89A-F][0-9A-F])+)/i',
839 'wfExpandIRI_callback',
845 * Private callback for wfExpandIRI
846 * @param array $matches
849 function wfExpandIRI_callback( $matches ) {
850 return urldecode( $matches[1] );
854 * Make URL indexes, appropriate for the el_index field of externallinks.
859 function wfMakeUrlIndexes( $url ) {
860 $bits = wfParseUrl( $url );
862 // Reverse the labels in the hostname, convert to lower case
863 // For emails reverse domainpart only
864 if ( $bits['scheme'] == 'mailto' ) {
865 $mailparts = explode( '@', $bits['host'], 2 );
866 if ( count( $mailparts ) === 2 ) {
867 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
869 // No domain specified, don't mangle it
872 $reversedHost = $domainpart . '@' . $mailparts[0];
874 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
876 // Add an extra dot to the end
877 // Why? Is it in wrong place in mailto links?
878 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
879 $reversedHost .= '.';
881 // Reconstruct the pseudo-URL
882 $prot = $bits['scheme'];
883 $index = $prot . $bits['delimiter'] . $reversedHost;
884 // Leave out user and password. Add the port, path, query and fragment
885 if ( isset( $bits['port'] ) ) {
886 $index .= ':' . $bits['port'];
888 if ( isset( $bits['path'] ) ) {
889 $index .= $bits['path'];
893 if ( isset( $bits['query'] ) ) {
894 $index .= '?' . $bits['query'];
896 if ( isset( $bits['fragment'] ) ) {
897 $index .= '#' . $bits['fragment'];
901 return array( "http:$index", "https:$index" );
903 return array( $index );
908 * Check whether a given URL has a domain that occurs in a given set of domains
909 * @param string $url URL
910 * @param array $domains Array of domains (strings)
911 * @return bool True if the host part of $url ends in one of the strings in $domains
913 function wfMatchesDomainList( $url, $domains ) {
914 $bits = wfParseUrl( $url );
915 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
916 $host = '.' . $bits['host'];
917 foreach ( (array)$domains as $domain ) {
918 $domain = '.' . $domain;
919 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
928 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
929 * In normal operation this is a NOP.
931 * Controlling globals:
932 * $wgDebugLogFile - points to the log file
933 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
934 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
936 * @param string $text
937 * @param string|bool $dest Destination of the message:
938 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
939 * - 'log': only to the log and not in HTML
940 * For backward compatibility, it can also take a boolean:
941 * - true: same as 'all'
942 * - false: same as 'log'
944 function wfDebug( $text, $dest = 'all' ) {
945 global $wgDebugLogFile, $wgDebugRawPage, $wgDebugLogPrefix;
947 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
951 // Turn $dest into a string if it's a boolean (for b/c)
952 if ( $dest === true ) {
954 } elseif ( $dest === false ) {
958 $timer = wfDebugTimer();
959 if ( $timer !== '' ) {
960 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
963 if ( $dest === 'all' ) {
964 MWDebug
::debugMsg( $text );
967 if ( $wgDebugLogFile != '' ) {
968 # Strip unprintables; they can switch terminal modes when binary data
969 # gets dumped, which is pretty annoying.
970 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
971 $text = $wgDebugLogPrefix . $text;
972 wfErrorLog( $text, $wgDebugLogFile );
977 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
980 function wfIsDebugRawPage() {
982 if ( $cache !== null ) {
985 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
986 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
988 isset( $_SERVER['SCRIPT_NAME'] )
989 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1000 * Get microsecond timestamps for debug logs
1004 function wfDebugTimer() {
1005 global $wgDebugTimestamps, $wgRequestTime;
1007 if ( !$wgDebugTimestamps ) {
1011 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1012 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1013 return "$prefix $mem ";
1017 * Send a line giving PHP memory usage.
1019 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1021 function wfDebugMem( $exact = false ) {
1022 $mem = memory_get_usage();
1024 $mem = floor( $mem / 1024 ) . ' KiB';
1028 wfDebug( "Memory usage: $mem\n" );
1032 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
1033 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string
1034 * filename or an associative array mapping 'destination' to the desired filename. The
1035 * associative array may also contain a 'sample' key with an integer value, specifying
1036 * a sampling factor.
1038 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1040 * @param string $logGroup
1041 * @param string $text
1042 * @param string|bool $dest Destination of the message:
1043 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1044 * - 'log': only to the log and not in HTML
1045 * - 'private': only to the specifc log if set in $wgDebugLogGroups and
1046 * discarded otherwise
1047 * For backward compatibility, it can also take a boolean:
1048 * - true: same as 'all'
1049 * - false: same as 'private'
1051 function wfDebugLog( $logGroup, $text, $dest = 'all' ) {
1052 global $wgDebugLogGroups;
1054 $text = trim( $text ) . "\n";
1056 // Turn $dest into a string if it's a boolean (for b/c)
1057 if ( $dest === true ) {
1059 } elseif ( $dest === false ) {
1063 if ( !isset( $wgDebugLogGroups[$logGroup] ) ) {
1064 if ( $dest !== 'private' ) {
1065 wfDebug( "[$logGroup] $text", $dest );
1070 if ( $dest === 'all' ) {
1071 MWDebug
::debugMsg( "[$logGroup] $text" );
1074 $logConfig = $wgDebugLogGroups[$logGroup];
1075 if ( $logConfig === false ) {
1078 if ( is_array( $logConfig ) ) {
1079 if ( isset( $logConfig['sample'] ) && mt_rand( 1, $logConfig['sample'] ) !== 1 ) {
1082 $destination = $logConfig['destination'];
1084 $destination = strval( $logConfig );
1087 $time = wfTimestamp( TS_DB
);
1089 $host = wfHostname();
1090 wfErrorLog( "$time $host $wiki: $text", $destination );
1094 * Log for database errors
1096 * @param string $text Database error message.
1098 function wfLogDBError( $text ) {
1099 global $wgDBerrorLog, $wgDBerrorLogTZ;
1100 static $logDBErrorTimeZoneObject = null;
1102 if ( $wgDBerrorLog ) {
1103 $host = wfHostname();
1106 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
1107 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
1110 // Workaround for https://bugs.php.net/bug.php?id=52063
1111 // Can be removed when min PHP > 5.3.2
1112 if ( $logDBErrorTimeZoneObject === null ) {
1113 $d = date_create( "now" );
1115 $d = date_create( "now", $logDBErrorTimeZoneObject );
1118 $date = $d->format( 'D M j G:i:s T Y' );
1120 $text = "$date\t$host\t$wiki\t" . trim( $text ) . "\n";
1121 wfErrorLog( $text, $wgDBerrorLog );
1126 * Throws a warning that $function is deprecated
1128 * @param string $function
1129 * @param string|bool $version Version of MediaWiki that the function
1130 * was deprecated in (Added in 1.19).
1131 * @param string|bool $component Added in 1.19.
1132 * @param int $callerOffset How far up the call stack is the original
1133 * caller. 2 = function that called the function that called
1134 * wfDeprecated (Added in 1.20)
1138 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1139 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1143 * Send a warning either to the debug log or in a PHP error depending on
1144 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1146 * @param string $msg Message to send
1147 * @param int $callerOffset Number of items to go back in the backtrace to
1148 * find the correct caller (1 = function calling wfWarn, ...)
1149 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1150 * only used when $wgDevelopmentWarnings is true
1152 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1153 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1157 * Send a warning as a PHP error and the debug log. This is intended for logging
1158 * warnings in production. For logging development warnings, use WfWarn instead.
1160 * @param string $msg Message to send
1161 * @param int $callerOffset Number of items to go back in the backtrace to
1162 * find the correct caller (1 = function calling wfLogWarning, ...)
1163 * @param int $level PHP error level; defaults to E_USER_WARNING
1165 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1166 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1170 * Log to a file without getting "file size exceeded" signals.
1172 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1173 * send lines to the specified port, prefixed by the specified prefix and a space.
1175 * @param string $text
1176 * @param string $file Filename
1177 * @throws MWException
1179 function wfErrorLog( $text, $file ) {
1180 if ( substr( $file, 0, 4 ) == 'udp:' ) {
1181 # Needs the sockets extension
1182 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
1183 // IPv6 bracketed host
1185 $port = intval( $m[3] );
1186 $prefix = isset( $m[4] ) ?
$m[4] : false;
1188 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
1190 if ( !IP
::isIPv4( $host ) ) {
1191 $host = gethostbyname( $host );
1193 $port = intval( $m[3] );
1194 $prefix = isset( $m[4] ) ?
$m[4] : false;
1197 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
1200 // Clean it up for the multiplexer
1201 if ( strval( $prefix ) !== '' ) {
1202 $text = preg_replace( '/^/m', $prefix . ' ', $text );
1205 if ( strlen( $text ) > 65506 ) {
1206 $text = substr( $text, 0, 65506 );
1209 if ( substr( $text, -1 ) != "\n" ) {
1212 } elseif ( strlen( $text ) > 65507 ) {
1213 $text = substr( $text, 0, 65507 );
1216 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
1221 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
1222 socket_close( $sock );
1224 wfSuppressWarnings();
1225 $exists = file_exists( $file );
1226 $size = $exists ?
filesize( $file ) : false;
1227 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
1228 file_put_contents( $file, $text, FILE_APPEND
);
1230 wfRestoreWarnings();
1237 function wfLogProfilingData() {
1238 global $wgRequestTime, $wgDebugLogFile, $wgDebugLogGroups, $wgDebugRawPage;
1239 global $wgProfileLimit, $wgUser, $wgRequest;
1241 StatCounter
::singleton()->flush();
1243 $profiler = Profiler
::instance();
1245 # Profiling must actually be enabled...
1246 if ( $profiler->isStub() ) {
1250 // Get total page request time and only show pages that longer than
1251 // $wgProfileLimit time (default is 0)
1252 $elapsed = microtime( true ) - $wgRequestTime;
1253 if ( $elapsed <= $wgProfileLimit ) {
1257 $profiler->logData();
1259 // Check whether this should be logged in the debug file.
1260 if ( isset( $wgDebugLogGroups['profileoutput'] )
1261 && $wgDebugLogGroups['profileoutput'] === false
1263 // Explicitely disabled
1266 if ( !isset( $wgDebugLogGroups['profileoutput'] ) && $wgDebugLogFile == '' ) {
1267 // Logging not enabled; no point going further
1270 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1275 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1276 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
1278 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1279 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
1281 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1282 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
1285 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
1287 // Don't load $wgUser at this late stage just for statistics purposes
1288 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
1289 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1290 $forward .= ' anon';
1293 // Command line script uses a FauxRequest object which does not have
1294 // any knowledge about an URL and throw an exception instead.
1296 $requestUrl = $wgRequest->getRequestURL();
1297 } catch ( MWException
$e ) {
1298 $requestUrl = 'n/a';
1301 $log = sprintf( "%s\t%04.3f\t%s\n",
1302 gmdate( 'YmdHis' ), $elapsed,
1303 urldecode( $requestUrl . $forward ) );
1305 wfDebugLog( 'profileoutput', $log . $profiler->getOutput() );
1309 * Increment a statistics counter
1311 * @param string $key
1315 function wfIncrStats( $key, $count = 1 ) {
1316 StatCounter
::singleton()->incr( $key, $count );
1320 * Check whether the wiki is in read-only mode.
1324 function wfReadOnly() {
1325 return wfReadOnlyReason() !== false;
1329 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1331 * @return string|bool String when in read-only mode; false otherwise
1333 function wfReadOnlyReason() {
1334 global $wgReadOnly, $wgReadOnlyFile;
1336 if ( $wgReadOnly === null ) {
1337 // Set $wgReadOnly for faster access next time
1338 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1339 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1341 $wgReadOnly = false;
1349 * Return a Language object from $langcode
1351 * @param Language|string|bool $langcode Either:
1352 * - a Language object
1353 * - code of the language to get the message for, if it is
1354 * a valid code create a language for that language, if
1355 * it is a string but not a valid code then make a basic
1357 * - a boolean: if it's false then use the global object for
1358 * the current user's language (as a fallback for the old parameter
1359 * functionality), or if it is true then use global object
1360 * for the wiki's content language.
1363 function wfGetLangObj( $langcode = false ) {
1364 # Identify which language to get or create a language object for.
1365 # Using is_object here due to Stub objects.
1366 if ( is_object( $langcode ) ) {
1367 # Great, we already have the object (hopefully)!
1371 global $wgContLang, $wgLanguageCode;
1372 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1373 # $langcode is the language code of the wikis content language object.
1374 # or it is a boolean and value is true
1379 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1380 # $langcode is the language code of user language object.
1381 # or it was a boolean and value is false
1385 $validCodes = array_keys( Language
::fetchLanguageNames() );
1386 if ( in_array( $langcode, $validCodes ) ) {
1387 # $langcode corresponds to a valid language.
1388 return Language
::factory( $langcode );
1391 # $langcode is a string, but not a valid language code; use content language.
1392 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1397 * This is the function for getting translated interface messages.
1399 * @see Message class for documentation how to use them.
1400 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1402 * This function replaces all old wfMsg* functions.
1404 * @param string $key Message key
1405 * @param mixed $params,... Normal message parameters
1410 * @see Message::__construct
1412 function wfMessage( $key /*...*/ ) {
1413 $params = func_get_args();
1414 array_shift( $params );
1415 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1416 $params = $params[0];
1418 return new Message( $key, $params );
1422 * This function accepts multiple message keys and returns a message instance
1423 * for the first message which is non-empty. If all messages are empty then an
1424 * instance of the first message key is returned.
1426 * @param string|string[] $keys,... Message keys
1431 * @see Message::newFallbackSequence
1433 function wfMessageFallback( /*...*/ ) {
1434 $args = func_get_args();
1435 return call_user_func_array( 'Message::newFallbackSequence', $args );
1439 * Get a message from anywhere, for the current user language.
1441 * Use wfMsgForContent() instead if the message should NOT
1442 * change depending on the user preferences.
1444 * @deprecated since 1.18
1446 * @param string $key Lookup key for the message, usually
1447 * defined in languages/Language.php
1449 * Parameters to the message, which can be used to insert variable text into
1450 * it, can be passed to this function in the following formats:
1451 * - One per argument, starting at the second parameter
1452 * - As an array in the second parameter
1453 * These are not shown in the function definition.
1457 function wfMsg( $key ) {
1458 wfDeprecated( __METHOD__
, '1.21' );
1460 $args = func_get_args();
1461 array_shift( $args );
1462 return wfMsgReal( $key, $args );
1466 * Same as above except doesn't transform the message
1468 * @deprecated since 1.18
1470 * @param string $key
1473 function wfMsgNoTrans( $key ) {
1474 wfDeprecated( __METHOD__
, '1.21' );
1476 $args = func_get_args();
1477 array_shift( $args );
1478 return wfMsgReal( $key, $args, true, false, false );
1482 * Get a message from anywhere, for the current global language
1483 * set with $wgLanguageCode.
1485 * Use this if the message should NOT change dependent on the
1486 * language set in the user's preferences. This is the case for
1487 * most text written into logs, as well as link targets (such as
1488 * the name of the copyright policy page). Link titles, on the
1489 * other hand, should be shown in the UI language.
1491 * Note that MediaWiki allows users to change the user interface
1492 * language in their preferences, but a single installation
1493 * typically only contains content in one language.
1495 * Be wary of this distinction: If you use wfMsg() where you should
1496 * use wfMsgForContent(), a user of the software may have to
1497 * customize potentially hundreds of messages in
1498 * order to, e.g., fix a link in every possible language.
1500 * @deprecated since 1.18
1502 * @param string $key Lookup key for the message, usually
1503 * defined in languages/Language.php
1506 function wfMsgForContent( $key ) {
1507 wfDeprecated( __METHOD__
, '1.21' );
1509 global $wgForceUIMsgAsContentMsg;
1510 $args = func_get_args();
1511 array_shift( $args );
1513 if ( is_array( $wgForceUIMsgAsContentMsg )
1514 && in_array( $key, $wgForceUIMsgAsContentMsg )
1516 $forcontent = false;
1518 return wfMsgReal( $key, $args, true, $forcontent );
1522 * Same as above except doesn't transform the message
1524 * @deprecated since 1.18
1526 * @param string $key
1529 function wfMsgForContentNoTrans( $key ) {
1530 wfDeprecated( __METHOD__
, '1.21' );
1532 global $wgForceUIMsgAsContentMsg;
1533 $args = func_get_args();
1534 array_shift( $args );
1536 if ( is_array( $wgForceUIMsgAsContentMsg )
1537 && in_array( $key, $wgForceUIMsgAsContentMsg )
1539 $forcontent = false;
1541 return wfMsgReal( $key, $args, true, $forcontent, false );
1545 * Really get a message
1547 * @deprecated since 1.18
1549 * @param string $key Key to get.
1550 * @param array $args
1551 * @param bool $useDB
1552 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1553 * @param bool $transform Whether or not to transform the message.
1554 * @return string The requested message.
1556 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1557 wfDeprecated( __METHOD__
, '1.21' );
1559 wfProfileIn( __METHOD__
);
1560 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1561 $message = wfMsgReplaceArgs( $message, $args );
1562 wfProfileOut( __METHOD__
);
1567 * Fetch a message string value, but don't replace any keys yet.
1569 * @deprecated since 1.18
1571 * @param string $key
1572 * @param bool $useDB
1573 * @param string|bool $langCode Code of the language to get the message for, or
1574 * behaves as a content language switch if it is a boolean.
1575 * @param bool $transform Whether to parse magic words, etc.
1578 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1579 wfDeprecated( __METHOD__
, '1.21' );
1581 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1583 $cache = MessageCache
::singleton();
1584 $message = $cache->get( $key, $useDB, $langCode );
1585 if ( $message === false ) {
1586 $message = '<' . htmlspecialchars( $key ) . '>';
1587 } elseif ( $transform ) {
1588 $message = $cache->transform( $message );
1594 * Replace message parameter keys on the given formatted output.
1596 * @param string $message
1597 * @param array $args
1601 function wfMsgReplaceArgs( $message, $args ) {
1602 # Fix windows line-endings
1603 # Some messages are split with explode("\n", $msg)
1604 $message = str_replace( "\r", '', $message );
1606 // Replace arguments
1607 if ( count( $args ) ) {
1608 if ( is_array( $args[0] ) ) {
1609 $args = array_values( $args[0] );
1611 $replacementKeys = array();
1612 foreach ( $args as $n => $param ) {
1613 $replacementKeys['$' . ( $n +
1 )] = $param;
1615 $message = strtr( $message, $replacementKeys );
1622 * Return an HTML-escaped version of a message.
1623 * Parameter replacements, if any, are done *after* the HTML-escaping,
1624 * so parameters may contain HTML (eg links or form controls). Be sure
1625 * to pre-escape them if you really do want plaintext, or just wrap
1626 * the whole thing in htmlspecialchars().
1628 * @deprecated since 1.18
1630 * @param string $key
1631 * @param string $args,... Parameters
1634 function wfMsgHtml( $key ) {
1635 wfDeprecated( __METHOD__
, '1.21' );
1637 $args = func_get_args();
1638 array_shift( $args );
1639 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1643 * Return an HTML version of message
1644 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1645 * so parameters may contain HTML (eg links or form controls). Be sure
1646 * to pre-escape them if you really do want plaintext, or just wrap
1647 * the whole thing in htmlspecialchars().
1649 * @deprecated since 1.18
1651 * @param string $key
1652 * @param string $args,... Parameters
1655 function wfMsgWikiHtml( $key ) {
1656 wfDeprecated( __METHOD__
, '1.21' );
1658 $args = func_get_args();
1659 array_shift( $args );
1660 return wfMsgReplaceArgs(
1661 MessageCache
::singleton()->parse( wfMsgGetKey( $key ), null,
1662 /* can't be set to false */ true, /* interface */ true )->getText(),
1667 * Returns message in the requested format
1669 * @deprecated since 1.18
1671 * @param string $key Key of the message
1672 * @param array $options Processing rules.
1673 * Can take the following options:
1674 * parse: parses wikitext to HTML
1675 * parseinline: parses wikitext to HTML and removes the surrounding
1676 * p's added by parser or tidy
1677 * escape: filters message through htmlspecialchars
1678 * escapenoentities: same, but allows entity references like   through
1679 * replaceafter: parameters are substituted after parsing or escaping
1680 * parsemag: transform the message using magic phrases
1681 * content: fetch message for content language instead of interface
1682 * Also can accept a single associative argument, of the form 'language' => 'xx':
1683 * language: Language object or language code to fetch message for
1684 * (overridden by content).
1685 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1689 function wfMsgExt( $key, $options ) {
1690 wfDeprecated( __METHOD__
, '1.21' );
1692 $args = func_get_args();
1693 array_shift( $args );
1694 array_shift( $args );
1695 $options = (array)$options;
1697 foreach ( $options as $arrayKey => $option ) {
1698 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1699 # An unknown index, neither numeric nor "language"
1700 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
1701 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1702 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1703 'replaceafter', 'parsemag', 'content' ) ) ) {
1704 # A numeric index with unknown value
1705 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
1709 if ( in_array( 'content', $options, true ) ) {
1712 $langCodeObj = null;
1713 } elseif ( array_key_exists( 'language', $options ) ) {
1714 $forContent = false;
1715 $langCode = wfGetLangObj( $options['language'] );
1716 $langCodeObj = $langCode;
1718 $forContent = false;
1720 $langCodeObj = null;
1723 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1725 if ( !in_array( 'replaceafter', $options, true ) ) {
1726 $string = wfMsgReplaceArgs( $string, $args );
1729 $messageCache = MessageCache
::singleton();
1730 $parseInline = in_array( 'parseinline', $options, true );
1731 if ( in_array( 'parse', $options, true ) ||
$parseInline ) {
1732 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1733 if ( $string instanceof ParserOutput
) {
1734 $string = $string->getText();
1737 if ( $parseInline ) {
1738 $string = Parser
::stripOuterParagraph( $string );
1740 } elseif ( in_array( 'parsemag', $options, true ) ) {
1741 $string = $messageCache->transform( $string,
1742 !$forContent, $langCodeObj );
1745 if ( in_array( 'escape', $options, true ) ) {
1746 $string = htmlspecialchars ( $string );
1747 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1748 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
1751 if ( in_array( 'replaceafter', $options, true ) ) {
1752 $string = wfMsgReplaceArgs( $string, $args );
1759 * Since wfMsg() and co suck, they don't return false if the message key they
1760 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1761 * nonexistence of messages by checking the MessageCache::get() result directly.
1763 * @deprecated since 1.18. Use Message::isDisabled().
1765 * @param string $key The message key looked up
1766 * @return bool True if the message *doesn't* exist.
1768 function wfEmptyMsg( $key ) {
1769 wfDeprecated( __METHOD__
, '1.21' );
1771 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1775 * Fetch server name for use in error reporting etc.
1776 * Use real server name if available, so we know which machine
1777 * in a server farm generated the current page.
1781 function wfHostname() {
1783 if ( is_null( $host ) ) {
1785 # Hostname overriding
1786 global $wgOverrideHostname;
1787 if ( $wgOverrideHostname !== false ) {
1788 # Set static and skip any detection
1789 $host = $wgOverrideHostname;
1793 if ( function_exists( 'posix_uname' ) ) {
1794 // This function not present on Windows
1795 $uname = posix_uname();
1799 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1800 $host = $uname['nodename'];
1801 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1802 # Windows computer name
1803 $host = getenv( 'COMPUTERNAME' );
1805 # This may be a virtual server.
1806 $host = $_SERVER['SERVER_NAME'];
1813 * Returns a script tag that stores the amount of time it took MediaWiki to
1814 * handle the request in milliseconds as 'wgBackendResponseTime'.
1816 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1817 * hostname of the server handling the request.
1821 function wfReportTime() {
1822 global $wgRequestTime, $wgShowHostnames;
1824 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1825 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1826 if ( $wgShowHostnames ) {
1827 $reportVars['wgHostname'] = wfHostname();
1829 return Skin
::makeVariablesScript( $reportVars );
1833 * Safety wrapper for debug_backtrace().
1835 * Will return an empty array if debug_backtrace is disabled, otherwise
1836 * the output from debug_backtrace() (trimmed).
1838 * @param int $limit This parameter can be used to limit the number of stack frames returned
1840 * @return array Array of backtrace information
1842 function wfDebugBacktrace( $limit = 0 ) {
1843 static $disabled = null;
1845 if ( is_null( $disabled ) ) {
1846 $disabled = !function_exists( 'debug_backtrace' );
1848 wfDebug( "debug_backtrace() is disabled\n" );
1855 if ( $limit && version_compare( PHP_VERSION
, '5.4.0', '>=' ) ) {
1856 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1858 return array_slice( debug_backtrace(), 1 );
1863 * Get a debug backtrace as a string
1867 function wfBacktrace() {
1868 global $wgCommandLineMode;
1870 if ( $wgCommandLineMode ) {
1875 $backtrace = wfDebugBacktrace();
1876 foreach ( $backtrace as $call ) {
1877 if ( isset( $call['file'] ) ) {
1878 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1879 $file = $f[count( $f ) - 1];
1883 if ( isset( $call['line'] ) ) {
1884 $line = $call['line'];
1888 if ( $wgCommandLineMode ) {
1889 $msg .= "$file line $line calls ";
1891 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1893 if ( !empty( $call['class'] ) ) {
1894 $msg .= $call['class'] . $call['type'];
1896 $msg .= $call['function'] . '()';
1898 if ( $wgCommandLineMode ) {
1904 if ( $wgCommandLineMode ) {
1914 * Get the name of the function which called this function
1915 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1916 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1917 * wfGetCaller( 3 ) is the parent of that.
1922 function wfGetCaller( $level = 2 ) {
1923 $backtrace = wfDebugBacktrace( $level +
1 );
1924 if ( isset( $backtrace[$level] ) ) {
1925 return wfFormatStackFrame( $backtrace[$level] );
1932 * Return a string consisting of callers in the stack. Useful sometimes
1933 * for profiling specific points.
1935 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1938 function wfGetAllCallers( $limit = 3 ) {
1939 $trace = array_reverse( wfDebugBacktrace() );
1940 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1941 $limit = count( $trace ) - 1;
1943 $trace = array_slice( $trace, -$limit - 1, $limit );
1944 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1948 * Return a string representation of frame
1950 * @param array $frame
1953 function wfFormatStackFrame( $frame ) {
1954 return isset( $frame['class'] ) ?
1955 $frame['class'] . '::' . $frame['function'] :
1959 /* Some generic result counters, pulled out of SearchEngine */
1964 * @param int $offset
1968 function wfShowingResults( $offset, $limit ) {
1969 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
1974 * @todo FIXME: We may want to blacklist some broken browsers
1976 * @param bool $force
1977 * @return bool Whereas client accept gzip compression
1979 function wfClientAcceptsGzip( $force = false ) {
1980 static $result = null;
1981 if ( $result === null ||
$force ) {
1983 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1984 # @todo FIXME: We may want to blacklist some broken browsers
1987 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1988 $_SERVER['HTTP_ACCEPT_ENCODING'],
1992 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1996 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2005 * Obtain the offset and limit values from the request string;
2006 * used in special pages
2008 * @param int $deflimit Default limit if none supplied
2009 * @param string $optionname Name of a user preference to check against
2011 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2013 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2015 wfDeprecated( __METHOD__
, '1.24' );
2016 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2020 * Escapes the given text so that it may be output using addWikiText()
2021 * without any linking, formatting, etc. making its way through. This
2022 * is achieved by substituting certain characters with HTML entities.
2023 * As required by the callers, "<nowiki>" is not used.
2025 * @param string $text Text to be escaped
2028 function wfEscapeWikiText( $text ) {
2029 static $repl = null, $repl2 = null;
2030 if ( $repl === null ) {
2032 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
2033 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
2034 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
2035 "\n#" => "\n#", "\r#" => "\r#",
2036 "\n*" => "\n*", "\r*" => "\r*",
2037 "\n:" => "\n:", "\r:" => "\r:",
2038 "\n " => "\n ", "\r " => "\r ",
2039 "\n\n" => "\n ", "\r\n" => " \n",
2040 "\n\r" => "\n ", "\r\r" => "\r ",
2041 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
2042 "\n----" => "\n----", "\r----" => "\r----",
2043 '__' => '__', '://' => '://',
2046 // We have to catch everything "\s" matches in PCRE
2047 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2048 $repl["$magic "] = "$magic ";
2049 $repl["$magic\t"] = "$magic	";
2050 $repl["$magic\r"] = "$magic ";
2051 $repl["$magic\n"] = "$magic ";
2052 $repl["$magic\f"] = "$magic";
2055 // And handle protocols that don't use "://"
2056 global $wgUrlProtocols;
2058 foreach ( $wgUrlProtocols as $prot ) {
2059 if ( substr( $prot, -1 ) === ':' ) {
2060 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2063 $repl2 = $repl2 ?
'/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2065 $text = substr( strtr( "\n$text", $repl ), 1 );
2066 $text = preg_replace( $repl2, '$1:', $text );
2071 * Sets dest to source and returns the original value of dest
2072 * If source is NULL, it just returns the value, it doesn't set the variable
2073 * If force is true, it will set the value even if source is NULL
2075 * @param mixed $dest
2076 * @param mixed $source
2077 * @param bool $force
2080 function wfSetVar( &$dest, $source, $force = false ) {
2082 if ( !is_null( $source ) ||
$force ) {
2089 * As for wfSetVar except setting a bit
2093 * @param bool $state
2097 function wfSetBit( &$dest, $bit, $state = true ) {
2098 $temp = (bool)( $dest & $bit );
2099 if ( !is_null( $state ) ) {
2110 * A wrapper around the PHP function var_export().
2111 * Either print it or add it to the regular output ($wgOut).
2113 * @param mixed $var A PHP variable to dump.
2115 function wfVarDump( $var ) {
2117 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2118 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
2121 $wgOut->addHTML( $s );
2126 * Provide a simple HTTP error.
2128 * @param int|string $code
2129 * @param string $label
2130 * @param string $desc
2132 function wfHttpError( $code, $label, $desc ) {
2135 header( "HTTP/1.0 $code $label" );
2136 header( "Status: $code $label" );
2137 $wgOut->sendCacheControl();
2139 header( 'Content-type: text/html; charset=utf-8' );
2140 print "<!doctype html>" .
2141 '<html><head><title>' .
2142 htmlspecialchars( $label ) .
2143 '</title></head><body><h1>' .
2144 htmlspecialchars( $label ) .
2146 nl2br( htmlspecialchars( $desc ) ) .
2147 "</p></body></html>\n";
2151 * Clear away any user-level output buffers, discarding contents.
2153 * Suitable for 'starting afresh', for instance when streaming
2154 * relatively large amounts of data without buffering, or wanting to
2155 * output image files without ob_gzhandler's compression.
2157 * The optional $resetGzipEncoding parameter controls suppression of
2158 * the Content-Encoding header sent by ob_gzhandler; by default it
2159 * is left. See comments for wfClearOutputBuffers() for why it would
2162 * Note that some PHP configuration options may add output buffer
2163 * layers which cannot be removed; these are left in place.
2165 * @param bool $resetGzipEncoding
2167 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2168 if ( $resetGzipEncoding ) {
2169 // Suppress Content-Encoding and Content-Length
2170 // headers from 1.10+s wfOutputHandler
2171 global $wgDisableOutputCompression;
2172 $wgDisableOutputCompression = true;
2174 while ( $status = ob_get_status() ) {
2175 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2176 // Probably from zlib.output_compression or other
2177 // PHP-internal setting which can't be removed.
2179 // Give up, and hope the result doesn't break
2183 if ( !ob_end_clean() ) {
2184 // Could not remove output buffer handler; abort now
2185 // to avoid getting in some kind of infinite loop.
2188 if ( $resetGzipEncoding ) {
2189 if ( $status['name'] == 'ob_gzhandler' ) {
2190 // Reset the 'Content-Encoding' field set by this handler
2191 // so we can start fresh.
2192 header_remove( 'Content-Encoding' );
2200 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2202 * Clear away output buffers, but keep the Content-Encoding header
2203 * produced by ob_gzhandler, if any.
2205 * This should be used for HTTP 304 responses, where you need to
2206 * preserve the Content-Encoding header of the real result, but
2207 * also need to suppress the output of ob_gzhandler to keep to spec
2208 * and avoid breaking Firefox in rare cases where the headers and
2209 * body are broken over two packets.
2211 function wfClearOutputBuffers() {
2212 wfResetOutputBuffers( false );
2216 * Converts an Accept-* header into an array mapping string values to quality
2219 * @param string $accept
2220 * @param string $def Default
2221 * @return float[] Associative array of string => float pairs
2223 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2224 # No arg means accept anything (per HTTP spec)
2226 return array( $def => 1.0 );
2231 $parts = explode( ',', $accept );
2233 foreach ( $parts as $part ) {
2234 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2235 $values = explode( ';', trim( $part ) );
2237 if ( count( $values ) == 1 ) {
2238 $prefs[$values[0]] = 1.0;
2239 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2240 $prefs[$values[0]] = floatval( $match[1] );
2248 * Checks if a given MIME type matches any of the keys in the given
2249 * array. Basic wildcards are accepted in the array keys.
2251 * Returns the matching MIME type (or wildcard) if a match, otherwise
2254 * @param string $type
2255 * @param array $avail
2259 function mimeTypeMatch( $type, $avail ) {
2260 if ( array_key_exists( $type, $avail ) ) {
2263 $parts = explode( '/', $type );
2264 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2265 return $parts[0] . '/*';
2266 } elseif ( array_key_exists( '*/*', $avail ) ) {
2275 * Returns the 'best' match between a client's requested internet media types
2276 * and the server's list of available types. Each list should be an associative
2277 * array of type to preference (preference is a float between 0.0 and 1.0).
2278 * Wildcards in the types are acceptable.
2280 * @param array $cprefs Client's acceptable type list
2281 * @param array $sprefs Server's offered types
2284 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2285 * XXX: generalize to negotiate other stuff
2287 function wfNegotiateType( $cprefs, $sprefs ) {
2290 foreach ( array_keys( $sprefs ) as $type ) {
2291 $parts = explode( '/', $type );
2292 if ( $parts[1] != '*' ) {
2293 $ckey = mimeTypeMatch( $type, $cprefs );
2295 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2300 foreach ( array_keys( $cprefs ) as $type ) {
2301 $parts = explode( '/', $type );
2302 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2303 $skey = mimeTypeMatch( $type, $sprefs );
2305 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2313 foreach ( array_keys( $combine ) as $type ) {
2314 if ( $combine[$type] > $bestq ) {
2316 $bestq = $combine[$type];
2324 * Reference-counted warning suppression
2328 function wfSuppressWarnings( $end = false ) {
2329 static $suppressCount = 0;
2330 static $originalLevel = false;
2333 if ( $suppressCount ) {
2335 if ( !$suppressCount ) {
2336 error_reporting( $originalLevel );
2340 if ( !$suppressCount ) {
2341 $originalLevel = error_reporting( E_ALL
& ~
(
2356 * Restore error level to previous value
2358 function wfRestoreWarnings() {
2359 wfSuppressWarnings( true );
2362 # Autodetect, convert and provide timestamps of various types
2365 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2367 define( 'TS_UNIX', 0 );
2370 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2372 define( 'TS_MW', 1 );
2375 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2377 define( 'TS_DB', 2 );
2380 * RFC 2822 format, for E-mail and HTTP headers
2382 define( 'TS_RFC2822', 3 );
2385 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2387 * This is used by Special:Export
2389 define( 'TS_ISO_8601', 4 );
2392 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2394 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2395 * DateTime tag and page 36 for the DateTimeOriginal and
2396 * DateTimeDigitized tags.
2398 define( 'TS_EXIF', 5 );
2401 * Oracle format time.
2403 define( 'TS_ORACLE', 6 );
2406 * Postgres format time.
2408 define( 'TS_POSTGRES', 7 );
2411 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2413 define( 'TS_ISO_8601_BASIC', 9 );
2416 * Get a timestamp string in one of various formats
2418 * @param mixed $outputtype A timestamp in one of the supported formats, the
2419 * function will autodetect which format is supplied and act accordingly.
2420 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2421 * @return string|bool String / false The same date in the format specified in $outputtype or false
2423 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2425 $timestamp = new MWTimestamp( $ts );
2426 return $timestamp->getTimestamp( $outputtype );
2427 } catch ( TimestampException
$e ) {
2428 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2434 * Return a formatted timestamp, or null if input is null.
2435 * For dealing with nullable timestamp columns in the database.
2437 * @param int $outputtype
2441 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2442 if ( is_null( $ts ) ) {
2445 return wfTimestamp( $outputtype, $ts );
2450 * Convenience function; returns MediaWiki timestamp for the present time.
2454 function wfTimestampNow() {
2456 return wfTimestamp( TS_MW
, time() );
2460 * Check if the operating system is Windows
2462 * @return bool True if it's Windows, false otherwise.
2464 function wfIsWindows() {
2465 static $isWindows = null;
2466 if ( $isWindows === null ) {
2467 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2473 * Check if we are running under HHVM
2477 function wfIsHHVM() {
2478 return defined( 'HHVM_VERSION' );
2482 * Swap two variables
2484 * @deprecated since 1.24
2488 function swap( &$x, &$y ) {
2489 wfDeprecated( __FUNCTION__
, '1.24' );
2496 * Tries to get the system directory for temporary files. First
2497 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2498 * environment variables are then checked in sequence, and if none are
2499 * set try sys_get_temp_dir().
2501 * NOTE: When possible, use instead the tmpfile() function to create
2502 * temporary files to avoid race conditions on file creation, etc.
2506 function wfTempDir() {
2507 global $wgTmpDirectory;
2509 if ( $wgTmpDirectory !== false ) {
2510 return $wgTmpDirectory;
2513 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2515 foreach ( $tmpDir as $tmp ) {
2516 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2520 return sys_get_temp_dir();
2524 * Make directory, and make all parent directories if they don't exist
2526 * @param string $dir Full path to directory to create
2527 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2528 * @param string $caller Optional caller param for debugging.
2529 * @throws MWException
2532 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2533 global $wgDirectoryMode;
2535 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2536 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2539 if ( !is_null( $caller ) ) {
2540 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2543 if ( strval( $dir ) === '' ||
( file_exists( $dir ) && is_dir( $dir ) ) ) {
2547 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2549 if ( is_null( $mode ) ) {
2550 $mode = $wgDirectoryMode;
2553 // Turn off the normal warning, we're doing our own below
2554 wfSuppressWarnings();
2555 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2556 wfRestoreWarnings();
2559 //directory may have been created on another request since we last checked
2560 if ( is_dir( $dir ) ) {
2564 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2565 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2571 * Remove a directory and all its content.
2572 * Does not hide error.
2573 * @param string $dir
2575 function wfRecursiveRemoveDir( $dir ) {
2576 wfDebug( __FUNCTION__
. "( $dir )\n" );
2577 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2578 if ( is_dir( $dir ) ) {
2579 $objects = scandir( $dir );
2580 foreach ( $objects as $object ) {
2581 if ( $object != "." && $object != ".." ) {
2582 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2583 wfRecursiveRemoveDir( $dir . '/' . $object );
2585 unlink( $dir . '/' . $object );
2595 * @param int $nr The number to format
2596 * @param int $acc The number of digits after the decimal point, default 2
2597 * @param bool $round Whether or not to round the value, default true
2600 function wfPercent( $nr, $acc = 2, $round = true ) {
2601 $ret = sprintf( "%.${acc}f", $nr );
2602 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2606 * Safety wrapper around ini_get() for boolean settings.
2607 * The values returned from ini_get() are pre-normalized for settings
2608 * set via php.ini or php_flag/php_admin_flag... but *not*
2609 * for those set via php_value/php_admin_value.
2611 * It's fairly common for people to use php_value instead of php_flag,
2612 * which can leave you with an 'off' setting giving a false positive
2613 * for code that just takes the ini_get() return value as a boolean.
2615 * To make things extra interesting, setting via php_value accepts
2616 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2617 * Unrecognized values go false... again opposite PHP's own coercion
2618 * from string to bool.
2620 * Luckily, 'properly' set settings will always come back as '0' or '1',
2621 * so we only have to worry about them and the 'improper' settings.
2623 * I frickin' hate PHP... :P
2625 * @param string $setting
2628 function wfIniGetBool( $setting ) {
2629 $val = strtolower( ini_get( $setting ) );
2630 // 'on' and 'true' can't have whitespace around them, but '1' can.
2634 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2638 * Windows-compatible version of escapeshellarg()
2639 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2640 * function puts single quotes in regardless of OS.
2642 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2643 * earlier distro releases of PHP)
2645 * @param string $args,...
2648 function wfEscapeShellArg( /*...*/ ) {
2649 wfInitShellLocale();
2651 $args = func_get_args();
2654 foreach ( $args as $arg ) {
2661 if ( wfIsWindows() ) {
2662 // Escaping for an MSVC-style command line parser and CMD.EXE
2663 // @codingStandardsIgnoreStart For long URLs
2665 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2666 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2669 // Double the backslashes before any double quotes. Escape the double quotes.
2670 // @codingStandardsIgnoreEnd
2671 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2674 foreach ( $tokens as $token ) {
2675 if ( $iteration %
2 == 1 ) {
2676 // Delimiter, a double quote preceded by zero or more slashes
2677 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2678 } elseif ( $iteration %
4 == 2 ) {
2679 // ^ in $token will be outside quotes, need to be escaped
2680 $arg .= str_replace( '^', '^^', $token );
2681 } else { // $iteration % 4 == 0
2682 // ^ in $token will appear inside double quotes, so leave as is
2687 // Double the backslashes before the end of the string, because
2688 // we will soon add a quote
2690 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2691 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2694 // Add surrounding quotes
2695 $retVal .= '"' . $arg . '"';
2697 $retVal .= escapeshellarg( $arg );
2704 * Check if wfShellExec() is effectively disabled via php.ini config
2706 * @return bool|string False or one of (safemode,disabled)
2709 function wfShellExecDisabled() {
2710 static $disabled = null;
2711 if ( is_null( $disabled ) ) {
2712 if ( wfIniGetBool( 'safe_mode' ) ) {
2713 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2714 $disabled = 'safemode';
2715 } elseif ( !function_exists( 'proc_open' ) ) {
2716 wfDebug( "proc_open() is disabled\n" );
2717 $disabled = 'disabled';
2726 * Execute a shell command, with time and memory limits mirrored from the PHP
2727 * configuration if supported.
2729 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2730 * or an array of unescaped arguments, in which case each value will be escaped
2731 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2732 * @param null|mixed &$retval Optional, will receive the program's exit code.
2733 * (non-zero is usually failure). If there is an error from
2734 * read, select, or proc_open(), this will be set to -1.
2735 * @param array $environ Optional environment variables which should be
2736 * added to the executed command environment.
2737 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2738 * this overwrites the global wgMaxShell* limits.
2739 * @param array $options Array of options:
2740 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2741 * including errors from limit.sh
2743 * @return string Collected stdout as a string
2745 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2746 $limits = array(), $options = array()
2748 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2749 $wgMaxShellWallClockTime, $wgShellCgroup;
2751 $disabled = wfShellExecDisabled();
2754 return $disabled == 'safemode' ?
2755 'Unable to run external programs in safe mode.' :
2756 'Unable to run external programs, proc_open() is disabled.';
2759 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2761 wfInitShellLocale();
2764 foreach ( $environ as $k => $v ) {
2765 if ( wfIsWindows() ) {
2766 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2767 * appear in the environment variable, so we must use carat escaping as documented in
2768 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2769 * Note however that the quote isn't listed there, but is needed, and the parentheses
2770 * are listed there but doesn't appear to need it.
2772 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2774 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2775 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2777 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2780 if ( is_array( $cmd ) ) {
2781 // Command line may be given as an array, escape each value and glue them together with a space
2783 foreach ( $cmd as $val ) {
2784 $cmdVals[] = wfEscapeShellArg( $val );
2786 $cmd = implode( ' ', $cmdVals );
2789 $cmd = $envcmd . $cmd;
2791 $useLogPipe = false;
2792 if ( is_executable( '/bin/bash' ) ) {
2793 $time = intval ( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2794 if ( isset( $limits['walltime'] ) ) {
2795 $wallTime = intval( $limits['walltime'] );
2796 } elseif ( isset( $limits['time'] ) ) {
2799 $wallTime = intval( $wgMaxShellWallClockTime );
2801 $mem = intval ( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2802 $filesize = intval ( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2804 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2805 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2806 escapeshellarg( $cmd ) . ' ' .
2808 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2809 "MW_CPU_LIMIT=$time; " .
2810 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2811 "MW_MEM_LIMIT=$mem; " .
2812 "MW_FILE_SIZE_LIMIT=$filesize; " .
2813 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2814 "MW_USE_LOG_PIPE=yes"
2817 } elseif ( $includeStderr ) {
2820 } elseif ( $includeStderr ) {
2823 wfDebug( "wfShellExec: $cmd\n" );
2826 0 => array( 'file', 'php://stdin', 'r' ),
2827 1 => array( 'pipe', 'w' ),
2828 2 => array( 'file', 'php://stderr', 'w' ) );
2829 if ( $useLogPipe ) {
2830 $desc[3] = array( 'pipe', 'w' );
2833 $proc = proc_open( $cmd, $desc, $pipes );
2835 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2839 $outBuffer = $logBuffer = '';
2840 $emptyArray = array();
2844 // According to the documentation, it is possible for stream_select()
2845 // to fail due to EINTR. I haven't managed to induce this in testing
2846 // despite sending various signals. If it did happen, the error
2847 // message would take the form:
2849 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2851 // where [4] is the value of the macro EINTR and "Interrupted system
2852 // call" is string which according to the Linux manual is "possibly"
2853 // localised according to LC_MESSAGES.
2854 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2855 $eintrMessage = "stream_select(): unable to select [$eintr]";
2857 // Build a table mapping resource IDs to pipe FDs to work around a
2858 // PHP 5.3 issue in which stream_select() does not preserve array keys
2859 // <https://bugs.php.net/bug.php?id=53427>.
2861 foreach ( $pipes as $fd => $pipe ) {
2862 $fds[(int)$pipe] = $fd;
2869 while ( $running === true ||
$numReadyPipes !== 0 ) {
2871 $status = proc_get_status( $proc );
2872 // If the process has terminated, switch to nonblocking selects
2873 // for getting any data still waiting to be read.
2874 if ( !$status['running'] ) {
2880 $readyPipes = $pipes;
2883 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2884 @trigger_error
( '' );
2885 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
2886 if ( $numReadyPipes === false ) {
2887 // @codingStandardsIgnoreEnd
2888 $error = error_get_last();
2889 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2892 trigger_error( $error['message'], E_USER_WARNING
);
2893 $logMsg = $error['message'];
2897 foreach ( $readyPipes as $pipe ) {
2898 $block = fread( $pipe, 65536 );
2899 $fd = $fds[(int)$pipe];
2900 if ( $block === '' ) {
2902 fclose( $pipes[$fd] );
2903 unset( $pipes[$fd] );
2907 } elseif ( $block === false ) {
2909 $logMsg = "Error reading from pipe";
2911 } elseif ( $fd == 1 ) {
2913 $outBuffer .= $block;
2914 } elseif ( $fd == 3 ) {
2916 $logBuffer .= $block;
2917 if ( strpos( $block, "\n" ) !== false ) {
2918 $lines = explode( "\n", $logBuffer );
2919 $logBuffer = array_pop( $lines );
2920 foreach ( $lines as $line ) {
2921 wfDebugLog( 'exec', $line );
2928 foreach ( $pipes as $pipe ) {
2932 // Use the status previously collected if possible, since proc_get_status()
2933 // just calls waitpid() which will not return anything useful the second time.
2935 $status = proc_get_status( $proc );
2938 if ( $logMsg !== false ) {
2939 // Read/select error
2941 proc_close( $proc );
2942 } elseif ( $status['signaled'] ) {
2943 $logMsg = "Exited with signal {$status['termsig']}";
2944 $retval = 128 +
$status['termsig'];
2945 proc_close( $proc );
2947 if ( $status['running'] ) {
2948 $retval = proc_close( $proc );
2950 $retval = $status['exitcode'];
2951 proc_close( $proc );
2953 if ( $retval == 127 ) {
2954 $logMsg = "Possibly missing executable file";
2955 } elseif ( $retval >= 129 && $retval <= 192 ) {
2956 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2960 if ( $logMsg !== false ) {
2961 wfDebugLog( 'exec', "$logMsg: $cmd" );
2968 * Execute a shell command, returning both stdout and stderr. Convenience
2969 * function, as all the arguments to wfShellExec can become unwieldy.
2971 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2972 * @param string $cmd Command line, properly escaped for shell.
2973 * @param null|mixed &$retval Optional, will receive the program's exit code.
2974 * (non-zero is usually failure)
2975 * @param array $environ Optional environment variables which should be
2976 * added to the executed command environment.
2977 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2978 * this overwrites the global wgMaxShell* limits.
2979 * @return string Collected stdout and stderr as a string
2981 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2982 return wfShellExec( $cmd, $retval, $environ, $limits, array( 'duplicateStderr' => true ) );
2986 * Workaround for http://bugs.php.net/bug.php?id=45132
2987 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2989 function wfInitShellLocale() {
2990 static $done = false;
2995 global $wgShellLocale;
2996 if ( !wfIniGetBool( 'safe_mode' ) ) {
2997 putenv( "LC_CTYPE=$wgShellLocale" );
2998 setlocale( LC_CTYPE
, $wgShellLocale );
3003 * Alias to wfShellWikiCmd()
3005 * @see wfShellWikiCmd()
3007 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
3008 return wfShellWikiCmd( $script, $parameters, $options );
3012 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3013 * Note that $parameters should be a flat array and an option with an argument
3014 * should consist of two consecutive items in the array (do not use "--option value").
3016 * @param string $script MediaWiki cli script path
3017 * @param array $parameters Arguments and options to the script
3018 * @param array $options Associative array of options:
3019 * 'php': The path to the php executable
3020 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3023 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3025 // Give site config file a chance to run the script in a wrapper.
3026 // The caller may likely want to call wfBasename() on $script.
3027 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3028 $cmd = isset( $options['php'] ) ?
array( $options['php'] ) : array( $wgPhpCli );
3029 if ( isset( $options['wrapper'] ) ) {
3030 $cmd[] = $options['wrapper'];
3033 // Escape each parameter for shell
3034 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
3038 * wfMerge attempts to merge differences between three texts.
3039 * Returns true for a clean merge and false for failure or a conflict.
3041 * @param string $old
3042 * @param string $mine
3043 * @param string $yours
3044 * @param string $result
3047 function wfMerge( $old, $mine, $yours, &$result ) {
3050 # This check may also protect against code injection in
3051 # case of broken installations.
3052 wfSuppressWarnings();
3053 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3054 wfRestoreWarnings();
3056 if ( !$haveDiff3 ) {
3057 wfDebug( "diff3 not found\n" );
3061 # Make temporary files
3063 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3064 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3065 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3067 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3068 # a newline character. To avoid this, we normalize the trailing whitespace before
3069 # creating the diff.
3071 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3072 fclose( $oldtextFile );
3073 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3074 fclose( $mytextFile );
3075 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3076 fclose( $yourtextFile );
3078 # Check for a conflict
3079 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
3080 wfEscapeShellArg( $mytextName ) . ' ' .
3081 wfEscapeShellArg( $oldtextName ) . ' ' .
3082 wfEscapeShellArg( $yourtextName );
3083 $handle = popen( $cmd, 'r' );
3085 if ( fgets( $handle, 1024 ) ) {
3093 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
3094 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
3095 $handle = popen( $cmd, 'r' );
3098 $data = fread( $handle, 8192 );
3099 if ( strlen( $data ) == 0 ) {
3105 unlink( $mytextName );
3106 unlink( $oldtextName );
3107 unlink( $yourtextName );
3109 if ( $result === '' && $old !== '' && !$conflict ) {
3110 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3117 * Returns unified plain-text diff of two texts.
3118 * Useful for machine processing of diffs.
3120 * @param string $before The text before the changes.
3121 * @param string $after The text after the changes.
3122 * @param string $params Command-line options for the diff command.
3123 * @return string Unified diff of $before and $after
3125 function wfDiff( $before, $after, $params = '-u' ) {
3126 if ( $before == $after ) {
3131 wfSuppressWarnings();
3132 $haveDiff = $wgDiff && file_exists( $wgDiff );
3133 wfRestoreWarnings();
3135 # This check may also protect against code injection in
3136 # case of broken installations.
3138 wfDebug( "diff executable not found\n" );
3139 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3140 $format = new UnifiedDiffFormatter();
3141 return $format->format( $diffs );
3144 # Make temporary files
3146 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3147 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3149 fwrite( $oldtextFile, $before );
3150 fclose( $oldtextFile );
3151 fwrite( $newtextFile, $after );
3152 fclose( $newtextFile );
3154 // Get the diff of the two files
3155 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3157 $h = popen( $cmd, 'r' );
3162 $data = fread( $h, 8192 );
3163 if ( strlen( $data ) == 0 ) {
3171 unlink( $oldtextName );
3172 unlink( $newtextName );
3174 // Kill the --- and +++ lines. They're not useful.
3175 $diff_lines = explode( "\n", $diff );
3176 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
3177 unset( $diff_lines[0] );
3179 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
3180 unset( $diff_lines[1] );
3183 $diff = implode( "\n", $diff_lines );
3189 * This function works like "use VERSION" in Perl, the program will die with a
3190 * backtrace if the current version of PHP is less than the version provided
3192 * This is useful for extensions which due to their nature are not kept in sync
3193 * with releases, and might depend on other versions of PHP than the main code
3195 * Note: PHP might die due to parsing errors in some cases before it ever
3196 * manages to call this function, such is life
3198 * @see perldoc -f use
3200 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3201 * @throws MWException
3203 function wfUsePHP( $req_ver ) {
3204 $php_ver = PHP_VERSION
;
3206 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3207 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3212 * This function works like "use VERSION" in Perl except it checks the version
3213 * of MediaWiki, the program will die with a backtrace if the current version
3214 * of MediaWiki is less than the version provided.
3216 * This is useful for extensions which due to their nature are not kept in sync
3219 * Note: Due to the behavior of PHP's version_compare() which is used in this
3220 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3221 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3222 * targeted version number. For example if you wanted to allow any variation
3223 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3224 * not result in the same comparison due to the internal logic of
3225 * version_compare().
3227 * @see perldoc -f use
3229 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3230 * @throws MWException
3232 function wfUseMW( $req_ver ) {
3235 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3236 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3241 * Return the final portion of a pathname.
3242 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3243 * http://bugs.php.net/bug.php?id=33898
3245 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3246 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3248 * @param string $path
3249 * @param string $suffix String to remove if present
3252 function wfBaseName( $path, $suffix = '' ) {
3253 if ( $suffix == '' ) {
3256 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3260 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3268 * Generate a relative path name to the given file.
3269 * May explode on non-matching case-insensitive paths,
3270 * funky symlinks, etc.
3272 * @param string $path Absolute destination path including target filename
3273 * @param string $from Absolute source path, directory only
3276 function wfRelativePath( $path, $from ) {
3277 // Normalize mixed input on Windows...
3278 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
3279 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
3281 // Trim trailing slashes -- fix for drive root
3282 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
3283 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
3285 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
3286 $against = explode( DIRECTORY_SEPARATOR
, $from );
3288 if ( $pieces[0] !== $against[0] ) {
3289 // Non-matching Windows drive letters?
3290 // Return a full path.
3294 // Trim off common prefix
3295 while ( count( $pieces ) && count( $against )
3296 && $pieces[0] == $against[0] ) {
3297 array_shift( $pieces );
3298 array_shift( $against );
3301 // relative dots to bump us to the parent
3302 while ( count( $against ) ) {
3303 array_unshift( $pieces, '..' );
3304 array_shift( $against );
3307 array_push( $pieces, wfBaseName( $path ) );
3309 return implode( DIRECTORY_SEPARATOR
, $pieces );
3313 * Convert an arbitrarily-long digit string from one numeric base
3314 * to another, optionally zero-padding to a minimum column width.
3316 * Supports base 2 through 36; digit values 10-36 are represented
3317 * as lowercase letters a-z. Input is case-insensitive.
3319 * @param string $input Input number
3320 * @param int $sourceBase Base of the input number
3321 * @param int $destBase Desired base of the output
3322 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3323 * @param bool $lowercase Whether to output in lowercase or uppercase
3324 * @param string $engine Either "gmp", "bcmath", or "php"
3325 * @return string|bool The output number as a string, or false on error
3327 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3328 $lowercase = true, $engine = 'auto'
3330 $input = (string)$input;
3336 $sourceBase != (int)$sourceBase ||
3337 $destBase != (int)$destBase ||
3338 $pad != (int)$pad ||
3340 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3347 static $baseChars = array(
3348 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3349 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3350 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3351 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3352 34 => 'y', 35 => 'z',
3354 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3355 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3356 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3357 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3358 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3359 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3362 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' ||
$engine == 'gmp' ) ) {
3363 $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
3364 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' ||
$engine == 'bcmath' ) ) {
3366 foreach ( str_split( strtolower( $input ) ) as $char ) {
3367 $decimal = bcmul( $decimal, $sourceBase );
3368 $decimal = bcadd( $decimal, $baseChars[$char] );
3371 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3372 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3373 $result .= $baseChars[bcmod( $decimal, $destBase )];
3375 // @codingStandardsIgnoreEnd
3377 $result = strrev( $result );
3379 $inDigits = array();
3380 foreach ( str_split( strtolower( $input ) ) as $char ) {
3381 $inDigits[] = $baseChars[$char];
3384 // Iterate over the input, modulo-ing out an output digit
3385 // at a time until input is gone.
3387 while ( $inDigits ) {
3389 $workDigits = array();
3392 foreach ( $inDigits as $digit ) {
3393 $work *= $sourceBase;
3396 if ( $workDigits ||
$work >= $destBase ) {
3397 $workDigits[] = (int)( $work / $destBase );
3402 // All that division leaves us with a remainder,
3403 // which is conveniently our next output digit.
3404 $result .= $baseChars[$work];
3407 $inDigits = $workDigits;
3410 $result = strrev( $result );
3413 if ( !$lowercase ) {
3414 $result = strtoupper( $result );
3417 return str_pad( $result, $pad, '0', STR_PAD_LEFT
);
3421 * Check if there is sufficient entropy in php's built-in session generation
3423 * @return bool True = there is sufficient entropy
3425 function wfCheckEntropy() {
3427 ( wfIsWindows() && version_compare( PHP_VERSION
, '5.3.3', '>=' ) )
3428 ||
ini_get( 'session.entropy_file' )
3430 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3434 * Override session_id before session startup if php's built-in
3435 * session generation code is not secure.
3437 function wfFixSessionID() {
3438 // If the cookie or session id is already set we already have a session and should abort
3439 if ( isset( $_COOKIE[session_name()] ) ||
session_id() ) {
3443 // PHP's built-in session entropy is enabled if:
3444 // - entropy_file is set or you're on Windows with php 5.3.3+
3445 // - AND entropy_length is > 0
3446 // We treat it as disabled if it doesn't have an entropy length of at least 32
3447 $entropyEnabled = wfCheckEntropy();
3449 // If built-in entropy is not enabled or not sufficient override PHP's
3450 // built in session id generation code
3451 if ( !$entropyEnabled ) {
3452 wfDebug( __METHOD__
. ": PHP's built in entropy is disabled or not sufficient, " .
3453 "overriding session id generation using our cryptrand source.\n" );
3454 session_id( MWCryptRand
::generateHex( 32 ) );
3459 * Reset the session_id
3463 function wfResetSessionID() {
3464 global $wgCookieSecure;
3465 $oldSessionId = session_id();
3466 $cookieParams = session_get_cookie_params();
3467 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3468 session_regenerate_id( false );
3472 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
3475 $newSessionId = session_id();
3476 wfRunHooks( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3480 * Initialise php session
3482 * @param bool $sessionId
3484 function wfSetupSession( $sessionId = false ) {
3485 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3486 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3487 if ( $wgSessionsInObjectCache ||
$wgSessionsInMemcached ) {
3488 ObjectCacheSessionHandler
::install();
3489 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3490 # Only set this if $wgSessionHandler isn't null and session.save_handler
3491 # hasn't already been set to the desired value (that causes errors)
3492 ini_set( 'session.save_handler', $wgSessionHandler );
3494 session_set_cookie_params(
3495 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3496 session_cache_limiter( 'private, must-revalidate' );
3498 session_id( $sessionId );
3502 wfSuppressWarnings();
3504 wfRestoreWarnings();
3508 * Get an object from the precompiled serialized directory
3510 * @param string $name
3511 * @return mixed The variable on success, false on failure
3513 function wfGetPrecompiledData( $name ) {
3516 $file = "$IP/serialized/$name";
3517 if ( file_exists( $file ) ) {
3518 $blob = file_get_contents( $file );
3520 return unserialize( $blob );
3529 * @param string $args,...
3532 function wfMemcKey( /*...*/ ) {
3533 global $wgCachePrefix;
3534 $prefix = $wgCachePrefix === false ?
wfWikiID() : $wgCachePrefix;
3535 $args = func_get_args();
3536 $key = $prefix . ':' . implode( ':', $args );
3537 $key = str_replace( ' ', '_', $key );
3542 * Get a cache key for a foreign DB
3545 * @param string $prefix
3546 * @param string $args,...
3549 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3550 $args = array_slice( func_get_args(), 2 );
3552 $key = "$db-$prefix:" . implode( ':', $args );
3554 $key = $db . ':' . implode( ':', $args );
3556 return str_replace( ' ', '_', $key );
3560 * Get an ASCII string identifying this wiki
3561 * This is used as a prefix in memcached keys
3565 function wfWikiID() {
3566 global $wgDBprefix, $wgDBname;
3567 if ( $wgDBprefix ) {
3568 return "$wgDBname-$wgDBprefix";
3575 * Split a wiki ID into DB name and table prefix
3577 * @param string $wiki
3581 function wfSplitWikiID( $wiki ) {
3582 $bits = explode( '-', $wiki, 2 );
3583 if ( count( $bits ) < 2 ) {
3590 * Get a Database object.
3592 * @param int $db Index of the connection to get. May be DB_MASTER for the
3593 * master (for write queries), DB_SLAVE for potentially lagged read
3594 * queries, or an integer >= 0 for a particular server.
3596 * @param string|string[] $groups Query groups. An array of group names that this query
3597 * belongs to. May contain a single string if the query is only
3600 * @param string|bool $wiki The wiki ID, or false for the current wiki
3602 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3603 * will always return the same object, unless the underlying connection or load
3604 * balancer is manually destroyed.
3606 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3607 * updater to ensure that a proper database is being updated.
3609 * @return DatabaseBase
3611 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3612 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3616 * Get a load balancer object.
3618 * @param string|bool $wiki Wiki ID, or false for the current wiki
3619 * @return LoadBalancer
3621 function wfGetLB( $wiki = false ) {
3622 return wfGetLBFactory()->getMainLB( $wiki );
3626 * Get the load balancer factory object
3630 function &wfGetLBFactory() {
3631 return LBFactory
::singleton();
3636 * Shortcut for RepoGroup::singleton()->findFile()
3638 * @param string $title String or Title object
3639 * @param array $options Associative array of options:
3640 * time: requested time for an archived image, or false for the
3641 * current version. An image object will be returned which was
3642 * created at the specified time.
3644 * ignoreRedirect: If true, do not follow file redirects
3646 * private: If true, return restricted (deleted) files if the current
3647 * user is allowed to view them. Otherwise, such files will not
3650 * bypassCache: If true, do not use the process-local cache of File objects
3652 * @return File|bool File, or false if the file does not exist
3654 function wfFindFile( $title, $options = array() ) {
3655 return RepoGroup
::singleton()->findFile( $title, $options );
3659 * Get an object referring to a locally registered file.
3660 * Returns a valid placeholder object if the file does not exist.
3662 * @param Title|string $title
3663 * @return LocalFile|null A File, or null if passed an invalid Title
3665 function wfLocalFile( $title ) {
3666 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3670 * Should low-performance queries be disabled?
3673 * @codeCoverageIgnore
3675 function wfQueriesMustScale() {
3676 global $wgMiserMode;
3678 ||
( SiteStats
::pages() > 100000
3679 && SiteStats
::edits() > 1000000
3680 && SiteStats
::users() > 10000 );
3684 * Get the path to a specified script file, respecting file
3685 * extensions; this is a wrapper around $wgScriptExtension etc.
3686 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3688 * @param string $script Script filename, sans extension
3691 function wfScript( $script = 'index' ) {
3692 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3693 if ( $script === 'index' ) {
3695 } elseif ( $script === 'load' ) {
3696 return $wgLoadScript;
3698 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3703 * Get the script URL.
3705 * @return string Script URL
3707 function wfGetScriptUrl() {
3708 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3710 # as it was called, minus the query string.
3712 # Some sites use Apache rewrite rules to handle subdomains,
3713 # and have PHP set up in a weird way that causes PHP_SELF
3714 # to contain the rewritten URL instead of the one that the
3715 # outside world sees.
3717 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3718 # provides containing the "before" URL.
3719 return $_SERVER['SCRIPT_NAME'];
3721 return $_SERVER['URL'];
3726 * Convenience function converts boolean values into "true"
3727 * or "false" (string) values
3729 * @param bool $value
3732 function wfBoolToStr( $value ) {
3733 return $value ?
'true' : 'false';
3737 * Get a platform-independent path to the null file, e.g. /dev/null
3741 function wfGetNull() {
3742 return wfIsWindows() ?
'NUL' : '/dev/null';
3746 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3747 * and waiting for it to go down, this waits for the slaves to catch up to the
3748 * master position. Use this when updating very large numbers of rows, as
3749 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3750 * a no-op if there are no slaves.
3752 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3753 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3754 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3755 * @return bool Success (able to connect and no timeouts reached)
3757 function wfWaitForSlaves( $ifWritesSince = false, $wiki = false, $cluster = false ) {
3758 // B/C: first argument used to be "max seconds of lag"; ignore such values
3759 $ifWritesSince = ( $ifWritesSince > 1e9
) ?
$ifWritesSince : false;
3761 if ( $cluster !== false ) {
3762 $lb = wfGetLBFactory()->getExternalLB( $cluster );
3764 $lb = wfGetLB( $wiki );
3767 // bug 27975 - Don't try to wait for slaves if there are none
3768 // Prevents permission error when getting master position
3769 if ( $lb->getServerCount() > 1 ) {
3770 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3771 return true; // assume no writes done
3773 $dbw = $lb->getConnection( DB_MASTER
, array(), $wiki );
3774 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3775 return true; // no writes since the last wait
3777 $pos = $dbw->getMasterPos();
3778 // The DBMS may not support getMasterPos() or the whole
3779 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3780 if ( $pos !== false ) {
3781 return $lb->waitForAll( $pos, PHP_SAPI
=== 'cli' ?
86400 : null );
3789 * Count down from $seconds to zero on the terminal, with a one-second pause
3790 * between showing each number. For use in command-line scripts.
3792 * @codeCoverageIgnore
3793 * @param int $seconds
3795 function wfCountDown( $seconds ) {
3796 for ( $i = $seconds; $i >= 0; $i-- ) {
3797 if ( $i != $seconds ) {
3798 echo str_repeat( "\x08", strlen( $i +
1 ) );
3810 * Replace all invalid characters with -
3811 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3812 * By default, $wgIllegalFileChars = ':'
3814 * @param string $name Filename to process
3817 function wfStripIllegalFilenameChars( $name ) {
3818 global $wgIllegalFileChars;
3819 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3820 $name = wfBaseName( $name );
3821 $name = preg_replace(
3822 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3830 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3832 * @return int Value the memory limit was set to.
3834 function wfMemoryLimit() {
3835 global $wgMemoryLimit;
3836 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3837 if ( $memlimit != -1 ) {
3838 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3839 if ( $conflimit == -1 ) {
3840 wfDebug( "Removing PHP's memory limit\n" );
3841 wfSuppressWarnings();
3842 ini_set( 'memory_limit', $conflimit );
3843 wfRestoreWarnings();
3845 } elseif ( $conflimit > $memlimit ) {
3846 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3847 wfSuppressWarnings();
3848 ini_set( 'memory_limit', $conflimit );
3849 wfRestoreWarnings();
3857 * Converts shorthand byte notation to integer form
3859 * @param string $string
3862 function wfShorthandToInteger( $string = '' ) {
3863 $string = trim( $string );
3864 if ( $string === '' ) {
3867 $last = $string[strlen( $string ) - 1];
3868 $val = intval( $string );
3873 // break intentionally missing
3877 // break intentionally missing
3887 * Get the normalised IETF language tag
3888 * See unit test for examples.
3890 * @param string $code The language code.
3891 * @return string The language code which complying with BCP 47 standards.
3893 function wfBCP47( $code ) {
3894 $codeSegment = explode( '-', $code );
3896 foreach ( $codeSegment as $segNo => $seg ) {
3897 // when previous segment is x, it is a private segment and should be lc
3898 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3899 $codeBCP[$segNo] = strtolower( $seg );
3900 // ISO 3166 country code
3901 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3902 $codeBCP[$segNo] = strtoupper( $seg );
3903 // ISO 15924 script code
3904 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3905 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3906 // Use lowercase for other cases
3908 $codeBCP[$segNo] = strtolower( $seg );
3911 $langCode = implode( '-', $codeBCP );
3916 * Get a cache object.
3918 * @param int $inputType Cache type, one the the CACHE_* constants.
3921 function wfGetCache( $inputType ) {
3922 return ObjectCache
::getInstance( $inputType );
3926 * Get the main cache object
3930 function wfGetMainCache() {
3931 global $wgMainCacheType;
3932 return ObjectCache
::getInstance( $wgMainCacheType );
3936 * Get the cache object used by the message cache
3940 function wfGetMessageCacheStorage() {
3941 global $wgMessageCacheType;
3942 return ObjectCache
::getInstance( $wgMessageCacheType );
3946 * Get the cache object used by the parser cache
3950 function wfGetParserCacheStorage() {
3951 global $wgParserCacheType;
3952 return ObjectCache
::getInstance( $wgParserCacheType );
3956 * Get the cache object used by the language converter
3960 function wfGetLangConverterCacheStorage() {
3961 global $wgLanguageConverterCacheType;
3962 return ObjectCache
::getInstance( $wgLanguageConverterCacheType );
3966 * Call hook functions defined in $wgHooks
3968 * @param string $event Event name
3969 * @param array $args Parameters passed to hook functions
3970 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
3972 * @return bool True if no handler aborted the hook
3974 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
3975 return Hooks
::run( $event, $args, $deprecatedVersion );
3979 * Wrapper around php's unpack.
3981 * @param string $format The format string (See php's docs)
3982 * @param string $data A binary string of binary data
3983 * @param int|bool $length The minimum length of $data or false. This is to
3984 * prevent reading beyond the end of $data. false to disable the check.
3986 * Also be careful when using this function to read unsigned 32 bit integer
3987 * because php might make it negative.
3989 * @throws MWException If $data not long enough, or if unpack fails
3990 * @return array Associative array of the extracted data
3992 function wfUnpack( $format, $data, $length = false ) {
3993 if ( $length !== false ) {
3994 $realLen = strlen( $data );
3995 if ( $realLen < $length ) {
3996 throw new MWException( "Tried to use wfUnpack on a "
3997 . "string of length $realLen, but needed one "
3998 . "of at least length $length."
4003 wfSuppressWarnings();
4004 $result = unpack( $format, $data );
4005 wfRestoreWarnings();
4007 if ( $result === false ) {
4008 // If it cannot extract the packed data.
4009 throw new MWException( "unpack could not unpack binary data" );
4015 * Determine if an image exists on the 'bad image list'.
4017 * The format of MediaWiki:Bad_image_list is as follows:
4018 * * Only list items (lines starting with "*") are considered
4019 * * The first link on a line must be a link to a bad image
4020 * * Any subsequent links on the same line are considered to be exceptions,
4021 * i.e. articles where the image may occur inline.
4023 * @param string $name The image name to check
4024 * @param Title|bool $contextTitle The page on which the image occurs, if known
4025 * @param string $blacklist Wikitext of a file blacklist
4028 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4029 static $badImageCache = null; // based on bad_image_list msg
4030 wfProfileIn( __METHOD__
);
4033 $redirectTitle = RepoGroup
::singleton()->checkRedirect( Title
::makeTitle( NS_FILE
, $name ) );
4034 if ( $redirectTitle ) {
4035 $name = $redirectTitle->getDBkey();
4038 # Run the extension hook
4040 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
4041 wfProfileOut( __METHOD__
);
4045 $cacheable = ( $blacklist === null );
4046 if ( $cacheable && $badImageCache !== null ) {
4047 $badImages = $badImageCache;
4048 } else { // cache miss
4049 if ( $blacklist === null ) {
4050 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4052 # Build the list now
4053 $badImages = array();
4054 $lines = explode( "\n", $blacklist );
4055 foreach ( $lines as $line ) {
4057 if ( substr( $line, 0, 1 ) !== '*' ) {
4063 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4067 $exceptions = array();
4068 $imageDBkey = false;
4069 foreach ( $m[1] as $i => $titleText ) {
4070 $title = Title
::newFromText( $titleText );
4071 if ( !is_null( $title ) ) {
4073 $imageDBkey = $title->getDBkey();
4075 $exceptions[$title->getPrefixedDBkey()] = true;
4080 if ( $imageDBkey !== false ) {
4081 $badImages[$imageDBkey] = $exceptions;
4085 $badImageCache = $badImages;
4089 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
4090 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4091 wfProfileOut( __METHOD__
);
4096 * Determine whether the client at a given source IP is likely to be able to
4097 * access the wiki via HTTPS.
4099 * @param string $ip The IPv4/6 address in the normal human-readable form
4102 function wfCanIPUseHTTPS( $ip ) {
4104 wfRunHooks( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4109 * Work out the IP address based on various globals
4110 * For trusted proxies, use the XFF client IP (first of the chain)
4112 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4115 function wfGetIP() {
4116 wfDeprecated( __METHOD__
, '1.19' );
4118 return $wgRequest->getIP();
4122 * Checks if an IP is a trusted proxy provider.
4123 * Useful to tell if X-Forwarded-For data is possibly bogus.
4124 * Squid cache servers for the site are whitelisted.
4125 * @deprecated Since 1.24, use IP::isTrustedProxy()
4130 function wfIsTrustedProxy( $ip ) {
4131 return IP
::isTrustedProxy( $ip );
4135 * Checks if an IP matches a proxy we've configured.
4136 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4140 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4142 function wfIsConfiguredProxy( $ip ) {
4143 return IP
::isConfiguredProxy( $ip );