thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / GlobalFunctions.php
bloba44e45b5535d237907133b826714e207dfbe8e17
1 <?php
2 /**
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
20 * @file
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
28 /// @cond
30 /**
31 * Compatibility functions
33 * We support PHP 5.3.2 and up.
34 * Re-implementations of newer functions or functions in non-standard
35 * PHP extensions may be included here.
38 if ( !function_exists( 'iconv' ) ) {
39 /**
40 * @codeCoverageIgnore
41 * @return string
43 function iconv( $from, $to, $string ) {
44 return Fallback::iconv( $from, $to, $string );
48 if ( !function_exists( 'mb_substr' ) ) {
49 /**
50 * @codeCoverageIgnore
51 * @return string
53 function mb_substr( $str, $start, $count = 'end' ) {
54 return Fallback::mb_substr( $str, $start, $count );
57 /**
58 * @codeCoverageIgnore
59 * @return int
61 function mb_substr_split_unicode( $str, $splitPos ) {
62 return Fallback::mb_substr_split_unicode( $str, $splitPos );
66 if ( !function_exists( 'mb_strlen' ) ) {
67 /**
68 * @codeCoverageIgnore
69 * @return int
71 function mb_strlen( $str, $enc = '' ) {
72 return Fallback::mb_strlen( $str, $enc );
76 if ( !function_exists( 'mb_strpos' ) ) {
77 /**
78 * @codeCoverageIgnore
79 * @return int
81 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
82 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
87 if ( !function_exists( 'mb_strrpos' ) ) {
88 /**
89 * @codeCoverageIgnore
90 * @return int
92 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
93 return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding );
96 /// @endcond
98 /**
99 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
100 * @param $a array
101 * @param $b array
102 * @return array
104 function wfArrayDiff2( $a, $b ) {
105 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
109 * @param $a
110 * @param $b
111 * @return int
113 function wfArrayDiff2_cmp( $a, $b ) {
114 if ( !is_array( $a ) ) {
115 return strcmp( $a, $b );
116 } elseif ( count( $a ) !== count( $b ) ) {
117 return count( $a ) < count( $b ) ? -1 : 1;
118 } else {
119 reset( $a );
120 reset( $b );
121 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
122 $cmp = strcmp( $valueA, $valueB );
123 if ( $cmp !== 0 ) {
124 return $cmp;
127 return 0;
132 * Array lookup
133 * Returns an array where the values in the first array are replaced by the
134 * values in the second array with the corresponding keys
136 * @param $a Array
137 * @param $b Array
138 * @return array
140 function wfArrayLookup( $a, $b ) {
141 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
145 * Appends to second array if $value differs from that in $default
147 * @param $key String|Int
148 * @param $value Mixed
149 * @param $default Mixed
150 * @param array $changed to alter
151 * @throws MWException
153 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
154 if ( is_null( $changed ) ) {
155 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
157 if ( $default[$key] !== $value ) {
158 $changed[$key] = $value;
163 * Backwards array plus for people who haven't bothered to read the PHP manual
164 * XXX: will not darn your socks for you.
166 * @param $array1 Array
167 * @param [$array2, [...]] Arrays
168 * @return Array
170 function wfArrayMerge( $array1/* ... */ ) {
171 $args = func_get_args();
172 $args = array_reverse( $args, true );
173 $out = array();
174 foreach ( $args as $arg ) {
175 $out += $arg;
177 return $out;
181 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
182 * e.g.
183 * wfMergeErrorArrays(
184 * array( array( 'x' ) ),
185 * array( array( 'x', '2' ) ),
186 * array( array( 'x' ) ),
187 * array( array( 'y' ) )
188 * );
189 * returns:
190 * array(
191 * array( 'x', '2' ),
192 * array( 'x' ),
193 * array( 'y' )
195 * @param varargs
196 * @return Array
198 function wfMergeErrorArrays( /*...*/ ) {
199 $args = func_get_args();
200 $out = array();
201 foreach ( $args as $errors ) {
202 foreach ( $errors as $params ) {
203 # @todo FIXME: Sometimes get nested arrays for $params,
204 # which leads to E_NOTICEs
205 $spec = implode( "\t", $params );
206 $out[$spec] = $params;
209 return array_values( $out );
213 * Insert array into another array after the specified *KEY*
215 * @param array $array The array.
216 * @param array $insert The array to insert.
217 * @param $after Mixed: The key to insert after
218 * @return Array
220 function wfArrayInsertAfter( array $array, array $insert, $after ) {
221 // Find the offset of the element to insert after.
222 $keys = array_keys( $array );
223 $offsetByKey = array_flip( $keys );
225 $offset = $offsetByKey[$after];
227 // Insert at the specified offset
228 $before = array_slice( $array, 0, $offset + 1, true );
229 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
231 $output = $before + $insert + $after;
233 return $output;
237 * Recursively converts the parameter (an object) to an array with the same data
239 * @param $objOrArray Object|Array
240 * @param $recursive Bool
241 * @return Array
243 function wfObjectToArray( $objOrArray, $recursive = true ) {
244 $array = array();
245 if ( is_object( $objOrArray ) ) {
246 $objOrArray = get_object_vars( $objOrArray );
248 foreach ( $objOrArray as $key => $value ) {
249 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
250 $value = wfObjectToArray( $value );
253 $array[$key] = $value;
256 return $array;
260 * Get a random decimal value between 0 and 1, in a way
261 * not likely to give duplicate values for any realistic
262 * number of articles.
264 * @return string
266 function wfRandom() {
267 # The maximum random value is "only" 2^31-1, so get two random
268 # values to reduce the chance of dupes
269 $max = mt_getrandmax() + 1;
270 $rand = number_format( ( mt_rand() * $max + mt_rand() )
271 / $max / $max, 12, '.', '' );
272 return $rand;
276 * Get a random string containing a number of pseudo-random hex
277 * characters.
278 * @note This is not secure, if you are trying to generate some sort
279 * of token please use MWCryptRand instead.
281 * @param int $length The length of the string to generate
282 * @return String
283 * @since 1.20
285 function wfRandomString( $length = 32 ) {
286 $str = '';
287 for ( $n = 0; $n < $length; $n += 7 ) {
288 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
290 return substr( $str, 0, $length );
294 * We want some things to be included as literal characters in our title URLs
295 * for prettiness, which urlencode encodes by default. According to RFC 1738,
296 * all of the following should be safe:
298 * ;:@&=$-_.+!*'(),
300 * But + is not safe because it's used to indicate a space; &= are only safe in
301 * paths and not in queries (and we don't distinguish here); ' seems kind of
302 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
303 * is reserved, we don't care. So the list we unescape is:
305 * ;:@$!*(),/
307 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
308 * so no fancy : for IIS7.
310 * %2F in the page titles seems to fatally break for some reason.
312 * @param $s String:
313 * @return string
315 function wfUrlencode( $s ) {
316 static $needle;
317 if ( is_null( $s ) ) {
318 $needle = null;
319 return '';
322 if ( is_null( $needle ) ) {
323 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
324 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
325 $needle[] = '%3A';
329 $s = urlencode( $s );
330 $s = str_ireplace(
331 $needle,
332 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
336 return $s;
340 * This function takes two arrays as input, and returns a CGI-style string, e.g.
341 * "days=7&limit=100". Options in the first array override options in the second.
342 * Options set to null or false will not be output.
344 * @param array $array1 ( String|Array )
345 * @param array $array2 ( String|Array )
346 * @param $prefix String
347 * @return String
349 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
350 if ( !is_null( $array2 ) ) {
351 $array1 = $array1 + $array2;
354 $cgi = '';
355 foreach ( $array1 as $key => $value ) {
356 if ( !is_null( $value ) && $value !== false ) {
357 if ( $cgi != '' ) {
358 $cgi .= '&';
360 if ( $prefix !== '' ) {
361 $key = $prefix . "[$key]";
363 if ( is_array( $value ) ) {
364 $firstTime = true;
365 foreach ( $value as $k => $v ) {
366 $cgi .= $firstTime ? '' : '&';
367 if ( is_array( $v ) ) {
368 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
369 } else {
370 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
372 $firstTime = false;
374 } else {
375 if ( is_object( $value ) ) {
376 $value = $value->__toString();
378 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
382 return $cgi;
386 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
387 * its argument and returns the same string in array form. This allows compatibility
388 * with legacy functions that accept raw query strings instead of nice
389 * arrays. Of course, keys and values are urldecode()d.
391 * @param string $query query string
392 * @return array Array version of input
394 function wfCgiToArray( $query ) {
395 if ( isset( $query[0] ) && $query[0] == '?' ) {
396 $query = substr( $query, 1 );
398 $bits = explode( '&', $query );
399 $ret = array();
400 foreach ( $bits as $bit ) {
401 if ( $bit === '' ) {
402 continue;
404 if ( strpos( $bit, '=' ) === false ) {
405 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
406 $key = $bit;
407 $value = '';
408 } else {
409 list( $key, $value ) = explode( '=', $bit );
411 $key = urldecode( $key );
412 $value = urldecode( $value );
413 if ( strpos( $key, '[' ) !== false ) {
414 $keys = array_reverse( explode( '[', $key ) );
415 $key = array_pop( $keys );
416 $temp = $value;
417 foreach ( $keys as $k ) {
418 $k = substr( $k, 0, -1 );
419 $temp = array( $k => $temp );
421 if ( isset( $ret[$key] ) ) {
422 $ret[$key] = array_merge( $ret[$key], $temp );
423 } else {
424 $ret[$key] = $temp;
426 } else {
427 $ret[$key] = $value;
430 return $ret;
434 * Append a query string to an existing URL, which may or may not already
435 * have query string parameters already. If so, they will be combined.
437 * @param $url String
438 * @param $query Mixed: string or associative array
439 * @return string
441 function wfAppendQuery( $url, $query ) {
442 if ( is_array( $query ) ) {
443 $query = wfArrayToCgi( $query );
445 if ( $query != '' ) {
446 if ( false === strpos( $url, '?' ) ) {
447 $url .= '?';
448 } else {
449 $url .= '&';
451 $url .= $query;
453 return $url;
457 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
458 * is correct.
460 * The meaning of the PROTO_* constants is as follows:
461 * PROTO_HTTP: Output a URL starting with http://
462 * PROTO_HTTPS: Output a URL starting with https://
463 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
464 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending on which protocol was used for the current incoming request
465 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer. For protocol-relative URLs, use the protocol of $wgCanonicalServer
466 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
468 * @todo this won't work with current-path-relative URLs
469 * like "subdir/foo.html", etc.
471 * @param string $url either fully-qualified or a local path + query
472 * @param $defaultProto Mixed: one of the PROTO_* constants. Determines the
473 * protocol to use if $url or $wgServer is
474 * protocol-relative
475 * @return string Fully-qualified URL, current-path-relative URL or false if
476 * no valid URL can be constructed
478 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
479 global $wgServer, $wgCanonicalServer, $wgInternalServer;
480 $serverUrl = $wgServer;
481 if ( $defaultProto === PROTO_CANONICAL ) {
482 $serverUrl = $wgCanonicalServer;
484 // Make $wgInternalServer fall back to $wgServer if not set
485 if ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
486 $serverUrl = $wgInternalServer;
488 if ( $defaultProto === PROTO_CURRENT ) {
489 $defaultProto = WebRequest::detectProtocol() . '://';
492 // Analyze $serverUrl to obtain its protocol
493 $bits = wfParseUrl( $serverUrl );
494 $serverHasProto = $bits && $bits['scheme'] != '';
496 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
497 if ( $serverHasProto ) {
498 $defaultProto = $bits['scheme'] . '://';
499 } else {
500 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol. This really isn't supposed to happen
501 // Fall back to HTTP in this ridiculous case
502 $defaultProto = PROTO_HTTP;
506 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
508 if ( substr( $url, 0, 2 ) == '//' ) {
509 $url = $defaultProtoWithoutSlashes . $url;
510 } elseif ( substr( $url, 0, 1 ) == '/' ) {
511 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes, otherwise leave it alone
512 $url = ( $serverHasProto ? '' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
515 $bits = wfParseUrl( $url );
516 if ( $bits && isset( $bits['path'] ) ) {
517 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
518 return wfAssembleUrl( $bits );
519 } elseif ( $bits ) {
520 # No path to expand
521 return $url;
522 } elseif ( substr( $url, 0, 1 ) != '/' ) {
523 # URL is a relative path
524 return wfRemoveDotSegments( $url );
527 # Expanded URL is not valid.
528 return false;
532 * This function will reassemble a URL parsed with wfParseURL. This is useful
533 * if you need to edit part of a URL and put it back together.
535 * This is the basic structure used (brackets contain keys for $urlParts):
536 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
538 * @todo Need to integrate this into wfExpandUrl (bug 32168)
540 * @since 1.19
541 * @param array $urlParts URL parts, as output from wfParseUrl
542 * @return string URL assembled from its component parts
544 function wfAssembleUrl( $urlParts ) {
545 $result = '';
547 if ( isset( $urlParts['delimiter'] ) ) {
548 if ( isset( $urlParts['scheme'] ) ) {
549 $result .= $urlParts['scheme'];
552 $result .= $urlParts['delimiter'];
555 if ( isset( $urlParts['host'] ) ) {
556 if ( isset( $urlParts['user'] ) ) {
557 $result .= $urlParts['user'];
558 if ( isset( $urlParts['pass'] ) ) {
559 $result .= ':' . $urlParts['pass'];
561 $result .= '@';
564 $result .= $urlParts['host'];
566 if ( isset( $urlParts['port'] ) ) {
567 $result .= ':' . $urlParts['port'];
571 if ( isset( $urlParts['path'] ) ) {
572 $result .= $urlParts['path'];
575 if ( isset( $urlParts['query'] ) ) {
576 $result .= '?' . $urlParts['query'];
579 if ( isset( $urlParts['fragment'] ) ) {
580 $result .= '#' . $urlParts['fragment'];
583 return $result;
587 * Remove all dot-segments in the provided URL path. For example,
588 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
589 * RFC3986 section 5.2.4.
591 * @todo Need to integrate this into wfExpandUrl (bug 32168)
593 * @param string $urlPath URL path, potentially containing dot-segments
594 * @return string URL path with all dot-segments removed
596 function wfRemoveDotSegments( $urlPath ) {
597 $output = '';
598 $inputOffset = 0;
599 $inputLength = strlen( $urlPath );
601 while ( $inputOffset < $inputLength ) {
602 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
603 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
604 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
605 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
606 $trimOutput = false;
608 if ( $prefixLengthTwo == './' ) {
609 # Step A, remove leading "./"
610 $inputOffset += 2;
611 } elseif ( $prefixLengthThree == '../' ) {
612 # Step A, remove leading "../"
613 $inputOffset += 3;
614 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
615 # Step B, replace leading "/.$" with "/"
616 $inputOffset += 1;
617 $urlPath[$inputOffset] = '/';
618 } elseif ( $prefixLengthThree == '/./' ) {
619 # Step B, replace leading "/./" with "/"
620 $inputOffset += 2;
621 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
622 # Step C, replace leading "/..$" with "/" and
623 # remove last path component in output
624 $inputOffset += 2;
625 $urlPath[$inputOffset] = '/';
626 $trimOutput = true;
627 } elseif ( $prefixLengthFour == '/../' ) {
628 # Step C, replace leading "/../" with "/" and
629 # remove last path component in output
630 $inputOffset += 3;
631 $trimOutput = true;
632 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
633 # Step D, remove "^.$"
634 $inputOffset += 1;
635 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
636 # Step D, remove "^..$"
637 $inputOffset += 2;
638 } else {
639 # Step E, move leading path segment to output
640 if ( $prefixLengthOne == '/' ) {
641 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
642 } else {
643 $slashPos = strpos( $urlPath, '/', $inputOffset );
645 if ( $slashPos === false ) {
646 $output .= substr( $urlPath, $inputOffset );
647 $inputOffset = $inputLength;
648 } else {
649 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
650 $inputOffset += $slashPos - $inputOffset;
654 if ( $trimOutput ) {
655 $slashPos = strrpos( $output, '/' );
656 if ( $slashPos === false ) {
657 $output = '';
658 } else {
659 $output = substr( $output, 0, $slashPos );
664 return $output;
668 * Returns a regular expression of url protocols
670 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
671 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
672 * @return String
674 function wfUrlProtocols( $includeProtocolRelative = true ) {
675 global $wgUrlProtocols;
677 // Cache return values separately based on $includeProtocolRelative
678 static $withProtRel = null, $withoutProtRel = null;
679 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
680 if ( !is_null( $cachedValue ) ) {
681 return $cachedValue;
684 // Support old-style $wgUrlProtocols strings, for backwards compatibility
685 // with LocalSettings files from 1.5
686 if ( is_array( $wgUrlProtocols ) ) {
687 $protocols = array();
688 foreach ( $wgUrlProtocols as $protocol ) {
689 // Filter out '//' if !$includeProtocolRelative
690 if ( $includeProtocolRelative || $protocol !== '//' ) {
691 $protocols[] = preg_quote( $protocol, '/' );
695 $retval = implode( '|', $protocols );
696 } else {
697 // Ignore $includeProtocolRelative in this case
698 // This case exists for pre-1.6 compatibility, and we can safely assume
699 // that '//' won't appear in a pre-1.6 config because protocol-relative
700 // URLs weren't supported until 1.18
701 $retval = $wgUrlProtocols;
704 // Cache return value
705 if ( $includeProtocolRelative ) {
706 $withProtRel = $retval;
707 } else {
708 $withoutProtRel = $retval;
710 return $retval;
714 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
715 * you need a regex that matches all URL protocols but does not match protocol-
716 * relative URLs
717 * @return String
719 function wfUrlProtocolsWithoutProtRel() {
720 return wfUrlProtocols( false );
724 * parse_url() work-alike, but non-broken. Differences:
726 * 1) Does not raise warnings on bad URLs (just returns false)
727 * 2) Handles protocols that don't use :// (e.g., mailto: and news: , as well as protocol-relative URLs) correctly
728 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2))
730 * @param string $url a URL to parse
731 * @return Array: bits of the URL in an associative array, per PHP docs
733 function wfParseUrl( $url ) {
734 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
736 // Protocol-relative URLs are handled really badly by parse_url(). It's so bad that the easiest
737 // way to handle them is to just prepend 'http:' and strip the protocol out later
738 $wasRelative = substr( $url, 0, 2 ) == '//';
739 if ( $wasRelative ) {
740 $url = "http:$url";
742 wfSuppressWarnings();
743 $bits = parse_url( $url );
744 wfRestoreWarnings();
745 // parse_url() returns an array without scheme for some invalid URLs, e.g.
746 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
747 if ( !$bits || !isset( $bits['scheme'] ) ) {
748 return false;
751 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
752 $bits['scheme'] = strtolower( $bits['scheme'] );
754 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
755 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
756 $bits['delimiter'] = '://';
757 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
758 $bits['delimiter'] = ':';
759 // parse_url detects for news: and mailto: the host part of an url as path
760 // We have to correct this wrong detection
761 if ( isset( $bits['path'] ) ) {
762 $bits['host'] = $bits['path'];
763 $bits['path'] = '';
765 } else {
766 return false;
769 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
770 if ( !isset( $bits['host'] ) ) {
771 $bits['host'] = '';
773 // bug 45069
774 if ( isset( $bits['path'] ) ) {
775 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
776 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
777 $bits['path'] = '/' . $bits['path'];
779 } else {
780 $bits['path'] = '';
784 // If the URL was protocol-relative, fix scheme and delimiter
785 if ( $wasRelative ) {
786 $bits['scheme'] = '';
787 $bits['delimiter'] = '//';
789 return $bits;
793 * Take a URL, make sure it's expanded to fully qualified, and replace any
794 * encoded non-ASCII Unicode characters with their UTF-8 original forms
795 * for more compact display and legibility for local audiences.
797 * @todo handle punycode domains too
799 * @param $url string
800 * @return string
802 function wfExpandIRI( $url ) {
803 return preg_replace_callback( '/((?:%[89A-F][0-9A-F])+)/i', 'wfExpandIRI_callback', wfExpandUrl( $url ) );
807 * Private callback for wfExpandIRI
808 * @param array $matches
809 * @return string
811 function wfExpandIRI_callback( $matches ) {
812 return urldecode( $matches[1] );
816 * Make URL indexes, appropriate for the el_index field of externallinks.
818 * @param $url String
819 * @return array
821 function wfMakeUrlIndexes( $url ) {
822 $bits = wfParseUrl( $url );
824 // Reverse the labels in the hostname, convert to lower case
825 // For emails reverse domainpart only
826 if ( $bits['scheme'] == 'mailto' ) {
827 $mailparts = explode( '@', $bits['host'], 2 );
828 if ( count( $mailparts ) === 2 ) {
829 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
830 } else {
831 // No domain specified, don't mangle it
832 $domainpart = '';
834 $reversedHost = $domainpart . '@' . $mailparts[0];
835 } else {
836 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
838 // Add an extra dot to the end
839 // Why? Is it in wrong place in mailto links?
840 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
841 $reversedHost .= '.';
843 // Reconstruct the pseudo-URL
844 $prot = $bits['scheme'];
845 $index = $prot . $bits['delimiter'] . $reversedHost;
846 // Leave out user and password. Add the port, path, query and fragment
847 if ( isset( $bits['port'] ) ) {
848 $index .= ':' . $bits['port'];
850 if ( isset( $bits['path'] ) ) {
851 $index .= $bits['path'];
852 } else {
853 $index .= '/';
855 if ( isset( $bits['query'] ) ) {
856 $index .= '?' . $bits['query'];
858 if ( isset( $bits['fragment'] ) ) {
859 $index .= '#' . $bits['fragment'];
862 if ( $prot == '' ) {
863 return array( "http:$index", "https:$index" );
864 } else {
865 return array( $index );
870 * Check whether a given URL has a domain that occurs in a given set of domains
871 * @param string $url URL
872 * @param array $domains Array of domains (strings)
873 * @return bool True if the host part of $url ends in one of the strings in $domains
875 function wfMatchesDomainList( $url, $domains ) {
876 $bits = wfParseUrl( $url );
877 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
878 foreach ( (array)$domains as $domain ) {
879 // FIXME: This gives false positives. http://nds-nl.wikipedia.org will match nl.wikipedia.org
880 // We should use something that interprets dots instead
881 if ( substr( $bits['host'], -strlen( $domain ) ) === $domain ) {
882 return true;
886 return false;
890 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
891 * In normal operation this is a NOP.
893 * Controlling globals:
894 * $wgDebugLogFile - points to the log file
895 * $wgProfileOnly - if set, normal debug messages will not be recorded.
896 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
897 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
899 * @param $text String
900 * @param bool $logonly set true to avoid appearing in HTML when $wgDebugComments is set
902 function wfDebug( $text, $logonly = false ) {
903 global $wgDebugLogFile, $wgProfileOnly, $wgDebugRawPage, $wgDebugLogPrefix;
905 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
906 return;
909 $timer = wfDebugTimer();
910 if ( $timer !== '' ) {
911 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
914 if ( !$logonly ) {
915 MWDebug::debugMsg( $text );
918 if ( wfRunHooks( 'Debug', array( $text, null /* no log group */ ) ) ) {
919 if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
920 # Strip unprintables; they can switch terminal modes when binary data
921 # gets dumped, which is pretty annoying.
922 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
923 $text = $wgDebugLogPrefix . $text;
924 wfErrorLog( $text, $wgDebugLogFile );
930 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
931 * @return bool
933 function wfIsDebugRawPage() {
934 static $cache;
935 if ( $cache !== null ) {
936 return $cache;
938 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
939 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
940 || (
941 isset( $_SERVER['SCRIPT_NAME'] )
942 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
945 $cache = true;
946 } else {
947 $cache = false;
949 return $cache;
953 * Get microsecond timestamps for debug logs
955 * @return string
957 function wfDebugTimer() {
958 global $wgDebugTimestamps, $wgRequestTime;
960 if ( !$wgDebugTimestamps ) {
961 return '';
964 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
965 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
966 return "$prefix $mem ";
970 * Send a line giving PHP memory usage.
972 * @param bool $exact print exact values instead of kilobytes (default: false)
974 function wfDebugMem( $exact = false ) {
975 $mem = memory_get_usage();
976 if ( !$exact ) {
977 $mem = floor( $mem / 1024 ) . ' kilobytes';
978 } else {
979 $mem .= ' bytes';
981 wfDebug( "Memory usage: $mem\n" );
985 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
986 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
988 * @param $logGroup String
989 * @param $text String
990 * @param bool $public whether to log the event in the public log if no private
991 * log file is specified, (default true)
993 function wfDebugLog( $logGroup, $text, $public = true ) {
994 global $wgDebugLogGroups;
995 $text = trim( $text ) . "\n";
996 if ( isset( $wgDebugLogGroups[$logGroup] ) ) {
997 $time = wfTimestamp( TS_DB );
998 $wiki = wfWikiID();
999 $host = wfHostname();
1000 if ( wfRunHooks( 'Debug', array( $text, $logGroup ) ) ) {
1001 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
1003 } elseif ( $public === true ) {
1004 wfDebug( "[$logGroup] $text", false );
1009 * Log for database errors
1011 * @param string $text database error message.
1013 function wfLogDBError( $text ) {
1014 global $wgDBerrorLog, $wgDBerrorLogTZ;
1015 static $logDBErrorTimeZoneObject = null;
1017 if ( $wgDBerrorLog ) {
1018 $host = wfHostname();
1019 $wiki = wfWikiID();
1021 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
1022 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
1025 // Workaround for https://bugs.php.net/bug.php?id=52063
1026 // Can be removed when min PHP > 5.3.2
1027 if ( $logDBErrorTimeZoneObject === null ) {
1028 $d = date_create( "now" );
1029 } else {
1030 $d = date_create( "now", $logDBErrorTimeZoneObject );
1033 $date = $d->format( 'D M j G:i:s T Y' );
1035 $text = "$date\t$host\t$wiki\t$text";
1036 wfErrorLog( $text, $wgDBerrorLog );
1041 * Throws a warning that $function is deprecated
1043 * @param $function String
1044 * @param string|bool $version Version of MediaWiki that the function was deprecated in (Added in 1.19).
1045 * @param string|bool $component Added in 1.19.
1046 * @param $callerOffset integer: How far up the call stack is the original
1047 * caller. 2 = function that called the function that called
1048 * wfDeprecated (Added in 1.20)
1050 * @return null
1052 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1053 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1057 * Send a warning either to the debug log or in a PHP error depending on
1058 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1060 * @param string $msg message to send
1061 * @param $callerOffset Integer: number of items to go back in the backtrace to
1062 * find the correct caller (1 = function calling wfWarn, ...)
1063 * @param $level Integer: PHP error level; defaults to E_USER_NOTICE;
1064 * only used when $wgDevelopmentWarnings is true
1066 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1067 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1071 * Send a warning as a PHP error and the debug log. This is intended for logging
1072 * warnings in production. For logging development warnings, use WfWarn instead.
1074 * @param $msg String: message to send
1075 * @param $callerOffset Integer: number of items to go back in the backtrace to
1076 * find the correct caller (1 = function calling wfLogWarning, ...)
1077 * @param $level Integer: PHP error level; defaults to E_USER_WARNING
1079 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1080 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1084 * Log to a file without getting "file size exceeded" signals.
1086 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1087 * send lines to the specified port, prefixed by the specified prefix and a space.
1089 * @param $text String
1090 * @param string $file filename
1091 * @throws MWException
1093 function wfErrorLog( $text, $file ) {
1094 if ( substr( $file, 0, 4 ) == 'udp:' ) {
1095 # Needs the sockets extension
1096 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
1097 // IPv6 bracketed host
1098 $host = $m[2];
1099 $port = intval( $m[3] );
1100 $prefix = isset( $m[4] ) ? $m[4] : false;
1101 $domain = AF_INET6;
1102 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
1103 $host = $m[2];
1104 if ( !IP::isIPv4( $host ) ) {
1105 $host = gethostbyname( $host );
1107 $port = intval( $m[3] );
1108 $prefix = isset( $m[4] ) ? $m[4] : false;
1109 $domain = AF_INET;
1110 } else {
1111 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
1114 // Clean it up for the multiplexer
1115 if ( strval( $prefix ) !== '' ) {
1116 $text = preg_replace( '/^/m', $prefix . ' ', $text );
1118 // Limit to 64KB
1119 if ( strlen( $text ) > 65506 ) {
1120 $text = substr( $text, 0, 65506 );
1123 if ( substr( $text, -1 ) != "\n" ) {
1124 $text .= "\n";
1126 } elseif ( strlen( $text ) > 65507 ) {
1127 $text = substr( $text, 0, 65507 );
1130 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
1131 if ( !$sock ) {
1132 return;
1135 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
1136 socket_close( $sock );
1137 } else {
1138 wfSuppressWarnings();
1139 $exists = file_exists( $file );
1140 $size = $exists ? filesize( $file ) : false;
1141 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
1142 file_put_contents( $file, $text, FILE_APPEND );
1144 wfRestoreWarnings();
1149 * @todo document
1151 function wfLogProfilingData() {
1152 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
1153 global $wgProfileLimit, $wgUser;
1155 StatCounter::singleton()->flush();
1157 $profiler = Profiler::instance();
1159 # Profiling must actually be enabled...
1160 if ( $profiler->isStub() ) {
1161 return;
1164 // Get total page request time and only show pages that longer than
1165 // $wgProfileLimit time (default is 0)
1166 $elapsed = microtime( true ) - $wgRequestTime;
1167 if ( $elapsed <= $wgProfileLimit ) {
1168 return;
1171 $profiler->logData();
1173 // Check whether this should be logged in the debug file.
1174 if ( $wgDebugLogFile == '' || ( !$wgDebugRawPage && wfIsDebugRawPage() ) ) {
1175 return;
1178 $forward = '';
1179 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1180 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
1182 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1183 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
1185 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1186 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
1188 if ( $forward ) {
1189 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
1191 // Don't load $wgUser at this late stage just for statistics purposes
1192 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
1193 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1194 $forward .= ' anon';
1197 // Command line script uses a FauxRequest object which does not have
1198 // any knowledge about an URL and throw an exception instead.
1199 try {
1200 $requestUrl = $wgRequest->getRequestURL();
1201 } catch ( MWException $e ) {
1202 $requestUrl = 'n/a';
1205 $log = sprintf( "%s\t%04.3f\t%s\n",
1206 gmdate( 'YmdHis' ), $elapsed,
1207 urldecode( $requestUrl . $forward ) );
1209 wfErrorLog( $log . $profiler->getOutput(), $wgDebugLogFile );
1213 * Increment a statistics counter
1215 * @param $key String
1216 * @param $count Int
1217 * @return void
1219 function wfIncrStats( $key, $count = 1 ) {
1220 StatCounter::singleton()->incr( $key, $count );
1224 * Check if the wiki read-only lock file is present. This can be used to lock
1225 * off editing functions, but doesn't guarantee that the database will not be
1226 * modified.
1228 * @return bool
1230 function wfReadOnly() {
1231 global $wgReadOnlyFile, $wgReadOnly;
1233 if ( !is_null( $wgReadOnly ) ) {
1234 return (bool)$wgReadOnly;
1236 if ( $wgReadOnlyFile == '' ) {
1237 return false;
1239 // Set $wgReadOnly for faster access next time
1240 if ( is_file( $wgReadOnlyFile ) ) {
1241 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1242 } else {
1243 $wgReadOnly = false;
1245 return (bool)$wgReadOnly;
1249 * @return bool
1251 function wfReadOnlyReason() {
1252 global $wgReadOnly;
1253 wfReadOnly();
1254 return $wgReadOnly;
1258 * Return a Language object from $langcode
1260 * @param $langcode Mixed: either:
1261 * - a Language object
1262 * - code of the language to get the message for, if it is
1263 * a valid code create a language for that language, if
1264 * it is a string but not a valid code then make a basic
1265 * language object
1266 * - a boolean: if it's false then use the global object for
1267 * the current user's language (as a fallback for the old parameter
1268 * functionality), or if it is true then use global object
1269 * for the wiki's content language.
1270 * @return Language object
1272 function wfGetLangObj( $langcode = false ) {
1273 # Identify which language to get or create a language object for.
1274 # Using is_object here due to Stub objects.
1275 if ( is_object( $langcode ) ) {
1276 # Great, we already have the object (hopefully)!
1277 return $langcode;
1280 global $wgContLang, $wgLanguageCode;
1281 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1282 # $langcode is the language code of the wikis content language object.
1283 # or it is a boolean and value is true
1284 return $wgContLang;
1287 global $wgLang;
1288 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1289 # $langcode is the language code of user language object.
1290 # or it was a boolean and value is false
1291 return $wgLang;
1294 $validCodes = array_keys( Language::fetchLanguageNames() );
1295 if ( in_array( $langcode, $validCodes ) ) {
1296 # $langcode corresponds to a valid language.
1297 return Language::factory( $langcode );
1300 # $langcode is a string, but not a valid language code; use content language.
1301 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1302 return $wgContLang;
1306 * Old function when $wgBetterDirectionality existed
1307 * All usage removed, wfUILang can be removed in near future
1309 * @deprecated since 1.18
1310 * @return Language
1312 function wfUILang() {
1313 wfDeprecated( __METHOD__, '1.18' );
1314 global $wgLang;
1315 return $wgLang;
1319 * This is the function for getting translated interface messages.
1321 * @see Message class for documentation how to use them.
1322 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1324 * This function replaces all old wfMsg* functions.
1326 * @param $key \string Message key.
1327 * Varargs: normal message parameters.
1328 * @return Message
1329 * @since 1.17
1331 function wfMessage( $key /*...*/) {
1332 $params = func_get_args();
1333 array_shift( $params );
1334 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1335 $params = $params[0];
1337 return new Message( $key, $params );
1341 * This function accepts multiple message keys and returns a message instance
1342 * for the first message which is non-empty. If all messages are empty then an
1343 * instance of the first message key is returned.
1344 * @param varargs: message keys
1345 * @return Message
1346 * @since 1.18
1348 function wfMessageFallback( /*...*/ ) {
1349 $args = func_get_args();
1350 return MWFunction::callArray( 'Message::newFallbackSequence', $args );
1354 * Get a message from anywhere, for the current user language.
1356 * Use wfMsgForContent() instead if the message should NOT
1357 * change depending on the user preferences.
1359 * @deprecated since 1.18
1361 * @param string $key lookup key for the message, usually
1362 * defined in languages/Language.php
1364 * Parameters to the message, which can be used to insert variable text into
1365 * it, can be passed to this function in the following formats:
1366 * - One per argument, starting at the second parameter
1367 * - As an array in the second parameter
1368 * These are not shown in the function definition.
1370 * @return String
1372 function wfMsg( $key ) {
1373 wfDeprecated( __METHOD__, '1.21' );
1375 $args = func_get_args();
1376 array_shift( $args );
1377 return wfMsgReal( $key, $args );
1381 * Same as above except doesn't transform the message
1383 * @deprecated since 1.18
1385 * @param $key String
1386 * @return String
1388 function wfMsgNoTrans( $key ) {
1389 wfDeprecated( __METHOD__, '1.21' );
1391 $args = func_get_args();
1392 array_shift( $args );
1393 return wfMsgReal( $key, $args, true, false, false );
1397 * Get a message from anywhere, for the current global language
1398 * set with $wgLanguageCode.
1400 * Use this if the message should NOT change dependent on the
1401 * language set in the user's preferences. This is the case for
1402 * most text written into logs, as well as link targets (such as
1403 * the name of the copyright policy page). Link titles, on the
1404 * other hand, should be shown in the UI language.
1406 * Note that MediaWiki allows users to change the user interface
1407 * language in their preferences, but a single installation
1408 * typically only contains content in one language.
1410 * Be wary of this distinction: If you use wfMsg() where you should
1411 * use wfMsgForContent(), a user of the software may have to
1412 * customize potentially hundreds of messages in
1413 * order to, e.g., fix a link in every possible language.
1415 * @deprecated since 1.18
1417 * @param string $key lookup key for the message, usually
1418 * defined in languages/Language.php
1419 * @return String
1421 function wfMsgForContent( $key ) {
1422 wfDeprecated( __METHOD__, '1.21' );
1424 global $wgForceUIMsgAsContentMsg;
1425 $args = func_get_args();
1426 array_shift( $args );
1427 $forcontent = true;
1428 if ( is_array( $wgForceUIMsgAsContentMsg ) &&
1429 in_array( $key, $wgForceUIMsgAsContentMsg ) )
1431 $forcontent = false;
1433 return wfMsgReal( $key, $args, true, $forcontent );
1437 * Same as above except doesn't transform the message
1439 * @deprecated since 1.18
1441 * @param $key String
1442 * @return String
1444 function wfMsgForContentNoTrans( $key ) {
1445 wfDeprecated( __METHOD__, '1.21' );
1447 global $wgForceUIMsgAsContentMsg;
1448 $args = func_get_args();
1449 array_shift( $args );
1450 $forcontent = true;
1451 if ( is_array( $wgForceUIMsgAsContentMsg ) &&
1452 in_array( $key, $wgForceUIMsgAsContentMsg ) )
1454 $forcontent = false;
1456 return wfMsgReal( $key, $args, true, $forcontent, false );
1460 * Really get a message
1462 * @deprecated since 1.18
1464 * @param string $key key to get.
1465 * @param $args
1466 * @param $useDB Boolean
1467 * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
1468 * @param $transform Boolean: Whether or not to transform the message.
1469 * @return String: the requested message.
1471 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1472 wfDeprecated( __METHOD__, '1.21' );
1474 wfProfileIn( __METHOD__ );
1475 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1476 $message = wfMsgReplaceArgs( $message, $args );
1477 wfProfileOut( __METHOD__ );
1478 return $message;
1482 * Fetch a message string value, but don't replace any keys yet.
1484 * @deprecated since 1.18
1486 * @param $key String
1487 * @param $useDB Bool
1488 * @param string $langCode Code of the language to get the message for, or
1489 * behaves as a content language switch if it is a boolean.
1490 * @param $transform Boolean: whether to parse magic words, etc.
1491 * @return string
1493 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1494 wfDeprecated( __METHOD__, '1.21' );
1496 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1498 $cache = MessageCache::singleton();
1499 $message = $cache->get( $key, $useDB, $langCode );
1500 if ( $message === false ) {
1501 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
1502 } elseif ( $transform ) {
1503 $message = $cache->transform( $message );
1505 return $message;
1509 * Replace message parameter keys on the given formatted output.
1511 * @param $message String
1512 * @param $args Array
1513 * @return string
1514 * @private
1516 function wfMsgReplaceArgs( $message, $args ) {
1517 # Fix windows line-endings
1518 # Some messages are split with explode("\n", $msg)
1519 $message = str_replace( "\r", '', $message );
1521 // Replace arguments
1522 if ( count( $args ) ) {
1523 if ( is_array( $args[0] ) ) {
1524 $args = array_values( $args[0] );
1526 $replacementKeys = array();
1527 foreach ( $args as $n => $param ) {
1528 $replacementKeys['$' . ( $n + 1 )] = $param;
1530 $message = strtr( $message, $replacementKeys );
1533 return $message;
1537 * Return an HTML-escaped version of a message.
1538 * Parameter replacements, if any, are done *after* the HTML-escaping,
1539 * so parameters may contain HTML (eg links or form controls). Be sure
1540 * to pre-escape them if you really do want plaintext, or just wrap
1541 * the whole thing in htmlspecialchars().
1543 * @deprecated since 1.18
1545 * @param $key String
1546 * @param string ... parameters
1547 * @return string
1549 function wfMsgHtml( $key ) {
1550 wfDeprecated( __METHOD__, '1.21' );
1552 $args = func_get_args();
1553 array_shift( $args );
1554 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1558 * Return an HTML version of message
1559 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1560 * so parameters may contain HTML (eg links or form controls). Be sure
1561 * to pre-escape them if you really do want plaintext, or just wrap
1562 * the whole thing in htmlspecialchars().
1564 * @deprecated since 1.18
1566 * @param $key String
1567 * @param string ... parameters
1568 * @return string
1570 function wfMsgWikiHtml( $key ) {
1571 wfDeprecated( __METHOD__, '1.21' );
1573 $args = func_get_args();
1574 array_shift( $args );
1575 return wfMsgReplaceArgs(
1576 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
1577 /* can't be set to false */ true, /* interface */ true )->getText(),
1578 $args );
1582 * Returns message in the requested format
1584 * @deprecated since 1.18
1586 * @param string $key key of the message
1587 * @param array $options processing rules. Can take the following options:
1588 * <i>parse</i>: parses wikitext to HTML
1589 * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
1590 * p's added by parser or tidy
1591 * <i>escape</i>: filters message through htmlspecialchars
1592 * <i>escapenoentities</i>: same, but allows entity references like &#160; through
1593 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
1594 * <i>parsemag</i>: transform the message using magic phrases
1595 * <i>content</i>: fetch message for content language instead of interface
1596 * Also can accept a single associative argument, of the form 'language' => 'xx':
1597 * <i>language</i>: Language object or language code to fetch message for
1598 * (overridden by <i>content</i>).
1599 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1601 * @return String
1603 function wfMsgExt( $key, $options ) {
1604 wfDeprecated( __METHOD__, '1.21' );
1606 $args = func_get_args();
1607 array_shift( $args );
1608 array_shift( $args );
1609 $options = (array)$options;
1611 foreach ( $options as $arrayKey => $option ) {
1612 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1613 # An unknown index, neither numeric nor "language"
1614 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
1615 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1616 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1617 'replaceafter', 'parsemag', 'content' ) ) ) {
1618 # A numeric index with unknown value
1619 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
1623 if ( in_array( 'content', $options, true ) ) {
1624 $forContent = true;
1625 $langCode = true;
1626 $langCodeObj = null;
1627 } elseif ( array_key_exists( 'language', $options ) ) {
1628 $forContent = false;
1629 $langCode = wfGetLangObj( $options['language'] );
1630 $langCodeObj = $langCode;
1631 } else {
1632 $forContent = false;
1633 $langCode = false;
1634 $langCodeObj = null;
1637 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1639 if ( !in_array( 'replaceafter', $options, true ) ) {
1640 $string = wfMsgReplaceArgs( $string, $args );
1643 $messageCache = MessageCache::singleton();
1644 $parseInline = in_array( 'parseinline', $options, true );
1645 if ( in_array( 'parse', $options, true ) || $parseInline ) {
1646 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1647 if ( $string instanceof ParserOutput ) {
1648 $string = $string->getText();
1651 if ( $parseInline ) {
1652 $m = array();
1653 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
1654 $string = $m[1];
1657 } elseif ( in_array( 'parsemag', $options, true ) ) {
1658 $string = $messageCache->transform( $string,
1659 !$forContent, $langCodeObj );
1662 if ( in_array( 'escape', $options, true ) ) {
1663 $string = htmlspecialchars ( $string );
1664 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1665 $string = Sanitizer::escapeHtmlAllowEntities( $string );
1668 if ( in_array( 'replaceafter', $options, true ) ) {
1669 $string = wfMsgReplaceArgs( $string, $args );
1672 return $string;
1676 * Since wfMsg() and co suck, they don't return false if the message key they
1677 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1678 * nonexistence of messages by checking the MessageCache::get() result directly.
1680 * @deprecated since 1.18. Use Message::isDisabled().
1682 * @param $key String: the message key looked up
1683 * @return Boolean True if the message *doesn't* exist.
1685 function wfEmptyMsg( $key ) {
1686 wfDeprecated( __METHOD__, '1.21' );
1688 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1692 * Throw a debugging exception. This function previously once exited the process,
1693 * but now throws an exception instead, with similar results.
1695 * @param string $msg message shown when dying.
1696 * @throws MWException
1698 function wfDebugDieBacktrace( $msg = '' ) {
1699 throw new MWException( $msg );
1703 * Fetch server name for use in error reporting etc.
1704 * Use real server name if available, so we know which machine
1705 * in a server farm generated the current page.
1707 * @return string
1709 function wfHostname() {
1710 static $host;
1711 if ( is_null( $host ) ) {
1713 # Hostname overriding
1714 global $wgOverrideHostname;
1715 if ( $wgOverrideHostname !== false ) {
1716 # Set static and skip any detection
1717 $host = $wgOverrideHostname;
1718 return $host;
1721 if ( function_exists( 'posix_uname' ) ) {
1722 // This function not present on Windows
1723 $uname = posix_uname();
1724 } else {
1725 $uname = false;
1727 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1728 $host = $uname['nodename'];
1729 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1730 # Windows computer name
1731 $host = getenv( 'COMPUTERNAME' );
1732 } else {
1733 # This may be a virtual server.
1734 $host = $_SERVER['SERVER_NAME'];
1737 return $host;
1741 * Returns a HTML comment with the elapsed time since request.
1742 * This method has no side effects.
1744 * @return string
1746 function wfReportTime() {
1747 global $wgRequestTime, $wgShowHostnames;
1749 $elapsed = microtime( true ) - $wgRequestTime;
1751 return $wgShowHostnames
1752 ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
1753 : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
1757 * Safety wrapper for debug_backtrace().
1759 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
1760 * murky circumstances, which may be triggered in part by stub objects
1761 * or other fancy talking'.
1763 * Will return an empty array if Zend Optimizer is detected or if
1764 * debug_backtrace is disabled, otherwise the output from
1765 * debug_backtrace() (trimmed).
1767 * @param int $limit This parameter can be used to limit the number of stack frames returned
1769 * @return array of backtrace information
1771 function wfDebugBacktrace( $limit = 0 ) {
1772 static $disabled = null;
1774 if ( extension_loaded( 'Zend Optimizer' ) ) {
1775 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
1776 return array();
1779 if ( is_null( $disabled ) ) {
1780 $disabled = false;
1781 $functions = explode( ',', ini_get( 'disable_functions' ) );
1782 $functions = array_map( 'trim', $functions );
1783 $functions = array_map( 'strtolower', $functions );
1784 if ( in_array( 'debug_backtrace', $functions ) ) {
1785 wfDebug( "debug_backtrace is in disabled_functions\n" );
1786 $disabled = true;
1789 if ( $disabled ) {
1790 return array();
1793 if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
1794 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1795 } else {
1796 return array_slice( debug_backtrace(), 1 );
1801 * Get a debug backtrace as a string
1803 * @return string
1805 function wfBacktrace() {
1806 global $wgCommandLineMode;
1808 if ( $wgCommandLineMode ) {
1809 $msg = '';
1810 } else {
1811 $msg = "<ul>\n";
1813 $backtrace = wfDebugBacktrace();
1814 foreach ( $backtrace as $call ) {
1815 if ( isset( $call['file'] ) ) {
1816 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
1817 $file = $f[count( $f ) - 1];
1818 } else {
1819 $file = '-';
1821 if ( isset( $call['line'] ) ) {
1822 $line = $call['line'];
1823 } else {
1824 $line = '-';
1826 if ( $wgCommandLineMode ) {
1827 $msg .= "$file line $line calls ";
1828 } else {
1829 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1831 if ( !empty( $call['class'] ) ) {
1832 $msg .= $call['class'] . $call['type'];
1834 $msg .= $call['function'] . '()';
1836 if ( $wgCommandLineMode ) {
1837 $msg .= "\n";
1838 } else {
1839 $msg .= "</li>\n";
1842 if ( $wgCommandLineMode ) {
1843 $msg .= "\n";
1844 } else {
1845 $msg .= "</ul>\n";
1848 return $msg;
1852 * Get the name of the function which called this function
1853 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1854 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1855 * wfGetCaller( 3 ) is the parent of that.
1857 * @param $level Int
1858 * @return string
1860 function wfGetCaller( $level = 2 ) {
1861 $backtrace = wfDebugBacktrace( $level + 1 );
1862 if ( isset( $backtrace[$level] ) ) {
1863 return wfFormatStackFrame( $backtrace[$level] );
1864 } else {
1865 return 'unknown';
1870 * Return a string consisting of callers in the stack. Useful sometimes
1871 * for profiling specific points.
1873 * @param int $limit The maximum depth of the stack frame to return, or false for
1874 * the entire stack.
1875 * @return String
1877 function wfGetAllCallers( $limit = 3 ) {
1878 $trace = array_reverse( wfDebugBacktrace() );
1879 if ( !$limit || $limit > count( $trace ) - 1 ) {
1880 $limit = count( $trace ) - 1;
1882 $trace = array_slice( $trace, -$limit - 1, $limit );
1883 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1887 * Return a string representation of frame
1889 * @param $frame Array
1890 * @return string
1892 function wfFormatStackFrame( $frame ) {
1893 return isset( $frame['class'] ) ?
1894 $frame['class'] . '::' . $frame['function'] :
1895 $frame['function'];
1898 /* Some generic result counters, pulled out of SearchEngine */
1901 * @todo document
1903 * @param $offset Int
1904 * @param $limit Int
1905 * @return String
1907 function wfShowingResults( $offset, $limit ) {
1908 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1912 * Generate (prev x| next x) (20|50|100...) type links for paging
1914 * @param $offset String
1915 * @param $limit Integer
1916 * @param $link String
1917 * @param string $query optional URL query parameter string
1918 * @param bool $atend optional param for specified if this is the last page
1919 * @return String
1920 * @deprecated in 1.19; use Language::viewPrevNext() instead
1922 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
1923 wfDeprecated( __METHOD__, '1.19' );
1925 global $wgLang;
1927 $query = wfCgiToArray( $query );
1929 if ( is_object( $link ) ) {
1930 $title = $link;
1931 } else {
1932 $title = Title::newFromText( $link );
1933 if ( is_null( $title ) ) {
1934 return false;
1938 return $wgLang->viewPrevNext( $title, $offset, $limit, $query, $atend );
1942 * Make a list item, used by various special pages
1944 * @param string $page Page link
1945 * @param string $details Text between brackets
1946 * @param $oppositedm Boolean Add the direction mark opposite to your
1947 * language, to display text properly
1948 * @return String
1949 * @deprecated since 1.19; use Language::specialList() instead
1951 function wfSpecialList( $page, $details, $oppositedm = true ) {
1952 wfDeprecated( __METHOD__, '1.19' );
1954 global $wgLang;
1955 return $wgLang->specialList( $page, $details, $oppositedm );
1959 * @todo document
1960 * @todo FIXME: We may want to blacklist some broken browsers
1962 * @param $force Bool
1963 * @return bool Whereas client accept gzip compression
1965 function wfClientAcceptsGzip( $force = false ) {
1966 static $result = null;
1967 if ( $result === null || $force ) {
1968 $result = false;
1969 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1970 # @todo FIXME: We may want to blacklist some broken browsers
1971 $m = array();
1972 if ( preg_match(
1973 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1974 $_SERVER['HTTP_ACCEPT_ENCODING'],
1975 $m )
1978 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
1979 $result = false;
1980 return $result;
1982 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
1983 $result = true;
1987 return $result;
1991 * Obtain the offset and limit values from the request string;
1992 * used in special pages
1994 * @param int $deflimit default limit if none supplied
1995 * @param string $optionname Name of a user preference to check against
1996 * @return array
1999 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2000 global $wgRequest;
2001 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2005 * Escapes the given text so that it may be output using addWikiText()
2006 * without any linking, formatting, etc. making its way through. This
2007 * is achieved by substituting certain characters with HTML entities.
2008 * As required by the callers, "<nowiki>" is not used.
2010 * @param string $text text to be escaped
2011 * @return String
2013 function wfEscapeWikiText( $text ) {
2014 $text = strtr( "\n$text", array(
2015 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
2016 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
2017 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;',
2018 "\n#" => "\n&#35;", "\n*" => "\n&#42;",
2019 "\n:" => "\n&#58;", "\n;" => "\n&#59;",
2020 '://' => '&#58;//', 'ISBN ' => 'ISBN&#32;', 'RFC ' => 'RFC&#32;',
2021 ) );
2022 return substr( $text, 1 );
2026 * Get the current unix timestamp with microseconds. Useful for profiling
2027 * @return Float
2029 function wfTime() {
2030 return microtime( true );
2034 * Sets dest to source and returns the original value of dest
2035 * If source is NULL, it just returns the value, it doesn't set the variable
2036 * If force is true, it will set the value even if source is NULL
2038 * @param $dest Mixed
2039 * @param $source Mixed
2040 * @param $force Bool
2041 * @return Mixed
2043 function wfSetVar( &$dest, $source, $force = false ) {
2044 $temp = $dest;
2045 if ( !is_null( $source ) || $force ) {
2046 $dest = $source;
2048 return $temp;
2052 * As for wfSetVar except setting a bit
2054 * @param $dest Int
2055 * @param $bit Int
2056 * @param $state Bool
2058 * @return bool
2060 function wfSetBit( &$dest, $bit, $state = true ) {
2061 $temp = (bool)( $dest & $bit );
2062 if ( !is_null( $state ) ) {
2063 if ( $state ) {
2064 $dest |= $bit;
2065 } else {
2066 $dest &= ~$bit;
2069 return $temp;
2073 * A wrapper around the PHP function var_export().
2074 * Either print it or add it to the regular output ($wgOut).
2076 * @param $var mixed A PHP variable to dump.
2078 function wfVarDump( $var ) {
2079 global $wgOut;
2080 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2081 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
2082 print $s;
2083 } else {
2084 $wgOut->addHTML( $s );
2089 * Provide a simple HTTP error.
2091 * @param $code Int|String
2092 * @param $label String
2093 * @param $desc String
2095 function wfHttpError( $code, $label, $desc ) {
2096 global $wgOut;
2097 $wgOut->disable();
2098 header( "HTTP/1.0 $code $label" );
2099 header( "Status: $code $label" );
2100 $wgOut->sendCacheControl();
2102 header( 'Content-type: text/html; charset=utf-8' );
2103 print "<!doctype html>" .
2104 '<html><head><title>' .
2105 htmlspecialchars( $label ) .
2106 '</title></head><body><h1>' .
2107 htmlspecialchars( $label ) .
2108 '</h1><p>' .
2109 nl2br( htmlspecialchars( $desc ) ) .
2110 "</p></body></html>\n";
2114 * Clear away any user-level output buffers, discarding contents.
2116 * Suitable for 'starting afresh', for instance when streaming
2117 * relatively large amounts of data without buffering, or wanting to
2118 * output image files without ob_gzhandler's compression.
2120 * The optional $resetGzipEncoding parameter controls suppression of
2121 * the Content-Encoding header sent by ob_gzhandler; by default it
2122 * is left. See comments for wfClearOutputBuffers() for why it would
2123 * be used.
2125 * Note that some PHP configuration options may add output buffer
2126 * layers which cannot be removed; these are left in place.
2128 * @param $resetGzipEncoding Bool
2130 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2131 if ( $resetGzipEncoding ) {
2132 // Suppress Content-Encoding and Content-Length
2133 // headers from 1.10+s wfOutputHandler
2134 global $wgDisableOutputCompression;
2135 $wgDisableOutputCompression = true;
2137 while ( $status = ob_get_status() ) {
2138 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2139 // Probably from zlib.output_compression or other
2140 // PHP-internal setting which can't be removed.
2142 // Give up, and hope the result doesn't break
2143 // output behavior.
2144 break;
2146 if ( !ob_end_clean() ) {
2147 // Could not remove output buffer handler; abort now
2148 // to avoid getting in some kind of infinite loop.
2149 break;
2151 if ( $resetGzipEncoding ) {
2152 if ( $status['name'] == 'ob_gzhandler' ) {
2153 // Reset the 'Content-Encoding' field set by this handler
2154 // so we can start fresh.
2155 header_remove( 'Content-Encoding' );
2156 break;
2163 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2165 * Clear away output buffers, but keep the Content-Encoding header
2166 * produced by ob_gzhandler, if any.
2168 * This should be used for HTTP 304 responses, where you need to
2169 * preserve the Content-Encoding header of the real result, but
2170 * also need to suppress the output of ob_gzhandler to keep to spec
2171 * and avoid breaking Firefox in rare cases where the headers and
2172 * body are broken over two packets.
2174 function wfClearOutputBuffers() {
2175 wfResetOutputBuffers( false );
2179 * Converts an Accept-* header into an array mapping string values to quality
2180 * factors
2182 * @param $accept String
2183 * @param string $def default
2184 * @return Array
2186 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2187 # No arg means accept anything (per HTTP spec)
2188 if ( !$accept ) {
2189 return array( $def => 1.0 );
2192 $prefs = array();
2194 $parts = explode( ',', $accept );
2196 foreach ( $parts as $part ) {
2197 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2198 $values = explode( ';', trim( $part ) );
2199 $match = array();
2200 if ( count( $values ) == 1 ) {
2201 $prefs[$values[0]] = 1.0;
2202 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2203 $prefs[$values[0]] = floatval( $match[1] );
2207 return $prefs;
2211 * Checks if a given MIME type matches any of the keys in the given
2212 * array. Basic wildcards are accepted in the array keys.
2214 * Returns the matching MIME type (or wildcard) if a match, otherwise
2215 * NULL if no match.
2217 * @param $type String
2218 * @param $avail Array
2219 * @return string
2220 * @private
2222 function mimeTypeMatch( $type, $avail ) {
2223 if ( array_key_exists( $type, $avail ) ) {
2224 return $type;
2225 } else {
2226 $parts = explode( '/', $type );
2227 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2228 return $parts[0] . '/*';
2229 } elseif ( array_key_exists( '*/*', $avail ) ) {
2230 return '*/*';
2231 } else {
2232 return null;
2238 * Returns the 'best' match between a client's requested internet media types
2239 * and the server's list of available types. Each list should be an associative
2240 * array of type to preference (preference is a float between 0.0 and 1.0).
2241 * Wildcards in the types are acceptable.
2243 * @param array $cprefs client's acceptable type list
2244 * @param array $sprefs server's offered types
2245 * @return string
2247 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2248 * XXX: generalize to negotiate other stuff
2250 function wfNegotiateType( $cprefs, $sprefs ) {
2251 $combine = array();
2253 foreach ( array_keys( $sprefs ) as $type ) {
2254 $parts = explode( '/', $type );
2255 if ( $parts[1] != '*' ) {
2256 $ckey = mimeTypeMatch( $type, $cprefs );
2257 if ( $ckey ) {
2258 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2263 foreach ( array_keys( $cprefs ) as $type ) {
2264 $parts = explode( '/', $type );
2265 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2266 $skey = mimeTypeMatch( $type, $sprefs );
2267 if ( $skey ) {
2268 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2273 $bestq = 0;
2274 $besttype = null;
2276 foreach ( array_keys( $combine ) as $type ) {
2277 if ( $combine[$type] > $bestq ) {
2278 $besttype = $type;
2279 $bestq = $combine[$type];
2283 return $besttype;
2287 * Reference-counted warning suppression
2289 * @param $end Bool
2291 function wfSuppressWarnings( $end = false ) {
2292 static $suppressCount = 0;
2293 static $originalLevel = false;
2295 if ( $end ) {
2296 if ( $suppressCount ) {
2297 --$suppressCount;
2298 if ( !$suppressCount ) {
2299 error_reporting( $originalLevel );
2302 } else {
2303 if ( !$suppressCount ) {
2304 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT ) );
2306 ++$suppressCount;
2311 * Restore error level to previous value
2313 function wfRestoreWarnings() {
2314 wfSuppressWarnings( true );
2317 # Autodetect, convert and provide timestamps of various types
2320 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2322 define( 'TS_UNIX', 0 );
2325 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2327 define( 'TS_MW', 1 );
2330 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2332 define( 'TS_DB', 2 );
2335 * RFC 2822 format, for E-mail and HTTP headers
2337 define( 'TS_RFC2822', 3 );
2340 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2342 * This is used by Special:Export
2344 define( 'TS_ISO_8601', 4 );
2347 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2349 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2350 * DateTime tag and page 36 for the DateTimeOriginal and
2351 * DateTimeDigitized tags.
2353 define( 'TS_EXIF', 5 );
2356 * Oracle format time.
2358 define( 'TS_ORACLE', 6 );
2361 * Postgres format time.
2363 define( 'TS_POSTGRES', 7 );
2366 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2368 define( 'TS_ISO_8601_BASIC', 9 );
2371 * Get a timestamp string in one of various formats
2373 * @param $outputtype Mixed: A timestamp in one of the supported formats, the
2374 * function will autodetect which format is supplied and act
2375 * accordingly.
2376 * @param $ts Mixed: optional timestamp to convert, default 0 for the current time
2377 * @return Mixed: String / false The same date in the format specified in $outputtype or false
2379 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2380 try {
2381 $timestamp = new MWTimestamp( $ts );
2382 return $timestamp->getTimestamp( $outputtype );
2383 } catch ( TimestampException $e ) {
2384 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2385 return false;
2390 * Return a formatted timestamp, or null if input is null.
2391 * For dealing with nullable timestamp columns in the database.
2393 * @param $outputtype Integer
2394 * @param $ts String
2395 * @return String
2397 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2398 if ( is_null( $ts ) ) {
2399 return null;
2400 } else {
2401 return wfTimestamp( $outputtype, $ts );
2406 * Convenience function; returns MediaWiki timestamp for the present time.
2408 * @return string
2410 function wfTimestampNow() {
2411 # return NOW
2412 return wfTimestamp( TS_MW, time() );
2416 * Check if the operating system is Windows
2418 * @return Bool: true if it's Windows, False otherwise.
2420 function wfIsWindows() {
2421 static $isWindows = null;
2422 if ( $isWindows === null ) {
2423 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2425 return $isWindows;
2429 * Check if we are running under HipHop
2431 * @return Bool
2433 function wfIsHipHop() {
2434 return function_exists( 'hphp_thread_set_warmup_enabled' );
2438 * Swap two variables
2440 * @param $x Mixed
2441 * @param $y Mixed
2443 function swap( &$x, &$y ) {
2444 $z = $x;
2445 $x = $y;
2446 $y = $z;
2450 * Tries to get the system directory for temporary files. First
2451 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2452 * environment variables are then checked in sequence, and if none are
2453 * set try sys_get_temp_dir().
2455 * NOTE: When possible, use instead the tmpfile() function to create
2456 * temporary files to avoid race conditions on file creation, etc.
2458 * @return String
2460 function wfTempDir() {
2461 global $wgTmpDirectory;
2463 if ( $wgTmpDirectory !== false ) {
2464 return $wgTmpDirectory;
2467 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2469 foreach ( $tmpDir as $tmp ) {
2470 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2471 return $tmp;
2474 return sys_get_temp_dir();
2478 * Make directory, and make all parent directories if they don't exist
2480 * @param string $dir full path to directory to create
2481 * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
2482 * @param string $caller optional caller param for debugging.
2483 * @throws MWException
2484 * @return bool
2486 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2487 global $wgDirectoryMode;
2489 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
2490 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
2493 if ( !is_null( $caller ) ) {
2494 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2497 if ( strval( $dir ) === '' || file_exists( $dir ) ) {
2498 return true;
2501 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2503 if ( is_null( $mode ) ) {
2504 $mode = $wgDirectoryMode;
2507 // Turn off the normal warning, we're doing our own below
2508 wfSuppressWarnings();
2509 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2510 wfRestoreWarnings();
2512 if ( !$ok ) {
2513 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2514 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2516 return $ok;
2520 * Remove a directory and all its content.
2521 * Does not hide error.
2523 function wfRecursiveRemoveDir( $dir ) {
2524 wfDebug( __FUNCTION__ . "( $dir )\n" );
2525 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2526 if ( is_dir( $dir ) ) {
2527 $objects = scandir( $dir );
2528 foreach ( $objects as $object ) {
2529 if ( $object != "." && $object != ".." ) {
2530 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2531 wfRecursiveRemoveDir( $dir . '/' . $object );
2532 } else {
2533 unlink( $dir . '/' . $object );
2537 reset( $objects );
2538 rmdir( $dir );
2543 * @param $nr Mixed: the number to format
2544 * @param $acc Integer: the number of digits after the decimal point, default 2
2545 * @param $round Boolean: whether or not to round the value, default true
2546 * @return float
2548 function wfPercent( $nr, $acc = 2, $round = true ) {
2549 $ret = sprintf( "%.${acc}f", $nr );
2550 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2554 * Find out whether or not a mixed variable exists in a string
2556 * @deprecated Just use str(i)pos
2557 * @param $needle String
2558 * @param $str String
2559 * @param $insensitive Boolean
2560 * @return Boolean
2562 function in_string( $needle, $str, $insensitive = false ) {
2563 wfDeprecated( __METHOD__, '1.21' );
2564 $func = 'strpos';
2565 if ( $insensitive ) {
2566 $func = 'stripos';
2569 return $func( $str, $needle ) !== false;
2573 * Safety wrapper around ini_get() for boolean settings.
2574 * The values returned from ini_get() are pre-normalized for settings
2575 * set via php.ini or php_flag/php_admin_flag... but *not*
2576 * for those set via php_value/php_admin_value.
2578 * It's fairly common for people to use php_value instead of php_flag,
2579 * which can leave you with an 'off' setting giving a false positive
2580 * for code that just takes the ini_get() return value as a boolean.
2582 * To make things extra interesting, setting via php_value accepts
2583 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2584 * Unrecognized values go false... again opposite PHP's own coercion
2585 * from string to bool.
2587 * Luckily, 'properly' set settings will always come back as '0' or '1',
2588 * so we only have to worry about them and the 'improper' settings.
2590 * I frickin' hate PHP... :P
2592 * @param $setting String
2593 * @return Bool
2595 function wfIniGetBool( $setting ) {
2596 $val = strtolower( ini_get( $setting ) );
2597 // 'on' and 'true' can't have whitespace around them, but '1' can.
2598 return $val == 'on'
2599 || $val == 'true'
2600 || $val == 'yes'
2601 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2605 * Wrapper function for PHP's dl(). This doesn't work in most situations from
2606 * PHP 5.3 onward, and is usually disabled in shared environments anyway.
2608 * @param string $extension A PHP extension. The file suffix (.so or .dll)
2609 * should be omitted
2610 * @param string $fileName Name of the library, if not $extension.suffix
2611 * @return Bool - Whether or not the extension is loaded
2613 function wfDl( $extension, $fileName = null ) {
2614 if ( extension_loaded( $extension ) ) {
2615 return true;
2618 $canDl = false;
2619 if ( PHP_SAPI == 'cli' || PHP_SAPI == 'cgi' || PHP_SAPI == 'embed' ) {
2620 $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
2621 && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
2624 if ( $canDl ) {
2625 $fileName = $fileName ? $fileName : $extension;
2626 if ( wfIsWindows() ) {
2627 $fileName = 'php_' . $fileName;
2629 wfSuppressWarnings();
2630 dl( $fileName . '.' . PHP_SHLIB_SUFFIX );
2631 wfRestoreWarnings();
2633 return extension_loaded( $extension );
2637 * Windows-compatible version of escapeshellarg()
2638 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2639 * function puts single quotes in regardless of OS.
2641 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2642 * earlier distro releases of PHP)
2644 * @param varargs
2645 * @return String
2647 function wfEscapeShellArg() {
2648 wfInitShellLocale();
2650 $args = func_get_args();
2651 $first = true;
2652 $retVal = '';
2653 foreach ( $args as $arg ) {
2654 if ( !$first ) {
2655 $retVal .= ' ';
2656 } else {
2657 $first = false;
2660 if ( wfIsWindows() ) {
2661 // Escaping for an MSVC-style command line parser and CMD.EXE
2662 // Refs:
2663 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2664 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2665 // * Bug #13518
2666 // * CR r63214
2667 // Double the backslashes before any double quotes. Escape the double quotes.
2668 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
2669 $arg = '';
2670 $iteration = 0;
2671 foreach ( $tokens as $token ) {
2672 if ( $iteration % 2 == 1 ) {
2673 // Delimiter, a double quote preceded by zero or more slashes
2674 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2675 } elseif ( $iteration % 4 == 2 ) {
2676 // ^ in $token will be outside quotes, need to be escaped
2677 $arg .= str_replace( '^', '^^', $token );
2678 } else { // $iteration % 4 == 0
2679 // ^ in $token will appear inside double quotes, so leave as is
2680 $arg .= $token;
2682 $iteration++;
2684 // Double the backslashes before the end of the string, because
2685 // we will soon add a quote
2686 $m = array();
2687 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2688 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2691 // Add surrounding quotes
2692 $retVal .= '"' . $arg . '"';
2693 } else {
2694 $retVal .= escapeshellarg( $arg );
2697 return $retVal;
2701 * Check if wfShellExec() is effectively disabled via php.ini config
2702 * @return bool|string False or one of (safemode,disabled)
2703 * @since 1.22
2705 function wfShellExecDisabled() {
2706 static $disabled = null;
2707 if ( is_null( $disabled ) ) {
2708 $disabled = false;
2709 if ( wfIniGetBool( 'safe_mode' ) ) {
2710 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2711 $disabled = 'safemode';
2712 } else {
2713 $functions = explode( ',', ini_get( 'disable_functions' ) );
2714 $functions = array_map( 'trim', $functions );
2715 $functions = array_map( 'strtolower', $functions );
2716 if ( in_array( 'passthru', $functions ) ) {
2717 wfDebug( "passthru is in disabled_functions\n" );
2718 $disabled = 'passthru';
2722 return $disabled;
2726 * Execute a shell command, with time and memory limits mirrored from the PHP
2727 * configuration if supported.
2728 * @param string $cmd Command line, properly escaped for shell.
2729 * @param &$retval null|Mixed optional, will receive the program's exit code.
2730 * (non-zero is usually failure)
2731 * @param array $environ optional environment variables which should be
2732 * added to the executed command environment.
2733 * @param array $limits optional array with limits(filesize, memory, time, walltime)
2734 * this overwrites the global wgShellMax* limits.
2735 * @return string collected stdout as a string (trailing newlines stripped)
2737 function wfShellExec( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2738 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2739 $wgMaxShellWallClockTime, $wgShellCgroup;
2741 $disabled = wfShellExecDisabled();
2742 if ( $disabled ) {
2743 $retval = 1;
2744 return $disabled == 'safemode' ?
2745 'Unable to run external programs in safe mode.' :
2746 'Unable to run external programs, passthru() is disabled.';
2749 wfInitShellLocale();
2751 $envcmd = '';
2752 foreach ( $environ as $k => $v ) {
2753 if ( wfIsWindows() ) {
2754 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2755 * appear in the environment variable, so we must use carat escaping as documented in
2756 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2757 * Note however that the quote isn't listed there, but is needed, and the parentheses
2758 * are listed there but doesn't appear to need it.
2760 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2761 } else {
2762 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2763 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2765 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2768 $cmd = $envcmd . $cmd;
2770 if ( php_uname( 's' ) == 'Linux' ) {
2771 $time = intval ( isset( $limits['time'] ) ? $limits['time'] : $wgMaxShellTime );
2772 if ( isset( $limits['walltime'] ) ) {
2773 $wallTime = intval( $limits['walltime'] );
2774 } elseif ( isset( $limits['time'] ) ) {
2775 $wallTime = $time;
2776 } else {
2777 $wallTime = intval( $wgMaxShellWallClockTime );
2779 $mem = intval ( isset( $limits['memory'] ) ? $limits['memory'] : $wgMaxShellMemory );
2780 $filesize = intval ( isset( $limits['filesize'] ) ? $limits['filesize'] : $wgMaxShellFileSize );
2782 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
2783 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2784 escapeshellarg( $cmd ) . ' ' .
2785 escapeshellarg(
2786 "MW_CPU_LIMIT=$time; " .
2787 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2788 "MW_MEM_LIMIT=$mem; " .
2789 "MW_FILE_SIZE_LIMIT=$filesize; " .
2790 "MW_WALL_CLOCK_LIMIT=$wallTime"
2794 wfDebug( "wfShellExec: $cmd\n" );
2796 $retval = 1; // error by default?
2797 ob_start();
2798 passthru( $cmd, $retval );
2799 $output = ob_get_contents();
2800 ob_end_clean();
2802 if ( $retval == 127 ) {
2803 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2805 return $output;
2809 * Workaround for http://bugs.php.net/bug.php?id=45132
2810 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2812 function wfInitShellLocale() {
2813 static $done = false;
2814 if ( $done ) {
2815 return;
2817 $done = true;
2818 global $wgShellLocale;
2819 if ( !wfIniGetBool( 'safe_mode' ) ) {
2820 putenv( "LC_CTYPE=$wgShellLocale" );
2821 setlocale( LC_CTYPE, $wgShellLocale );
2826 * Alias to wfShellWikiCmd()
2827 * @see wfShellWikiCmd()
2829 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
2830 return wfShellWikiCmd( $script, $parameters, $options );
2834 * Generate a shell-escaped command line string to run a MediaWiki cli script.
2835 * Note that $parameters should be a flat array and an option with an argument
2836 * should consist of two consecutive items in the array (do not use "--option value").
2837 * @param string $script MediaWiki cli script path
2838 * @param array $parameters Arguments and options to the script
2839 * @param array $options Associative array of options:
2840 * 'php': The path to the php executable
2841 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
2842 * @return Array
2844 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
2845 global $wgPhpCli;
2846 // Give site config file a chance to run the script in a wrapper.
2847 // The caller may likely want to call wfBasename() on $script.
2848 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
2849 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
2850 if ( isset( $options['wrapper'] ) ) {
2851 $cmd[] = $options['wrapper'];
2853 $cmd[] = $script;
2854 // Escape each parameter for shell
2855 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
2859 * wfMerge attempts to merge differences between three texts.
2860 * Returns true for a clean merge and false for failure or a conflict.
2862 * @param $old String
2863 * @param $mine String
2864 * @param $yours String
2865 * @param $result String
2866 * @return Bool
2868 function wfMerge( $old, $mine, $yours, &$result ) {
2869 global $wgDiff3;
2871 # This check may also protect against code injection in
2872 # case of broken installations.
2873 wfSuppressWarnings();
2874 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2875 wfRestoreWarnings();
2877 if ( !$haveDiff3 ) {
2878 wfDebug( "diff3 not found\n" );
2879 return false;
2882 # Make temporary files
2883 $td = wfTempDir();
2884 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2885 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
2886 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
2888 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
2889 # a newline character. To avoid this, we normalize the trailing whitespace before
2890 # creating the diff.
2892 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
2893 fclose( $oldtextFile );
2894 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
2895 fclose( $mytextFile );
2896 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
2897 fclose( $yourtextFile );
2899 # Check for a conflict
2900 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
2901 wfEscapeShellArg( $mytextName ) . ' ' .
2902 wfEscapeShellArg( $oldtextName ) . ' ' .
2903 wfEscapeShellArg( $yourtextName );
2904 $handle = popen( $cmd, 'r' );
2906 if ( fgets( $handle, 1024 ) ) {
2907 $conflict = true;
2908 } else {
2909 $conflict = false;
2911 pclose( $handle );
2913 # Merge differences
2914 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
2915 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
2916 $handle = popen( $cmd, 'r' );
2917 $result = '';
2918 do {
2919 $data = fread( $handle, 8192 );
2920 if ( strlen( $data ) == 0 ) {
2921 break;
2923 $result .= $data;
2924 } while ( true );
2925 pclose( $handle );
2926 unlink( $mytextName );
2927 unlink( $oldtextName );
2928 unlink( $yourtextName );
2930 if ( $result === '' && $old !== '' && !$conflict ) {
2931 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
2932 $conflict = true;
2934 return !$conflict;
2938 * Returns unified plain-text diff of two texts.
2939 * Useful for machine processing of diffs.
2941 * @param string $before the text before the changes.
2942 * @param string $after the text after the changes.
2943 * @param string $params command-line options for the diff command.
2944 * @return String: unified diff of $before and $after
2946 function wfDiff( $before, $after, $params = '-u' ) {
2947 if ( $before == $after ) {
2948 return '';
2951 global $wgDiff;
2952 wfSuppressWarnings();
2953 $haveDiff = $wgDiff && file_exists( $wgDiff );
2954 wfRestoreWarnings();
2956 # This check may also protect against code injection in
2957 # case of broken installations.
2958 if ( !$haveDiff ) {
2959 wfDebug( "diff executable not found\n" );
2960 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
2961 $format = new UnifiedDiffFormatter();
2962 return $format->format( $diffs );
2965 # Make temporary files
2966 $td = wfTempDir();
2967 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
2968 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
2970 fwrite( $oldtextFile, $before );
2971 fclose( $oldtextFile );
2972 fwrite( $newtextFile, $after );
2973 fclose( $newtextFile );
2975 // Get the diff of the two files
2976 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
2978 $h = popen( $cmd, 'r' );
2980 $diff = '';
2982 do {
2983 $data = fread( $h, 8192 );
2984 if ( strlen( $data ) == 0 ) {
2985 break;
2987 $diff .= $data;
2988 } while ( true );
2990 // Clean up
2991 pclose( $h );
2992 unlink( $oldtextName );
2993 unlink( $newtextName );
2995 // Kill the --- and +++ lines. They're not useful.
2996 $diff_lines = explode( "\n", $diff );
2997 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
2998 unset( $diff_lines[0] );
3000 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
3001 unset( $diff_lines[1] );
3004 $diff = implode( "\n", $diff_lines );
3006 return $diff;
3010 * This function works like "use VERSION" in Perl, the program will die with a
3011 * backtrace if the current version of PHP is less than the version provided
3013 * This is useful for extensions which due to their nature are not kept in sync
3014 * with releases, and might depend on other versions of PHP than the main code
3016 * Note: PHP might die due to parsing errors in some cases before it ever
3017 * manages to call this function, such is life
3019 * @see perldoc -f use
3021 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
3022 * a float
3023 * @throws MWException
3025 function wfUsePHP( $req_ver ) {
3026 $php_ver = PHP_VERSION;
3028 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3029 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3034 * This function works like "use VERSION" in Perl except it checks the version
3035 * of MediaWiki, the program will die with a backtrace if the current version
3036 * of MediaWiki is less than the version provided.
3038 * This is useful for extensions which due to their nature are not kept in sync
3039 * with releases
3041 * @see perldoc -f use
3043 * @param $req_ver Mixed: the version to check, can be a string, an integer, or
3044 * a float
3045 * @throws MWException
3047 function wfUseMW( $req_ver ) {
3048 global $wgVersion;
3050 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3051 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3056 * Return the final portion of a pathname.
3057 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3058 * http://bugs.php.net/bug.php?id=33898
3060 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3061 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3063 * @param $path String
3064 * @param string $suffix to remove if present
3065 * @return String
3067 function wfBaseName( $path, $suffix = '' ) {
3068 $encSuffix = ( $suffix == '' )
3069 ? ''
3070 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
3071 $matches = array();
3072 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3073 return $matches[1];
3074 } else {
3075 return '';
3080 * Generate a relative path name to the given file.
3081 * May explode on non-matching case-insensitive paths,
3082 * funky symlinks, etc.
3084 * @param string $path absolute destination path including target filename
3085 * @param string $from Absolute source path, directory only
3086 * @return String
3088 function wfRelativePath( $path, $from ) {
3089 // Normalize mixed input on Windows...
3090 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
3091 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
3093 // Trim trailing slashes -- fix for drive root
3094 $path = rtrim( $path, DIRECTORY_SEPARATOR );
3095 $from = rtrim( $from, DIRECTORY_SEPARATOR );
3097 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
3098 $against = explode( DIRECTORY_SEPARATOR, $from );
3100 if ( $pieces[0] !== $against[0] ) {
3101 // Non-matching Windows drive letters?
3102 // Return a full path.
3103 return $path;
3106 // Trim off common prefix
3107 while ( count( $pieces ) && count( $against )
3108 && $pieces[0] == $against[0] ) {
3109 array_shift( $pieces );
3110 array_shift( $against );
3113 // relative dots to bump us to the parent
3114 while ( count( $against ) ) {
3115 array_unshift( $pieces, '..' );
3116 array_shift( $against );
3119 array_push( $pieces, wfBaseName( $path ) );
3121 return implode( DIRECTORY_SEPARATOR, $pieces );
3125 * Do any deferred updates and clear the list
3127 * @deprecated since 1.19
3128 * @see DeferredUpdates::doUpdate()
3129 * @param $commit string
3131 function wfDoUpdates( $commit = '' ) {
3132 wfDeprecated( __METHOD__, '1.19' );
3133 DeferredUpdates::doUpdates( $commit );
3137 * Convert an arbitrarily-long digit string from one numeric base
3138 * to another, optionally zero-padding to a minimum column width.
3140 * Supports base 2 through 36; digit values 10-36 are represented
3141 * as lowercase letters a-z. Input is case-insensitive.
3143 * @param string $input Input number
3144 * @param int $sourceBase Base of the input number
3145 * @param int $destBase Desired base of the output
3146 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3147 * @param bool $lowercase Whether to output in lowercase or uppercase
3148 * @param string $engine Either "gmp", "bcmath", or "php"
3149 * @return string|bool The output number as a string, or false on error
3151 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true, $engine = 'auto' ) {
3152 $input = (string)$input;
3153 if (
3154 $sourceBase < 2 ||
3155 $sourceBase > 36 ||
3156 $destBase < 2 ||
3157 $destBase > 36 ||
3158 $sourceBase != (int) $sourceBase ||
3159 $destBase != (int) $destBase ||
3160 $pad != (int) $pad ||
3161 !preg_match( "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i", $input )
3163 return false;
3166 static $baseChars = array(
3167 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3168 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3169 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3170 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3171 34 => 'y', 35 => 'z',
3173 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3174 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3175 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3176 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3177 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3178 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3181 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' || $engine == 'gmp' ) ) {
3182 $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
3183 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' || $engine == 'bcmath' ) ) {
3184 $decimal = '0';
3185 foreach ( str_split( strtolower( $input ) ) as $char ) {
3186 $decimal = bcmul( $decimal, $sourceBase );
3187 $decimal = bcadd( $decimal, $baseChars[$char] );
3190 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3191 $result .= $baseChars[bcmod( $decimal, $destBase )];
3194 $result = strrev( $result );
3195 } else {
3196 $inDigits = array();
3197 foreach ( str_split( strtolower( $input ) ) as $char ) {
3198 $inDigits[] = $baseChars[$char];
3201 // Iterate over the input, modulo-ing out an output digit
3202 // at a time until input is gone.
3203 $result = '';
3204 while ( $inDigits ) {
3205 $work = 0;
3206 $workDigits = array();
3208 // Long division...
3209 foreach ( $inDigits as $digit ) {
3210 $work *= $sourceBase;
3211 $work += $digit;
3213 if ( $workDigits || $work >= $destBase ) {
3214 $workDigits[] = (int) ( $work / $destBase );
3216 $work %= $destBase;
3219 // All that division leaves us with a remainder,
3220 // which is conveniently our next output digit.
3221 $result .= $baseChars[$work];
3223 // And we continue!
3224 $inDigits = $workDigits;
3227 $result = strrev( $result );
3230 if ( !$lowercase ) {
3231 $result = strtoupper( $result );
3234 return str_pad( $result, $pad, '0', STR_PAD_LEFT );
3238 * Create an object with a given name and an array of construct parameters
3240 * @param $name String
3241 * @param array $p parameters
3242 * @return object
3243 * @deprecated since 1.18, warnings in 1.18, removal in 1.20
3245 function wfCreateObject( $name, $p ) {
3246 wfDeprecated( __FUNCTION__, '1.18' );
3247 return MWFunction::newObj( $name, $p );
3251 * @return bool
3253 function wfHttpOnlySafe() {
3254 global $wgHttpOnlyBlacklist;
3256 if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
3257 foreach ( $wgHttpOnlyBlacklist as $regex ) {
3258 if ( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3259 return false;
3264 return true;
3268 * Check if there is sufficient entropy in php's built-in session generation
3269 * @return bool true = there is sufficient entropy
3271 function wfCheckEntropy() {
3272 return (
3273 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
3274 || ini_get( 'session.entropy_file' )
3276 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3280 * Override session_id before session startup if php's built-in
3281 * session generation code is not secure.
3283 function wfFixSessionID() {
3284 // If the cookie or session id is already set we already have a session and should abort
3285 if ( isset( $_COOKIE[session_name()] ) || session_id() ) {
3286 return;
3289 // PHP's built-in session entropy is enabled if:
3290 // - entropy_file is set or you're on Windows with php 5.3.3+
3291 // - AND entropy_length is > 0
3292 // We treat it as disabled if it doesn't have an entropy length of at least 32
3293 $entropyEnabled = wfCheckEntropy();
3295 // If built-in entropy is not enabled or not sufficient override php's built in session id generation code
3296 if ( !$entropyEnabled ) {
3297 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, overriding session id generation using our cryptrand source.\n" );
3298 session_id( MWCryptRand::generateHex( 32 ) );
3303 * Initialise php session
3305 * @param $sessionId Bool
3307 function wfSetupSession( $sessionId = false ) {
3308 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3309 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3310 if ( $wgSessionsInObjectCache || $wgSessionsInMemcached ) {
3311 ObjectCacheSessionHandler::install();
3312 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3313 # Only set this if $wgSessionHandler isn't null and session.save_handler
3314 # hasn't already been set to the desired value (that causes errors)
3315 ini_set( 'session.save_handler', $wgSessionHandler );
3317 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
3318 wfDebugLog( 'cookie',
3319 'session_set_cookie_params: "' . implode( '", "',
3320 array(
3322 $wgCookiePath,
3323 $wgCookieDomain,
3324 $wgCookieSecure,
3325 $httpOnlySafe ) ) . '"' );
3326 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
3327 session_cache_limiter( 'private, must-revalidate' );
3328 if ( $sessionId ) {
3329 session_id( $sessionId );
3330 } else {
3331 wfFixSessionID();
3333 wfSuppressWarnings();
3334 session_start();
3335 wfRestoreWarnings();
3339 * Get an object from the precompiled serialized directory
3341 * @param $name String
3342 * @return Mixed: the variable on success, false on failure
3344 function wfGetPrecompiledData( $name ) {
3345 global $IP;
3347 $file = "$IP/serialized/$name";
3348 if ( file_exists( $file ) ) {
3349 $blob = file_get_contents( $file );
3350 if ( $blob ) {
3351 return unserialize( $blob );
3354 return false;
3358 * Get a cache key
3360 * @param varargs
3361 * @return String
3363 function wfMemcKey( /*... */ ) {
3364 global $wgCachePrefix;
3365 $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix;
3366 $args = func_get_args();
3367 $key = $prefix . ':' . implode( ':', $args );
3368 $key = str_replace( ' ', '_', $key );
3369 return $key;
3373 * Get a cache key for a foreign DB
3375 * @param $db String
3376 * @param $prefix String
3377 * @param varargs String
3378 * @return String
3380 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3381 $args = array_slice( func_get_args(), 2 );
3382 if ( $prefix ) {
3383 $key = "$db-$prefix:" . implode( ':', $args );
3384 } else {
3385 $key = $db . ':' . implode( ':', $args );
3387 return $key;
3391 * Get an ASCII string identifying this wiki
3392 * This is used as a prefix in memcached keys
3394 * @return String
3396 function wfWikiID() {
3397 global $wgDBprefix, $wgDBname;
3398 if ( $wgDBprefix ) {
3399 return "$wgDBname-$wgDBprefix";
3400 } else {
3401 return $wgDBname;
3406 * Split a wiki ID into DB name and table prefix
3408 * @param $wiki String
3410 * @return array
3412 function wfSplitWikiID( $wiki ) {
3413 $bits = explode( '-', $wiki, 2 );
3414 if ( count( $bits ) < 2 ) {
3415 $bits[] = '';
3417 return $bits;
3421 * Get a Database object.
3423 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3424 * master (for write queries), DB_SLAVE for potentially lagged read
3425 * queries, or an integer >= 0 for a particular server.
3427 * @param $groups Mixed: query groups. An array of group names that this query
3428 * belongs to. May contain a single string if the query is only
3429 * in one group.
3431 * @param string $wiki the wiki ID, or false for the current wiki
3433 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3434 * will always return the same object, unless the underlying connection or load
3435 * balancer is manually destroyed.
3437 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3438 * updater to ensure that a proper database is being updated.
3440 * @return DatabaseBase
3442 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3443 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3447 * Get a load balancer object.
3449 * @param string $wiki wiki ID, or false for the current wiki
3450 * @return LoadBalancer
3452 function wfGetLB( $wiki = false ) {
3453 return wfGetLBFactory()->getMainLB( $wiki );
3457 * Get the load balancer factory object
3459 * @return LBFactory
3461 function &wfGetLBFactory() {
3462 return LBFactory::singleton();
3466 * Find a file.
3467 * Shortcut for RepoGroup::singleton()->findFile()
3469 * @param string $title or Title object
3470 * @param array $options Associative array of options:
3471 * time: requested time for an archived image, or false for the
3472 * current version. An image object will be returned which was
3473 * created at the specified time.
3475 * ignoreRedirect: If true, do not follow file redirects
3477 * private: If true, return restricted (deleted) files if the current
3478 * user is allowed to view them. Otherwise, such files will not
3479 * be found.
3481 * bypassCache: If true, do not use the process-local cache of File objects
3483 * @return File, or false if the file does not exist
3485 function wfFindFile( $title, $options = array() ) {
3486 return RepoGroup::singleton()->findFile( $title, $options );
3490 * Get an object referring to a locally registered file.
3491 * Returns a valid placeholder object if the file does not exist.
3493 * @param $title Title|String
3494 * @return LocalFile|null A File, or null if passed an invalid Title
3496 function wfLocalFile( $title ) {
3497 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3501 * Stream a file to the browser. Back-compat alias for StreamFile::stream()
3502 * @deprecated since 1.19
3504 function wfStreamFile( $fname, $headers = array() ) {
3505 wfDeprecated( __FUNCTION__, '1.19' );
3506 StreamFile::stream( $fname, $headers );
3510 * Should low-performance queries be disabled?
3512 * @return Boolean
3513 * @codeCoverageIgnore
3515 function wfQueriesMustScale() {
3516 global $wgMiserMode;
3517 return $wgMiserMode
3518 || ( SiteStats::pages() > 100000
3519 && SiteStats::edits() > 1000000
3520 && SiteStats::users() > 10000 );
3524 * Get the path to a specified script file, respecting file
3525 * extensions; this is a wrapper around $wgScriptExtension etc.
3526 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3528 * @param string $script script filename, sans extension
3529 * @return String
3531 function wfScript( $script = 'index' ) {
3532 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3533 if ( $script === 'index' ) {
3534 return $wgScript;
3535 } elseif ( $script === 'load' ) {
3536 return $wgLoadScript;
3537 } else {
3538 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3543 * Get the script URL.
3545 * @return string script URL
3547 function wfGetScriptUrl() {
3548 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3550 # as it was called, minus the query string.
3552 # Some sites use Apache rewrite rules to handle subdomains,
3553 # and have PHP set up in a weird way that causes PHP_SELF
3554 # to contain the rewritten URL instead of the one that the
3555 # outside world sees.
3557 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3558 # provides containing the "before" URL.
3559 return $_SERVER['SCRIPT_NAME'];
3560 } else {
3561 return $_SERVER['URL'];
3566 * Convenience function converts boolean values into "true"
3567 * or "false" (string) values
3569 * @param $value Boolean
3570 * @return String
3572 function wfBoolToStr( $value ) {
3573 return $value ? 'true' : 'false';
3577 * Get a platform-independent path to the null file, e.g. /dev/null
3579 * @return string
3581 function wfGetNull() {
3582 return wfIsWindows()
3583 ? 'NUL'
3584 : '/dev/null';
3588 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3589 * and waiting for it to go down, this waits for the slaves to catch up to the
3590 * master position. Use this when updating very large numbers of rows, as
3591 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3592 * a no-op if there are no slaves.
3594 * @param $maxLag Integer (deprecated)
3595 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3596 * @param $cluster string cluster name accepted by LBFactory
3598 function wfWaitForSlaves( $maxLag = false, $wiki = false, $cluster = false ) {
3599 $lb = ( $cluster !== false )
3600 ? wfGetLBFactory()->getExternalLB( $cluster )
3601 : wfGetLB( $wiki );
3602 // bug 27975 - Don't try to wait for slaves if there are none
3603 // Prevents permission error when getting master position
3604 if ( $lb->getServerCount() > 1 ) {
3605 $dbw = $lb->getConnection( DB_MASTER, array(), $wiki );
3606 $pos = $dbw->getMasterPos();
3607 // The DBMS may not support getMasterPos() or the whole
3608 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3609 if ( $pos !== false ) {
3610 $lb->waitForAll( $pos );
3616 * Used to be used for outputting text in the installer/updater
3617 * @deprecated since 1.18, warnings in 1.18, remove in 1.20
3619 function wfOut( $s ) {
3620 wfDeprecated( __FUNCTION__, '1.18' );
3621 global $wgCommandLineMode;
3622 if ( $wgCommandLineMode ) {
3623 echo $s;
3624 } else {
3625 echo htmlspecialchars( $s );
3627 flush();
3631 * Count down from $n to zero on the terminal, with a one-second pause
3632 * between showing each number. For use in command-line scripts.
3633 * @codeCoverageIgnore
3634 * @param $n int
3636 function wfCountDown( $n ) {
3637 for ( $i = $n; $i >= 0; $i-- ) {
3638 if ( $i != $n ) {
3639 echo str_repeat( "\x08", strlen( $i + 1 ) );
3641 echo $i;
3642 flush();
3643 if ( $i ) {
3644 sleep( 1 );
3647 echo "\n";
3651 * Generate a random 32-character hexadecimal token.
3652 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3653 * characters before hashing.
3654 * @return string
3655 * @codeCoverageIgnore
3656 * @deprecated since 1.20; Please use MWCryptRand for security purposes and wfRandomString for pseudo-random strings
3657 * @warning This method is NOT secure. Additionally it has many callers that use it for pseudo-random purposes.
3659 function wfGenerateToken( $salt = '' ) {
3660 wfDeprecated( __METHOD__, '1.20' );
3661 $salt = serialize( $salt );
3662 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3666 * Replace all invalid characters with -
3667 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3668 * By default, $wgIllegalFileChars = ':'
3670 * @param $name Mixed: filename to process
3671 * @return String
3673 function wfStripIllegalFilenameChars( $name ) {
3674 global $wgIllegalFileChars;
3675 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
3676 $name = wfBaseName( $name );
3677 $name = preg_replace(
3678 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
3679 '-',
3680 $name
3682 return $name;
3686 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3688 * @return Integer value memory was set to.
3690 function wfMemoryLimit() {
3691 global $wgMemoryLimit;
3692 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3693 if ( $memlimit != -1 ) {
3694 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3695 if ( $conflimit == -1 ) {
3696 wfDebug( "Removing PHP's memory limit\n" );
3697 wfSuppressWarnings();
3698 ini_set( 'memory_limit', $conflimit );
3699 wfRestoreWarnings();
3700 return $conflimit;
3701 } elseif ( $conflimit > $memlimit ) {
3702 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3703 wfSuppressWarnings();
3704 ini_set( 'memory_limit', $conflimit );
3705 wfRestoreWarnings();
3706 return $conflimit;
3709 return $memlimit;
3713 * Converts shorthand byte notation to integer form
3715 * @param $string String
3716 * @return Integer
3718 function wfShorthandToInteger( $string = '' ) {
3719 $string = trim( $string );
3720 if ( $string === '' ) {
3721 return -1;
3723 $last = $string[strlen( $string ) - 1];
3724 $val = intval( $string );
3725 switch ( $last ) {
3726 case 'g':
3727 case 'G':
3728 $val *= 1024;
3729 // break intentionally missing
3730 case 'm':
3731 case 'M':
3732 $val *= 1024;
3733 // break intentionally missing
3734 case 'k':
3735 case 'K':
3736 $val *= 1024;
3739 return $val;
3743 * Get the normalised IETF language tag
3744 * See unit test for examples.
3746 * @param string $code The language code.
3747 * @return String: The language code which complying with BCP 47 standards.
3749 function wfBCP47( $code ) {
3750 $codeSegment = explode( '-', $code );
3751 $codeBCP = array();
3752 foreach ( $codeSegment as $segNo => $seg ) {
3753 if ( count( $codeSegment ) > 0 ) {
3754 // when previous segment is x, it is a private segment and should be lc
3755 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3756 $codeBCP[$segNo] = strtolower( $seg );
3757 // ISO 3166 country code
3758 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3759 $codeBCP[$segNo] = strtoupper( $seg );
3760 // ISO 15924 script code
3761 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3762 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3763 // Use lowercase for other cases
3764 } else {
3765 $codeBCP[$segNo] = strtolower( $seg );
3767 } else {
3768 // Use lowercase for single segment
3769 $codeBCP[$segNo] = strtolower( $seg );
3772 $langCode = implode( '-', $codeBCP );
3773 return $langCode;
3777 * Get a cache object.
3779 * @param $inputType integer Cache type, one the the CACHE_* constants.
3780 * @return BagOStuff
3782 function wfGetCache( $inputType ) {
3783 return ObjectCache::getInstance( $inputType );
3787 * Get the main cache object
3789 * @return BagOStuff
3791 function wfGetMainCache() {
3792 global $wgMainCacheType;
3793 return ObjectCache::getInstance( $wgMainCacheType );
3797 * Get the cache object used by the message cache
3799 * @return BagOStuff
3801 function wfGetMessageCacheStorage() {
3802 global $wgMessageCacheType;
3803 return ObjectCache::getInstance( $wgMessageCacheType );
3807 * Get the cache object used by the parser cache
3809 * @return BagOStuff
3811 function wfGetParserCacheStorage() {
3812 global $wgParserCacheType;
3813 return ObjectCache::getInstance( $wgParserCacheType );
3817 * Get the cache object used by the language converter
3819 * @return BagOStuff
3821 function wfGetLangConverterCacheStorage() {
3822 global $wgLanguageConverterCacheType;
3823 return ObjectCache::getInstance( $wgLanguageConverterCacheType );
3827 * Call hook functions defined in $wgHooks
3829 * @param string $event event name
3830 * @param array $args parameters passed to hook functions
3831 * @return Boolean True if no handler aborted the hook
3833 function wfRunHooks( $event, array $args = array() ) {
3834 return Hooks::run( $event, $args );
3838 * Wrapper around php's unpack.
3840 * @param string $format The format string (See php's docs)
3841 * @param $data: A binary string of binary data
3842 * @param $length integer or false: The minimum length of $data. This is to
3843 * prevent reading beyond the end of $data. false to disable the check.
3845 * Also be careful when using this function to read unsigned 32 bit integer
3846 * because php might make it negative.
3848 * @throws MWException if $data not long enough, or if unpack fails
3849 * @return array Associative array of the extracted data
3851 function wfUnpack( $format, $data, $length = false ) {
3852 if ( $length !== false ) {
3853 $realLen = strlen( $data );
3854 if ( $realLen < $length ) {
3855 throw new MWException( "Tried to use wfUnpack on a "
3856 . "string of length $realLen, but needed one "
3857 . "of at least length $length."
3862 wfSuppressWarnings();
3863 $result = unpack( $format, $data );
3864 wfRestoreWarnings();
3866 if ( $result === false ) {
3867 // If it cannot extract the packed data.
3868 throw new MWException( "unpack could not unpack binary data" );
3870 return $result;
3874 * Determine if an image exists on the 'bad image list'.
3876 * The format of MediaWiki:Bad_image_list is as follows:
3877 * * Only list items (lines starting with "*") are considered
3878 * * The first link on a line must be a link to a bad image
3879 * * Any subsequent links on the same line are considered to be exceptions,
3880 * i.e. articles where the image may occur inline.
3882 * @param string $name the image name to check
3883 * @param $contextTitle Title|bool the page on which the image occurs, if known
3884 * @param string $blacklist wikitext of a file blacklist
3885 * @return bool
3887 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
3888 static $badImageCache = null; // based on bad_image_list msg
3889 wfProfileIn( __METHOD__ );
3891 # Handle redirects
3892 $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) );
3893 if ( $redirectTitle ) {
3894 $name = $redirectTitle->getDBkey();
3897 # Run the extension hook
3898 $bad = false;
3899 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
3900 wfProfileOut( __METHOD__ );
3901 return $bad;
3904 $cacheable = ( $blacklist === null );
3905 if ( $cacheable && $badImageCache !== null ) {
3906 $badImages = $badImageCache;
3907 } else { // cache miss
3908 if ( $blacklist === null ) {
3909 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
3911 # Build the list now
3912 $badImages = array();
3913 $lines = explode( "\n", $blacklist );
3914 foreach ( $lines as $line ) {
3915 # List items only
3916 if ( substr( $line, 0, 1 ) !== '*' ) {
3917 continue;
3920 # Find all links
3921 $m = array();
3922 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
3923 continue;
3926 $exceptions = array();
3927 $imageDBkey = false;
3928 foreach ( $m[1] as $i => $titleText ) {
3929 $title = Title::newFromText( $titleText );
3930 if ( !is_null( $title ) ) {
3931 if ( $i == 0 ) {
3932 $imageDBkey = $title->getDBkey();
3933 } else {
3934 $exceptions[$title->getPrefixedDBkey()] = true;
3939 if ( $imageDBkey !== false ) {
3940 $badImages[$imageDBkey] = $exceptions;
3943 if ( $cacheable ) {
3944 $badImageCache = $badImages;
3948 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
3949 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
3950 wfProfileOut( __METHOD__ );
3951 return $bad;