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' ) ) {
94 function gzdecode( $data ) {
95 return gzinflate( substr( $data, 10, -8 ) );
99 // hash_equals function only exists in PHP >= 5.6.0
100 if ( !function_exists( 'hash_equals' ) ) {
102 * Check whether a user-provided string is equal to a fixed-length secret without
103 * revealing bytes of the secret through timing differences.
105 * This timing guarantee -- that a partial match takes the same time as a complete
106 * mismatch -- is why this function is used in some security-sensitive parts of the code.
107 * For example, it shouldn't be possible to guess an HMAC signature one byte at a time.
109 * Longer explanation: http://www.emerose.com/timing-attacks-explained
111 * @codeCoverageIgnore
112 * @param string $known_string Fixed-length secret to compare against
113 * @param string $user_string User-provided string
114 * @return bool True if the strings are the same, false otherwise
116 function hash_equals( $known_string, $user_string ) {
117 // Strict type checking as in PHP's native implementation
118 if ( !is_string( $known_string ) ) {
119 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
120 gettype( $known_string ) . ' given', E_USER_WARNING
);
125 if ( !is_string( $user_string ) ) {
126 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
127 gettype( $user_string ) . ' given', E_USER_WARNING
);
132 // Note that we do one thing PHP doesn't: try to avoid leaking information about
133 // relative lengths of $known_string and $user_string, and of multiple $known_strings.
134 // However, lengths may still inevitably leak through, for example, CPU cache misses.
135 $known_string_len = strlen( $known_string );
136 $user_string_len = strlen( $user_string );
137 $result = $known_string_len ^
$user_string_len;
138 for ( $i = 0; $i < $user_string_len; $i++
) {
139 $result |
= ord( $known_string[$i %
$known_string_len] ) ^
ord( $user_string[$i] );
142 return ( $result === 0 );
148 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
153 function wfArrayDiff2( $a, $b ) {
154 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
158 * @param array|string $a
159 * @param array|string $b
162 function wfArrayDiff2_cmp( $a, $b ) {
163 if ( is_string( $a ) && is_string( $b ) ) {
164 return strcmp( $a, $b );
165 } elseif ( count( $a ) !== count( $b ) ) {
166 return count( $a ) < count( $b ) ?
-1 : 1;
170 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
171 $cmp = strcmp( $valueA, $valueB );
181 * Appends to second array if $value differs from that in $default
183 * @param string|int $key
184 * @param mixed $value
185 * @param mixed $default
186 * @param array $changed Array to alter
187 * @throws MWException
189 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
190 if ( is_null( $changed ) ) {
191 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
193 if ( $default[$key] !== $value ) {
194 $changed[$key] = $value;
199 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
201 * wfMergeErrorArrays(
202 * array( array( 'x' ) ),
203 * array( array( 'x', '2' ) ),
204 * array( array( 'x' ) ),
205 * array( array( 'y' ) )
214 * @param array $array1,...
217 function wfMergeErrorArrays( /*...*/ ) {
218 $args = func_get_args();
220 foreach ( $args as $errors ) {
221 foreach ( $errors as $params ) {
222 # @todo FIXME: Sometimes get nested arrays for $params,
223 # which leads to E_NOTICEs
224 $spec = implode( "\t", $params );
225 $out[$spec] = $params;
228 return array_values( $out );
232 * Insert array into another array after the specified *KEY*
234 * @param array $array The array.
235 * @param array $insert The array to insert.
236 * @param mixed $after The key to insert after
239 function wfArrayInsertAfter( array $array, array $insert, $after ) {
240 // Find the offset of the element to insert after.
241 $keys = array_keys( $array );
242 $offsetByKey = array_flip( $keys );
244 $offset = $offsetByKey[$after];
246 // Insert at the specified offset
247 $before = array_slice( $array, 0, $offset +
1, true );
248 $after = array_slice( $array, $offset +
1, count( $array ) - $offset, true );
250 $output = $before +
$insert +
$after;
256 * Recursively converts the parameter (an object) to an array with the same data
258 * @param object|array $objOrArray
259 * @param bool $recursive
262 function wfObjectToArray( $objOrArray, $recursive = true ) {
264 if ( is_object( $objOrArray ) ) {
265 $objOrArray = get_object_vars( $objOrArray );
267 foreach ( $objOrArray as $key => $value ) {
268 if ( $recursive && ( is_object( $value ) ||
is_array( $value ) ) ) {
269 $value = wfObjectToArray( $value );
272 $array[$key] = $value;
279 * Get a random decimal value between 0 and 1, in a way
280 * not likely to give duplicate values for any realistic
281 * number of articles.
285 function wfRandom() {
286 # The maximum random value is "only" 2^31-1, so get two random
287 # values to reduce the chance of dupes
288 $max = mt_getrandmax() +
1;
289 $rand = number_format( ( mt_rand() * $max +
mt_rand() ) / $max / $max, 12, '.', '' );
295 * Get a random string containing a number of pseudo-random hex
297 * @note This is not secure, if you are trying to generate some sort
298 * of token please use MWCryptRand instead.
300 * @param int $length The length of the string to generate
304 function wfRandomString( $length = 32 ) {
306 for ( $n = 0; $n < $length; $n +
= 7 ) {
307 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
309 return substr( $str, 0, $length );
313 * We want some things to be included as literal characters in our title URLs
314 * for prettiness, which urlencode encodes by default. According to RFC 1738,
315 * all of the following should be safe:
319 * But + is not safe because it's used to indicate a space; &= are only safe in
320 * paths and not in queries (and we don't distinguish here); ' seems kind of
321 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
322 * is reserved, we don't care. So the list we unescape is:
326 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
327 * so no fancy : for IIS7.
329 * %2F in the page titles seems to fatally break for some reason.
334 function wfUrlencode( $s ) {
337 if ( is_null( $s ) ) {
342 if ( is_null( $needle ) ) {
343 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
344 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
345 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
351 $s = urlencode( $s );
354 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
362 * This function takes two arrays as input, and returns a CGI-style string, e.g.
363 * "days=7&limit=100". Options in the first array override options in the second.
364 * Options set to null or false will not be output.
366 * @param array $array1 ( String|Array )
367 * @param array $array2 ( String|Array )
368 * @param string $prefix
371 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
372 if ( !is_null( $array2 ) ) {
373 $array1 = $array1 +
$array2;
377 foreach ( $array1 as $key => $value ) {
378 if ( !is_null( $value ) && $value !== false ) {
382 if ( $prefix !== '' ) {
383 $key = $prefix . "[$key]";
385 if ( is_array( $value ) ) {
387 foreach ( $value as $k => $v ) {
388 $cgi .= $firstTime ?
'' : '&';
389 if ( is_array( $v ) ) {
390 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
392 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
397 if ( is_object( $value ) ) {
398 $value = $value->__toString();
400 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
408 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
409 * its argument and returns the same string in array form. This allows compatibility
410 * with legacy functions that accept raw query strings instead of nice
411 * arrays. Of course, keys and values are urldecode()d.
413 * @param string $query Query string
414 * @return string[] Array version of input
416 function wfCgiToArray( $query ) {
417 if ( isset( $query[0] ) && $query[0] == '?' ) {
418 $query = substr( $query, 1 );
420 $bits = explode( '&', $query );
422 foreach ( $bits as $bit ) {
426 if ( strpos( $bit, '=' ) === false ) {
427 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
431 list( $key, $value ) = explode( '=', $bit );
433 $key = urldecode( $key );
434 $value = urldecode( $value );
435 if ( strpos( $key, '[' ) !== false ) {
436 $keys = array_reverse( explode( '[', $key ) );
437 $key = array_pop( $keys );
439 foreach ( $keys as $k ) {
440 $k = substr( $k, 0, -1 );
441 $temp = array( $k => $temp );
443 if ( isset( $ret[$key] ) ) {
444 $ret[$key] = array_merge( $ret[$key], $temp );
456 * Append a query string to an existing URL, which may or may not already
457 * have query string parameters already. If so, they will be combined.
460 * @param string|string[] $query String or associative array
463 function wfAppendQuery( $url, $query ) {
464 if ( is_array( $query ) ) {
465 $query = wfArrayToCgi( $query );
467 if ( $query != '' ) {
468 if ( false === strpos( $url, '?' ) ) {
479 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
482 * The meaning of the PROTO_* constants is as follows:
483 * PROTO_HTTP: Output a URL starting with http://
484 * PROTO_HTTPS: Output a URL starting with https://
485 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
486 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
487 * on which protocol was used for the current incoming request
488 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
489 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
490 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
492 * @todo this won't work with current-path-relative URLs
493 * like "subdir/foo.html", etc.
495 * @param string $url Either fully-qualified or a local path + query
496 * @param string $defaultProto One of the PROTO_* constants. Determines the
497 * protocol to use if $url or $wgServer is protocol-relative
498 * @return string Fully-qualified URL, current-path-relative URL or false if
499 * no valid URL can be constructed
501 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT
) {
502 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
504 if ( $defaultProto === PROTO_CANONICAL
) {
505 $serverUrl = $wgCanonicalServer;
506 } elseif ( $defaultProto === PROTO_INTERNAL
&& $wgInternalServer !== false ) {
507 // Make $wgInternalServer fall back to $wgServer if not set
508 $serverUrl = $wgInternalServer;
510 $serverUrl = $wgServer;
511 if ( $defaultProto === PROTO_CURRENT
) {
512 $defaultProto = $wgRequest->getProtocol() . '://';
516 // Analyze $serverUrl to obtain its protocol
517 $bits = wfParseUrl( $serverUrl );
518 $serverHasProto = $bits && $bits['scheme'] != '';
520 if ( $defaultProto === PROTO_CANONICAL ||
$defaultProto === PROTO_INTERNAL
) {
521 if ( $serverHasProto ) {
522 $defaultProto = $bits['scheme'] . '://';
524 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
525 // This really isn't supposed to happen. Fall back to HTTP in this
527 $defaultProto = PROTO_HTTP
;
531 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
533 if ( substr( $url, 0, 2 ) == '//' ) {
534 $url = $defaultProtoWithoutSlashes . $url;
535 } elseif ( substr( $url, 0, 1 ) == '/' ) {
536 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
537 // otherwise leave it alone.
538 $url = ( $serverHasProto ?
'' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
541 $bits = wfParseUrl( $url );
543 // ensure proper port for HTTPS arrives in URL
544 // https://bugzilla.wikimedia.org/show_bug.cgi?id=65184
545 if ( $defaultProto === PROTO_HTTPS
&& $wgHttpsPort != 443 ) {
546 $bits['port'] = $wgHttpsPort;
549 if ( $bits && isset( $bits['path'] ) ) {
550 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
551 return wfAssembleUrl( $bits );
555 } elseif ( substr( $url, 0, 1 ) != '/' ) {
556 # URL is a relative path
557 return wfRemoveDotSegments( $url );
560 # Expanded URL is not valid.
565 * This function will reassemble a URL parsed with wfParseURL. This is useful
566 * if you need to edit part of a URL and put it back together.
568 * This is the basic structure used (brackets contain keys for $urlParts):
569 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
571 * @todo Need to integrate this into wfExpandUrl (bug 32168)
574 * @param array $urlParts URL parts, as output from wfParseUrl
575 * @return string URL assembled from its component parts
577 function wfAssembleUrl( $urlParts ) {
580 if ( isset( $urlParts['delimiter'] ) ) {
581 if ( isset( $urlParts['scheme'] ) ) {
582 $result .= $urlParts['scheme'];
585 $result .= $urlParts['delimiter'];
588 if ( isset( $urlParts['host'] ) ) {
589 if ( isset( $urlParts['user'] ) ) {
590 $result .= $urlParts['user'];
591 if ( isset( $urlParts['pass'] ) ) {
592 $result .= ':' . $urlParts['pass'];
597 $result .= $urlParts['host'];
599 if ( isset( $urlParts['port'] ) ) {
600 $result .= ':' . $urlParts['port'];
604 if ( isset( $urlParts['path'] ) ) {
605 $result .= $urlParts['path'];
608 if ( isset( $urlParts['query'] ) ) {
609 $result .= '?' . $urlParts['query'];
612 if ( isset( $urlParts['fragment'] ) ) {
613 $result .= '#' . $urlParts['fragment'];
620 * Remove all dot-segments in the provided URL path. For example,
621 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
622 * RFC3986 section 5.2.4.
624 * @todo Need to integrate this into wfExpandUrl (bug 32168)
626 * @param string $urlPath URL path, potentially containing dot-segments
627 * @return string URL path with all dot-segments removed
629 function wfRemoveDotSegments( $urlPath ) {
632 $inputLength = strlen( $urlPath );
634 while ( $inputOffset < $inputLength ) {
635 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
636 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
637 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
638 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
641 if ( $prefixLengthTwo == './' ) {
642 # Step A, remove leading "./"
644 } elseif ( $prefixLengthThree == '../' ) {
645 # Step A, remove leading "../"
647 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset +
2 == $inputLength ) ) {
648 # Step B, replace leading "/.$" with "/"
650 $urlPath[$inputOffset] = '/';
651 } elseif ( $prefixLengthThree == '/./' ) {
652 # Step B, replace leading "/./" with "/"
654 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset +
3 == $inputLength ) ) {
655 # Step C, replace leading "/..$" with "/" and
656 # remove last path component in output
658 $urlPath[$inputOffset] = '/';
660 } elseif ( $prefixLengthFour == '/../' ) {
661 # Step C, replace leading "/../" with "/" and
662 # remove last path component in output
665 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset +
1 == $inputLength ) ) {
666 # Step D, remove "^.$"
668 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset +
2 == $inputLength ) ) {
669 # Step D, remove "^..$"
672 # Step E, move leading path segment to output
673 if ( $prefixLengthOne == '/' ) {
674 $slashPos = strpos( $urlPath, '/', $inputOffset +
1 );
676 $slashPos = strpos( $urlPath, '/', $inputOffset );
678 if ( $slashPos === false ) {
679 $output .= substr( $urlPath, $inputOffset );
680 $inputOffset = $inputLength;
682 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
683 $inputOffset +
= $slashPos - $inputOffset;
688 $slashPos = strrpos( $output, '/' );
689 if ( $slashPos === false ) {
692 $output = substr( $output, 0, $slashPos );
701 * Returns a regular expression of url protocols
703 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
704 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
707 function wfUrlProtocols( $includeProtocolRelative = true ) {
708 global $wgUrlProtocols;
710 // Cache return values separately based on $includeProtocolRelative
711 static $withProtRel = null, $withoutProtRel = null;
712 $cachedValue = $includeProtocolRelative ?
$withProtRel : $withoutProtRel;
713 if ( !is_null( $cachedValue ) ) {
717 // Support old-style $wgUrlProtocols strings, for backwards compatibility
718 // with LocalSettings files from 1.5
719 if ( is_array( $wgUrlProtocols ) ) {
720 $protocols = array();
721 foreach ( $wgUrlProtocols as $protocol ) {
722 // Filter out '//' if !$includeProtocolRelative
723 if ( $includeProtocolRelative ||
$protocol !== '//' ) {
724 $protocols[] = preg_quote( $protocol, '/' );
728 $retval = implode( '|', $protocols );
730 // Ignore $includeProtocolRelative in this case
731 // This case exists for pre-1.6 compatibility, and we can safely assume
732 // that '//' won't appear in a pre-1.6 config because protocol-relative
733 // URLs weren't supported until 1.18
734 $retval = $wgUrlProtocols;
737 // Cache return value
738 if ( $includeProtocolRelative ) {
739 $withProtRel = $retval;
741 $withoutProtRel = $retval;
747 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
748 * you need a regex that matches all URL protocols but does not match protocol-
752 function wfUrlProtocolsWithoutProtRel() {
753 return wfUrlProtocols( false );
757 * parse_url() work-alike, but non-broken. Differences:
759 * 1) Does not raise warnings on bad URLs (just returns false).
760 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
761 * protocol-relative URLs) correctly.
762 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
764 * @param string $url A URL to parse
765 * @return string[] Bits of the URL in an associative array, per PHP docs
767 function wfParseUrl( $url ) {
768 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
770 // Protocol-relative URLs are handled really badly by parse_url(). It's so
771 // bad that the easiest way to handle them is to just prepend 'http:' and
772 // strip the protocol out later.
773 $wasRelative = substr( $url, 0, 2 ) == '//';
774 if ( $wasRelative ) {
777 wfSuppressWarnings();
778 $bits = parse_url( $url );
780 // parse_url() returns an array without scheme for some invalid URLs, e.g.
781 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
782 if ( !$bits ||
!isset( $bits['scheme'] ) ) {
786 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
787 $bits['scheme'] = strtolower( $bits['scheme'] );
789 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
790 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
791 $bits['delimiter'] = '://';
792 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
793 $bits['delimiter'] = ':';
794 // parse_url detects for news: and mailto: the host part of an url as path
795 // We have to correct this wrong detection
796 if ( isset( $bits['path'] ) ) {
797 $bits['host'] = $bits['path'];
804 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
805 if ( !isset( $bits['host'] ) ) {
809 if ( isset( $bits['path'] ) ) {
810 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
811 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
812 $bits['path'] = '/' . $bits['path'];
819 // If the URL was protocol-relative, fix scheme and delimiter
820 if ( $wasRelative ) {
821 $bits['scheme'] = '';
822 $bits['delimiter'] = '//';
828 * Take a URL, make sure it's expanded to fully qualified, and replace any
829 * encoded non-ASCII Unicode characters with their UTF-8 original forms
830 * for more compact display and legibility for local audiences.
832 * @todo handle punycode domains too
837 function wfExpandIRI( $url ) {
838 return preg_replace_callback(
839 '/((?:%[89A-F][0-9A-F])+)/i',
840 'wfExpandIRI_callback',
846 * Private callback for wfExpandIRI
847 * @param array $matches
850 function wfExpandIRI_callback( $matches ) {
851 return urldecode( $matches[1] );
855 * Make URL indexes, appropriate for the el_index field of externallinks.
860 function wfMakeUrlIndexes( $url ) {
861 $bits = wfParseUrl( $url );
863 // Reverse the labels in the hostname, convert to lower case
864 // For emails reverse domainpart only
865 if ( $bits['scheme'] == 'mailto' ) {
866 $mailparts = explode( '@', $bits['host'], 2 );
867 if ( count( $mailparts ) === 2 ) {
868 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
870 // No domain specified, don't mangle it
873 $reversedHost = $domainpart . '@' . $mailparts[0];
875 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
877 // Add an extra dot to the end
878 // Why? Is it in wrong place in mailto links?
879 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
880 $reversedHost .= '.';
882 // Reconstruct the pseudo-URL
883 $prot = $bits['scheme'];
884 $index = $prot . $bits['delimiter'] . $reversedHost;
885 // Leave out user and password. Add the port, path, query and fragment
886 if ( isset( $bits['port'] ) ) {
887 $index .= ':' . $bits['port'];
889 if ( isset( $bits['path'] ) ) {
890 $index .= $bits['path'];
894 if ( isset( $bits['query'] ) ) {
895 $index .= '?' . $bits['query'];
897 if ( isset( $bits['fragment'] ) ) {
898 $index .= '#' . $bits['fragment'];
902 return array( "http:$index", "https:$index" );
904 return array( $index );
909 * Check whether a given URL has a domain that occurs in a given set of domains
910 * @param string $url URL
911 * @param array $domains Array of domains (strings)
912 * @return bool True if the host part of $url ends in one of the strings in $domains
914 function wfMatchesDomainList( $url, $domains ) {
915 $bits = wfParseUrl( $url );
916 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
917 $host = '.' . $bits['host'];
918 foreach ( (array)$domains as $domain ) {
919 $domain = '.' . $domain;
920 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
929 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
930 * In normal operation this is a NOP.
932 * Controlling globals:
933 * $wgDebugLogFile - points to the log file
934 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
935 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
937 * @param string $text
938 * @param string|bool $dest Destination of the message:
939 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
940 * - 'log': only to the log and not in HTML
941 * For backward compatibility, it can also take a boolean:
942 * - true: same as 'all'
943 * - false: same as 'log'
945 function wfDebug( $text, $dest = 'all' ) {
946 global $wgDebugLogFile, $wgDebugRawPage, $wgDebugLogPrefix;
948 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
952 // Turn $dest into a string if it's a boolean (for b/c)
953 if ( $dest === true ) {
955 } elseif ( $dest === false ) {
959 $timer = wfDebugTimer();
960 if ( $timer !== '' ) {
961 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
964 if ( $dest === 'all' ) {
965 MWDebug
::debugMsg( $text );
968 if ( $wgDebugLogFile != '' ) {
969 # Strip unprintables; they can switch terminal modes when binary data
970 # gets dumped, which is pretty annoying.
971 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
972 $text = $wgDebugLogPrefix . $text;
973 wfErrorLog( $text, $wgDebugLogFile );
978 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
981 function wfIsDebugRawPage() {
983 if ( $cache !== null ) {
986 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
987 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
989 isset( $_SERVER['SCRIPT_NAME'] )
990 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1001 * Get microsecond timestamps for debug logs
1005 function wfDebugTimer() {
1006 global $wgDebugTimestamps, $wgRequestTime;
1008 if ( !$wgDebugTimestamps ) {
1012 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1013 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1014 return "$prefix $mem ";
1018 * Send a line giving PHP memory usage.
1020 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1022 function wfDebugMem( $exact = false ) {
1023 $mem = memory_get_usage();
1025 $mem = floor( $mem / 1024 ) . ' KiB';
1029 wfDebug( "Memory usage: $mem\n" );
1033 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
1034 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string
1035 * filename or an associative array mapping 'destination' to the desired filename. The
1036 * associative array may also contain a 'sample' key with an integer value, specifying
1037 * a sampling factor.
1039 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1041 * @param string $logGroup
1042 * @param string $text
1043 * @param string|bool $dest Destination of the message:
1044 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1045 * - 'log': only to the log and not in HTML
1046 * - 'private': only to the specifc log if set in $wgDebugLogGroups and
1047 * discarded otherwise
1048 * For backward compatibility, it can also take a boolean:
1049 * - true: same as 'all'
1050 * - false: same as 'private'
1052 function wfDebugLog( $logGroup, $text, $dest = 'all' ) {
1053 global $wgDebugLogGroups;
1055 $text = trim( $text ) . "\n";
1057 // Turn $dest into a string if it's a boolean (for b/c)
1058 if ( $dest === true ) {
1060 } elseif ( $dest === false ) {
1064 if ( !isset( $wgDebugLogGroups[$logGroup] ) ) {
1065 if ( $dest !== 'private' ) {
1066 wfDebug( "[$logGroup] $text", $dest );
1071 if ( $dest === 'all' ) {
1072 MWDebug
::debugMsg( "[$logGroup] $text" );
1075 $logConfig = $wgDebugLogGroups[$logGroup];
1076 if ( $logConfig === false ) {
1079 if ( is_array( $logConfig ) ) {
1080 if ( isset( $logConfig['sample'] ) && mt_rand( 1, $logConfig['sample'] ) !== 1 ) {
1083 $destination = $logConfig['destination'];
1085 $destination = strval( $logConfig );
1088 $time = wfTimestamp( TS_DB
);
1090 $host = wfHostname();
1091 wfErrorLog( "$time $host $wiki: $text", $destination );
1095 * Log for database errors
1097 * @param string $text Database error message.
1099 function wfLogDBError( $text ) {
1100 global $wgDBerrorLog, $wgDBerrorLogTZ;
1101 static $logDBErrorTimeZoneObject = null;
1103 if ( $wgDBerrorLog ) {
1104 $host = wfHostname();
1107 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
1108 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
1111 // Workaround for https://bugs.php.net/bug.php?id=52063
1112 // Can be removed when min PHP > 5.3.2
1113 if ( $logDBErrorTimeZoneObject === null ) {
1114 $d = date_create( "now" );
1116 $d = date_create( "now", $logDBErrorTimeZoneObject );
1119 $date = $d->format( 'D M j G:i:s T Y' );
1121 $text = "$date\t$host\t$wiki\t" . trim( $text ) . "\n";
1122 wfErrorLog( $text, $wgDBerrorLog );
1127 * Throws a warning that $function is deprecated
1129 * @param string $function
1130 * @param string|bool $version Version of MediaWiki that the function
1131 * was deprecated in (Added in 1.19).
1132 * @param string|bool $component Added in 1.19.
1133 * @param int $callerOffset How far up the call stack is the original
1134 * caller. 2 = function that called the function that called
1135 * wfDeprecated (Added in 1.20)
1139 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1140 MWDebug
::deprecated( $function, $version, $component, $callerOffset +
1 );
1144 * Send a warning either to the debug log or in a PHP error depending on
1145 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1147 * @param string $msg Message to send
1148 * @param int $callerOffset Number of items to go back in the backtrace to
1149 * find the correct caller (1 = function calling wfWarn, ...)
1150 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1151 * only used when $wgDevelopmentWarnings is true
1153 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
1154 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'auto' );
1158 * Send a warning as a PHP error and the debug log. This is intended for logging
1159 * warnings in production. For logging development warnings, use WfWarn instead.
1161 * @param string $msg Message to send
1162 * @param int $callerOffset Number of items to go back in the backtrace to
1163 * find the correct caller (1 = function calling wfLogWarning, ...)
1164 * @param int $level PHP error level; defaults to E_USER_WARNING
1166 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING
) {
1167 MWDebug
::warning( $msg, $callerOffset +
1, $level, 'production' );
1171 * Log to a file without getting "file size exceeded" signals.
1173 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1174 * send lines to the specified port, prefixed by the specified prefix and a space.
1176 * @param string $text
1177 * @param string $file Filename
1178 * @throws MWException
1180 function wfErrorLog( $text, $file ) {
1181 if ( substr( $file, 0, 4 ) == 'udp:' ) {
1182 # Needs the sockets extension
1183 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
1184 // IPv6 bracketed host
1186 $port = intval( $m[3] );
1187 $prefix = isset( $m[4] ) ?
$m[4] : false;
1189 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
1191 if ( !IP
::isIPv4( $host ) ) {
1192 $host = gethostbyname( $host );
1194 $port = intval( $m[3] );
1195 $prefix = isset( $m[4] ) ?
$m[4] : false;
1198 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
1201 // Clean it up for the multiplexer
1202 if ( strval( $prefix ) !== '' ) {
1203 $text = preg_replace( '/^/m', $prefix . ' ', $text );
1206 if ( strlen( $text ) > 65506 ) {
1207 $text = substr( $text, 0, 65506 );
1210 if ( substr( $text, -1 ) != "\n" ) {
1213 } elseif ( strlen( $text ) > 65507 ) {
1214 $text = substr( $text, 0, 65507 );
1217 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
1222 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
1223 socket_close( $sock );
1225 wfSuppressWarnings();
1226 $exists = file_exists( $file );
1227 $size = $exists ?
filesize( $file ) : false;
1228 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
1229 file_put_contents( $file, $text, FILE_APPEND
);
1231 wfRestoreWarnings();
1238 function wfLogProfilingData() {
1239 global $wgRequestTime, $wgDebugLogFile, $wgDebugLogGroups, $wgDebugRawPage;
1240 global $wgProfileLimit, $wgUser, $wgRequest;
1242 StatCounter
::singleton()->flush();
1244 $profiler = Profiler
::instance();
1246 # Profiling must actually be enabled...
1247 if ( $profiler->isStub() ) {
1251 // Get total page request time and only show pages that longer than
1252 // $wgProfileLimit time (default is 0)
1253 $elapsed = microtime( true ) - $wgRequestTime;
1254 if ( $elapsed <= $wgProfileLimit ) {
1258 $profiler->logData();
1260 // Check whether this should be logged in the debug file.
1261 if ( isset( $wgDebugLogGroups['profileoutput'] )
1262 && $wgDebugLogGroups['profileoutput'] === false
1264 // Explicitely disabled
1267 if ( !isset( $wgDebugLogGroups['profileoutput'] ) && $wgDebugLogFile == '' ) {
1268 // Logging not enabled; no point going further
1271 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1276 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1277 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
1279 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1280 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
1282 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1283 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
1286 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
1288 // Don't load $wgUser at this late stage just for statistics purposes
1289 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
1290 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1291 $forward .= ' anon';
1294 // Command line script uses a FauxRequest object which does not have
1295 // any knowledge about an URL and throw an exception instead.
1297 $requestUrl = $wgRequest->getRequestURL();
1298 } catch ( MWException
$e ) {
1299 $requestUrl = 'n/a';
1302 $log = sprintf( "%s\t%04.3f\t%s\n",
1303 gmdate( 'YmdHis' ), $elapsed,
1304 urldecode( $requestUrl . $forward ) );
1306 wfDebugLog( 'profileoutput', $log . $profiler->getOutput() );
1310 * Increment a statistics counter
1312 * @param string $key
1316 function wfIncrStats( $key, $count = 1 ) {
1317 StatCounter
::singleton()->incr( $key, $count );
1321 * Check whether the wiki is in read-only mode.
1325 function wfReadOnly() {
1326 return wfReadOnlyReason() !== false;
1330 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1332 * @return string|bool String when in read-only mode; false otherwise
1334 function wfReadOnlyReason() {
1335 global $wgReadOnly, $wgReadOnlyFile;
1337 if ( $wgReadOnly === null ) {
1338 // Set $wgReadOnly for faster access next time
1339 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1340 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1342 $wgReadOnly = false;
1350 * Return a Language object from $langcode
1352 * @param Language|string|bool $langcode Either:
1353 * - a Language object
1354 * - code of the language to get the message for, if it is
1355 * a valid code create a language for that language, if
1356 * it is a string but not a valid code then make a basic
1358 * - a boolean: if it's false then use the global object for
1359 * the current user's language (as a fallback for the old parameter
1360 * functionality), or if it is true then use global object
1361 * for the wiki's content language.
1364 function wfGetLangObj( $langcode = false ) {
1365 # Identify which language to get or create a language object for.
1366 # Using is_object here due to Stub objects.
1367 if ( is_object( $langcode ) ) {
1368 # Great, we already have the object (hopefully)!
1372 global $wgContLang, $wgLanguageCode;
1373 if ( $langcode === true ||
$langcode === $wgLanguageCode ) {
1374 # $langcode is the language code of the wikis content language object.
1375 # or it is a boolean and value is true
1380 if ( $langcode === false ||
$langcode === $wgLang->getCode() ) {
1381 # $langcode is the language code of user language object.
1382 # or it was a boolean and value is false
1386 $validCodes = array_keys( Language
::fetchLanguageNames() );
1387 if ( in_array( $langcode, $validCodes ) ) {
1388 # $langcode corresponds to a valid language.
1389 return Language
::factory( $langcode );
1392 # $langcode is a string, but not a valid language code; use content language.
1393 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1398 * This is the function for getting translated interface messages.
1400 * @see Message class for documentation how to use them.
1401 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1403 * This function replaces all old wfMsg* functions.
1405 * @param string $key Message key
1406 * @param mixed $params,... Normal message parameters
1411 * @see Message::__construct
1413 function wfMessage( $key /*...*/ ) {
1414 $params = func_get_args();
1415 array_shift( $params );
1416 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1417 $params = $params[0];
1419 return new Message( $key, $params );
1423 * This function accepts multiple message keys and returns a message instance
1424 * for the first message which is non-empty. If all messages are empty then an
1425 * instance of the first message key is returned.
1427 * @param string|string[] $keys,... Message keys
1432 * @see Message::newFallbackSequence
1434 function wfMessageFallback( /*...*/ ) {
1435 $args = func_get_args();
1436 return call_user_func_array( 'Message::newFallbackSequence', $args );
1440 * Get a message from anywhere, for the current user language.
1442 * Use wfMsgForContent() instead if the message should NOT
1443 * change depending on the user preferences.
1445 * @deprecated since 1.18
1447 * @param string $key Lookup key for the message, usually
1448 * defined in languages/Language.php
1450 * Parameters to the message, which can be used to insert variable text into
1451 * it, can be passed to this function in the following formats:
1452 * - One per argument, starting at the second parameter
1453 * - As an array in the second parameter
1454 * These are not shown in the function definition.
1458 function wfMsg( $key ) {
1459 wfDeprecated( __METHOD__
, '1.21' );
1461 $args = func_get_args();
1462 array_shift( $args );
1463 return wfMsgReal( $key, $args );
1467 * Same as above except doesn't transform the message
1469 * @deprecated since 1.18
1471 * @param string $key
1474 function wfMsgNoTrans( $key ) {
1475 wfDeprecated( __METHOD__
, '1.21' );
1477 $args = func_get_args();
1478 array_shift( $args );
1479 return wfMsgReal( $key, $args, true, false, false );
1483 * Get a message from anywhere, for the current global language
1484 * set with $wgLanguageCode.
1486 * Use this if the message should NOT change dependent on the
1487 * language set in the user's preferences. This is the case for
1488 * most text written into logs, as well as link targets (such as
1489 * the name of the copyright policy page). Link titles, on the
1490 * other hand, should be shown in the UI language.
1492 * Note that MediaWiki allows users to change the user interface
1493 * language in their preferences, but a single installation
1494 * typically only contains content in one language.
1496 * Be wary of this distinction: If you use wfMsg() where you should
1497 * use wfMsgForContent(), a user of the software may have to
1498 * customize potentially hundreds of messages in
1499 * order to, e.g., fix a link in every possible language.
1501 * @deprecated since 1.18
1503 * @param string $key Lookup key for the message, usually
1504 * defined in languages/Language.php
1507 function wfMsgForContent( $key ) {
1508 wfDeprecated( __METHOD__
, '1.21' );
1510 global $wgForceUIMsgAsContentMsg;
1511 $args = func_get_args();
1512 array_shift( $args );
1514 if ( is_array( $wgForceUIMsgAsContentMsg )
1515 && in_array( $key, $wgForceUIMsgAsContentMsg )
1517 $forcontent = false;
1519 return wfMsgReal( $key, $args, true, $forcontent );
1523 * Same as above except doesn't transform the message
1525 * @deprecated since 1.18
1527 * @param string $key
1530 function wfMsgForContentNoTrans( $key ) {
1531 wfDeprecated( __METHOD__
, '1.21' );
1533 global $wgForceUIMsgAsContentMsg;
1534 $args = func_get_args();
1535 array_shift( $args );
1537 if ( is_array( $wgForceUIMsgAsContentMsg )
1538 && in_array( $key, $wgForceUIMsgAsContentMsg )
1540 $forcontent = false;
1542 return wfMsgReal( $key, $args, true, $forcontent, false );
1546 * Really get a message
1548 * @deprecated since 1.18
1550 * @param string $key Key to get.
1551 * @param array $args
1552 * @param bool $useDB
1553 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1554 * @param bool $transform Whether or not to transform the message.
1555 * @return string The requested message.
1557 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1558 wfDeprecated( __METHOD__
, '1.21' );
1560 wfProfileIn( __METHOD__
);
1561 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1562 $message = wfMsgReplaceArgs( $message, $args );
1563 wfProfileOut( __METHOD__
);
1568 * Fetch a message string value, but don't replace any keys yet.
1570 * @deprecated since 1.18
1572 * @param string $key
1573 * @param bool $useDB
1574 * @param string|bool $langCode Code of the language to get the message for, or
1575 * behaves as a content language switch if it is a boolean.
1576 * @param bool $transform Whether to parse magic words, etc.
1579 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1580 wfDeprecated( __METHOD__
, '1.21' );
1582 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1584 $cache = MessageCache
::singleton();
1585 $message = $cache->get( $key, $useDB, $langCode );
1586 if ( $message === false ) {
1587 $message = '<' . htmlspecialchars( $key ) . '>';
1588 } elseif ( $transform ) {
1589 $message = $cache->transform( $message );
1595 * Replace message parameter keys on the given formatted output.
1597 * @param string $message
1598 * @param array $args
1602 function wfMsgReplaceArgs( $message, $args ) {
1603 # Fix windows line-endings
1604 # Some messages are split with explode("\n", $msg)
1605 $message = str_replace( "\r", '', $message );
1607 // Replace arguments
1608 if ( count( $args ) ) {
1609 if ( is_array( $args[0] ) ) {
1610 $args = array_values( $args[0] );
1612 $replacementKeys = array();
1613 foreach ( $args as $n => $param ) {
1614 $replacementKeys['$' . ( $n +
1 )] = $param;
1616 $message = strtr( $message, $replacementKeys );
1623 * Return an HTML-escaped version of a message.
1624 * Parameter replacements, if any, are done *after* the HTML-escaping,
1625 * so parameters may contain HTML (eg links or form controls). Be sure
1626 * to pre-escape them if you really do want plaintext, or just wrap
1627 * the whole thing in htmlspecialchars().
1629 * @deprecated since 1.18
1631 * @param string $key
1632 * @param string $args,... Parameters
1635 function wfMsgHtml( $key ) {
1636 wfDeprecated( __METHOD__
, '1.21' );
1638 $args = func_get_args();
1639 array_shift( $args );
1640 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1644 * Return an HTML version of message
1645 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1646 * so parameters may contain HTML (eg links or form controls). Be sure
1647 * to pre-escape them if you really do want plaintext, or just wrap
1648 * the whole thing in htmlspecialchars().
1650 * @deprecated since 1.18
1652 * @param string $key
1653 * @param string $args,... Parameters
1656 function wfMsgWikiHtml( $key ) {
1657 wfDeprecated( __METHOD__
, '1.21' );
1659 $args = func_get_args();
1660 array_shift( $args );
1661 return wfMsgReplaceArgs(
1662 MessageCache
::singleton()->parse( wfMsgGetKey( $key ), null,
1663 /* can't be set to false */ true, /* interface */ true )->getText(),
1668 * Returns message in the requested format
1670 * @deprecated since 1.18
1672 * @param string $key Key of the message
1673 * @param array $options Processing rules.
1674 * Can take the following options:
1675 * parse: parses wikitext to HTML
1676 * parseinline: parses wikitext to HTML and removes the surrounding
1677 * p's added by parser or tidy
1678 * escape: filters message through htmlspecialchars
1679 * escapenoentities: same, but allows entity references like   through
1680 * replaceafter: parameters are substituted after parsing or escaping
1681 * parsemag: transform the message using magic phrases
1682 * content: fetch message for content language instead of interface
1683 * Also can accept a single associative argument, of the form 'language' => 'xx':
1684 * language: Language object or language code to fetch message for
1685 * (overridden by content).
1686 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1690 function wfMsgExt( $key, $options ) {
1691 wfDeprecated( __METHOD__
, '1.21' );
1693 $args = func_get_args();
1694 array_shift( $args );
1695 array_shift( $args );
1696 $options = (array)$options;
1698 foreach ( $options as $arrayKey => $option ) {
1699 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1700 # An unknown index, neither numeric nor "language"
1701 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING
);
1702 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1703 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1704 'replaceafter', 'parsemag', 'content' ) ) ) {
1705 # A numeric index with unknown value
1706 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING
);
1710 if ( in_array( 'content', $options, true ) ) {
1713 $langCodeObj = null;
1714 } elseif ( array_key_exists( 'language', $options ) ) {
1715 $forContent = false;
1716 $langCode = wfGetLangObj( $options['language'] );
1717 $langCodeObj = $langCode;
1719 $forContent = false;
1721 $langCodeObj = null;
1724 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1726 if ( !in_array( 'replaceafter', $options, true ) ) {
1727 $string = wfMsgReplaceArgs( $string, $args );
1730 $messageCache = MessageCache
::singleton();
1731 $parseInline = in_array( 'parseinline', $options, true );
1732 if ( in_array( 'parse', $options, true ) ||
$parseInline ) {
1733 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1734 if ( $string instanceof ParserOutput
) {
1735 $string = $string->getText();
1738 if ( $parseInline ) {
1739 $string = Parser
::stripOuterParagraph( $string );
1741 } elseif ( in_array( 'parsemag', $options, true ) ) {
1742 $string = $messageCache->transform( $string,
1743 !$forContent, $langCodeObj );
1746 if ( in_array( 'escape', $options, true ) ) {
1747 $string = htmlspecialchars ( $string );
1748 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1749 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
1752 if ( in_array( 'replaceafter', $options, true ) ) {
1753 $string = wfMsgReplaceArgs( $string, $args );
1760 * Since wfMsg() and co suck, they don't return false if the message key they
1761 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1762 * nonexistence of messages by checking the MessageCache::get() result directly.
1764 * @deprecated since 1.18. Use Message::isDisabled().
1766 * @param string $key The message key looked up
1767 * @return bool True if the message *doesn't* exist.
1769 function wfEmptyMsg( $key ) {
1770 wfDeprecated( __METHOD__
, '1.21' );
1772 return MessageCache
::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1776 * Fetch server name for use in error reporting etc.
1777 * Use real server name if available, so we know which machine
1778 * in a server farm generated the current page.
1782 function wfHostname() {
1784 if ( is_null( $host ) ) {
1786 # Hostname overriding
1787 global $wgOverrideHostname;
1788 if ( $wgOverrideHostname !== false ) {
1789 # Set static and skip any detection
1790 $host = $wgOverrideHostname;
1794 if ( function_exists( 'posix_uname' ) ) {
1795 // This function not present on Windows
1796 $uname = posix_uname();
1800 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1801 $host = $uname['nodename'];
1802 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1803 # Windows computer name
1804 $host = getenv( 'COMPUTERNAME' );
1806 # This may be a virtual server.
1807 $host = $_SERVER['SERVER_NAME'];
1814 * Returns a script tag that stores the amount of time it took MediaWiki to
1815 * handle the request in milliseconds as 'wgBackendResponseTime'.
1817 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1818 * hostname of the server handling the request.
1822 function wfReportTime() {
1823 global $wgRequestTime, $wgShowHostnames;
1825 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1826 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1827 if ( $wgShowHostnames ) {
1828 $reportVars['wgHostname'] = wfHostname();
1830 return Skin
::makeVariablesScript( $reportVars );
1834 * Safety wrapper for debug_backtrace().
1836 * Will return an empty array if debug_backtrace is disabled, otherwise
1837 * the output from debug_backtrace() (trimmed).
1839 * @param int $limit This parameter can be used to limit the number of stack frames returned
1841 * @return array Array of backtrace information
1843 function wfDebugBacktrace( $limit = 0 ) {
1844 static $disabled = null;
1846 if ( is_null( $disabled ) ) {
1847 $disabled = !function_exists( 'debug_backtrace' );
1849 wfDebug( "debug_backtrace() is disabled\n" );
1856 if ( $limit && version_compare( PHP_VERSION
, '5.4.0', '>=' ) ) {
1857 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT
, $limit +
1 ), 1 );
1859 return array_slice( debug_backtrace(), 1 );
1864 * Get a debug backtrace as a string
1868 function wfBacktrace() {
1869 global $wgCommandLineMode;
1871 if ( $wgCommandLineMode ) {
1876 $backtrace = wfDebugBacktrace();
1877 foreach ( $backtrace as $call ) {
1878 if ( isset( $call['file'] ) ) {
1879 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
1880 $file = $f[count( $f ) - 1];
1884 if ( isset( $call['line'] ) ) {
1885 $line = $call['line'];
1889 if ( $wgCommandLineMode ) {
1890 $msg .= "$file line $line calls ";
1892 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1894 if ( !empty( $call['class'] ) ) {
1895 $msg .= $call['class'] . $call['type'];
1897 $msg .= $call['function'] . '()';
1899 if ( $wgCommandLineMode ) {
1905 if ( $wgCommandLineMode ) {
1915 * Get the name of the function which called this function
1916 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1917 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1918 * wfGetCaller( 3 ) is the parent of that.
1923 function wfGetCaller( $level = 2 ) {
1924 $backtrace = wfDebugBacktrace( $level +
1 );
1925 if ( isset( $backtrace[$level] ) ) {
1926 return wfFormatStackFrame( $backtrace[$level] );
1933 * Return a string consisting of callers in the stack. Useful sometimes
1934 * for profiling specific points.
1936 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1939 function wfGetAllCallers( $limit = 3 ) {
1940 $trace = array_reverse( wfDebugBacktrace() );
1941 if ( !$limit ||
$limit > count( $trace ) - 1 ) {
1942 $limit = count( $trace ) - 1;
1944 $trace = array_slice( $trace, -$limit - 1, $limit );
1945 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1949 * Return a string representation of frame
1951 * @param array $frame
1954 function wfFormatStackFrame( $frame ) {
1955 return isset( $frame['class'] ) ?
1956 $frame['class'] . '::' . $frame['function'] :
1960 /* Some generic result counters, pulled out of SearchEngine */
1965 * @param int $offset
1969 function wfShowingResults( $offset, $limit ) {
1970 return wfMessage( 'showingresults' )->numParams( $limit, $offset +
1 )->parse();
1975 * @todo FIXME: We may want to blacklist some broken browsers
1977 * @param bool $force
1978 * @return bool Whereas client accept gzip compression
1980 function wfClientAcceptsGzip( $force = false ) {
1981 static $result = null;
1982 if ( $result === null ||
$force ) {
1984 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1985 # @todo FIXME: We may want to blacklist some broken browsers
1988 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1989 $_SERVER['HTTP_ACCEPT_ENCODING'],
1993 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1997 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2006 * Obtain the offset and limit values from the request string;
2007 * used in special pages
2009 * @param int $deflimit Default limit if none supplied
2010 * @param string $optionname Name of a user preference to check against
2012 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2014 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2016 wfDeprecated( __METHOD__
, '1.24' );
2017 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2021 * Escapes the given text so that it may be output using addWikiText()
2022 * without any linking, formatting, etc. making its way through. This
2023 * is achieved by substituting certain characters with HTML entities.
2024 * As required by the callers, "<nowiki>" is not used.
2026 * @param string $text Text to be escaped
2029 function wfEscapeWikiText( $text ) {
2030 static $repl = null, $repl2 = null;
2031 if ( $repl === null ) {
2033 '"' => '"', '&' => '&', "'" => ''', '<' => '<',
2034 '=' => '=', '>' => '>', '[' => '[', ']' => ']',
2035 '{' => '{', '|' => '|', '}' => '}', ';' => ';',
2036 "\n#" => "\n#", "\r#" => "\r#",
2037 "\n*" => "\n*", "\r*" => "\r*",
2038 "\n:" => "\n:", "\r:" => "\r:",
2039 "\n " => "\n ", "\r " => "\r ",
2040 "\n\n" => "\n ", "\r\n" => " \n",
2041 "\n\r" => "\n ", "\r\r" => "\r ",
2042 "\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
2043 "\n----" => "\n----", "\r----" => "\r----",
2044 '__' => '__', '://' => '://',
2047 // We have to catch everything "\s" matches in PCRE
2048 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2049 $repl["$magic "] = "$magic ";
2050 $repl["$magic\t"] = "$magic	";
2051 $repl["$magic\r"] = "$magic ";
2052 $repl["$magic\n"] = "$magic ";
2053 $repl["$magic\f"] = "$magic";
2056 // And handle protocols that don't use "://"
2057 global $wgUrlProtocols;
2059 foreach ( $wgUrlProtocols as $prot ) {
2060 if ( substr( $prot, -1 ) === ':' ) {
2061 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2064 $repl2 = $repl2 ?
'/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2066 $text = substr( strtr( "\n$text", $repl ), 1 );
2067 $text = preg_replace( $repl2, '$1:', $text );
2072 * Sets dest to source and returns the original value of dest
2073 * If source is NULL, it just returns the value, it doesn't set the variable
2074 * If force is true, it will set the value even if source is NULL
2076 * @param mixed $dest
2077 * @param mixed $source
2078 * @param bool $force
2081 function wfSetVar( &$dest, $source, $force = false ) {
2083 if ( !is_null( $source ) ||
$force ) {
2090 * As for wfSetVar except setting a bit
2094 * @param bool $state
2098 function wfSetBit( &$dest, $bit, $state = true ) {
2099 $temp = (bool)( $dest & $bit );
2100 if ( !is_null( $state ) ) {
2111 * A wrapper around the PHP function var_export().
2112 * Either print it or add it to the regular output ($wgOut).
2114 * @param mixed $var A PHP variable to dump.
2116 function wfVarDump( $var ) {
2118 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2119 if ( headers_sent() ||
!isset( $wgOut ) ||
!is_object( $wgOut ) ) {
2122 $wgOut->addHTML( $s );
2127 * Provide a simple HTTP error.
2129 * @param int|string $code
2130 * @param string $label
2131 * @param string $desc
2133 function wfHttpError( $code, $label, $desc ) {
2136 header( "HTTP/1.0 $code $label" );
2137 header( "Status: $code $label" );
2138 $wgOut->sendCacheControl();
2140 header( 'Content-type: text/html; charset=utf-8' );
2141 print "<!doctype html>" .
2142 '<html><head><title>' .
2143 htmlspecialchars( $label ) .
2144 '</title></head><body><h1>' .
2145 htmlspecialchars( $label ) .
2147 nl2br( htmlspecialchars( $desc ) ) .
2148 "</p></body></html>\n";
2152 * Clear away any user-level output buffers, discarding contents.
2154 * Suitable for 'starting afresh', for instance when streaming
2155 * relatively large amounts of data without buffering, or wanting to
2156 * output image files without ob_gzhandler's compression.
2158 * The optional $resetGzipEncoding parameter controls suppression of
2159 * the Content-Encoding header sent by ob_gzhandler; by default it
2160 * is left. See comments for wfClearOutputBuffers() for why it would
2163 * Note that some PHP configuration options may add output buffer
2164 * layers which cannot be removed; these are left in place.
2166 * @param bool $resetGzipEncoding
2168 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2169 if ( $resetGzipEncoding ) {
2170 // Suppress Content-Encoding and Content-Length
2171 // headers from 1.10+s wfOutputHandler
2172 global $wgDisableOutputCompression;
2173 $wgDisableOutputCompression = true;
2175 while ( $status = ob_get_status() ) {
2176 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2177 // Probably from zlib.output_compression or other
2178 // PHP-internal setting which can't be removed.
2180 // Give up, and hope the result doesn't break
2184 if ( !ob_end_clean() ) {
2185 // Could not remove output buffer handler; abort now
2186 // to avoid getting in some kind of infinite loop.
2189 if ( $resetGzipEncoding ) {
2190 if ( $status['name'] == 'ob_gzhandler' ) {
2191 // Reset the 'Content-Encoding' field set by this handler
2192 // so we can start fresh.
2193 header_remove( 'Content-Encoding' );
2201 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2203 * Clear away output buffers, but keep the Content-Encoding header
2204 * produced by ob_gzhandler, if any.
2206 * This should be used for HTTP 304 responses, where you need to
2207 * preserve the Content-Encoding header of the real result, but
2208 * also need to suppress the output of ob_gzhandler to keep to spec
2209 * and avoid breaking Firefox in rare cases where the headers and
2210 * body are broken over two packets.
2212 function wfClearOutputBuffers() {
2213 wfResetOutputBuffers( false );
2217 * Converts an Accept-* header into an array mapping string values to quality
2220 * @param string $accept
2221 * @param string $def Default
2222 * @return float[] Associative array of string => float pairs
2224 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2225 # No arg means accept anything (per HTTP spec)
2227 return array( $def => 1.0 );
2232 $parts = explode( ',', $accept );
2234 foreach ( $parts as $part ) {
2235 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2236 $values = explode( ';', trim( $part ) );
2238 if ( count( $values ) == 1 ) {
2239 $prefs[$values[0]] = 1.0;
2240 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2241 $prefs[$values[0]] = floatval( $match[1] );
2249 * Checks if a given MIME type matches any of the keys in the given
2250 * array. Basic wildcards are accepted in the array keys.
2252 * Returns the matching MIME type (or wildcard) if a match, otherwise
2255 * @param string $type
2256 * @param array $avail
2260 function mimeTypeMatch( $type, $avail ) {
2261 if ( array_key_exists( $type, $avail ) ) {
2264 $parts = explode( '/', $type );
2265 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2266 return $parts[0] . '/*';
2267 } elseif ( array_key_exists( '*/*', $avail ) ) {
2276 * Returns the 'best' match between a client's requested internet media types
2277 * and the server's list of available types. Each list should be an associative
2278 * array of type to preference (preference is a float between 0.0 and 1.0).
2279 * Wildcards in the types are acceptable.
2281 * @param array $cprefs Client's acceptable type list
2282 * @param array $sprefs Server's offered types
2285 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2286 * XXX: generalize to negotiate other stuff
2288 function wfNegotiateType( $cprefs, $sprefs ) {
2291 foreach ( array_keys( $sprefs ) as $type ) {
2292 $parts = explode( '/', $type );
2293 if ( $parts[1] != '*' ) {
2294 $ckey = mimeTypeMatch( $type, $cprefs );
2296 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2301 foreach ( array_keys( $cprefs ) as $type ) {
2302 $parts = explode( '/', $type );
2303 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2304 $skey = mimeTypeMatch( $type, $sprefs );
2306 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2314 foreach ( array_keys( $combine ) as $type ) {
2315 if ( $combine[$type] > $bestq ) {
2317 $bestq = $combine[$type];
2325 * Reference-counted warning suppression
2329 function wfSuppressWarnings( $end = false ) {
2330 static $suppressCount = 0;
2331 static $originalLevel = false;
2334 if ( $suppressCount ) {
2336 if ( !$suppressCount ) {
2337 error_reporting( $originalLevel );
2341 if ( !$suppressCount ) {
2342 $originalLevel = error_reporting( E_ALL
& ~
(
2357 * Restore error level to previous value
2359 function wfRestoreWarnings() {
2360 wfSuppressWarnings( true );
2363 # Autodetect, convert and provide timestamps of various types
2366 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2368 define( 'TS_UNIX', 0 );
2371 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2373 define( 'TS_MW', 1 );
2376 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2378 define( 'TS_DB', 2 );
2381 * RFC 2822 format, for E-mail and HTTP headers
2383 define( 'TS_RFC2822', 3 );
2386 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2388 * This is used by Special:Export
2390 define( 'TS_ISO_8601', 4 );
2393 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2395 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2396 * DateTime tag and page 36 for the DateTimeOriginal and
2397 * DateTimeDigitized tags.
2399 define( 'TS_EXIF', 5 );
2402 * Oracle format time.
2404 define( 'TS_ORACLE', 6 );
2407 * Postgres format time.
2409 define( 'TS_POSTGRES', 7 );
2412 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2414 define( 'TS_ISO_8601_BASIC', 9 );
2417 * Get a timestamp string in one of various formats
2419 * @param mixed $outputtype A timestamp in one of the supported formats, the
2420 * function will autodetect which format is supplied and act accordingly.
2421 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2422 * @return string|bool String / false The same date in the format specified in $outputtype or false
2424 function wfTimestamp( $outputtype = TS_UNIX
, $ts = 0 ) {
2426 $timestamp = new MWTimestamp( $ts );
2427 return $timestamp->getTimestamp( $outputtype );
2428 } catch ( TimestampException
$e ) {
2429 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2435 * Return a formatted timestamp, or null if input is null.
2436 * For dealing with nullable timestamp columns in the database.
2438 * @param int $outputtype
2442 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
2443 if ( is_null( $ts ) ) {
2446 return wfTimestamp( $outputtype, $ts );
2451 * Convenience function; returns MediaWiki timestamp for the present time.
2455 function wfTimestampNow() {
2457 return wfTimestamp( TS_MW
, time() );
2461 * Check if the operating system is Windows
2463 * @return bool True if it's Windows, false otherwise.
2465 function wfIsWindows() {
2466 static $isWindows = null;
2467 if ( $isWindows === null ) {
2468 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2474 * Check if we are running under HHVM
2478 function wfIsHHVM() {
2479 return defined( 'HHVM_VERSION' );
2483 * Swap two variables
2485 * @deprecated since 1.24
2489 function swap( &$x, &$y ) {
2490 wfDeprecated( __FUNCTION__
, '1.24' );
2497 * Tries to get the system directory for temporary files. First
2498 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2499 * environment variables are then checked in sequence, and if none are
2500 * set try sys_get_temp_dir().
2502 * NOTE: When possible, use instead the tmpfile() function to create
2503 * temporary files to avoid race conditions on file creation, etc.
2507 function wfTempDir() {
2508 global $wgTmpDirectory;
2510 if ( $wgTmpDirectory !== false ) {
2511 return $wgTmpDirectory;
2514 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2516 foreach ( $tmpDir as $tmp ) {
2517 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2521 return sys_get_temp_dir();
2525 * Make directory, and make all parent directories if they don't exist
2527 * @param string $dir Full path to directory to create
2528 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2529 * @param string $caller Optional caller param for debugging.
2530 * @throws MWException
2533 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2534 global $wgDirectoryMode;
2536 if ( FileBackend
::isStoragePath( $dir ) ) { // sanity
2537 throw new MWException( __FUNCTION__
. " given storage path '$dir'." );
2540 if ( !is_null( $caller ) ) {
2541 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2544 if ( strval( $dir ) === '' ||
( file_exists( $dir ) && is_dir( $dir ) ) ) {
2548 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR
, $dir );
2550 if ( is_null( $mode ) ) {
2551 $mode = $wgDirectoryMode;
2554 // Turn off the normal warning, we're doing our own below
2555 wfSuppressWarnings();
2556 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2557 wfRestoreWarnings();
2560 //directory may have been created on another request since we last checked
2561 if ( is_dir( $dir ) ) {
2565 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2566 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2572 * Remove a directory and all its content.
2573 * Does not hide error.
2574 * @param string $dir
2576 function wfRecursiveRemoveDir( $dir ) {
2577 wfDebug( __FUNCTION__
. "( $dir )\n" );
2578 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2579 if ( is_dir( $dir ) ) {
2580 $objects = scandir( $dir );
2581 foreach ( $objects as $object ) {
2582 if ( $object != "." && $object != ".." ) {
2583 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2584 wfRecursiveRemoveDir( $dir . '/' . $object );
2586 unlink( $dir . '/' . $object );
2596 * @param int $nr The number to format
2597 * @param int $acc The number of digits after the decimal point, default 2
2598 * @param bool $round Whether or not to round the value, default true
2601 function wfPercent( $nr, $acc = 2, $round = true ) {
2602 $ret = sprintf( "%.${acc}f", $nr );
2603 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2607 * Safety wrapper around ini_get() for boolean settings.
2608 * The values returned from ini_get() are pre-normalized for settings
2609 * set via php.ini or php_flag/php_admin_flag... but *not*
2610 * for those set via php_value/php_admin_value.
2612 * It's fairly common for people to use php_value instead of php_flag,
2613 * which can leave you with an 'off' setting giving a false positive
2614 * for code that just takes the ini_get() return value as a boolean.
2616 * To make things extra interesting, setting via php_value accepts
2617 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2618 * Unrecognized values go false... again opposite PHP's own coercion
2619 * from string to bool.
2621 * Luckily, 'properly' set settings will always come back as '0' or '1',
2622 * so we only have to worry about them and the 'improper' settings.
2624 * I frickin' hate PHP... :P
2626 * @param string $setting
2629 function wfIniGetBool( $setting ) {
2630 $val = strtolower( ini_get( $setting ) );
2631 // 'on' and 'true' can't have whitespace around them, but '1' can.
2635 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2639 * Windows-compatible version of escapeshellarg()
2640 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2641 * function puts single quotes in regardless of OS.
2643 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2644 * earlier distro releases of PHP)
2646 * @param string $args,...
2649 function wfEscapeShellArg( /*...*/ ) {
2650 wfInitShellLocale();
2652 $args = func_get_args();
2655 foreach ( $args as $arg ) {
2662 if ( wfIsWindows() ) {
2663 // Escaping for an MSVC-style command line parser and CMD.EXE
2664 // @codingStandardsIgnoreStart For long URLs
2666 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2667 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2670 // Double the backslashes before any double quotes. Escape the double quotes.
2671 // @codingStandardsIgnoreEnd
2672 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
2675 foreach ( $tokens as $token ) {
2676 if ( $iteration %
2 == 1 ) {
2677 // Delimiter, a double quote preceded by zero or more slashes
2678 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2679 } elseif ( $iteration %
4 == 2 ) {
2680 // ^ in $token will be outside quotes, need to be escaped
2681 $arg .= str_replace( '^', '^^', $token );
2682 } else { // $iteration % 4 == 0
2683 // ^ in $token will appear inside double quotes, so leave as is
2688 // Double the backslashes before the end of the string, because
2689 // we will soon add a quote
2691 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2692 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2695 // Add surrounding quotes
2696 $retVal .= '"' . $arg . '"';
2698 $retVal .= escapeshellarg( $arg );
2705 * Check if wfShellExec() is effectively disabled via php.ini config
2707 * @return bool|string False or one of (safemode,disabled)
2710 function wfShellExecDisabled() {
2711 static $disabled = null;
2712 if ( is_null( $disabled ) ) {
2713 if ( wfIniGetBool( 'safe_mode' ) ) {
2714 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2715 $disabled = 'safemode';
2716 } elseif ( !function_exists( 'proc_open' ) ) {
2717 wfDebug( "proc_open() is disabled\n" );
2718 $disabled = 'disabled';
2727 * Execute a shell command, with time and memory limits mirrored from the PHP
2728 * configuration if supported.
2730 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2731 * or an array of unescaped arguments, in which case each value will be escaped
2732 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2733 * @param null|mixed &$retval Optional, will receive the program's exit code.
2734 * (non-zero is usually failure). If there is an error from
2735 * read, select, or proc_open(), this will be set to -1.
2736 * @param array $environ Optional environment variables which should be
2737 * added to the executed command environment.
2738 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2739 * this overwrites the global wgMaxShell* limits.
2740 * @param array $options Array of options:
2741 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2742 * including errors from limit.sh
2744 * @return string Collected stdout as a string
2746 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2747 $limits = array(), $options = array()
2749 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2750 $wgMaxShellWallClockTime, $wgShellCgroup;
2752 $disabled = wfShellExecDisabled();
2755 return $disabled == 'safemode' ?
2756 'Unable to run external programs in safe mode.' :
2757 'Unable to run external programs, proc_open() is disabled.';
2760 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2762 wfInitShellLocale();
2765 foreach ( $environ as $k => $v ) {
2766 if ( wfIsWindows() ) {
2767 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2768 * appear in the environment variable, so we must use carat escaping as documented in
2769 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2770 * Note however that the quote isn't listed there, but is needed, and the parentheses
2771 * are listed there but doesn't appear to need it.
2773 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2775 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2776 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2778 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2781 if ( is_array( $cmd ) ) {
2782 // Command line may be given as an array, escape each value and glue them together with a space
2784 foreach ( $cmd as $val ) {
2785 $cmdVals[] = wfEscapeShellArg( $val );
2787 $cmd = implode( ' ', $cmdVals );
2790 $cmd = $envcmd . $cmd;
2792 $useLogPipe = false;
2793 if ( is_executable( '/bin/bash' ) ) {
2794 $time = intval ( isset( $limits['time'] ) ?
$limits['time'] : $wgMaxShellTime );
2795 if ( isset( $limits['walltime'] ) ) {
2796 $wallTime = intval( $limits['walltime'] );
2797 } elseif ( isset( $limits['time'] ) ) {
2800 $wallTime = intval( $wgMaxShellWallClockTime );
2802 $mem = intval ( isset( $limits['memory'] ) ?
$limits['memory'] : $wgMaxShellMemory );
2803 $filesize = intval ( isset( $limits['filesize'] ) ?
$limits['filesize'] : $wgMaxShellFileSize );
2805 if ( $time > 0 ||
$mem > 0 ||
$filesize > 0 ||
$wallTime > 0 ) {
2806 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2807 escapeshellarg( $cmd ) . ' ' .
2809 "MW_INCLUDE_STDERR=" . ( $includeStderr ?
'1' : '' ) . ';' .
2810 "MW_CPU_LIMIT=$time; " .
2811 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2812 "MW_MEM_LIMIT=$mem; " .
2813 "MW_FILE_SIZE_LIMIT=$filesize; " .
2814 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2815 "MW_USE_LOG_PIPE=yes"
2818 } elseif ( $includeStderr ) {
2821 } elseif ( $includeStderr ) {
2824 wfDebug( "wfShellExec: $cmd\n" );
2827 0 => array( 'file', 'php://stdin', 'r' ),
2828 1 => array( 'pipe', 'w' ),
2829 2 => array( 'file', 'php://stderr', 'w' ) );
2830 if ( $useLogPipe ) {
2831 $desc[3] = array( 'pipe', 'w' );
2834 $proc = proc_open( $cmd, $desc, $pipes );
2836 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2840 $outBuffer = $logBuffer = '';
2841 $emptyArray = array();
2845 // According to the documentation, it is possible for stream_select()
2846 // to fail due to EINTR. I haven't managed to induce this in testing
2847 // despite sending various signals. If it did happen, the error
2848 // message would take the form:
2850 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2852 // where [4] is the value of the macro EINTR and "Interrupted system
2853 // call" is string which according to the Linux manual is "possibly"
2854 // localised according to LC_MESSAGES.
2855 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR
: 4;
2856 $eintrMessage = "stream_select(): unable to select [$eintr]";
2858 // Build a table mapping resource IDs to pipe FDs to work around a
2859 // PHP 5.3 issue in which stream_select() does not preserve array keys
2860 // <https://bugs.php.net/bug.php?id=53427>.
2862 foreach ( $pipes as $fd => $pipe ) {
2863 $fds[(int)$pipe] = $fd;
2870 while ( $running === true ||
$numReadyPipes !== 0 ) {
2872 $status = proc_get_status( $proc );
2873 // If the process has terminated, switch to nonblocking selects
2874 // for getting any data still waiting to be read.
2875 if ( !$status['running'] ) {
2881 $readyPipes = $pipes;
2884 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2885 @trigger_error
( '' );
2886 $numReadyPipes = @stream_select
( $readyPipes, $emptyArray, $emptyArray, $timeout );
2887 if ( $numReadyPipes === false ) {
2888 // @codingStandardsIgnoreEnd
2889 $error = error_get_last();
2890 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2893 trigger_error( $error['message'], E_USER_WARNING
);
2894 $logMsg = $error['message'];
2898 foreach ( $readyPipes as $pipe ) {
2899 $block = fread( $pipe, 65536 );
2900 $fd = $fds[(int)$pipe];
2901 if ( $block === '' ) {
2903 fclose( $pipes[$fd] );
2904 unset( $pipes[$fd] );
2908 } elseif ( $block === false ) {
2910 $logMsg = "Error reading from pipe";
2912 } elseif ( $fd == 1 ) {
2914 $outBuffer .= $block;
2915 } elseif ( $fd == 3 ) {
2917 $logBuffer .= $block;
2918 if ( strpos( $block, "\n" ) !== false ) {
2919 $lines = explode( "\n", $logBuffer );
2920 $logBuffer = array_pop( $lines );
2921 foreach ( $lines as $line ) {
2922 wfDebugLog( 'exec', $line );
2929 foreach ( $pipes as $pipe ) {
2933 // Use the status previously collected if possible, since proc_get_status()
2934 // just calls waitpid() which will not return anything useful the second time.
2936 $status = proc_get_status( $proc );
2939 if ( $logMsg !== false ) {
2940 // Read/select error
2942 proc_close( $proc );
2943 } elseif ( $status['signaled'] ) {
2944 $logMsg = "Exited with signal {$status['termsig']}";
2945 $retval = 128 +
$status['termsig'];
2946 proc_close( $proc );
2948 if ( $status['running'] ) {
2949 $retval = proc_close( $proc );
2951 $retval = $status['exitcode'];
2952 proc_close( $proc );
2954 if ( $retval == 127 ) {
2955 $logMsg = "Possibly missing executable file";
2956 } elseif ( $retval >= 129 && $retval <= 192 ) {
2957 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2961 if ( $logMsg !== false ) {
2962 wfDebugLog( 'exec', "$logMsg: $cmd" );
2969 * Execute a shell command, returning both stdout and stderr. Convenience
2970 * function, as all the arguments to wfShellExec can become unwieldy.
2972 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2973 * @param string $cmd Command line, properly escaped for shell.
2974 * @param null|mixed &$retval Optional, will receive the program's exit code.
2975 * (non-zero is usually failure)
2976 * @param array $environ Optional environment variables which should be
2977 * added to the executed command environment.
2978 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2979 * this overwrites the global wgMaxShell* limits.
2980 * @return string Collected stdout and stderr as a string
2982 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2983 return wfShellExec( $cmd, $retval, $environ, $limits, array( 'duplicateStderr' => true ) );
2987 * Workaround for http://bugs.php.net/bug.php?id=45132
2988 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2990 function wfInitShellLocale() {
2991 static $done = false;
2996 global $wgShellLocale;
2997 if ( !wfIniGetBool( 'safe_mode' ) ) {
2998 putenv( "LC_CTYPE=$wgShellLocale" );
2999 setlocale( LC_CTYPE
, $wgShellLocale );
3004 * Alias to wfShellWikiCmd()
3006 * @see wfShellWikiCmd()
3008 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
3009 return wfShellWikiCmd( $script, $parameters, $options );
3013 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3014 * Note that $parameters should be a flat array and an option with an argument
3015 * should consist of two consecutive items in the array (do not use "--option value").
3017 * @param string $script MediaWiki cli script path
3018 * @param array $parameters Arguments and options to the script
3019 * @param array $options Associative array of options:
3020 * 'php': The path to the php executable
3021 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3024 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3026 // Give site config file a chance to run the script in a wrapper.
3027 // The caller may likely want to call wfBasename() on $script.
3028 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3029 $cmd = isset( $options['php'] ) ?
array( $options['php'] ) : array( $wgPhpCli );
3030 if ( isset( $options['wrapper'] ) ) {
3031 $cmd[] = $options['wrapper'];
3034 // Escape each parameter for shell
3035 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
3039 * wfMerge attempts to merge differences between three texts.
3040 * Returns true for a clean merge and false for failure or a conflict.
3042 * @param string $old
3043 * @param string $mine
3044 * @param string $yours
3045 * @param string $result
3048 function wfMerge( $old, $mine, $yours, &$result ) {
3051 # This check may also protect against code injection in
3052 # case of broken installations.
3053 wfSuppressWarnings();
3054 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3055 wfRestoreWarnings();
3057 if ( !$haveDiff3 ) {
3058 wfDebug( "diff3 not found\n" );
3062 # Make temporary files
3064 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3065 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3066 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3068 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3069 # a newline character. To avoid this, we normalize the trailing whitespace before
3070 # creating the diff.
3072 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3073 fclose( $oldtextFile );
3074 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3075 fclose( $mytextFile );
3076 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3077 fclose( $yourtextFile );
3079 # Check for a conflict
3080 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
3081 wfEscapeShellArg( $mytextName ) . ' ' .
3082 wfEscapeShellArg( $oldtextName ) . ' ' .
3083 wfEscapeShellArg( $yourtextName );
3084 $handle = popen( $cmd, 'r' );
3086 if ( fgets( $handle, 1024 ) ) {
3094 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
3095 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
3096 $handle = popen( $cmd, 'r' );
3099 $data = fread( $handle, 8192 );
3100 if ( strlen( $data ) == 0 ) {
3106 unlink( $mytextName );
3107 unlink( $oldtextName );
3108 unlink( $yourtextName );
3110 if ( $result === '' && $old !== '' && !$conflict ) {
3111 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3118 * Returns unified plain-text diff of two texts.
3119 * Useful for machine processing of diffs.
3121 * @param string $before The text before the changes.
3122 * @param string $after The text after the changes.
3123 * @param string $params Command-line options for the diff command.
3124 * @return string Unified diff of $before and $after
3126 function wfDiff( $before, $after, $params = '-u' ) {
3127 if ( $before == $after ) {
3132 wfSuppressWarnings();
3133 $haveDiff = $wgDiff && file_exists( $wgDiff );
3134 wfRestoreWarnings();
3136 # This check may also protect against code injection in
3137 # case of broken installations.
3139 wfDebug( "diff executable not found\n" );
3140 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3141 $format = new UnifiedDiffFormatter();
3142 return $format->format( $diffs );
3145 # Make temporary files
3147 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3148 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3150 fwrite( $oldtextFile, $before );
3151 fclose( $oldtextFile );
3152 fwrite( $newtextFile, $after );
3153 fclose( $newtextFile );
3155 // Get the diff of the two files
3156 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3158 $h = popen( $cmd, 'r' );
3163 $data = fread( $h, 8192 );
3164 if ( strlen( $data ) == 0 ) {
3172 unlink( $oldtextName );
3173 unlink( $newtextName );
3175 // Kill the --- and +++ lines. They're not useful.
3176 $diff_lines = explode( "\n", $diff );
3177 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
3178 unset( $diff_lines[0] );
3180 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
3181 unset( $diff_lines[1] );
3184 $diff = implode( "\n", $diff_lines );
3190 * This function works like "use VERSION" in Perl, the program will die with a
3191 * backtrace if the current version of PHP is less than the version provided
3193 * This is useful for extensions which due to their nature are not kept in sync
3194 * with releases, and might depend on other versions of PHP than the main code
3196 * Note: PHP might die due to parsing errors in some cases before it ever
3197 * manages to call this function, such is life
3199 * @see perldoc -f use
3201 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3202 * @throws MWException
3204 function wfUsePHP( $req_ver ) {
3205 $php_ver = PHP_VERSION
;
3207 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3208 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3213 * This function works like "use VERSION" in Perl except it checks the version
3214 * of MediaWiki, the program will die with a backtrace if the current version
3215 * of MediaWiki is less than the version provided.
3217 * This is useful for extensions which due to their nature are not kept in sync
3220 * Note: Due to the behavior of PHP's version_compare() which is used in this
3221 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3222 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3223 * targeted version number. For example if you wanted to allow any variation
3224 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3225 * not result in the same comparison due to the internal logic of
3226 * version_compare().
3228 * @see perldoc -f use
3230 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3231 * @throws MWException
3233 function wfUseMW( $req_ver ) {
3236 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3237 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3242 * Return the final portion of a pathname.
3243 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3244 * http://bugs.php.net/bug.php?id=33898
3246 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3247 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3249 * @param string $path
3250 * @param string $suffix String to remove if present
3253 function wfBaseName( $path, $suffix = '' ) {
3254 if ( $suffix == '' ) {
3257 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3261 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3269 * Generate a relative path name to the given file.
3270 * May explode on non-matching case-insensitive paths,
3271 * funky symlinks, etc.
3273 * @param string $path Absolute destination path including target filename
3274 * @param string $from Absolute source path, directory only
3277 function wfRelativePath( $path, $from ) {
3278 // Normalize mixed input on Windows...
3279 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
3280 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
3282 // Trim trailing slashes -- fix for drive root
3283 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
3284 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
3286 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
3287 $against = explode( DIRECTORY_SEPARATOR
, $from );
3289 if ( $pieces[0] !== $against[0] ) {
3290 // Non-matching Windows drive letters?
3291 // Return a full path.
3295 // Trim off common prefix
3296 while ( count( $pieces ) && count( $against )
3297 && $pieces[0] == $against[0] ) {
3298 array_shift( $pieces );
3299 array_shift( $against );
3302 // relative dots to bump us to the parent
3303 while ( count( $against ) ) {
3304 array_unshift( $pieces, '..' );
3305 array_shift( $against );
3308 array_push( $pieces, wfBaseName( $path ) );
3310 return implode( DIRECTORY_SEPARATOR
, $pieces );
3314 * Convert an arbitrarily-long digit string from one numeric base
3315 * to another, optionally zero-padding to a minimum column width.
3317 * Supports base 2 through 36; digit values 10-36 are represented
3318 * as lowercase letters a-z. Input is case-insensitive.
3320 * @param string $input Input number
3321 * @param int $sourceBase Base of the input number
3322 * @param int $destBase Desired base of the output
3323 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3324 * @param bool $lowercase Whether to output in lowercase or uppercase
3325 * @param string $engine Either "gmp", "bcmath", or "php"
3326 * @return string|bool The output number as a string, or false on error
3328 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3329 $lowercase = true, $engine = 'auto'
3331 $input = (string)$input;
3337 $sourceBase != (int)$sourceBase ||
3338 $destBase != (int)$destBase ||
3339 $pad != (int)$pad ||
3341 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3348 static $baseChars = array(
3349 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3350 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3351 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3352 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3353 34 => 'y', 35 => 'z',
3355 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3356 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3357 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3358 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3359 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3360 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3363 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' ||
$engine == 'gmp' ) ) {
3364 $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
3365 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' ||
$engine == 'bcmath' ) ) {
3367 foreach ( str_split( strtolower( $input ) ) as $char ) {
3368 $decimal = bcmul( $decimal, $sourceBase );
3369 $decimal = bcadd( $decimal, $baseChars[$char] );
3372 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3373 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3374 $result .= $baseChars[bcmod( $decimal, $destBase )];
3376 // @codingStandardsIgnoreEnd
3378 $result = strrev( $result );
3380 $inDigits = array();
3381 foreach ( str_split( strtolower( $input ) ) as $char ) {
3382 $inDigits[] = $baseChars[$char];
3385 // Iterate over the input, modulo-ing out an output digit
3386 // at a time until input is gone.
3388 while ( $inDigits ) {
3390 $workDigits = array();
3393 foreach ( $inDigits as $digit ) {
3394 $work *= $sourceBase;
3397 if ( $workDigits ||
$work >= $destBase ) {
3398 $workDigits[] = (int)( $work / $destBase );
3403 // All that division leaves us with a remainder,
3404 // which is conveniently our next output digit.
3405 $result .= $baseChars[$work];
3408 $inDigits = $workDigits;
3411 $result = strrev( $result );
3414 if ( !$lowercase ) {
3415 $result = strtoupper( $result );
3418 return str_pad( $result, $pad, '0', STR_PAD_LEFT
);
3422 * Check if there is sufficient entropy in php's built-in session generation
3424 * @return bool True = there is sufficient entropy
3426 function wfCheckEntropy() {
3428 ( wfIsWindows() && version_compare( PHP_VERSION
, '5.3.3', '>=' ) )
3429 ||
ini_get( 'session.entropy_file' )
3431 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3435 * Override session_id before session startup if php's built-in
3436 * session generation code is not secure.
3438 function wfFixSessionID() {
3439 // If the cookie or session id is already set we already have a session and should abort
3440 if ( isset( $_COOKIE[session_name()] ) ||
session_id() ) {
3444 // PHP's built-in session entropy is enabled if:
3445 // - entropy_file is set or you're on Windows with php 5.3.3+
3446 // - AND entropy_length is > 0
3447 // We treat it as disabled if it doesn't have an entropy length of at least 32
3448 $entropyEnabled = wfCheckEntropy();
3450 // If built-in entropy is not enabled or not sufficient override PHP's
3451 // built in session id generation code
3452 if ( !$entropyEnabled ) {
3453 wfDebug( __METHOD__
. ": PHP's built in entropy is disabled or not sufficient, " .
3454 "overriding session id generation using our cryptrand source.\n" );
3455 session_id( MWCryptRand
::generateHex( 32 ) );
3460 * Reset the session_id
3464 function wfResetSessionID() {
3465 global $wgCookieSecure;
3466 $oldSessionId = session_id();
3467 $cookieParams = session_get_cookie_params();
3468 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3469 session_regenerate_id( false );
3473 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
3476 $newSessionId = session_id();
3477 wfRunHooks( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3481 * Initialise php session
3483 * @param bool $sessionId
3485 function wfSetupSession( $sessionId = false ) {
3486 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3487 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3488 if ( $wgSessionsInObjectCache ||
$wgSessionsInMemcached ) {
3489 ObjectCacheSessionHandler
::install();
3490 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3491 # Only set this if $wgSessionHandler isn't null and session.save_handler
3492 # hasn't already been set to the desired value (that causes errors)
3493 ini_set( 'session.save_handler', $wgSessionHandler );
3495 session_set_cookie_params(
3496 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3497 session_cache_limiter( 'private, must-revalidate' );
3499 session_id( $sessionId );
3503 wfSuppressWarnings();
3505 wfRestoreWarnings();
3509 * Get an object from the precompiled serialized directory
3511 * @param string $name
3512 * @return mixed The variable on success, false on failure
3514 function wfGetPrecompiledData( $name ) {
3517 $file = "$IP/serialized/$name";
3518 if ( file_exists( $file ) ) {
3519 $blob = file_get_contents( $file );
3521 return unserialize( $blob );
3530 * @param string $args,...
3533 function wfMemcKey( /*...*/ ) {
3534 global $wgCachePrefix;
3535 $prefix = $wgCachePrefix === false ?
wfWikiID() : $wgCachePrefix;
3536 $args = func_get_args();
3537 $key = $prefix . ':' . implode( ':', $args );
3538 $key = str_replace( ' ', '_', $key );
3543 * Get a cache key for a foreign DB
3546 * @param string $prefix
3547 * @param string $args,...
3550 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3551 $args = array_slice( func_get_args(), 2 );
3553 $key = "$db-$prefix:" . implode( ':', $args );
3555 $key = $db . ':' . implode( ':', $args );
3557 return str_replace( ' ', '_', $key );
3561 * Get an ASCII string identifying this wiki
3562 * This is used as a prefix in memcached keys
3566 function wfWikiID() {
3567 global $wgDBprefix, $wgDBname;
3568 if ( $wgDBprefix ) {
3569 return "$wgDBname-$wgDBprefix";
3576 * Split a wiki ID into DB name and table prefix
3578 * @param string $wiki
3582 function wfSplitWikiID( $wiki ) {
3583 $bits = explode( '-', $wiki, 2 );
3584 if ( count( $bits ) < 2 ) {
3591 * Get a Database object.
3593 * @param int $db Index of the connection to get. May be DB_MASTER for the
3594 * master (for write queries), DB_SLAVE for potentially lagged read
3595 * queries, or an integer >= 0 for a particular server.
3597 * @param string|string[] $groups Query groups. An array of group names that this query
3598 * belongs to. May contain a single string if the query is only
3601 * @param string|bool $wiki The wiki ID, or false for the current wiki
3603 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3604 * will always return the same object, unless the underlying connection or load
3605 * balancer is manually destroyed.
3607 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3608 * updater to ensure that a proper database is being updated.
3610 * @return DatabaseBase
3612 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3613 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3617 * Get a load balancer object.
3619 * @param string|bool $wiki Wiki ID, or false for the current wiki
3620 * @return LoadBalancer
3622 function wfGetLB( $wiki = false ) {
3623 return wfGetLBFactory()->getMainLB( $wiki );
3627 * Get the load balancer factory object
3631 function &wfGetLBFactory() {
3632 return LBFactory
::singleton();
3637 * Shortcut for RepoGroup::singleton()->findFile()
3639 * @param string $title String or Title object
3640 * @param array $options Associative array of options:
3641 * time: requested time for an archived image, or false for the
3642 * current version. An image object will be returned which was
3643 * created at the specified time.
3645 * ignoreRedirect: If true, do not follow file redirects
3647 * private: If true, return restricted (deleted) files if the current
3648 * user is allowed to view them. Otherwise, such files will not
3651 * bypassCache: If true, do not use the process-local cache of File objects
3653 * @return File|bool File, or false if the file does not exist
3655 function wfFindFile( $title, $options = array() ) {
3656 return RepoGroup
::singleton()->findFile( $title, $options );
3660 * Get an object referring to a locally registered file.
3661 * Returns a valid placeholder object if the file does not exist.
3663 * @param Title|string $title
3664 * @return LocalFile|null A File, or null if passed an invalid Title
3666 function wfLocalFile( $title ) {
3667 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
3671 * Should low-performance queries be disabled?
3674 * @codeCoverageIgnore
3676 function wfQueriesMustScale() {
3677 global $wgMiserMode;
3679 ||
( SiteStats
::pages() > 100000
3680 && SiteStats
::edits() > 1000000
3681 && SiteStats
::users() > 10000 );
3685 * Get the path to a specified script file, respecting file
3686 * extensions; this is a wrapper around $wgScriptExtension etc.
3687 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3689 * @param string $script Script filename, sans extension
3692 function wfScript( $script = 'index' ) {
3693 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3694 if ( $script === 'index' ) {
3696 } elseif ( $script === 'load' ) {
3697 return $wgLoadScript;
3699 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3704 * Get the script URL.
3706 * @return string Script URL
3708 function wfGetScriptUrl() {
3709 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3711 # as it was called, minus the query string.
3713 # Some sites use Apache rewrite rules to handle subdomains,
3714 # and have PHP set up in a weird way that causes PHP_SELF
3715 # to contain the rewritten URL instead of the one that the
3716 # outside world sees.
3718 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3719 # provides containing the "before" URL.
3720 return $_SERVER['SCRIPT_NAME'];
3722 return $_SERVER['URL'];
3727 * Convenience function converts boolean values into "true"
3728 * or "false" (string) values
3730 * @param bool $value
3733 function wfBoolToStr( $value ) {
3734 return $value ?
'true' : 'false';
3738 * Get a platform-independent path to the null file, e.g. /dev/null
3742 function wfGetNull() {
3743 return wfIsWindows() ?
'NUL' : '/dev/null';
3747 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3748 * and waiting for it to go down, this waits for the slaves to catch up to the
3749 * master position. Use this when updating very large numbers of rows, as
3750 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3751 * a no-op if there are no slaves.
3753 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3754 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3755 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3756 * @return bool Success (able to connect and no timeouts reached)
3758 function wfWaitForSlaves( $ifWritesSince = false, $wiki = false, $cluster = false ) {
3759 // B/C: first argument used to be "max seconds of lag"; ignore such values
3760 $ifWritesSince = ( $ifWritesSince > 1e9
) ?
$ifWritesSince : false;
3762 if ( $cluster !== false ) {
3763 $lb = wfGetLBFactory()->getExternalLB( $cluster );
3765 $lb = wfGetLB( $wiki );
3768 // bug 27975 - Don't try to wait for slaves if there are none
3769 // Prevents permission error when getting master position
3770 if ( $lb->getServerCount() > 1 ) {
3771 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3772 return true; // assume no writes done
3774 $dbw = $lb->getConnection( DB_MASTER
, array(), $wiki );
3775 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3776 return true; // no writes since the last wait
3778 $pos = $dbw->getMasterPos();
3779 // The DBMS may not support getMasterPos() or the whole
3780 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3781 if ( $pos !== false ) {
3782 return $lb->waitForAll( $pos, PHP_SAPI
=== 'cli' ?
86400 : null );
3790 * Count down from $seconds to zero on the terminal, with a one-second pause
3791 * between showing each number. For use in command-line scripts.
3793 * @codeCoverageIgnore
3794 * @param int $seconds
3796 function wfCountDown( $seconds ) {
3797 for ( $i = $seconds; $i >= 0; $i-- ) {
3798 if ( $i != $seconds ) {
3799 echo str_repeat( "\x08", strlen( $i +
1 ) );
3811 * Replace all invalid characters with -
3812 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3813 * By default, $wgIllegalFileChars = ':'
3815 * @param string $name Filename to process
3818 function wfStripIllegalFilenameChars( $name ) {
3819 global $wgIllegalFileChars;
3820 $illegalFileChars = $wgIllegalFileChars ?
"|[" . $wgIllegalFileChars . "]" : '';
3821 $name = wfBaseName( $name );
3822 $name = preg_replace(
3823 "/[^" . Title
::legalChars() . "]" . $illegalFileChars . "/",
3831 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3833 * @return int Value the memory limit was set to.
3835 function wfMemoryLimit() {
3836 global $wgMemoryLimit;
3837 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3838 if ( $memlimit != -1 ) {
3839 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3840 if ( $conflimit == -1 ) {
3841 wfDebug( "Removing PHP's memory limit\n" );
3842 wfSuppressWarnings();
3843 ini_set( 'memory_limit', $conflimit );
3844 wfRestoreWarnings();
3846 } elseif ( $conflimit > $memlimit ) {
3847 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3848 wfSuppressWarnings();
3849 ini_set( 'memory_limit', $conflimit );
3850 wfRestoreWarnings();
3858 * Converts shorthand byte notation to integer form
3860 * @param string $string
3863 function wfShorthandToInteger( $string = '' ) {
3864 $string = trim( $string );
3865 if ( $string === '' ) {
3868 $last = $string[strlen( $string ) - 1];
3869 $val = intval( $string );
3874 // break intentionally missing
3878 // break intentionally missing
3888 * Get the normalised IETF language tag
3889 * See unit test for examples.
3891 * @param string $code The language code.
3892 * @return string The language code which complying with BCP 47 standards.
3894 function wfBCP47( $code ) {
3895 $codeSegment = explode( '-', $code );
3897 foreach ( $codeSegment as $segNo => $seg ) {
3898 // when previous segment is x, it is a private segment and should be lc
3899 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3900 $codeBCP[$segNo] = strtolower( $seg );
3901 // ISO 3166 country code
3902 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3903 $codeBCP[$segNo] = strtoupper( $seg );
3904 // ISO 15924 script code
3905 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3906 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3907 // Use lowercase for other cases
3909 $codeBCP[$segNo] = strtolower( $seg );
3912 $langCode = implode( '-', $codeBCP );
3917 * Get a cache object.
3919 * @param int $inputType Cache type, one the the CACHE_* constants.
3922 function wfGetCache( $inputType ) {
3923 return ObjectCache
::getInstance( $inputType );
3927 * Get the main cache object
3931 function wfGetMainCache() {
3932 global $wgMainCacheType;
3933 return ObjectCache
::getInstance( $wgMainCacheType );
3937 * Get the cache object used by the message cache
3941 function wfGetMessageCacheStorage() {
3942 global $wgMessageCacheType;
3943 return ObjectCache
::getInstance( $wgMessageCacheType );
3947 * Get the cache object used by the parser cache
3951 function wfGetParserCacheStorage() {
3952 global $wgParserCacheType;
3953 return ObjectCache
::getInstance( $wgParserCacheType );
3957 * Get the cache object used by the language converter
3961 function wfGetLangConverterCacheStorage() {
3962 global $wgLanguageConverterCacheType;
3963 return ObjectCache
::getInstance( $wgLanguageConverterCacheType );
3967 * Call hook functions defined in $wgHooks
3969 * @param string $event Event name
3970 * @param array $args Parameters passed to hook functions
3971 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
3973 * @return bool True if no handler aborted the hook
3975 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
3976 return Hooks
::run( $event, $args, $deprecatedVersion );
3980 * Wrapper around php's unpack.
3982 * @param string $format The format string (See php's docs)
3983 * @param string $data A binary string of binary data
3984 * @param int|bool $length The minimum length of $data or false. This is to
3985 * prevent reading beyond the end of $data. false to disable the check.
3987 * Also be careful when using this function to read unsigned 32 bit integer
3988 * because php might make it negative.
3990 * @throws MWException If $data not long enough, or if unpack fails
3991 * @return array Associative array of the extracted data
3993 function wfUnpack( $format, $data, $length = false ) {
3994 if ( $length !== false ) {
3995 $realLen = strlen( $data );
3996 if ( $realLen < $length ) {
3997 throw new MWException( "Tried to use wfUnpack on a "
3998 . "string of length $realLen, but needed one "
3999 . "of at least length $length."
4004 wfSuppressWarnings();
4005 $result = unpack( $format, $data );
4006 wfRestoreWarnings();
4008 if ( $result === false ) {
4009 // If it cannot extract the packed data.
4010 throw new MWException( "unpack could not unpack binary data" );
4016 * Determine if an image exists on the 'bad image list'.
4018 * The format of MediaWiki:Bad_image_list is as follows:
4019 * * Only list items (lines starting with "*") are considered
4020 * * The first link on a line must be a link to a bad image
4021 * * Any subsequent links on the same line are considered to be exceptions,
4022 * i.e. articles where the image may occur inline.
4024 * @param string $name The image name to check
4025 * @param Title|bool $contextTitle The page on which the image occurs, if known
4026 * @param string $blacklist Wikitext of a file blacklist
4029 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4030 static $badImageCache = null; // based on bad_image_list msg
4031 wfProfileIn( __METHOD__
);
4034 $redirectTitle = RepoGroup
::singleton()->checkRedirect( Title
::makeTitle( NS_FILE
, $name ) );
4035 if ( $redirectTitle ) {
4036 $name = $redirectTitle->getDBkey();
4039 # Run the extension hook
4041 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
4042 wfProfileOut( __METHOD__
);
4046 $cacheable = ( $blacklist === null );
4047 if ( $cacheable && $badImageCache !== null ) {
4048 $badImages = $badImageCache;
4049 } else { // cache miss
4050 if ( $blacklist === null ) {
4051 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4053 # Build the list now
4054 $badImages = array();
4055 $lines = explode( "\n", $blacklist );
4056 foreach ( $lines as $line ) {
4058 if ( substr( $line, 0, 1 ) !== '*' ) {
4064 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4068 $exceptions = array();
4069 $imageDBkey = false;
4070 foreach ( $m[1] as $i => $titleText ) {
4071 $title = Title
::newFromText( $titleText );
4072 if ( !is_null( $title ) ) {
4074 $imageDBkey = $title->getDBkey();
4076 $exceptions[$title->getPrefixedDBkey()] = true;
4081 if ( $imageDBkey !== false ) {
4082 $badImages[$imageDBkey] = $exceptions;
4086 $badImageCache = $badImages;
4090 $contextKey = $contextTitle ?
$contextTitle->getPrefixedDBkey() : false;
4091 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4092 wfProfileOut( __METHOD__
);
4097 * Determine whether the client at a given source IP is likely to be able to
4098 * access the wiki via HTTPS.
4100 * @param string $ip The IPv4/6 address in the normal human-readable form
4103 function wfCanIPUseHTTPS( $ip ) {
4105 wfRunHooks( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4110 * Work out the IP address based on various globals
4111 * For trusted proxies, use the XFF client IP (first of the chain)
4113 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4116 function wfGetIP() {
4117 wfDeprecated( __METHOD__
, '1.19' );
4119 return $wgRequest->getIP();
4123 * Checks if an IP is a trusted proxy provider.
4124 * Useful to tell if X-Forwarded-For data is possibly bogus.
4125 * Squid cache servers for the site are whitelisted.
4126 * @deprecated Since 1.24, use IP::isTrustedProxy()
4131 function wfIsTrustedProxy( $ip ) {
4132 return IP
::isTrustedProxy( $ip );
4136 * Checks if an IP matches a proxy we've configured.
4137 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4141 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4143 function wfIsConfiguredProxy( $ip ) {
4144 return IP
::isConfiguredProxy( $ip );