Merge "Article: Handle double redirects in data for mediawiki.action.view.redirect"
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2 /**
3 * Global functions used everywhere.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 if ( !defined( 'MEDIAWIKI' ) ) {
24 die( "This file is part of MediaWiki, it is not a valid entry point" );
25 }
26
27 // Hide compatibility functions from Doxygen
28 /// @cond
29
30 /**
31 * Compatibility functions
32 *
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.
36 */
37
38 if ( !function_exists( 'mb_substr' ) ) {
39 /**
40 * @codeCoverageIgnore
41 * @see Fallback::mb_substr
42 * @return string
43 */
44 function mb_substr( $str, $start, $count = 'end' ) {
45 return Fallback::mb_substr( $str, $start, $count );
46 }
47
48 /**
49 * @codeCoverageIgnore
50 * @see Fallback::mb_substr_split_unicode
51 * @return int
52 */
53 function mb_substr_split_unicode( $str, $splitPos ) {
54 return Fallback::mb_substr_split_unicode( $str, $splitPos );
55 }
56 }
57
58 if ( !function_exists( 'mb_strlen' ) ) {
59 /**
60 * @codeCoverageIgnore
61 * @see Fallback::mb_strlen
62 * @return int
63 */
64 function mb_strlen( $str, $enc = '' ) {
65 return Fallback::mb_strlen( $str, $enc );
66 }
67 }
68
69 if ( !function_exists( 'mb_strpos' ) ) {
70 /**
71 * @codeCoverageIgnore
72 * @see Fallback::mb_strpos
73 * @return int
74 */
75 function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
76 return Fallback::mb_strpos( $haystack, $needle, $offset, $encoding );
77 }
78 }
79
80 if ( !function_exists( 'mb_strrpos' ) ) {
81 /**
82 * @codeCoverageIgnore
83 * @see Fallback::mb_strrpos
84 * @return int
85 */
86 function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
87 return Fallback::mb_strrpos( $haystack, $needle, $offset, $encoding );
88 }
89 }
90
91 // gzdecode function only exists in PHP >= 5.4.0
92 // http://php.net/gzdecode
93 if ( !function_exists( 'gzdecode' ) ) {
94 /**
95 * @codeCoverageIgnore
96 * @param string $data
97 * @return string
98 */
99 function gzdecode( $data ) {
100 return gzinflate( substr( $data, 10, -8 ) );
101 }
102 }
103
104 // hash_equals function only exists in PHP >= 5.6.0
105 if ( !function_exists( 'hash_equals' ) ) {
106 /**
107 * Check whether a user-provided string is equal to a fixed-length secret without
108 * revealing bytes of the secret through timing differences.
109 *
110 * This timing guarantee -- that a partial match takes the same time as a complete
111 * mismatch -- is why this function is used in some security-sensitive parts of the code.
112 * For example, it shouldn't be possible to guess an HMAC signature one byte at a time.
113 *
114 * Longer explanation: http://www.emerose.com/timing-attacks-explained
115 *
116 * @codeCoverageIgnore
117 * @param string $known_string Fixed-length secret to compare against
118 * @param string $user_string User-provided string
119 * @return bool True if the strings are the same, false otherwise
120 */
121 function hash_equals( $known_string, $user_string ) {
122 // Strict type checking as in PHP's native implementation
123 if ( !is_string( $known_string ) ) {
124 trigger_error( 'hash_equals(): Expected known_string to be a string, ' .
125 gettype( $known_string ) . ' given', E_USER_WARNING );
126
127 return false;
128 }
129
130 if ( !is_string( $user_string ) ) {
131 trigger_error( 'hash_equals(): Expected user_string to be a string, ' .
132 gettype( $user_string ) . ' given', E_USER_WARNING );
133
134 return false;
135 }
136
137 // Note that we do one thing PHP doesn't: try to avoid leaking information about
138 // relative lengths of $known_string and $user_string, and of multiple $known_strings.
139 // However, lengths may still inevitably leak through, for example, CPU cache misses.
140 $known_string_len = strlen( $known_string );
141 $user_string_len = strlen( $user_string );
142 $result = $known_string_len ^ $user_string_len;
143 for ( $i = 0; $i < $user_string_len; $i++ ) {
144 $result |= ord( $known_string[$i % $known_string_len] ) ^ ord( $user_string[$i] );
145 }
146
147 return ( $result === 0 );
148 }
149 }
150 /// @endcond
151
152 /**
153 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
154 * @param array $a
155 * @param array $b
156 * @return array
157 */
158 function wfArrayDiff2( $a, $b ) {
159 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
160 }
161
162 /**
163 * @param array|string $a
164 * @param array|string $b
165 * @return int
166 */
167 function wfArrayDiff2_cmp( $a, $b ) {
168 if ( is_string( $a ) && is_string( $b ) ) {
169 return strcmp( $a, $b );
170 } elseif ( count( $a ) !== count( $b ) ) {
171 return count( $a ) < count( $b ) ? -1 : 1;
172 } else {
173 reset( $a );
174 reset( $b );
175 while ( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
176 $cmp = strcmp( $valueA, $valueB );
177 if ( $cmp !== 0 ) {
178 return $cmp;
179 }
180 }
181 return 0;
182 }
183 }
184
185 /**
186 * Appends to second array if $value differs from that in $default
187 *
188 * @param string|int $key
189 * @param mixed $value
190 * @param mixed $default
191 * @param array $changed Array to alter
192 * @throws MWException
193 */
194 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
195 if ( is_null( $changed ) ) {
196 throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
197 }
198 if ( $default[$key] !== $value ) {
199 $changed[$key] = $value;
200 }
201 }
202
203 /**
204 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
205 * e.g.
206 * wfMergeErrorArrays(
207 * array( array( 'x' ) ),
208 * array( array( 'x', '2' ) ),
209 * array( array( 'x' ) ),
210 * array( array( 'y' ) )
211 * );
212 * returns:
213 * array(
214 * array( 'x', '2' ),
215 * array( 'x' ),
216 * array( 'y' )
217 * )
218 *
219 * @param array $array1,...
220 * @return array
221 */
222 function wfMergeErrorArrays( /*...*/ ) {
223 $args = func_get_args();
224 $out = array();
225 foreach ( $args as $errors ) {
226 foreach ( $errors as $params ) {
227 # @todo FIXME: Sometimes get nested arrays for $params,
228 # which leads to E_NOTICEs
229 $spec = implode( "\t", $params );
230 $out[$spec] = $params;
231 }
232 }
233 return array_values( $out );
234 }
235
236 /**
237 * Insert array into another array after the specified *KEY*
238 *
239 * @param array $array The array.
240 * @param array $insert The array to insert.
241 * @param mixed $after The key to insert after
242 * @return array
243 */
244 function wfArrayInsertAfter( array $array, array $insert, $after ) {
245 // Find the offset of the element to insert after.
246 $keys = array_keys( $array );
247 $offsetByKey = array_flip( $keys );
248
249 $offset = $offsetByKey[$after];
250
251 // Insert at the specified offset
252 $before = array_slice( $array, 0, $offset + 1, true );
253 $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
254
255 $output = $before + $insert + $after;
256
257 return $output;
258 }
259
260 /**
261 * Recursively converts the parameter (an object) to an array with the same data
262 *
263 * @param object|array $objOrArray
264 * @param bool $recursive
265 * @return array
266 */
267 function wfObjectToArray( $objOrArray, $recursive = true ) {
268 $array = array();
269 if ( is_object( $objOrArray ) ) {
270 $objOrArray = get_object_vars( $objOrArray );
271 }
272 foreach ( $objOrArray as $key => $value ) {
273 if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
274 $value = wfObjectToArray( $value );
275 }
276
277 $array[$key] = $value;
278 }
279
280 return $array;
281 }
282
283 /**
284 * Get a random decimal value between 0 and 1, in a way
285 * not likely to give duplicate values for any realistic
286 * number of articles.
287 *
288 * @return string
289 */
290 function wfRandom() {
291 # The maximum random value is "only" 2^31-1, so get two random
292 # values to reduce the chance of dupes
293 $max = mt_getrandmax() + 1;
294 $rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
295
296 return $rand;
297 }
298
299 /**
300 * Get a random string containing a number of pseudo-random hex
301 * characters.
302 * @note This is not secure, if you are trying to generate some sort
303 * of token please use MWCryptRand instead.
304 *
305 * @param int $length The length of the string to generate
306 * @return string
307 * @since 1.20
308 */
309 function wfRandomString( $length = 32 ) {
310 $str = '';
311 for ( $n = 0; $n < $length; $n += 7 ) {
312 $str .= sprintf( '%07x', mt_rand() & 0xfffffff );
313 }
314 return substr( $str, 0, $length );
315 }
316
317 /**
318 * We want some things to be included as literal characters in our title URLs
319 * for prettiness, which urlencode encodes by default. According to RFC 1738,
320 * all of the following should be safe:
321 *
322 * ;:@&=$-_.+!*'(),
323 *
324 * But + is not safe because it's used to indicate a space; &= are only safe in
325 * paths and not in queries (and we don't distinguish here); ' seems kind of
326 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
327 * is reserved, we don't care. So the list we unescape is:
328 *
329 * ;:@$!*(),/
330 *
331 * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
332 * so no fancy : for IIS7.
333 *
334 * %2F in the page titles seems to fatally break for some reason.
335 *
336 * @param string $s
337 * @return string
338 */
339 function wfUrlencode( $s ) {
340 static $needle;
341
342 if ( is_null( $s ) ) {
343 $needle = null;
344 return '';
345 }
346
347 if ( is_null( $needle ) ) {
348 $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
349 if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
350 ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false )
351 ) {
352 $needle[] = '%3A';
353 }
354 }
355
356 $s = urlencode( $s );
357 $s = str_ireplace(
358 $needle,
359 array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
360 $s
361 );
362
363 return $s;
364 }
365
366 /**
367 * This function takes two arrays as input, and returns a CGI-style string, e.g.
368 * "days=7&limit=100". Options in the first array override options in the second.
369 * Options set to null or false will not be output.
370 *
371 * @param array $array1 ( String|Array )
372 * @param array $array2 ( String|Array )
373 * @param string $prefix
374 * @return string
375 */
376 function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
377 if ( !is_null( $array2 ) ) {
378 $array1 = $array1 + $array2;
379 }
380
381 $cgi = '';
382 foreach ( $array1 as $key => $value ) {
383 if ( !is_null( $value ) && $value !== false ) {
384 if ( $cgi != '' ) {
385 $cgi .= '&';
386 }
387 if ( $prefix !== '' ) {
388 $key = $prefix . "[$key]";
389 }
390 if ( is_array( $value ) ) {
391 $firstTime = true;
392 foreach ( $value as $k => $v ) {
393 $cgi .= $firstTime ? '' : '&';
394 if ( is_array( $v ) ) {
395 $cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
396 } else {
397 $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
398 }
399 $firstTime = false;
400 }
401 } else {
402 if ( is_object( $value ) ) {
403 $value = $value->__toString();
404 }
405 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
406 }
407 }
408 }
409 return $cgi;
410 }
411
412 /**
413 * This is the logical opposite of wfArrayToCgi(): it accepts a query string as
414 * its argument and returns the same string in array form. This allows compatibility
415 * with legacy functions that accept raw query strings instead of nice
416 * arrays. Of course, keys and values are urldecode()d.
417 *
418 * @param string $query Query string
419 * @return string[] Array version of input
420 */
421 function wfCgiToArray( $query ) {
422 if ( isset( $query[0] ) && $query[0] == '?' ) {
423 $query = substr( $query, 1 );
424 }
425 $bits = explode( '&', $query );
426 $ret = array();
427 foreach ( $bits as $bit ) {
428 if ( $bit === '' ) {
429 continue;
430 }
431 if ( strpos( $bit, '=' ) === false ) {
432 // Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
433 $key = $bit;
434 $value = '';
435 } else {
436 list( $key, $value ) = explode( '=', $bit );
437 }
438 $key = urldecode( $key );
439 $value = urldecode( $value );
440 if ( strpos( $key, '[' ) !== false ) {
441 $keys = array_reverse( explode( '[', $key ) );
442 $key = array_pop( $keys );
443 $temp = $value;
444 foreach ( $keys as $k ) {
445 $k = substr( $k, 0, -1 );
446 $temp = array( $k => $temp );
447 }
448 if ( isset( $ret[$key] ) ) {
449 $ret[$key] = array_merge( $ret[$key], $temp );
450 } else {
451 $ret[$key] = $temp;
452 }
453 } else {
454 $ret[$key] = $value;
455 }
456 }
457 return $ret;
458 }
459
460 /**
461 * Append a query string to an existing URL, which may or may not already
462 * have query string parameters already. If so, they will be combined.
463 *
464 * @param string $url
465 * @param string|string[] $query String or associative array
466 * @return string
467 */
468 function wfAppendQuery( $url, $query ) {
469 if ( is_array( $query ) ) {
470 $query = wfArrayToCgi( $query );
471 }
472 if ( $query != '' ) {
473 if ( false === strpos( $url, '?' ) ) {
474 $url .= '?';
475 } else {
476 $url .= '&';
477 }
478 $url .= $query;
479 }
480 return $url;
481 }
482
483 /**
484 * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
485 * is correct.
486 *
487 * The meaning of the PROTO_* constants is as follows:
488 * PROTO_HTTP: Output a URL starting with http://
489 * PROTO_HTTPS: Output a URL starting with https://
490 * PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL)
491 * PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending
492 * on which protocol was used for the current incoming request
493 * PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer.
494 * For protocol-relative URLs, use the protocol of $wgCanonicalServer
495 * PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer
496 *
497 * @todo this won't work with current-path-relative URLs
498 * like "subdir/foo.html", etc.
499 *
500 * @param string $url Either fully-qualified or a local path + query
501 * @param string $defaultProto One of the PROTO_* constants. Determines the
502 * protocol to use if $url or $wgServer is protocol-relative
503 * @return string Fully-qualified URL, current-path-relative URL or false if
504 * no valid URL can be constructed
505 */
506 function wfExpandUrl( $url, $defaultProto = PROTO_CURRENT ) {
507 global $wgServer, $wgCanonicalServer, $wgInternalServer, $wgRequest,
508 $wgHttpsPort;
509 if ( $defaultProto === PROTO_CANONICAL ) {
510 $serverUrl = $wgCanonicalServer;
511 } elseif ( $defaultProto === PROTO_INTERNAL && $wgInternalServer !== false ) {
512 // Make $wgInternalServer fall back to $wgServer if not set
513 $serverUrl = $wgInternalServer;
514 } else {
515 $serverUrl = $wgServer;
516 if ( $defaultProto === PROTO_CURRENT ) {
517 $defaultProto = $wgRequest->getProtocol() . '://';
518 }
519 }
520
521 // Analyze $serverUrl to obtain its protocol
522 $bits = wfParseUrl( $serverUrl );
523 $serverHasProto = $bits && $bits['scheme'] != '';
524
525 if ( $defaultProto === PROTO_CANONICAL || $defaultProto === PROTO_INTERNAL ) {
526 if ( $serverHasProto ) {
527 $defaultProto = $bits['scheme'] . '://';
528 } else {
529 // $wgCanonicalServer or $wgInternalServer doesn't have a protocol.
530 // This really isn't supposed to happen. Fall back to HTTP in this
531 // ridiculous case.
532 $defaultProto = PROTO_HTTP;
533 }
534 }
535
536 $defaultProtoWithoutSlashes = substr( $defaultProto, 0, -2 );
537
538 if ( substr( $url, 0, 2 ) == '//' ) {
539 $url = $defaultProtoWithoutSlashes . $url;
540 } elseif ( substr( $url, 0, 1 ) == '/' ) {
541 // If $serverUrl is protocol-relative, prepend $defaultProtoWithoutSlashes,
542 // otherwise leave it alone.
543 $url = ( $serverHasProto ? '' : $defaultProtoWithoutSlashes ) . $serverUrl . $url;
544 }
545
546 $bits = wfParseUrl( $url );
547
548 // ensure proper port for HTTPS arrives in URL
549 // https://bugzilla.wikimedia.org/show_bug.cgi?id=65184
550 if ( $defaultProto === PROTO_HTTPS && $wgHttpsPort != 443 ) {
551 $bits['port'] = $wgHttpsPort;
552 }
553
554 if ( $bits && isset( $bits['path'] ) ) {
555 $bits['path'] = wfRemoveDotSegments( $bits['path'] );
556 return wfAssembleUrl( $bits );
557 } elseif ( $bits ) {
558 # No path to expand
559 return $url;
560 } elseif ( substr( $url, 0, 1 ) != '/' ) {
561 # URL is a relative path
562 return wfRemoveDotSegments( $url );
563 }
564
565 # Expanded URL is not valid.
566 return false;
567 }
568
569 /**
570 * This function will reassemble a URL parsed with wfParseURL. This is useful
571 * if you need to edit part of a URL and put it back together.
572 *
573 * This is the basic structure used (brackets contain keys for $urlParts):
574 * [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]
575 *
576 * @todo Need to integrate this into wfExpandUrl (bug 32168)
577 *
578 * @since 1.19
579 * @param array $urlParts URL parts, as output from wfParseUrl
580 * @return string URL assembled from its component parts
581 */
582 function wfAssembleUrl( $urlParts ) {
583 $result = '';
584
585 if ( isset( $urlParts['delimiter'] ) ) {
586 if ( isset( $urlParts['scheme'] ) ) {
587 $result .= $urlParts['scheme'];
588 }
589
590 $result .= $urlParts['delimiter'];
591 }
592
593 if ( isset( $urlParts['host'] ) ) {
594 if ( isset( $urlParts['user'] ) ) {
595 $result .= $urlParts['user'];
596 if ( isset( $urlParts['pass'] ) ) {
597 $result .= ':' . $urlParts['pass'];
598 }
599 $result .= '@';
600 }
601
602 $result .= $urlParts['host'];
603
604 if ( isset( $urlParts['port'] ) ) {
605 $result .= ':' . $urlParts['port'];
606 }
607 }
608
609 if ( isset( $urlParts['path'] ) ) {
610 $result .= $urlParts['path'];
611 }
612
613 if ( isset( $urlParts['query'] ) ) {
614 $result .= '?' . $urlParts['query'];
615 }
616
617 if ( isset( $urlParts['fragment'] ) ) {
618 $result .= '#' . $urlParts['fragment'];
619 }
620
621 return $result;
622 }
623
624 /**
625 * Remove all dot-segments in the provided URL path. For example,
626 * '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see
627 * RFC3986 section 5.2.4.
628 *
629 * @todo Need to integrate this into wfExpandUrl (bug 32168)
630 *
631 * @param string $urlPath URL path, potentially containing dot-segments
632 * @return string URL path with all dot-segments removed
633 */
634 function wfRemoveDotSegments( $urlPath ) {
635 $output = '';
636 $inputOffset = 0;
637 $inputLength = strlen( $urlPath );
638
639 while ( $inputOffset < $inputLength ) {
640 $prefixLengthOne = substr( $urlPath, $inputOffset, 1 );
641 $prefixLengthTwo = substr( $urlPath, $inputOffset, 2 );
642 $prefixLengthThree = substr( $urlPath, $inputOffset, 3 );
643 $prefixLengthFour = substr( $urlPath, $inputOffset, 4 );
644 $trimOutput = false;
645
646 if ( $prefixLengthTwo == './' ) {
647 # Step A, remove leading "./"
648 $inputOffset += 2;
649 } elseif ( $prefixLengthThree == '../' ) {
650 # Step A, remove leading "../"
651 $inputOffset += 3;
652 } elseif ( ( $prefixLengthTwo == '/.' ) && ( $inputOffset + 2 == $inputLength ) ) {
653 # Step B, replace leading "/.$" with "/"
654 $inputOffset += 1;
655 $urlPath[$inputOffset] = '/';
656 } elseif ( $prefixLengthThree == '/./' ) {
657 # Step B, replace leading "/./" with "/"
658 $inputOffset += 2;
659 } elseif ( $prefixLengthThree == '/..' && ( $inputOffset + 3 == $inputLength ) ) {
660 # Step C, replace leading "/..$" with "/" and
661 # remove last path component in output
662 $inputOffset += 2;
663 $urlPath[$inputOffset] = '/';
664 $trimOutput = true;
665 } elseif ( $prefixLengthFour == '/../' ) {
666 # Step C, replace leading "/../" with "/" and
667 # remove last path component in output
668 $inputOffset += 3;
669 $trimOutput = true;
670 } elseif ( ( $prefixLengthOne == '.' ) && ( $inputOffset + 1 == $inputLength ) ) {
671 # Step D, remove "^.$"
672 $inputOffset += 1;
673 } elseif ( ( $prefixLengthTwo == '..' ) && ( $inputOffset + 2 == $inputLength ) ) {
674 # Step D, remove "^..$"
675 $inputOffset += 2;
676 } else {
677 # Step E, move leading path segment to output
678 if ( $prefixLengthOne == '/' ) {
679 $slashPos = strpos( $urlPath, '/', $inputOffset + 1 );
680 } else {
681 $slashPos = strpos( $urlPath, '/', $inputOffset );
682 }
683 if ( $slashPos === false ) {
684 $output .= substr( $urlPath, $inputOffset );
685 $inputOffset = $inputLength;
686 } else {
687 $output .= substr( $urlPath, $inputOffset, $slashPos - $inputOffset );
688 $inputOffset += $slashPos - $inputOffset;
689 }
690 }
691
692 if ( $trimOutput ) {
693 $slashPos = strrpos( $output, '/' );
694 if ( $slashPos === false ) {
695 $output = '';
696 } else {
697 $output = substr( $output, 0, $slashPos );
698 }
699 }
700 }
701
702 return $output;
703 }
704
705 /**
706 * Returns a regular expression of url protocols
707 *
708 * @param bool $includeProtocolRelative If false, remove '//' from the returned protocol list.
709 * DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
710 * @return string
711 */
712 function wfUrlProtocols( $includeProtocolRelative = true ) {
713 global $wgUrlProtocols;
714
715 // Cache return values separately based on $includeProtocolRelative
716 static $withProtRel = null, $withoutProtRel = null;
717 $cachedValue = $includeProtocolRelative ? $withProtRel : $withoutProtRel;
718 if ( !is_null( $cachedValue ) ) {
719 return $cachedValue;
720 }
721
722 // Support old-style $wgUrlProtocols strings, for backwards compatibility
723 // with LocalSettings files from 1.5
724 if ( is_array( $wgUrlProtocols ) ) {
725 $protocols = array();
726 foreach ( $wgUrlProtocols as $protocol ) {
727 // Filter out '//' if !$includeProtocolRelative
728 if ( $includeProtocolRelative || $protocol !== '//' ) {
729 $protocols[] = preg_quote( $protocol, '/' );
730 }
731 }
732
733 $retval = implode( '|', $protocols );
734 } else {
735 // Ignore $includeProtocolRelative in this case
736 // This case exists for pre-1.6 compatibility, and we can safely assume
737 // that '//' won't appear in a pre-1.6 config because protocol-relative
738 // URLs weren't supported until 1.18
739 $retval = $wgUrlProtocols;
740 }
741
742 // Cache return value
743 if ( $includeProtocolRelative ) {
744 $withProtRel = $retval;
745 } else {
746 $withoutProtRel = $retval;
747 }
748 return $retval;
749 }
750
751 /**
752 * Like wfUrlProtocols(), but excludes '//' from the protocol list. Use this if
753 * you need a regex that matches all URL protocols but does not match protocol-
754 * relative URLs
755 * @return string
756 */
757 function wfUrlProtocolsWithoutProtRel() {
758 return wfUrlProtocols( false );
759 }
760
761 /**
762 * parse_url() work-alike, but non-broken. Differences:
763 *
764 * 1) Does not raise warnings on bad URLs (just returns false).
765 * 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as
766 * protocol-relative URLs) correctly.
767 * 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).
768 *
769 * @param string $url A URL to parse
770 * @return string[] Bits of the URL in an associative array, per PHP docs
771 */
772 function wfParseUrl( $url ) {
773 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
774
775 // Protocol-relative URLs are handled really badly by parse_url(). It's so
776 // bad that the easiest way to handle them is to just prepend 'http:' and
777 // strip the protocol out later.
778 $wasRelative = substr( $url, 0, 2 ) == '//';
779 if ( $wasRelative ) {
780 $url = "http:$url";
781 }
782 wfSuppressWarnings();
783 $bits = parse_url( $url );
784 wfRestoreWarnings();
785 // parse_url() returns an array without scheme for some invalid URLs, e.g.
786 // parse_url("%0Ahttp://example.com") == array( 'host' => '%0Ahttp', 'path' => 'example.com' )
787 if ( !$bits || !isset( $bits['scheme'] ) ) {
788 return false;
789 }
790
791 // parse_url() incorrectly handles schemes case-sensitively. Convert it to lowercase.
792 $bits['scheme'] = strtolower( $bits['scheme'] );
793
794 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
795 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
796 $bits['delimiter'] = '://';
797 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
798 $bits['delimiter'] = ':';
799 // parse_url detects for news: and mailto: the host part of an url as path
800 // We have to correct this wrong detection
801 if ( isset( $bits['path'] ) ) {
802 $bits['host'] = $bits['path'];
803 $bits['path'] = '';
804 }
805 } else {
806 return false;
807 }
808
809 /* Provide an empty host for eg. file:/// urls (see bug 28627) */
810 if ( !isset( $bits['host'] ) ) {
811 $bits['host'] = '';
812
813 // bug 45069
814 if ( isset( $bits['path'] ) ) {
815 /* parse_url loses the third / for file:///c:/ urls (but not on variants) */
816 if ( substr( $bits['path'], 0, 1 ) !== '/' ) {
817 $bits['path'] = '/' . $bits['path'];
818 }
819 } else {
820 $bits['path'] = '';
821 }
822 }
823
824 // If the URL was protocol-relative, fix scheme and delimiter
825 if ( $wasRelative ) {
826 $bits['scheme'] = '';
827 $bits['delimiter'] = '//';
828 }
829 return $bits;
830 }
831
832 /**
833 * Take a URL, make sure it's expanded to fully qualified, and replace any
834 * encoded non-ASCII Unicode characters with their UTF-8 original forms
835 * for more compact display and legibility for local audiences.
836 *
837 * @todo handle punycode domains too
838 *
839 * @param string $url
840 * @return string
841 */
842 function wfExpandIRI( $url ) {
843 return preg_replace_callback(
844 '/((?:%[89A-F][0-9A-F])+)/i',
845 'wfExpandIRI_callback',
846 wfExpandUrl( $url )
847 );
848 }
849
850 /**
851 * Private callback for wfExpandIRI
852 * @param array $matches
853 * @return string
854 */
855 function wfExpandIRI_callback( $matches ) {
856 return urldecode( $matches[1] );
857 }
858
859 /**
860 * Make URL indexes, appropriate for the el_index field of externallinks.
861 *
862 * @param string $url
863 * @return array
864 */
865 function wfMakeUrlIndexes( $url ) {
866 $bits = wfParseUrl( $url );
867
868 // Reverse the labels in the hostname, convert to lower case
869 // For emails reverse domainpart only
870 if ( $bits['scheme'] == 'mailto' ) {
871 $mailparts = explode( '@', $bits['host'], 2 );
872 if ( count( $mailparts ) === 2 ) {
873 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
874 } else {
875 // No domain specified, don't mangle it
876 $domainpart = '';
877 }
878 $reversedHost = $domainpart . '@' . $mailparts[0];
879 } else {
880 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
881 }
882 // Add an extra dot to the end
883 // Why? Is it in wrong place in mailto links?
884 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
885 $reversedHost .= '.';
886 }
887 // Reconstruct the pseudo-URL
888 $prot = $bits['scheme'];
889 $index = $prot . $bits['delimiter'] . $reversedHost;
890 // Leave out user and password. Add the port, path, query and fragment
891 if ( isset( $bits['port'] ) ) {
892 $index .= ':' . $bits['port'];
893 }
894 if ( isset( $bits['path'] ) ) {
895 $index .= $bits['path'];
896 } else {
897 $index .= '/';
898 }
899 if ( isset( $bits['query'] ) ) {
900 $index .= '?' . $bits['query'];
901 }
902 if ( isset( $bits['fragment'] ) ) {
903 $index .= '#' . $bits['fragment'];
904 }
905
906 if ( $prot == '' ) {
907 return array( "http:$index", "https:$index" );
908 } else {
909 return array( $index );
910 }
911 }
912
913 /**
914 * Check whether a given URL has a domain that occurs in a given set of domains
915 * @param string $url URL
916 * @param array $domains Array of domains (strings)
917 * @return bool True if the host part of $url ends in one of the strings in $domains
918 */
919 function wfMatchesDomainList( $url, $domains ) {
920 $bits = wfParseUrl( $url );
921 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
922 $host = '.' . $bits['host'];
923 foreach ( (array)$domains as $domain ) {
924 $domain = '.' . $domain;
925 if ( substr( $host, -strlen( $domain ) ) === $domain ) {
926 return true;
927 }
928 }
929 }
930 return false;
931 }
932
933 /**
934 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
935 * In normal operation this is a NOP.
936 *
937 * Controlling globals:
938 * $wgDebugLogFile - points to the log file
939 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
940 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
941 *
942 * @param string $text
943 * @param string|bool $dest Destination of the message:
944 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
945 * - 'log': only to the log and not in HTML
946 * For backward compatibility, it can also take a boolean:
947 * - true: same as 'all'
948 * - false: same as 'log'
949 */
950 function wfDebug( $text, $dest = 'all' ) {
951 global $wgDebugLogFile, $wgDebugRawPage, $wgDebugLogPrefix;
952
953 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
954 return;
955 }
956
957 // Turn $dest into a string if it's a boolean (for b/c)
958 if ( $dest === true ) {
959 $dest = 'all';
960 } elseif ( $dest === false ) {
961 $dest = 'log';
962 }
963
964 $timer = wfDebugTimer();
965 if ( $timer !== '' ) {
966 $text = preg_replace( '/[^\n]/', $timer . '\0', $text, 1 );
967 }
968
969 if ( $dest === 'all' ) {
970 MWDebug::debugMsg( $text );
971 }
972
973 if ( $wgDebugLogFile != '' ) {
974 # Strip unprintables; they can switch terminal modes when binary data
975 # gets dumped, which is pretty annoying.
976 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
977 $text = $wgDebugLogPrefix . $text;
978 wfErrorLog( $text, $wgDebugLogFile );
979 }
980 }
981
982 /**
983 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
984 * @return bool
985 */
986 function wfIsDebugRawPage() {
987 static $cache;
988 if ( $cache !== null ) {
989 return $cache;
990 }
991 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
992 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
993 || (
994 isset( $_SERVER['SCRIPT_NAME'] )
995 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
996 )
997 ) {
998 $cache = true;
999 } else {
1000 $cache = false;
1001 }
1002 return $cache;
1003 }
1004
1005 /**
1006 * Get microsecond timestamps for debug logs
1007 *
1008 * @return string
1009 */
1010 function wfDebugTimer() {
1011 global $wgDebugTimestamps, $wgRequestTime;
1012
1013 if ( !$wgDebugTimestamps ) {
1014 return '';
1015 }
1016
1017 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1018 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1019 return "$prefix $mem ";
1020 }
1021
1022 /**
1023 * Send a line giving PHP memory usage.
1024 *
1025 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1026 */
1027 function wfDebugMem( $exact = false ) {
1028 $mem = memory_get_usage();
1029 if ( !$exact ) {
1030 $mem = floor( $mem / 1024 ) . ' KiB';
1031 } else {
1032 $mem .= ' B';
1033 }
1034 wfDebug( "Memory usage: $mem\n" );
1035 }
1036
1037 /**
1038 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
1039 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string
1040 * filename or an associative array mapping 'destination' to the desired filename. The
1041 * associative array may also contain a 'sample' key with an integer value, specifying
1042 * a sampling factor.
1043 *
1044 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1045 *
1046 * @param string $logGroup
1047 * @param string $text
1048 * @param string|bool $dest Destination of the message:
1049 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1050 * - 'log': only to the log and not in HTML
1051 * - 'private': only to the specifc log if set in $wgDebugLogGroups and
1052 * discarded otherwise
1053 * For backward compatibility, it can also take a boolean:
1054 * - true: same as 'all'
1055 * - false: same as 'private'
1056 */
1057 function wfDebugLog( $logGroup, $text, $dest = 'all' ) {
1058 global $wgDebugLogGroups;
1059
1060 $text = trim( $text ) . "\n";
1061
1062 // Turn $dest into a string if it's a boolean (for b/c)
1063 if ( $dest === true ) {
1064 $dest = 'all';
1065 } elseif ( $dest === false ) {
1066 $dest = 'private';
1067 }
1068
1069 if ( !isset( $wgDebugLogGroups[$logGroup] ) ) {
1070 if ( $dest !== 'private' ) {
1071 wfDebug( "[$logGroup] $text", $dest );
1072 }
1073 return;
1074 }
1075
1076 if ( $dest === 'all' ) {
1077 MWDebug::debugMsg( "[$logGroup] $text" );
1078 }
1079
1080 $logConfig = $wgDebugLogGroups[$logGroup];
1081 if ( $logConfig === false ) {
1082 return;
1083 }
1084 if ( is_array( $logConfig ) ) {
1085 if ( isset( $logConfig['sample'] ) && mt_rand( 1, $logConfig['sample'] ) !== 1 ) {
1086 return;
1087 }
1088 $destination = $logConfig['destination'];
1089 } else {
1090 $destination = strval( $logConfig );
1091 }
1092
1093 $time = wfTimestamp( TS_DB );
1094 $wiki = wfWikiID();
1095 $host = wfHostname();
1096 wfErrorLog( "$time $host $wiki: $text", $destination );
1097 }
1098
1099 /**
1100 * Log for database errors
1101 *
1102 * @param string $text Database error message.
1103 */
1104 function wfLogDBError( $text ) {
1105 global $wgDBerrorLog, $wgDBerrorLogTZ;
1106 static $logDBErrorTimeZoneObject = null;
1107
1108 if ( $wgDBerrorLog ) {
1109 $host = wfHostname();
1110 $wiki = wfWikiID();
1111
1112 if ( $wgDBerrorLogTZ && !$logDBErrorTimeZoneObject ) {
1113 $logDBErrorTimeZoneObject = new DateTimeZone( $wgDBerrorLogTZ );
1114 }
1115
1116 // Workaround for https://bugs.php.net/bug.php?id=52063
1117 // Can be removed when min PHP > 5.3.2
1118 if ( $logDBErrorTimeZoneObject === null ) {
1119 $d = date_create( "now" );
1120 } else {
1121 $d = date_create( "now", $logDBErrorTimeZoneObject );
1122 }
1123
1124 $date = $d->format( 'D M j G:i:s T Y' );
1125
1126 $text = "$date\t$host\t$wiki\t" . trim( $text ) . "\n";
1127 wfErrorLog( $text, $wgDBerrorLog );
1128 }
1129 }
1130
1131 /**
1132 * Throws a warning that $function is deprecated
1133 *
1134 * @param string $function
1135 * @param string|bool $version Version of MediaWiki that the function
1136 * was deprecated in (Added in 1.19).
1137 * @param string|bool $component Added in 1.19.
1138 * @param int $callerOffset How far up the call stack is the original
1139 * caller. 2 = function that called the function that called
1140 * wfDeprecated (Added in 1.20)
1141 *
1142 * @return null
1143 */
1144 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1145 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1146 }
1147
1148 /**
1149 * Send a warning either to the debug log or in a PHP error depending on
1150 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1151 *
1152 * @param string $msg Message to send
1153 * @param int $callerOffset Number of items to go back in the backtrace to
1154 * find the correct caller (1 = function calling wfWarn, ...)
1155 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1156 * only used when $wgDevelopmentWarnings is true
1157 */
1158 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1159 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1160 }
1161
1162 /**
1163 * Send a warning as a PHP error and the debug log. This is intended for logging
1164 * warnings in production. For logging development warnings, use WfWarn instead.
1165 *
1166 * @param string $msg Message to send
1167 * @param int $callerOffset Number of items to go back in the backtrace to
1168 * find the correct caller (1 = function calling wfLogWarning, ...)
1169 * @param int $level PHP error level; defaults to E_USER_WARNING
1170 */
1171 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1172 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1173 }
1174
1175 /**
1176 * Log to a file without getting "file size exceeded" signals.
1177 *
1178 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1179 * send lines to the specified port, prefixed by the specified prefix and a space.
1180 *
1181 * @param string $text
1182 * @param string $file Filename
1183 * @throws MWException
1184 */
1185 function wfErrorLog( $text, $file ) {
1186 if ( substr( $file, 0, 4 ) == 'udp:' ) {
1187 # Needs the sockets extension
1188 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
1189 // IPv6 bracketed host
1190 $host = $m[2];
1191 $port = intval( $m[3] );
1192 $prefix = isset( $m[4] ) ? $m[4] : false;
1193 $domain = AF_INET6;
1194 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
1195 $host = $m[2];
1196 if ( !IP::isIPv4( $host ) ) {
1197 $host = gethostbyname( $host );
1198 }
1199 $port = intval( $m[3] );
1200 $prefix = isset( $m[4] ) ? $m[4] : false;
1201 $domain = AF_INET;
1202 } else {
1203 throw new MWException( __METHOD__ . ': Invalid UDP specification' );
1204 }
1205
1206 // Clean it up for the multiplexer
1207 if ( strval( $prefix ) !== '' ) {
1208 $text = preg_replace( '/^/m', $prefix . ' ', $text );
1209
1210 // Limit to 64KB
1211 if ( strlen( $text ) > 65506 ) {
1212 $text = substr( $text, 0, 65506 );
1213 }
1214
1215 if ( substr( $text, -1 ) != "\n" ) {
1216 $text .= "\n";
1217 }
1218 } elseif ( strlen( $text ) > 65507 ) {
1219 $text = substr( $text, 0, 65507 );
1220 }
1221
1222 $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
1223 if ( !$sock ) {
1224 return;
1225 }
1226
1227 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
1228 socket_close( $sock );
1229 } else {
1230 wfSuppressWarnings();
1231 $exists = file_exists( $file );
1232 $size = $exists ? filesize( $file ) : false;
1233 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
1234 file_put_contents( $file, $text, FILE_APPEND );
1235 }
1236 wfRestoreWarnings();
1237 }
1238 }
1239
1240 /**
1241 * @todo document
1242 */
1243 function wfLogProfilingData() {
1244 global $wgRequestTime, $wgDebugLogFile, $wgDebugLogGroups, $wgDebugRawPage;
1245 global $wgProfileLimit, $wgUser, $wgRequest;
1246
1247 StatCounter::singleton()->flush();
1248
1249 $profiler = Profiler::instance();
1250
1251 # Profiling must actually be enabled...
1252 if ( $profiler->isStub() ) {
1253 return;
1254 }
1255
1256 // Get total page request time and only show pages that longer than
1257 // $wgProfileLimit time (default is 0)
1258 $elapsed = microtime( true ) - $wgRequestTime;
1259 if ( $elapsed <= $wgProfileLimit ) {
1260 return;
1261 }
1262
1263 $profiler->logData();
1264
1265 // Check whether this should be logged in the debug file.
1266 if ( isset( $wgDebugLogGroups['profileoutput'] )
1267 && $wgDebugLogGroups['profileoutput'] === false
1268 ) {
1269 // Explicitely disabled
1270 return;
1271 }
1272 if ( !isset( $wgDebugLogGroups['profileoutput'] ) && $wgDebugLogFile == '' ) {
1273 // Logging not enabled; no point going further
1274 return;
1275 }
1276 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1277 return;
1278 }
1279
1280 $forward = '';
1281 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1282 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
1283 }
1284 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1285 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
1286 }
1287 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1288 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
1289 }
1290 if ( $forward ) {
1291 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
1292 }
1293 // Don't load $wgUser at this late stage just for statistics purposes
1294 // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
1295 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1296 $forward .= ' anon';
1297 }
1298
1299 // Command line script uses a FauxRequest object which does not have
1300 // any knowledge about an URL and throw an exception instead.
1301 try {
1302 $requestUrl = $wgRequest->getRequestURL();
1303 } catch ( MWException $e ) {
1304 $requestUrl = 'n/a';
1305 }
1306
1307 $log = sprintf( "%s\t%04.3f\t%s\n",
1308 gmdate( 'YmdHis' ), $elapsed,
1309 urldecode( $requestUrl . $forward ) );
1310
1311 wfDebugLog( 'profileoutput', $log . $profiler->getOutput() );
1312 }
1313
1314 /**
1315 * Increment a statistics counter
1316 *
1317 * @param string $key
1318 * @param int $count
1319 * @return void
1320 */
1321 function wfIncrStats( $key, $count = 1 ) {
1322 StatCounter::singleton()->incr( $key, $count );
1323 }
1324
1325 /**
1326 * Check whether the wiki is in read-only mode.
1327 *
1328 * @return bool
1329 */
1330 function wfReadOnly() {
1331 return wfReadOnlyReason() !== false;
1332 }
1333
1334 /**
1335 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1336 *
1337 * @return string|bool String when in read-only mode; false otherwise
1338 */
1339 function wfReadOnlyReason() {
1340 global $wgReadOnly, $wgReadOnlyFile;
1341
1342 if ( $wgReadOnly === null ) {
1343 // Set $wgReadOnly for faster access next time
1344 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1345 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1346 } else {
1347 $wgReadOnly = false;
1348 }
1349 }
1350
1351 return $wgReadOnly;
1352 }
1353
1354 /**
1355 * Return a Language object from $langcode
1356 *
1357 * @param Language|string|bool $langcode Either:
1358 * - a Language object
1359 * - code of the language to get the message for, if it is
1360 * a valid code create a language for that language, if
1361 * it is a string but not a valid code then make a basic
1362 * language object
1363 * - a boolean: if it's false then use the global object for
1364 * the current user's language (as a fallback for the old parameter
1365 * functionality), or if it is true then use global object
1366 * for the wiki's content language.
1367 * @return Language
1368 */
1369 function wfGetLangObj( $langcode = false ) {
1370 # Identify which language to get or create a language object for.
1371 # Using is_object here due to Stub objects.
1372 if ( is_object( $langcode ) ) {
1373 # Great, we already have the object (hopefully)!
1374 return $langcode;
1375 }
1376
1377 global $wgContLang, $wgLanguageCode;
1378 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1379 # $langcode is the language code of the wikis content language object.
1380 # or it is a boolean and value is true
1381 return $wgContLang;
1382 }
1383
1384 global $wgLang;
1385 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1386 # $langcode is the language code of user language object.
1387 # or it was a boolean and value is false
1388 return $wgLang;
1389 }
1390
1391 $validCodes = array_keys( Language::fetchLanguageNames() );
1392 if ( in_array( $langcode, $validCodes ) ) {
1393 # $langcode corresponds to a valid language.
1394 return Language::factory( $langcode );
1395 }
1396
1397 # $langcode is a string, but not a valid language code; use content language.
1398 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1399 return $wgContLang;
1400 }
1401
1402 /**
1403 * This is the function for getting translated interface messages.
1404 *
1405 * @see Message class for documentation how to use them.
1406 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1407 *
1408 * This function replaces all old wfMsg* functions.
1409 *
1410 * @param string|string[] $key Message key, or array of keys
1411 * @param mixed $params,... Normal message parameters
1412 * @return Message
1413 *
1414 * @since 1.17
1415 *
1416 * @see Message::__construct
1417 */
1418 function wfMessage( $key /*...*/ ) {
1419 $params = func_get_args();
1420 array_shift( $params );
1421 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1422 $params = $params[0];
1423 }
1424 return new Message( $key, $params );
1425 }
1426
1427 /**
1428 * This function accepts multiple message keys and returns a message instance
1429 * for the first message which is non-empty. If all messages are empty then an
1430 * instance of the first message key is returned.
1431 *
1432 * @param string|string[] $keys,... Message keys
1433 * @return Message
1434 *
1435 * @since 1.18
1436 *
1437 * @see Message::newFallbackSequence
1438 */
1439 function wfMessageFallback( /*...*/ ) {
1440 $args = func_get_args();
1441 return call_user_func_array( 'Message::newFallbackSequence', $args );
1442 }
1443
1444 /**
1445 * Get a message from anywhere, for the current user language.
1446 *
1447 * Use wfMsgForContent() instead if the message should NOT
1448 * change depending on the user preferences.
1449 *
1450 * @deprecated since 1.18
1451 *
1452 * @param string $key Lookup key for the message, usually
1453 * defined in languages/Language.php
1454 *
1455 * Parameters to the message, which can be used to insert variable text into
1456 * it, can be passed to this function in the following formats:
1457 * - One per argument, starting at the second parameter
1458 * - As an array in the second parameter
1459 * These are not shown in the function definition.
1460 *
1461 * @return string
1462 */
1463 function wfMsg( $key ) {
1464 wfDeprecated( __METHOD__, '1.21' );
1465
1466 $args = func_get_args();
1467 array_shift( $args );
1468 return wfMsgReal( $key, $args );
1469 }
1470
1471 /**
1472 * Same as above except doesn't transform the message
1473 *
1474 * @deprecated since 1.18
1475 *
1476 * @param string $key
1477 * @return string
1478 */
1479 function wfMsgNoTrans( $key ) {
1480 wfDeprecated( __METHOD__, '1.21' );
1481
1482 $args = func_get_args();
1483 array_shift( $args );
1484 return wfMsgReal( $key, $args, true, false, false );
1485 }
1486
1487 /**
1488 * Get a message from anywhere, for the current global language
1489 * set with $wgLanguageCode.
1490 *
1491 * Use this if the message should NOT change dependent on the
1492 * language set in the user's preferences. This is the case for
1493 * most text written into logs, as well as link targets (such as
1494 * the name of the copyright policy page). Link titles, on the
1495 * other hand, should be shown in the UI language.
1496 *
1497 * Note that MediaWiki allows users to change the user interface
1498 * language in their preferences, but a single installation
1499 * typically only contains content in one language.
1500 *
1501 * Be wary of this distinction: If you use wfMsg() where you should
1502 * use wfMsgForContent(), a user of the software may have to
1503 * customize potentially hundreds of messages in
1504 * order to, e.g., fix a link in every possible language.
1505 *
1506 * @deprecated since 1.18
1507 *
1508 * @param string $key Lookup key for the message, usually
1509 * defined in languages/Language.php
1510 * @return string
1511 */
1512 function wfMsgForContent( $key ) {
1513 wfDeprecated( __METHOD__, '1.21' );
1514
1515 global $wgForceUIMsgAsContentMsg;
1516 $args = func_get_args();
1517 array_shift( $args );
1518 $forcontent = true;
1519 if ( is_array( $wgForceUIMsgAsContentMsg )
1520 && in_array( $key, $wgForceUIMsgAsContentMsg )
1521 ) {
1522 $forcontent = false;
1523 }
1524 return wfMsgReal( $key, $args, true, $forcontent );
1525 }
1526
1527 /**
1528 * Same as above except doesn't transform the message
1529 *
1530 * @deprecated since 1.18
1531 *
1532 * @param string $key
1533 * @return string
1534 */
1535 function wfMsgForContentNoTrans( $key ) {
1536 wfDeprecated( __METHOD__, '1.21' );
1537
1538 global $wgForceUIMsgAsContentMsg;
1539 $args = func_get_args();
1540 array_shift( $args );
1541 $forcontent = true;
1542 if ( is_array( $wgForceUIMsgAsContentMsg )
1543 && in_array( $key, $wgForceUIMsgAsContentMsg )
1544 ) {
1545 $forcontent = false;
1546 }
1547 return wfMsgReal( $key, $args, true, $forcontent, false );
1548 }
1549
1550 /**
1551 * Really get a message
1552 *
1553 * @deprecated since 1.18
1554 *
1555 * @param string $key Key to get.
1556 * @param array $args
1557 * @param bool $useDB
1558 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1559 * @param bool $transform Whether or not to transform the message.
1560 * @return string The requested message.
1561 */
1562 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1563 wfDeprecated( __METHOD__, '1.21' );
1564
1565 wfProfileIn( __METHOD__ );
1566 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1567 $message = wfMsgReplaceArgs( $message, $args );
1568 wfProfileOut( __METHOD__ );
1569 return $message;
1570 }
1571
1572 /**
1573 * Fetch a message string value, but don't replace any keys yet.
1574 *
1575 * @deprecated since 1.18
1576 *
1577 * @param string $key
1578 * @param bool $useDB
1579 * @param string|bool $langCode Code of the language to get the message for, or
1580 * behaves as a content language switch if it is a boolean.
1581 * @param bool $transform Whether to parse magic words, etc.
1582 * @return string
1583 */
1584 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1585 wfDeprecated( __METHOD__, '1.21' );
1586
1587 wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1588
1589 $cache = MessageCache::singleton();
1590 $message = $cache->get( $key, $useDB, $langCode );
1591 if ( $message === false ) {
1592 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
1593 } elseif ( $transform ) {
1594 $message = $cache->transform( $message );
1595 }
1596 return $message;
1597 }
1598
1599 /**
1600 * Replace message parameter keys on the given formatted output.
1601 *
1602 * @param string $message
1603 * @param array $args
1604 * @return string
1605 * @deprecated since 1.25 Use the RawMessage class
1606 * @private
1607 */
1608 function wfMsgReplaceArgs( $message, $args ) {
1609 # Fix windows line-endings
1610 # Some messages are split with explode("\n", $msg)
1611 $message = str_replace( "\r", '', $message );
1612
1613 // Replace arguments
1614 if ( count( $args ) ) {
1615 if ( is_array( $args[0] ) ) {
1616 $args = array_values( $args[0] );
1617 }
1618 $replacementKeys = array();
1619 foreach ( $args as $n => $param ) {
1620 $replacementKeys['$' . ( $n + 1 )] = $param;
1621 }
1622 $message = strtr( $message, $replacementKeys );
1623 }
1624
1625 return $message;
1626 }
1627
1628 /**
1629 * Return an HTML-escaped version of a message.
1630 * Parameter replacements, if any, are done *after* the HTML-escaping,
1631 * so parameters may contain HTML (eg links or form controls). Be sure
1632 * to pre-escape them if you really do want plaintext, or just wrap
1633 * the whole thing in htmlspecialchars().
1634 *
1635 * @deprecated since 1.18
1636 *
1637 * @param string $key
1638 * @param string $args,... Parameters
1639 * @return string
1640 */
1641 function wfMsgHtml( $key ) {
1642 wfDeprecated( __METHOD__, '1.21' );
1643
1644 $args = func_get_args();
1645 array_shift( $args );
1646 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1647 }
1648
1649 /**
1650 * Return an HTML version of message
1651 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1652 * so parameters may contain HTML (eg links or form controls). Be sure
1653 * to pre-escape them if you really do want plaintext, or just wrap
1654 * the whole thing in htmlspecialchars().
1655 *
1656 * @deprecated since 1.18
1657 *
1658 * @param string $key
1659 * @param string $args,... Parameters
1660 * @return string
1661 */
1662 function wfMsgWikiHtml( $key ) {
1663 wfDeprecated( __METHOD__, '1.21' );
1664
1665 $args = func_get_args();
1666 array_shift( $args );
1667 return wfMsgReplaceArgs(
1668 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
1669 /* can't be set to false */ true, /* interface */ true )->getText(),
1670 $args );
1671 }
1672
1673 /**
1674 * Returns message in the requested format
1675 *
1676 * @deprecated since 1.18
1677 *
1678 * @param string $key Key of the message
1679 * @param array $options Processing rules.
1680 * Can take the following options:
1681 * parse: parses wikitext to HTML
1682 * parseinline: parses wikitext to HTML and removes the surrounding
1683 * p's added by parser or tidy
1684 * escape: filters message through htmlspecialchars
1685 * escapenoentities: same, but allows entity references like &#160; through
1686 * replaceafter: parameters are substituted after parsing or escaping
1687 * parsemag: transform the message using magic phrases
1688 * content: fetch message for content language instead of interface
1689 * Also can accept a single associative argument, of the form 'language' => 'xx':
1690 * language: Language object or language code to fetch message for
1691 * (overridden by content).
1692 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1693 *
1694 * @return string
1695 */
1696 function wfMsgExt( $key, $options ) {
1697 wfDeprecated( __METHOD__, '1.21' );
1698
1699 $args = func_get_args();
1700 array_shift( $args );
1701 array_shift( $args );
1702 $options = (array)$options;
1703
1704 foreach ( $options as $arrayKey => $option ) {
1705 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1706 # An unknown index, neither numeric nor "language"
1707 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
1708 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
1709 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
1710 'replaceafter', 'parsemag', 'content' ) ) ) {
1711 # A numeric index with unknown value
1712 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
1713 }
1714 }
1715
1716 if ( in_array( 'content', $options, true ) ) {
1717 $forContent = true;
1718 $langCode = true;
1719 $langCodeObj = null;
1720 } elseif ( array_key_exists( 'language', $options ) ) {
1721 $forContent = false;
1722 $langCode = wfGetLangObj( $options['language'] );
1723 $langCodeObj = $langCode;
1724 } else {
1725 $forContent = false;
1726 $langCode = false;
1727 $langCodeObj = null;
1728 }
1729
1730 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1731
1732 if ( !in_array( 'replaceafter', $options, true ) ) {
1733 $string = wfMsgReplaceArgs( $string, $args );
1734 }
1735
1736 $messageCache = MessageCache::singleton();
1737 $parseInline = in_array( 'parseinline', $options, true );
1738 if ( in_array( 'parse', $options, true ) || $parseInline ) {
1739 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1740 if ( $string instanceof ParserOutput ) {
1741 $string = $string->getText();
1742 }
1743
1744 if ( $parseInline ) {
1745 $string = Parser::stripOuterParagraph( $string );
1746 }
1747 } elseif ( in_array( 'parsemag', $options, true ) ) {
1748 $string = $messageCache->transform( $string,
1749 !$forContent, $langCodeObj );
1750 }
1751
1752 if ( in_array( 'escape', $options, true ) ) {
1753 $string = htmlspecialchars ( $string );
1754 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1755 $string = Sanitizer::escapeHtmlAllowEntities( $string );
1756 }
1757
1758 if ( in_array( 'replaceafter', $options, true ) ) {
1759 $string = wfMsgReplaceArgs( $string, $args );
1760 }
1761
1762 return $string;
1763 }
1764
1765 /**
1766 * Since wfMsg() and co suck, they don't return false if the message key they
1767 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1768 * nonexistence of messages by checking the MessageCache::get() result directly.
1769 *
1770 * @deprecated since 1.18. Use Message::isDisabled().
1771 *
1772 * @param string $key The message key looked up
1773 * @return bool True if the message *doesn't* exist.
1774 */
1775 function wfEmptyMsg( $key ) {
1776 wfDeprecated( __METHOD__, '1.21' );
1777
1778 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1779 }
1780
1781 /**
1782 * Fetch server name for use in error reporting etc.
1783 * Use real server name if available, so we know which machine
1784 * in a server farm generated the current page.
1785 *
1786 * @return string
1787 */
1788 function wfHostname() {
1789 static $host;
1790 if ( is_null( $host ) ) {
1791
1792 # Hostname overriding
1793 global $wgOverrideHostname;
1794 if ( $wgOverrideHostname !== false ) {
1795 # Set static and skip any detection
1796 $host = $wgOverrideHostname;
1797 return $host;
1798 }
1799
1800 if ( function_exists( 'posix_uname' ) ) {
1801 // This function not present on Windows
1802 $uname = posix_uname();
1803 } else {
1804 $uname = false;
1805 }
1806 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1807 $host = $uname['nodename'];
1808 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1809 # Windows computer name
1810 $host = getenv( 'COMPUTERNAME' );
1811 } else {
1812 # This may be a virtual server.
1813 $host = $_SERVER['SERVER_NAME'];
1814 }
1815 }
1816 return $host;
1817 }
1818
1819 /**
1820 * Returns a script tag that stores the amount of time it took MediaWiki to
1821 * handle the request in milliseconds as 'wgBackendResponseTime'.
1822 *
1823 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1824 * hostname of the server handling the request.
1825 *
1826 * @return string
1827 */
1828 function wfReportTime() {
1829 global $wgRequestTime, $wgShowHostnames;
1830
1831 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1832 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1833 if ( $wgShowHostnames ) {
1834 $reportVars['wgHostname'] = wfHostname();
1835 }
1836 return Skin::makeVariablesScript( $reportVars );
1837 }
1838
1839 /**
1840 * Safety wrapper for debug_backtrace().
1841 *
1842 * Will return an empty array if debug_backtrace is disabled, otherwise
1843 * the output from debug_backtrace() (trimmed).
1844 *
1845 * @param int $limit This parameter can be used to limit the number of stack frames returned
1846 *
1847 * @return array Array of backtrace information
1848 */
1849 function wfDebugBacktrace( $limit = 0 ) {
1850 static $disabled = null;
1851
1852 if ( is_null( $disabled ) ) {
1853 $disabled = !function_exists( 'debug_backtrace' );
1854 if ( $disabled ) {
1855 wfDebug( "debug_backtrace() is disabled\n" );
1856 }
1857 }
1858 if ( $disabled ) {
1859 return array();
1860 }
1861
1862 if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
1863 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1864 } else {
1865 return array_slice( debug_backtrace(), 1 );
1866 }
1867 }
1868
1869 /**
1870 * Get a debug backtrace as a string
1871 *
1872 * @return string
1873 */
1874 function wfBacktrace() {
1875 global $wgCommandLineMode;
1876
1877 if ( $wgCommandLineMode ) {
1878 $msg = '';
1879 } else {
1880 $msg = "<ul>\n";
1881 }
1882 $backtrace = wfDebugBacktrace();
1883 foreach ( $backtrace as $call ) {
1884 if ( isset( $call['file'] ) ) {
1885 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
1886 $file = $f[count( $f ) - 1];
1887 } else {
1888 $file = '-';
1889 }
1890 if ( isset( $call['line'] ) ) {
1891 $line = $call['line'];
1892 } else {
1893 $line = '-';
1894 }
1895 if ( $wgCommandLineMode ) {
1896 $msg .= "$file line $line calls ";
1897 } else {
1898 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
1899 }
1900 if ( !empty( $call['class'] ) ) {
1901 $msg .= $call['class'] . $call['type'];
1902 }
1903 $msg .= $call['function'] . '()';
1904
1905 if ( $wgCommandLineMode ) {
1906 $msg .= "\n";
1907 } else {
1908 $msg .= "</li>\n";
1909 }
1910 }
1911 if ( $wgCommandLineMode ) {
1912 $msg .= "\n";
1913 } else {
1914 $msg .= "</ul>\n";
1915 }
1916
1917 return $msg;
1918 }
1919
1920 /**
1921 * Get the name of the function which called this function
1922 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1923 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1924 * wfGetCaller( 3 ) is the parent of that.
1925 *
1926 * @param int $level
1927 * @return string
1928 */
1929 function wfGetCaller( $level = 2 ) {
1930 $backtrace = wfDebugBacktrace( $level + 1 );
1931 if ( isset( $backtrace[$level] ) ) {
1932 return wfFormatStackFrame( $backtrace[$level] );
1933 } else {
1934 return 'unknown';
1935 }
1936 }
1937
1938 /**
1939 * Return a string consisting of callers in the stack. Useful sometimes
1940 * for profiling specific points.
1941 *
1942 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1943 * @return string
1944 */
1945 function wfGetAllCallers( $limit = 3 ) {
1946 $trace = array_reverse( wfDebugBacktrace() );
1947 if ( !$limit || $limit > count( $trace ) - 1 ) {
1948 $limit = count( $trace ) - 1;
1949 }
1950 $trace = array_slice( $trace, -$limit - 1, $limit );
1951 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1952 }
1953
1954 /**
1955 * Return a string representation of frame
1956 *
1957 * @param array $frame
1958 * @return string
1959 */
1960 function wfFormatStackFrame( $frame ) {
1961 return isset( $frame['class'] ) ?
1962 $frame['class'] . '::' . $frame['function'] :
1963 $frame['function'];
1964 }
1965
1966 /* Some generic result counters, pulled out of SearchEngine */
1967
1968 /**
1969 * @todo document
1970 *
1971 * @param int $offset
1972 * @param int $limit
1973 * @return string
1974 */
1975 function wfShowingResults( $offset, $limit ) {
1976 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1977 }
1978
1979 /**
1980 * @todo document
1981 * @todo FIXME: We may want to blacklist some broken browsers
1982 *
1983 * @param bool $force
1984 * @return bool Whereas client accept gzip compression
1985 */
1986 function wfClientAcceptsGzip( $force = false ) {
1987 static $result = null;
1988 if ( $result === null || $force ) {
1989 $result = false;
1990 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
1991 # @todo FIXME: We may want to blacklist some broken browsers
1992 $m = array();
1993 if ( preg_match(
1994 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1995 $_SERVER['HTTP_ACCEPT_ENCODING'],
1996 $m
1997 )
1998 ) {
1999 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2000 $result = false;
2001 return $result;
2002 }
2003 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2004 $result = true;
2005 }
2006 }
2007 }
2008 return $result;
2009 }
2010
2011 /**
2012 * Obtain the offset and limit values from the request string;
2013 * used in special pages
2014 *
2015 * @param int $deflimit Default limit if none supplied
2016 * @param string $optionname Name of a user preference to check against
2017 * @return array
2018 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2019 */
2020 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2021 global $wgRequest;
2022 wfDeprecated( __METHOD__, '1.24' );
2023 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2024 }
2025
2026 /**
2027 * Escapes the given text so that it may be output using addWikiText()
2028 * without any linking, formatting, etc. making its way through. This
2029 * is achieved by substituting certain characters with HTML entities.
2030 * As required by the callers, "<nowiki>" is not used.
2031 *
2032 * @param string $text Text to be escaped
2033 * @return string
2034 */
2035 function wfEscapeWikiText( $text ) {
2036 static $repl = null, $repl2 = null;
2037 if ( $repl === null ) {
2038 $repl = array(
2039 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
2040 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
2041 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
2042 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
2043 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
2044 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
2045 "\n " => "\n&#32;", "\r " => "\r&#32;",
2046 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
2047 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
2048 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
2049 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
2050 '__' => '_&#95;', '://' => '&#58;//',
2051 );
2052
2053 // We have to catch everything "\s" matches in PCRE
2054 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2055 $repl["$magic "] = "$magic&#32;";
2056 $repl["$magic\t"] = "$magic&#9;";
2057 $repl["$magic\r"] = "$magic&#13;";
2058 $repl["$magic\n"] = "$magic&#10;";
2059 $repl["$magic\f"] = "$magic&#12;";
2060 }
2061
2062 // And handle protocols that don't use "://"
2063 global $wgUrlProtocols;
2064 $repl2 = array();
2065 foreach ( $wgUrlProtocols as $prot ) {
2066 if ( substr( $prot, -1 ) === ':' ) {
2067 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2068 }
2069 }
2070 $repl2 = $repl2 ? '/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2071 }
2072 $text = substr( strtr( "\n$text", $repl ), 1 );
2073 $text = preg_replace( $repl2, '$1&#58;', $text );
2074 return $text;
2075 }
2076
2077 /**
2078 * Sets dest to source and returns the original value of dest
2079 * If source is NULL, it just returns the value, it doesn't set the variable
2080 * If force is true, it will set the value even if source is NULL
2081 *
2082 * @param mixed $dest
2083 * @param mixed $source
2084 * @param bool $force
2085 * @return mixed
2086 */
2087 function wfSetVar( &$dest, $source, $force = false ) {
2088 $temp = $dest;
2089 if ( !is_null( $source ) || $force ) {
2090 $dest = $source;
2091 }
2092 return $temp;
2093 }
2094
2095 /**
2096 * As for wfSetVar except setting a bit
2097 *
2098 * @param int $dest
2099 * @param int $bit
2100 * @param bool $state
2101 *
2102 * @return bool
2103 */
2104 function wfSetBit( &$dest, $bit, $state = true ) {
2105 $temp = (bool)( $dest & $bit );
2106 if ( !is_null( $state ) ) {
2107 if ( $state ) {
2108 $dest |= $bit;
2109 } else {
2110 $dest &= ~$bit;
2111 }
2112 }
2113 return $temp;
2114 }
2115
2116 /**
2117 * A wrapper around the PHP function var_export().
2118 * Either print it or add it to the regular output ($wgOut).
2119 *
2120 * @param mixed $var A PHP variable to dump.
2121 */
2122 function wfVarDump( $var ) {
2123 global $wgOut;
2124 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2125 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
2126 print $s;
2127 } else {
2128 $wgOut->addHTML( $s );
2129 }
2130 }
2131
2132 /**
2133 * Provide a simple HTTP error.
2134 *
2135 * @param int|string $code
2136 * @param string $label
2137 * @param string $desc
2138 */
2139 function wfHttpError( $code, $label, $desc ) {
2140 global $wgOut;
2141 $wgOut->disable();
2142 header( "HTTP/1.0 $code $label" );
2143 header( "Status: $code $label" );
2144 $wgOut->sendCacheControl();
2145
2146 header( 'Content-type: text/html; charset=utf-8' );
2147 print "<!doctype html>" .
2148 '<html><head><title>' .
2149 htmlspecialchars( $label ) .
2150 '</title></head><body><h1>' .
2151 htmlspecialchars( $label ) .
2152 '</h1><p>' .
2153 nl2br( htmlspecialchars( $desc ) ) .
2154 "</p></body></html>\n";
2155 }
2156
2157 /**
2158 * Clear away any user-level output buffers, discarding contents.
2159 *
2160 * Suitable for 'starting afresh', for instance when streaming
2161 * relatively large amounts of data without buffering, or wanting to
2162 * output image files without ob_gzhandler's compression.
2163 *
2164 * The optional $resetGzipEncoding parameter controls suppression of
2165 * the Content-Encoding header sent by ob_gzhandler; by default it
2166 * is left. See comments for wfClearOutputBuffers() for why it would
2167 * be used.
2168 *
2169 * Note that some PHP configuration options may add output buffer
2170 * layers which cannot be removed; these are left in place.
2171 *
2172 * @param bool $resetGzipEncoding
2173 */
2174 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2175 if ( $resetGzipEncoding ) {
2176 // Suppress Content-Encoding and Content-Length
2177 // headers from 1.10+s wfOutputHandler
2178 global $wgDisableOutputCompression;
2179 $wgDisableOutputCompression = true;
2180 }
2181 while ( $status = ob_get_status() ) {
2182 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2183 // Probably from zlib.output_compression or other
2184 // PHP-internal setting which can't be removed.
2185 //
2186 // Give up, and hope the result doesn't break
2187 // output behavior.
2188 break;
2189 }
2190 if ( !ob_end_clean() ) {
2191 // Could not remove output buffer handler; abort now
2192 // to avoid getting in some kind of infinite loop.
2193 break;
2194 }
2195 if ( $resetGzipEncoding ) {
2196 if ( $status['name'] == 'ob_gzhandler' ) {
2197 // Reset the 'Content-Encoding' field set by this handler
2198 // so we can start fresh.
2199 header_remove( 'Content-Encoding' );
2200 break;
2201 }
2202 }
2203 }
2204 }
2205
2206 /**
2207 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2208 *
2209 * Clear away output buffers, but keep the Content-Encoding header
2210 * produced by ob_gzhandler, if any.
2211 *
2212 * This should be used for HTTP 304 responses, where you need to
2213 * preserve the Content-Encoding header of the real result, but
2214 * also need to suppress the output of ob_gzhandler to keep to spec
2215 * and avoid breaking Firefox in rare cases where the headers and
2216 * body are broken over two packets.
2217 */
2218 function wfClearOutputBuffers() {
2219 wfResetOutputBuffers( false );
2220 }
2221
2222 /**
2223 * Converts an Accept-* header into an array mapping string values to quality
2224 * factors
2225 *
2226 * @param string $accept
2227 * @param string $def Default
2228 * @return float[] Associative array of string => float pairs
2229 */
2230 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2231 # No arg means accept anything (per HTTP spec)
2232 if ( !$accept ) {
2233 return array( $def => 1.0 );
2234 }
2235
2236 $prefs = array();
2237
2238 $parts = explode( ',', $accept );
2239
2240 foreach ( $parts as $part ) {
2241 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2242 $values = explode( ';', trim( $part ) );
2243 $match = array();
2244 if ( count( $values ) == 1 ) {
2245 $prefs[$values[0]] = 1.0;
2246 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2247 $prefs[$values[0]] = floatval( $match[1] );
2248 }
2249 }
2250
2251 return $prefs;
2252 }
2253
2254 /**
2255 * Checks if a given MIME type matches any of the keys in the given
2256 * array. Basic wildcards are accepted in the array keys.
2257 *
2258 * Returns the matching MIME type (or wildcard) if a match, otherwise
2259 * NULL if no match.
2260 *
2261 * @param string $type
2262 * @param array $avail
2263 * @return string
2264 * @private
2265 */
2266 function mimeTypeMatch( $type, $avail ) {
2267 if ( array_key_exists( $type, $avail ) ) {
2268 return $type;
2269 } else {
2270 $parts = explode( '/', $type );
2271 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2272 return $parts[0] . '/*';
2273 } elseif ( array_key_exists( '*/*', $avail ) ) {
2274 return '*/*';
2275 } else {
2276 return null;
2277 }
2278 }
2279 }
2280
2281 /**
2282 * Returns the 'best' match between a client's requested internet media types
2283 * and the server's list of available types. Each list should be an associative
2284 * array of type to preference (preference is a float between 0.0 and 1.0).
2285 * Wildcards in the types are acceptable.
2286 *
2287 * @param array $cprefs Client's acceptable type list
2288 * @param array $sprefs Server's offered types
2289 * @return string
2290 *
2291 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2292 * XXX: generalize to negotiate other stuff
2293 */
2294 function wfNegotiateType( $cprefs, $sprefs ) {
2295 $combine = array();
2296
2297 foreach ( array_keys( $sprefs ) as $type ) {
2298 $parts = explode( '/', $type );
2299 if ( $parts[1] != '*' ) {
2300 $ckey = mimeTypeMatch( $type, $cprefs );
2301 if ( $ckey ) {
2302 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2303 }
2304 }
2305 }
2306
2307 foreach ( array_keys( $cprefs ) as $type ) {
2308 $parts = explode( '/', $type );
2309 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2310 $skey = mimeTypeMatch( $type, $sprefs );
2311 if ( $skey ) {
2312 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2313 }
2314 }
2315 }
2316
2317 $bestq = 0;
2318 $besttype = null;
2319
2320 foreach ( array_keys( $combine ) as $type ) {
2321 if ( $combine[$type] > $bestq ) {
2322 $besttype = $type;
2323 $bestq = $combine[$type];
2324 }
2325 }
2326
2327 return $besttype;
2328 }
2329
2330 /**
2331 * Reference-counted warning suppression
2332 *
2333 * @param bool $end
2334 */
2335 function wfSuppressWarnings( $end = false ) {
2336 static $suppressCount = 0;
2337 static $originalLevel = false;
2338
2339 if ( $end ) {
2340 if ( $suppressCount ) {
2341 --$suppressCount;
2342 if ( !$suppressCount ) {
2343 error_reporting( $originalLevel );
2344 }
2345 }
2346 } else {
2347 if ( !$suppressCount ) {
2348 $originalLevel = error_reporting( E_ALL & ~(
2349 E_WARNING |
2350 E_NOTICE |
2351 E_USER_WARNING |
2352 E_USER_NOTICE |
2353 E_DEPRECATED |
2354 E_USER_DEPRECATED |
2355 E_STRICT
2356 ) );
2357 }
2358 ++$suppressCount;
2359 }
2360 }
2361
2362 /**
2363 * Restore error level to previous value
2364 */
2365 function wfRestoreWarnings() {
2366 wfSuppressWarnings( true );
2367 }
2368
2369 # Autodetect, convert and provide timestamps of various types
2370
2371 /**
2372 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2373 */
2374 define( 'TS_UNIX', 0 );
2375
2376 /**
2377 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2378 */
2379 define( 'TS_MW', 1 );
2380
2381 /**
2382 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2383 */
2384 define( 'TS_DB', 2 );
2385
2386 /**
2387 * RFC 2822 format, for E-mail and HTTP headers
2388 */
2389 define( 'TS_RFC2822', 3 );
2390
2391 /**
2392 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2393 *
2394 * This is used by Special:Export
2395 */
2396 define( 'TS_ISO_8601', 4 );
2397
2398 /**
2399 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2400 *
2401 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2402 * DateTime tag and page 36 for the DateTimeOriginal and
2403 * DateTimeDigitized tags.
2404 */
2405 define( 'TS_EXIF', 5 );
2406
2407 /**
2408 * Oracle format time.
2409 */
2410 define( 'TS_ORACLE', 6 );
2411
2412 /**
2413 * Postgres format time.
2414 */
2415 define( 'TS_POSTGRES', 7 );
2416
2417 /**
2418 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2419 */
2420 define( 'TS_ISO_8601_BASIC', 9 );
2421
2422 /**
2423 * Get a timestamp string in one of various formats
2424 *
2425 * @param mixed $outputtype A timestamp in one of the supported formats, the
2426 * function will autodetect which format is supplied and act accordingly.
2427 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2428 * @return string|bool String / false The same date in the format specified in $outputtype or false
2429 */
2430 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2431 try {
2432 $timestamp = new MWTimestamp( $ts );
2433 return $timestamp->getTimestamp( $outputtype );
2434 } catch ( TimestampException $e ) {
2435 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2436 return false;
2437 }
2438 }
2439
2440 /**
2441 * Return a formatted timestamp, or null if input is null.
2442 * For dealing with nullable timestamp columns in the database.
2443 *
2444 * @param int $outputtype
2445 * @param string $ts
2446 * @return string
2447 */
2448 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2449 if ( is_null( $ts ) ) {
2450 return null;
2451 } else {
2452 return wfTimestamp( $outputtype, $ts );
2453 }
2454 }
2455
2456 /**
2457 * Convenience function; returns MediaWiki timestamp for the present time.
2458 *
2459 * @return string
2460 */
2461 function wfTimestampNow() {
2462 # return NOW
2463 return wfTimestamp( TS_MW, time() );
2464 }
2465
2466 /**
2467 * Check if the operating system is Windows
2468 *
2469 * @return bool True if it's Windows, false otherwise.
2470 */
2471 function wfIsWindows() {
2472 static $isWindows = null;
2473 if ( $isWindows === null ) {
2474 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2475 }
2476 return $isWindows;
2477 }
2478
2479 /**
2480 * Check if we are running under HHVM
2481 *
2482 * @return bool
2483 */
2484 function wfIsHHVM() {
2485 return defined( 'HHVM_VERSION' );
2486 }
2487
2488 /**
2489 * Swap two variables
2490 *
2491 * @deprecated since 1.24
2492 * @param mixed $x
2493 * @param mixed $y
2494 */
2495 function swap( &$x, &$y ) {
2496 wfDeprecated( __FUNCTION__, '1.24' );
2497 $z = $x;
2498 $x = $y;
2499 $y = $z;
2500 }
2501
2502 /**
2503 * Tries to get the system directory for temporary files. First
2504 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2505 * environment variables are then checked in sequence, and if none are
2506 * set try sys_get_temp_dir().
2507 *
2508 * NOTE: When possible, use instead the tmpfile() function to create
2509 * temporary files to avoid race conditions on file creation, etc.
2510 *
2511 * @return string
2512 */
2513 function wfTempDir() {
2514 global $wgTmpDirectory;
2515
2516 if ( $wgTmpDirectory !== false ) {
2517 return $wgTmpDirectory;
2518 }
2519
2520 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2521
2522 foreach ( $tmpDir as $tmp ) {
2523 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2524 return $tmp;
2525 }
2526 }
2527 return sys_get_temp_dir();
2528 }
2529
2530 /**
2531 * Make directory, and make all parent directories if they don't exist
2532 *
2533 * @param string $dir Full path to directory to create
2534 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2535 * @param string $caller Optional caller param for debugging.
2536 * @throws MWException
2537 * @return bool
2538 */
2539 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2540 global $wgDirectoryMode;
2541
2542 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
2543 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
2544 }
2545
2546 if ( !is_null( $caller ) ) {
2547 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2548 }
2549
2550 if ( strval( $dir ) === '' || ( file_exists( $dir ) && is_dir( $dir ) ) ) {
2551 return true;
2552 }
2553
2554 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2555
2556 if ( is_null( $mode ) ) {
2557 $mode = $wgDirectoryMode;
2558 }
2559
2560 // Turn off the normal warning, we're doing our own below
2561 wfSuppressWarnings();
2562 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2563 wfRestoreWarnings();
2564
2565 if ( !$ok ) {
2566 //directory may have been created on another request since we last checked
2567 if ( is_dir( $dir ) ) {
2568 return true;
2569 }
2570
2571 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2572 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2573 }
2574 return $ok;
2575 }
2576
2577 /**
2578 * Remove a directory and all its content.
2579 * Does not hide error.
2580 * @param string $dir
2581 */
2582 function wfRecursiveRemoveDir( $dir ) {
2583 wfDebug( __FUNCTION__ . "( $dir )\n" );
2584 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2585 if ( is_dir( $dir ) ) {
2586 $objects = scandir( $dir );
2587 foreach ( $objects as $object ) {
2588 if ( $object != "." && $object != ".." ) {
2589 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2590 wfRecursiveRemoveDir( $dir . '/' . $object );
2591 } else {
2592 unlink( $dir . '/' . $object );
2593 }
2594 }
2595 }
2596 reset( $objects );
2597 rmdir( $dir );
2598 }
2599 }
2600
2601 /**
2602 * @param int $nr The number to format
2603 * @param int $acc The number of digits after the decimal point, default 2
2604 * @param bool $round Whether or not to round the value, default true
2605 * @return string
2606 */
2607 function wfPercent( $nr, $acc = 2, $round = true ) {
2608 $ret = sprintf( "%.${acc}f", $nr );
2609 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2610 }
2611
2612 /**
2613 * Safety wrapper around ini_get() for boolean settings.
2614 * The values returned from ini_get() are pre-normalized for settings
2615 * set via php.ini or php_flag/php_admin_flag... but *not*
2616 * for those set via php_value/php_admin_value.
2617 *
2618 * It's fairly common for people to use php_value instead of php_flag,
2619 * which can leave you with an 'off' setting giving a false positive
2620 * for code that just takes the ini_get() return value as a boolean.
2621 *
2622 * To make things extra interesting, setting via php_value accepts
2623 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2624 * Unrecognized values go false... again opposite PHP's own coercion
2625 * from string to bool.
2626 *
2627 * Luckily, 'properly' set settings will always come back as '0' or '1',
2628 * so we only have to worry about them and the 'improper' settings.
2629 *
2630 * I frickin' hate PHP... :P
2631 *
2632 * @param string $setting
2633 * @return bool
2634 */
2635 function wfIniGetBool( $setting ) {
2636 $val = strtolower( ini_get( $setting ) );
2637 // 'on' and 'true' can't have whitespace around them, but '1' can.
2638 return $val == 'on'
2639 || $val == 'true'
2640 || $val == 'yes'
2641 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2642 }
2643
2644 /**
2645 * Windows-compatible version of escapeshellarg()
2646 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2647 * function puts single quotes in regardless of OS.
2648 *
2649 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2650 * earlier distro releases of PHP)
2651 *
2652 * @param string $args,...
2653 * @return string
2654 */
2655 function wfEscapeShellArg( /*...*/ ) {
2656 wfInitShellLocale();
2657
2658 $args = func_get_args();
2659 $first = true;
2660 $retVal = '';
2661 foreach ( $args as $arg ) {
2662 if ( !$first ) {
2663 $retVal .= ' ';
2664 } else {
2665 $first = false;
2666 }
2667
2668 if ( wfIsWindows() ) {
2669 // Escaping for an MSVC-style command line parser and CMD.EXE
2670 // @codingStandardsIgnoreStart For long URLs
2671 // Refs:
2672 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2673 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2674 // * Bug #13518
2675 // * CR r63214
2676 // Double the backslashes before any double quotes. Escape the double quotes.
2677 // @codingStandardsIgnoreEnd
2678 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
2679 $arg = '';
2680 $iteration = 0;
2681 foreach ( $tokens as $token ) {
2682 if ( $iteration % 2 == 1 ) {
2683 // Delimiter, a double quote preceded by zero or more slashes
2684 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2685 } elseif ( $iteration % 4 == 2 ) {
2686 // ^ in $token will be outside quotes, need to be escaped
2687 $arg .= str_replace( '^', '^^', $token );
2688 } else { // $iteration % 4 == 0
2689 // ^ in $token will appear inside double quotes, so leave as is
2690 $arg .= $token;
2691 }
2692 $iteration++;
2693 }
2694 // Double the backslashes before the end of the string, because
2695 // we will soon add a quote
2696 $m = array();
2697 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2698 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2699 }
2700
2701 // Add surrounding quotes
2702 $retVal .= '"' . $arg . '"';
2703 } else {
2704 $retVal .= escapeshellarg( $arg );
2705 }
2706 }
2707 return $retVal;
2708 }
2709
2710 /**
2711 * Check if wfShellExec() is effectively disabled via php.ini config
2712 *
2713 * @return bool|string False or one of (safemode,disabled)
2714 * @since 1.22
2715 */
2716 function wfShellExecDisabled() {
2717 static $disabled = null;
2718 if ( is_null( $disabled ) ) {
2719 if ( wfIniGetBool( 'safe_mode' ) ) {
2720 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2721 $disabled = 'safemode';
2722 } elseif ( !function_exists( 'proc_open' ) ) {
2723 wfDebug( "proc_open() is disabled\n" );
2724 $disabled = 'disabled';
2725 } else {
2726 $disabled = false;
2727 }
2728 }
2729 return $disabled;
2730 }
2731
2732 /**
2733 * Execute a shell command, with time and memory limits mirrored from the PHP
2734 * configuration if supported.
2735 *
2736 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2737 * or an array of unescaped arguments, in which case each value will be escaped
2738 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2739 * @param null|mixed &$retval Optional, will receive the program's exit code.
2740 * (non-zero is usually failure). If there is an error from
2741 * read, select, or proc_open(), this will be set to -1.
2742 * @param array $environ Optional environment variables which should be
2743 * added to the executed command environment.
2744 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2745 * this overwrites the global wgMaxShell* limits.
2746 * @param array $options Array of options:
2747 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2748 * including errors from limit.sh
2749 *
2750 * @return string Collected stdout as a string
2751 */
2752 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2753 $limits = array(), $options = array()
2754 ) {
2755 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2756 $wgMaxShellWallClockTime, $wgShellCgroup;
2757
2758 $disabled = wfShellExecDisabled();
2759 if ( $disabled ) {
2760 $retval = 1;
2761 return $disabled == 'safemode' ?
2762 'Unable to run external programs in safe mode.' :
2763 'Unable to run external programs, proc_open() is disabled.';
2764 }
2765
2766 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2767
2768 wfInitShellLocale();
2769
2770 $envcmd = '';
2771 foreach ( $environ as $k => $v ) {
2772 if ( wfIsWindows() ) {
2773 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2774 * appear in the environment variable, so we must use carat escaping as documented in
2775 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2776 * Note however that the quote isn't listed there, but is needed, and the parentheses
2777 * are listed there but doesn't appear to need it.
2778 */
2779 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2780 } else {
2781 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2782 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2783 */
2784 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2785 }
2786 }
2787 if ( is_array( $cmd ) ) {
2788 // Command line may be given as an array, escape each value and glue them together with a space
2789 $cmdVals = array();
2790 foreach ( $cmd as $val ) {
2791 $cmdVals[] = wfEscapeShellArg( $val );
2792 }
2793 $cmd = implode( ' ', $cmdVals );
2794 }
2795
2796 $cmd = $envcmd . $cmd;
2797
2798 $useLogPipe = false;
2799 if ( is_executable( '/bin/bash' ) ) {
2800 $time = intval ( isset( $limits['time'] ) ? $limits['time'] : $wgMaxShellTime );
2801 if ( isset( $limits['walltime'] ) ) {
2802 $wallTime = intval( $limits['walltime'] );
2803 } elseif ( isset( $limits['time'] ) ) {
2804 $wallTime = $time;
2805 } else {
2806 $wallTime = intval( $wgMaxShellWallClockTime );
2807 }
2808 $mem = intval ( isset( $limits['memory'] ) ? $limits['memory'] : $wgMaxShellMemory );
2809 $filesize = intval ( isset( $limits['filesize'] ) ? $limits['filesize'] : $wgMaxShellFileSize );
2810
2811 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
2812 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2813 escapeshellarg( $cmd ) . ' ' .
2814 escapeshellarg(
2815 "MW_INCLUDE_STDERR=" . ( $includeStderr ? '1' : '' ) . ';' .
2816 "MW_CPU_LIMIT=$time; " .
2817 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2818 "MW_MEM_LIMIT=$mem; " .
2819 "MW_FILE_SIZE_LIMIT=$filesize; " .
2820 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2821 "MW_USE_LOG_PIPE=yes"
2822 );
2823 $useLogPipe = true;
2824 } elseif ( $includeStderr ) {
2825 $cmd .= ' 2>&1';
2826 }
2827 } elseif ( $includeStderr ) {
2828 $cmd .= ' 2>&1';
2829 }
2830 wfDebug( "wfShellExec: $cmd\n" );
2831
2832 $desc = array(
2833 0 => array( 'file', 'php://stdin', 'r' ),
2834 1 => array( 'pipe', 'w' ),
2835 2 => array( 'file', 'php://stderr', 'w' ) );
2836 if ( $useLogPipe ) {
2837 $desc[3] = array( 'pipe', 'w' );
2838 }
2839 $pipes = null;
2840 $proc = proc_open( $cmd, $desc, $pipes );
2841 if ( !$proc ) {
2842 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2843 $retval = -1;
2844 return '';
2845 }
2846 $outBuffer = $logBuffer = '';
2847 $emptyArray = array();
2848 $status = false;
2849 $logMsg = false;
2850
2851 // According to the documentation, it is possible for stream_select()
2852 // to fail due to EINTR. I haven't managed to induce this in testing
2853 // despite sending various signals. If it did happen, the error
2854 // message would take the form:
2855 //
2856 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2857 //
2858 // where [4] is the value of the macro EINTR and "Interrupted system
2859 // call" is string which according to the Linux manual is "possibly"
2860 // localised according to LC_MESSAGES.
2861 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
2862 $eintrMessage = "stream_select(): unable to select [$eintr]";
2863
2864 // Build a table mapping resource IDs to pipe FDs to work around a
2865 // PHP 5.3 issue in which stream_select() does not preserve array keys
2866 // <https://bugs.php.net/bug.php?id=53427>.
2867 $fds = array();
2868 foreach ( $pipes as $fd => $pipe ) {
2869 $fds[(int)$pipe] = $fd;
2870 }
2871
2872 $running = true;
2873 $timeout = null;
2874 $numReadyPipes = 0;
2875
2876 while ( $running === true || $numReadyPipes !== 0 ) {
2877 if ( $running ) {
2878 $status = proc_get_status( $proc );
2879 // If the process has terminated, switch to nonblocking selects
2880 // for getting any data still waiting to be read.
2881 if ( !$status['running'] ) {
2882 $running = false;
2883 $timeout = 0;
2884 }
2885 }
2886
2887 $readyPipes = $pipes;
2888
2889 // Clear last error
2890 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2891 @trigger_error( '' );
2892 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
2893 if ( $numReadyPipes === false ) {
2894 // @codingStandardsIgnoreEnd
2895 $error = error_get_last();
2896 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2897 continue;
2898 } else {
2899 trigger_error( $error['message'], E_USER_WARNING );
2900 $logMsg = $error['message'];
2901 break;
2902 }
2903 }
2904 foreach ( $readyPipes as $pipe ) {
2905 $block = fread( $pipe, 65536 );
2906 $fd = $fds[(int)$pipe];
2907 if ( $block === '' ) {
2908 // End of file
2909 fclose( $pipes[$fd] );
2910 unset( $pipes[$fd] );
2911 if ( !$pipes ) {
2912 break 2;
2913 }
2914 } elseif ( $block === false ) {
2915 // Read error
2916 $logMsg = "Error reading from pipe";
2917 break 2;
2918 } elseif ( $fd == 1 ) {
2919 // From stdout
2920 $outBuffer .= $block;
2921 } elseif ( $fd == 3 ) {
2922 // From log FD
2923 $logBuffer .= $block;
2924 if ( strpos( $block, "\n" ) !== false ) {
2925 $lines = explode( "\n", $logBuffer );
2926 $logBuffer = array_pop( $lines );
2927 foreach ( $lines as $line ) {
2928 wfDebugLog( 'exec', $line );
2929 }
2930 }
2931 }
2932 }
2933 }
2934
2935 foreach ( $pipes as $pipe ) {
2936 fclose( $pipe );
2937 }
2938
2939 // Use the status previously collected if possible, since proc_get_status()
2940 // just calls waitpid() which will not return anything useful the second time.
2941 if ( $running ) {
2942 $status = proc_get_status( $proc );
2943 }
2944
2945 if ( $logMsg !== false ) {
2946 // Read/select error
2947 $retval = -1;
2948 proc_close( $proc );
2949 } elseif ( $status['signaled'] ) {
2950 $logMsg = "Exited with signal {$status['termsig']}";
2951 $retval = 128 + $status['termsig'];
2952 proc_close( $proc );
2953 } else {
2954 if ( $status['running'] ) {
2955 $retval = proc_close( $proc );
2956 } else {
2957 $retval = $status['exitcode'];
2958 proc_close( $proc );
2959 }
2960 if ( $retval == 127 ) {
2961 $logMsg = "Possibly missing executable file";
2962 } elseif ( $retval >= 129 && $retval <= 192 ) {
2963 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2964 }
2965 }
2966
2967 if ( $logMsg !== false ) {
2968 wfDebugLog( 'exec', "$logMsg: $cmd" );
2969 }
2970
2971 return $outBuffer;
2972 }
2973
2974 /**
2975 * Execute a shell command, returning both stdout and stderr. Convenience
2976 * function, as all the arguments to wfShellExec can become unwieldy.
2977 *
2978 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
2979 * @param string $cmd Command line, properly escaped for shell.
2980 * @param null|mixed &$retval Optional, will receive the program's exit code.
2981 * (non-zero is usually failure)
2982 * @param array $environ Optional environment variables which should be
2983 * added to the executed command environment.
2984 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2985 * this overwrites the global wgMaxShell* limits.
2986 * @return string Collected stdout and stderr as a string
2987 */
2988 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
2989 return wfShellExec( $cmd, $retval, $environ, $limits, array( 'duplicateStderr' => true ) );
2990 }
2991
2992 /**
2993 * Workaround for http://bugs.php.net/bug.php?id=45132
2994 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2995 */
2996 function wfInitShellLocale() {
2997 static $done = false;
2998 if ( $done ) {
2999 return;
3000 }
3001 $done = true;
3002 global $wgShellLocale;
3003 if ( !wfIniGetBool( 'safe_mode' ) ) {
3004 putenv( "LC_CTYPE=$wgShellLocale" );
3005 setlocale( LC_CTYPE, $wgShellLocale );
3006 }
3007 }
3008
3009 /**
3010 * Alias to wfShellWikiCmd()
3011 *
3012 * @see wfShellWikiCmd()
3013 */
3014 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
3015 return wfShellWikiCmd( $script, $parameters, $options );
3016 }
3017
3018 /**
3019 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3020 * Note that $parameters should be a flat array and an option with an argument
3021 * should consist of two consecutive items in the array (do not use "--option value").
3022 *
3023 * @param string $script MediaWiki cli script path
3024 * @param array $parameters Arguments and options to the script
3025 * @param array $options Associative array of options:
3026 * 'php': The path to the php executable
3027 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3028 * @return string
3029 */
3030 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3031 global $wgPhpCli;
3032 // Give site config file a chance to run the script in a wrapper.
3033 // The caller may likely want to call wfBasename() on $script.
3034 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3035 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
3036 if ( isset( $options['wrapper'] ) ) {
3037 $cmd[] = $options['wrapper'];
3038 }
3039 $cmd[] = $script;
3040 // Escape each parameter for shell
3041 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
3042 }
3043
3044 /**
3045 * wfMerge attempts to merge differences between three texts.
3046 * Returns true for a clean merge and false for failure or a conflict.
3047 *
3048 * @param string $old
3049 * @param string $mine
3050 * @param string $yours
3051 * @param string $result
3052 * @return bool
3053 */
3054 function wfMerge( $old, $mine, $yours, &$result ) {
3055 global $wgDiff3;
3056
3057 # This check may also protect against code injection in
3058 # case of broken installations.
3059 wfSuppressWarnings();
3060 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3061 wfRestoreWarnings();
3062
3063 if ( !$haveDiff3 ) {
3064 wfDebug( "diff3 not found\n" );
3065 return false;
3066 }
3067
3068 # Make temporary files
3069 $td = wfTempDir();
3070 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3071 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3072 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3073
3074 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3075 # a newline character. To avoid this, we normalize the trailing whitespace before
3076 # creating the diff.
3077
3078 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3079 fclose( $oldtextFile );
3080 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3081 fclose( $mytextFile );
3082 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3083 fclose( $yourtextFile );
3084
3085 # Check for a conflict
3086 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
3087 wfEscapeShellArg( $mytextName ) . ' ' .
3088 wfEscapeShellArg( $oldtextName ) . ' ' .
3089 wfEscapeShellArg( $yourtextName );
3090 $handle = popen( $cmd, 'r' );
3091
3092 if ( fgets( $handle, 1024 ) ) {
3093 $conflict = true;
3094 } else {
3095 $conflict = false;
3096 }
3097 pclose( $handle );
3098
3099 # Merge differences
3100 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
3101 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
3102 $handle = popen( $cmd, 'r' );
3103 $result = '';
3104 do {
3105 $data = fread( $handle, 8192 );
3106 if ( strlen( $data ) == 0 ) {
3107 break;
3108 }
3109 $result .= $data;
3110 } while ( true );
3111 pclose( $handle );
3112 unlink( $mytextName );
3113 unlink( $oldtextName );
3114 unlink( $yourtextName );
3115
3116 if ( $result === '' && $old !== '' && !$conflict ) {
3117 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3118 $conflict = true;
3119 }
3120 return !$conflict;
3121 }
3122
3123 /**
3124 * Returns unified plain-text diff of two texts.
3125 * Useful for machine processing of diffs.
3126 *
3127 * @param string $before The text before the changes.
3128 * @param string $after The text after the changes.
3129 * @param string $params Command-line options for the diff command.
3130 * @return string Unified diff of $before and $after
3131 */
3132 function wfDiff( $before, $after, $params = '-u' ) {
3133 if ( $before == $after ) {
3134 return '';
3135 }
3136
3137 global $wgDiff;
3138 wfSuppressWarnings();
3139 $haveDiff = $wgDiff && file_exists( $wgDiff );
3140 wfRestoreWarnings();
3141
3142 # This check may also protect against code injection in
3143 # case of broken installations.
3144 if ( !$haveDiff ) {
3145 wfDebug( "diff executable not found\n" );
3146 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3147 $format = new UnifiedDiffFormatter();
3148 return $format->format( $diffs );
3149 }
3150
3151 # Make temporary files
3152 $td = wfTempDir();
3153 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3154 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3155
3156 fwrite( $oldtextFile, $before );
3157 fclose( $oldtextFile );
3158 fwrite( $newtextFile, $after );
3159 fclose( $newtextFile );
3160
3161 // Get the diff of the two files
3162 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3163
3164 $h = popen( $cmd, 'r' );
3165
3166 $diff = '';
3167
3168 do {
3169 $data = fread( $h, 8192 );
3170 if ( strlen( $data ) == 0 ) {
3171 break;
3172 }
3173 $diff .= $data;
3174 } while ( true );
3175
3176 // Clean up
3177 pclose( $h );
3178 unlink( $oldtextName );
3179 unlink( $newtextName );
3180
3181 // Kill the --- and +++ lines. They're not useful.
3182 $diff_lines = explode( "\n", $diff );
3183 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
3184 unset( $diff_lines[0] );
3185 }
3186 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
3187 unset( $diff_lines[1] );
3188 }
3189
3190 $diff = implode( "\n", $diff_lines );
3191
3192 return $diff;
3193 }
3194
3195 /**
3196 * This function works like "use VERSION" in Perl, the program will die with a
3197 * backtrace if the current version of PHP is less than the version provided
3198 *
3199 * This is useful for extensions which due to their nature are not kept in sync
3200 * with releases, and might depend on other versions of PHP than the main code
3201 *
3202 * Note: PHP might die due to parsing errors in some cases before it ever
3203 * manages to call this function, such is life
3204 *
3205 * @see perldoc -f use
3206 *
3207 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3208 * @throws MWException
3209 */
3210 function wfUsePHP( $req_ver ) {
3211 $php_ver = PHP_VERSION;
3212
3213 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3214 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3215 }
3216 }
3217
3218 /**
3219 * This function works like "use VERSION" in Perl except it checks the version
3220 * of MediaWiki, the program will die with a backtrace if the current version
3221 * of MediaWiki is less than the version provided.
3222 *
3223 * This is useful for extensions which due to their nature are not kept in sync
3224 * with releases
3225 *
3226 * Note: Due to the behavior of PHP's version_compare() which is used in this
3227 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3228 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3229 * targeted version number. For example if you wanted to allow any variation
3230 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3231 * not result in the same comparison due to the internal logic of
3232 * version_compare().
3233 *
3234 * @see perldoc -f use
3235 *
3236 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3237 * @throws MWException
3238 */
3239 function wfUseMW( $req_ver ) {
3240 global $wgVersion;
3241
3242 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3243 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3244 }
3245 }
3246
3247 /**
3248 * Return the final portion of a pathname.
3249 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3250 * http://bugs.php.net/bug.php?id=33898
3251 *
3252 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3253 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3254 *
3255 * @param string $path
3256 * @param string $suffix String to remove if present
3257 * @return string
3258 */
3259 function wfBaseName( $path, $suffix = '' ) {
3260 if ( $suffix == '' ) {
3261 $encSuffix = '';
3262 } else {
3263 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3264 }
3265
3266 $matches = array();
3267 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3268 return $matches[1];
3269 } else {
3270 return '';
3271 }
3272 }
3273
3274 /**
3275 * Generate a relative path name to the given file.
3276 * May explode on non-matching case-insensitive paths,
3277 * funky symlinks, etc.
3278 *
3279 * @param string $path Absolute destination path including target filename
3280 * @param string $from Absolute source path, directory only
3281 * @return string
3282 */
3283 function wfRelativePath( $path, $from ) {
3284 // Normalize mixed input on Windows...
3285 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
3286 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
3287
3288 // Trim trailing slashes -- fix for drive root
3289 $path = rtrim( $path, DIRECTORY_SEPARATOR );
3290 $from = rtrim( $from, DIRECTORY_SEPARATOR );
3291
3292 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
3293 $against = explode( DIRECTORY_SEPARATOR, $from );
3294
3295 if ( $pieces[0] !== $against[0] ) {
3296 // Non-matching Windows drive letters?
3297 // Return a full path.
3298 return $path;
3299 }
3300
3301 // Trim off common prefix
3302 while ( count( $pieces ) && count( $against )
3303 && $pieces[0] == $against[0] ) {
3304 array_shift( $pieces );
3305 array_shift( $against );
3306 }
3307
3308 // relative dots to bump us to the parent
3309 while ( count( $against ) ) {
3310 array_unshift( $pieces, '..' );
3311 array_shift( $against );
3312 }
3313
3314 array_push( $pieces, wfBaseName( $path ) );
3315
3316 return implode( DIRECTORY_SEPARATOR, $pieces );
3317 }
3318
3319 /**
3320 * Convert an arbitrarily-long digit string from one numeric base
3321 * to another, optionally zero-padding to a minimum column width.
3322 *
3323 * Supports base 2 through 36; digit values 10-36 are represented
3324 * as lowercase letters a-z. Input is case-insensitive.
3325 *
3326 * @param string $input Input number
3327 * @param int $sourceBase Base of the input number
3328 * @param int $destBase Desired base of the output
3329 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3330 * @param bool $lowercase Whether to output in lowercase or uppercase
3331 * @param string $engine Either "gmp", "bcmath", or "php"
3332 * @return string|bool The output number as a string, or false on error
3333 */
3334 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3335 $lowercase = true, $engine = 'auto'
3336 ) {
3337 $input = (string)$input;
3338 if (
3339 $sourceBase < 2 ||
3340 $sourceBase > 36 ||
3341 $destBase < 2 ||
3342 $destBase > 36 ||
3343 $sourceBase != (int)$sourceBase ||
3344 $destBase != (int)$destBase ||
3345 $pad != (int)$pad ||
3346 !preg_match(
3347 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3348 $input
3349 )
3350 ) {
3351 return false;
3352 }
3353
3354 static $baseChars = array(
3355 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3356 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3357 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3358 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3359 34 => 'y', 35 => 'z',
3360
3361 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3362 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3363 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3364 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3365 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3366 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3367 );
3368
3369 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' || $engine == 'gmp' ) ) {
3370 // Removing leading zeros works around broken base detection code in
3371 // some PHP versions (see <https://bugs.php.net/bug.php?id=50175> and
3372 // <https://bugs.php.net/bug.php?id=55398>).
3373 $result = gmp_strval( gmp_init( ltrim( $input, '0' ), $sourceBase ), $destBase );
3374 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' || $engine == 'bcmath' ) ) {
3375 $decimal = '0';
3376 foreach ( str_split( strtolower( $input ) ) as $char ) {
3377 $decimal = bcmul( $decimal, $sourceBase );
3378 $decimal = bcadd( $decimal, $baseChars[$char] );
3379 }
3380
3381 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3382 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3383 $result .= $baseChars[bcmod( $decimal, $destBase )];
3384 }
3385 // @codingStandardsIgnoreEnd
3386
3387 $result = strrev( $result );
3388 } else {
3389 $inDigits = array();
3390 foreach ( str_split( strtolower( $input ) ) as $char ) {
3391 $inDigits[] = $baseChars[$char];
3392 }
3393
3394 // Iterate over the input, modulo-ing out an output digit
3395 // at a time until input is gone.
3396 $result = '';
3397 while ( $inDigits ) {
3398 $work = 0;
3399 $workDigits = array();
3400
3401 // Long division...
3402 foreach ( $inDigits as $digit ) {
3403 $work *= $sourceBase;
3404 $work += $digit;
3405
3406 if ( $workDigits || $work >= $destBase ) {
3407 $workDigits[] = (int)( $work / $destBase );
3408 }
3409 $work %= $destBase;
3410 }
3411
3412 // All that division leaves us with a remainder,
3413 // which is conveniently our next output digit.
3414 $result .= $baseChars[$work];
3415
3416 // And we continue!
3417 $inDigits = $workDigits;
3418 }
3419
3420 $result = strrev( $result );
3421 }
3422
3423 if ( !$lowercase ) {
3424 $result = strtoupper( $result );
3425 }
3426
3427 return str_pad( $result, $pad, '0', STR_PAD_LEFT );
3428 }
3429
3430 /**
3431 * Check if there is sufficient entropy in php's built-in session generation
3432 *
3433 * @return bool True = there is sufficient entropy
3434 */
3435 function wfCheckEntropy() {
3436 return (
3437 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
3438 || ini_get( 'session.entropy_file' )
3439 )
3440 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3441 }
3442
3443 /**
3444 * Override session_id before session startup if php's built-in
3445 * session generation code is not secure.
3446 */
3447 function wfFixSessionID() {
3448 // If the cookie or session id is already set we already have a session and should abort
3449 if ( isset( $_COOKIE[session_name()] ) || session_id() ) {
3450 return;
3451 }
3452
3453 // PHP's built-in session entropy is enabled if:
3454 // - entropy_file is set or you're on Windows with php 5.3.3+
3455 // - AND entropy_length is > 0
3456 // We treat it as disabled if it doesn't have an entropy length of at least 32
3457 $entropyEnabled = wfCheckEntropy();
3458
3459 // If built-in entropy is not enabled or not sufficient override PHP's
3460 // built in session id generation code
3461 if ( !$entropyEnabled ) {
3462 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, " .
3463 "overriding session id generation using our cryptrand source.\n" );
3464 session_id( MWCryptRand::generateHex( 32 ) );
3465 }
3466 }
3467
3468 /**
3469 * Reset the session_id
3470 *
3471 * @since 1.22
3472 */
3473 function wfResetSessionID() {
3474 global $wgCookieSecure;
3475 $oldSessionId = session_id();
3476 $cookieParams = session_get_cookie_params();
3477 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3478 session_regenerate_id( false );
3479 } else {
3480 $tmp = $_SESSION;
3481 session_destroy();
3482 wfSetupSession( MWCryptRand::generateHex( 32 ) );
3483 $_SESSION = $tmp;
3484 }
3485 $newSessionId = session_id();
3486 wfRunHooks( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3487 }
3488
3489 /**
3490 * Initialise php session
3491 *
3492 * @param bool $sessionId
3493 */
3494 function wfSetupSession( $sessionId = false ) {
3495 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3496 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3497 if ( $wgSessionsInObjectCache || $wgSessionsInMemcached ) {
3498 ObjectCacheSessionHandler::install();
3499 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3500 # Only set this if $wgSessionHandler isn't null and session.save_handler
3501 # hasn't already been set to the desired value (that causes errors)
3502 ini_set( 'session.save_handler', $wgSessionHandler );
3503 }
3504 session_set_cookie_params(
3505 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3506 session_cache_limiter( 'private, must-revalidate' );
3507 if ( $sessionId ) {
3508 session_id( $sessionId );
3509 } else {
3510 wfFixSessionID();
3511 }
3512 wfSuppressWarnings();
3513 session_start();
3514 wfRestoreWarnings();
3515 }
3516
3517 /**
3518 * Get an object from the precompiled serialized directory
3519 *
3520 * @param string $name
3521 * @return mixed The variable on success, false on failure
3522 */
3523 function wfGetPrecompiledData( $name ) {
3524 global $IP;
3525
3526 $file = "$IP/serialized/$name";
3527 if ( file_exists( $file ) ) {
3528 $blob = file_get_contents( $file );
3529 if ( $blob ) {
3530 return unserialize( $blob );
3531 }
3532 }
3533 return false;
3534 }
3535
3536 /**
3537 * Get a cache key
3538 *
3539 * @param string $args,...
3540 * @return string
3541 */
3542 function wfMemcKey( /*...*/ ) {
3543 global $wgCachePrefix;
3544 $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix;
3545 $args = func_get_args();
3546 $key = $prefix . ':' . implode( ':', $args );
3547 $key = str_replace( ' ', '_', $key );
3548 return $key;
3549 }
3550
3551 /**
3552 * Get a cache key for a foreign DB
3553 *
3554 * @param string $db
3555 * @param string $prefix
3556 * @param string $args,...
3557 * @return string
3558 */
3559 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3560 $args = array_slice( func_get_args(), 2 );
3561 if ( $prefix ) {
3562 $key = "$db-$prefix:" . implode( ':', $args );
3563 } else {
3564 $key = $db . ':' . implode( ':', $args );
3565 }
3566 return str_replace( ' ', '_', $key );
3567 }
3568
3569 /**
3570 * Get an ASCII string identifying this wiki
3571 * This is used as a prefix in memcached keys
3572 *
3573 * @return string
3574 */
3575 function wfWikiID() {
3576 global $wgDBprefix, $wgDBname;
3577 if ( $wgDBprefix ) {
3578 return "$wgDBname-$wgDBprefix";
3579 } else {
3580 return $wgDBname;
3581 }
3582 }
3583
3584 /**
3585 * Split a wiki ID into DB name and table prefix
3586 *
3587 * @param string $wiki
3588 *
3589 * @return array
3590 */
3591 function wfSplitWikiID( $wiki ) {
3592 $bits = explode( '-', $wiki, 2 );
3593 if ( count( $bits ) < 2 ) {
3594 $bits[] = '';
3595 }
3596 return $bits;
3597 }
3598
3599 /**
3600 * Get a Database object.
3601 *
3602 * @param int $db Index of the connection to get. May be DB_MASTER for the
3603 * master (for write queries), DB_SLAVE for potentially lagged read
3604 * queries, or an integer >= 0 for a particular server.
3605 *
3606 * @param string|string[] $groups Query groups. An array of group names that this query
3607 * belongs to. May contain a single string if the query is only
3608 * in one group.
3609 *
3610 * @param string|bool $wiki The wiki ID, or false for the current wiki
3611 *
3612 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3613 * will always return the same object, unless the underlying connection or load
3614 * balancer is manually destroyed.
3615 *
3616 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3617 * updater to ensure that a proper database is being updated.
3618 *
3619 * @return DatabaseBase
3620 */
3621 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3622 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3623 }
3624
3625 /**
3626 * Get a load balancer object.
3627 *
3628 * @param string|bool $wiki Wiki ID, or false for the current wiki
3629 * @return LoadBalancer
3630 */
3631 function wfGetLB( $wiki = false ) {
3632 return wfGetLBFactory()->getMainLB( $wiki );
3633 }
3634
3635 /**
3636 * Get the load balancer factory object
3637 *
3638 * @return LBFactory
3639 */
3640 function &wfGetLBFactory() {
3641 return LBFactory::singleton();
3642 }
3643
3644 /**
3645 * Find a file.
3646 * Shortcut for RepoGroup::singleton()->findFile()
3647 *
3648 * @param string $title String or Title object
3649 * @param array $options Associative array of options:
3650 * time: requested time for an archived image, or false for the
3651 * current version. An image object will be returned which was
3652 * created at the specified time.
3653 *
3654 * ignoreRedirect: If true, do not follow file redirects
3655 *
3656 * private: If true, return restricted (deleted) files if the current
3657 * user is allowed to view them. Otherwise, such files will not
3658 * be found.
3659 *
3660 * bypassCache: If true, do not use the process-local cache of File objects
3661 *
3662 * @return File|bool File, or false if the file does not exist
3663 */
3664 function wfFindFile( $title, $options = array() ) {
3665 return RepoGroup::singleton()->findFile( $title, $options );
3666 }
3667
3668 /**
3669 * Get an object referring to a locally registered file.
3670 * Returns a valid placeholder object if the file does not exist.
3671 *
3672 * @param Title|string $title
3673 * @return LocalFile|null A File, or null if passed an invalid Title
3674 */
3675 function wfLocalFile( $title ) {
3676 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3677 }
3678
3679 /**
3680 * Should low-performance queries be disabled?
3681 *
3682 * @return bool
3683 * @codeCoverageIgnore
3684 */
3685 function wfQueriesMustScale() {
3686 global $wgMiserMode;
3687 return $wgMiserMode
3688 || ( SiteStats::pages() > 100000
3689 && SiteStats::edits() > 1000000
3690 && SiteStats::users() > 10000 );
3691 }
3692
3693 /**
3694 * Get the path to a specified script file, respecting file
3695 * extensions; this is a wrapper around $wgScriptExtension etc.
3696 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3697 *
3698 * @param string $script Script filename, sans extension
3699 * @return string
3700 */
3701 function wfScript( $script = 'index' ) {
3702 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3703 if ( $script === 'index' ) {
3704 return $wgScript;
3705 } elseif ( $script === 'load' ) {
3706 return $wgLoadScript;
3707 } else {
3708 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3709 }
3710 }
3711
3712 /**
3713 * Get the script URL.
3714 *
3715 * @return string Script URL
3716 */
3717 function wfGetScriptUrl() {
3718 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3719 #
3720 # as it was called, minus the query string.
3721 #
3722 # Some sites use Apache rewrite rules to handle subdomains,
3723 # and have PHP set up in a weird way that causes PHP_SELF
3724 # to contain the rewritten URL instead of the one that the
3725 # outside world sees.
3726 #
3727 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3728 # provides containing the "before" URL.
3729 return $_SERVER['SCRIPT_NAME'];
3730 } else {
3731 return $_SERVER['URL'];
3732 }
3733 }
3734
3735 /**
3736 * Convenience function converts boolean values into "true"
3737 * or "false" (string) values
3738 *
3739 * @param bool $value
3740 * @return string
3741 */
3742 function wfBoolToStr( $value ) {
3743 return $value ? 'true' : 'false';
3744 }
3745
3746 /**
3747 * Get a platform-independent path to the null file, e.g. /dev/null
3748 *
3749 * @return string
3750 */
3751 function wfGetNull() {
3752 return wfIsWindows() ? 'NUL' : '/dev/null';
3753 }
3754
3755 /**
3756 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3757 * and waiting for it to go down, this waits for the slaves to catch up to the
3758 * master position. Use this when updating very large numbers of rows, as
3759 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3760 * a no-op if there are no slaves.
3761 *
3762 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3763 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3764 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3765 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3766 * @return bool Success (able to connect and no timeouts reached)
3767 */
3768 function wfWaitForSlaves(
3769 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3770 ) {
3771 // B/C: first argument used to be "max seconds of lag"; ignore such values
3772 $ifWritesSince = ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null;
3773
3774 if ( $timeout === null ) {
3775 $timeout = ( PHP_SAPI === 'cli' ) ? 86400 : 10;
3776 }
3777
3778 if ( $cluster !== false ) {
3779 $lb = wfGetLBFactory()->getExternalLB( $cluster );
3780 } else {
3781 $lb = wfGetLB( $wiki );
3782 }
3783
3784 // bug 27975 - Don't try to wait for slaves if there are none
3785 // Prevents permission error when getting master position
3786 if ( $lb->getServerCount() > 1 ) {
3787 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3788 return true; // assume no writes done
3789 }
3790 $dbw = $lb->getConnection( DB_MASTER, array(), $wiki );
3791 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3792 return true; // no writes since the last wait
3793 }
3794 $pos = $dbw->getMasterPos();
3795 // The DBMS may not support getMasterPos() or the whole
3796 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3797 if ( $pos !== false ) {
3798 return $lb->waitForAll( $pos, $timeout );
3799 }
3800 }
3801
3802 return true;
3803 }
3804
3805 /**
3806 * Count down from $seconds to zero on the terminal, with a one-second pause
3807 * between showing each number. For use in command-line scripts.
3808 *
3809 * @codeCoverageIgnore
3810 * @param int $seconds
3811 */
3812 function wfCountDown( $seconds ) {
3813 for ( $i = $seconds; $i >= 0; $i-- ) {
3814 if ( $i != $seconds ) {
3815 echo str_repeat( "\x08", strlen( $i + 1 ) );
3816 }
3817 echo $i;
3818 flush();
3819 if ( $i ) {
3820 sleep( 1 );
3821 }
3822 }
3823 echo "\n";
3824 }
3825
3826 /**
3827 * Replace all invalid characters with -
3828 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3829 * By default, $wgIllegalFileChars = ':'
3830 *
3831 * @param string $name Filename to process
3832 * @return string
3833 */
3834 function wfStripIllegalFilenameChars( $name ) {
3835 global $wgIllegalFileChars;
3836 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
3837 $name = wfBaseName( $name );
3838 $name = preg_replace(
3839 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
3840 '-',
3841 $name
3842 );
3843 return $name;
3844 }
3845
3846 /**
3847 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3848 *
3849 * @return int Value the memory limit was set to.
3850 */
3851 function wfMemoryLimit() {
3852 global $wgMemoryLimit;
3853 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3854 if ( $memlimit != -1 ) {
3855 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3856 if ( $conflimit == -1 ) {
3857 wfDebug( "Removing PHP's memory limit\n" );
3858 wfSuppressWarnings();
3859 ini_set( 'memory_limit', $conflimit );
3860 wfRestoreWarnings();
3861 return $conflimit;
3862 } elseif ( $conflimit > $memlimit ) {
3863 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3864 wfSuppressWarnings();
3865 ini_set( 'memory_limit', $conflimit );
3866 wfRestoreWarnings();
3867 return $conflimit;
3868 }
3869 }
3870 return $memlimit;
3871 }
3872
3873 /**
3874 * Converts shorthand byte notation to integer form
3875 *
3876 * @param string $string
3877 * @return int
3878 */
3879 function wfShorthandToInteger( $string = '' ) {
3880 $string = trim( $string );
3881 if ( $string === '' ) {
3882 return -1;
3883 }
3884 $last = $string[strlen( $string ) - 1];
3885 $val = intval( $string );
3886 switch ( $last ) {
3887 case 'g':
3888 case 'G':
3889 $val *= 1024;
3890 // break intentionally missing
3891 case 'm':
3892 case 'M':
3893 $val *= 1024;
3894 // break intentionally missing
3895 case 'k':
3896 case 'K':
3897 $val *= 1024;
3898 }
3899
3900 return $val;
3901 }
3902
3903 /**
3904 * Get the normalised IETF language tag
3905 * See unit test for examples.
3906 *
3907 * @param string $code The language code.
3908 * @return string The language code which complying with BCP 47 standards.
3909 */
3910 function wfBCP47( $code ) {
3911 $codeSegment = explode( '-', $code );
3912 $codeBCP = array();
3913 foreach ( $codeSegment as $segNo => $seg ) {
3914 // when previous segment is x, it is a private segment and should be lc
3915 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3916 $codeBCP[$segNo] = strtolower( $seg );
3917 // ISO 3166 country code
3918 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3919 $codeBCP[$segNo] = strtoupper( $seg );
3920 // ISO 15924 script code
3921 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3922 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3923 // Use lowercase for other cases
3924 } else {
3925 $codeBCP[$segNo] = strtolower( $seg );
3926 }
3927 }
3928 $langCode = implode( '-', $codeBCP );
3929 return $langCode;
3930 }
3931
3932 /**
3933 * Get a cache object.
3934 *
3935 * @param int $inputType Cache type, one the the CACHE_* constants.
3936 * @return BagOStuff
3937 */
3938 function wfGetCache( $inputType ) {
3939 return ObjectCache::getInstance( $inputType );
3940 }
3941
3942 /**
3943 * Get the main cache object
3944 *
3945 * @return BagOStuff
3946 */
3947 function wfGetMainCache() {
3948 global $wgMainCacheType;
3949 return ObjectCache::getInstance( $wgMainCacheType );
3950 }
3951
3952 /**
3953 * Get the cache object used by the message cache
3954 *
3955 * @return BagOStuff
3956 */
3957 function wfGetMessageCacheStorage() {
3958 global $wgMessageCacheType;
3959 return ObjectCache::getInstance( $wgMessageCacheType );
3960 }
3961
3962 /**
3963 * Get the cache object used by the parser cache
3964 *
3965 * @return BagOStuff
3966 */
3967 function wfGetParserCacheStorage() {
3968 global $wgParserCacheType;
3969 return ObjectCache::getInstance( $wgParserCacheType );
3970 }
3971
3972 /**
3973 * Get the cache object used by the language converter
3974 *
3975 * @return BagOStuff
3976 */
3977 function wfGetLangConverterCacheStorage() {
3978 global $wgLanguageConverterCacheType;
3979 return ObjectCache::getInstance( $wgLanguageConverterCacheType );
3980 }
3981
3982 /**
3983 * Call hook functions defined in $wgHooks
3984 *
3985 * @param string $event Event name
3986 * @param array $args Parameters passed to hook functions
3987 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
3988 *
3989 * @return bool True if no handler aborted the hook
3990 */
3991 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
3992 return Hooks::run( $event, $args, $deprecatedVersion );
3993 }
3994
3995 /**
3996 * Wrapper around php's unpack.
3997 *
3998 * @param string $format The format string (See php's docs)
3999 * @param string $data A binary string of binary data
4000 * @param int|bool $length The minimum length of $data or false. This is to
4001 * prevent reading beyond the end of $data. false to disable the check.
4002 *
4003 * Also be careful when using this function to read unsigned 32 bit integer
4004 * because php might make it negative.
4005 *
4006 * @throws MWException If $data not long enough, or if unpack fails
4007 * @return array Associative array of the extracted data
4008 */
4009 function wfUnpack( $format, $data, $length = false ) {
4010 if ( $length !== false ) {
4011 $realLen = strlen( $data );
4012 if ( $realLen < $length ) {
4013 throw new MWException( "Tried to use wfUnpack on a "
4014 . "string of length $realLen, but needed one "
4015 . "of at least length $length."
4016 );
4017 }
4018 }
4019
4020 wfSuppressWarnings();
4021 $result = unpack( $format, $data );
4022 wfRestoreWarnings();
4023
4024 if ( $result === false ) {
4025 // If it cannot extract the packed data.
4026 throw new MWException( "unpack could not unpack binary data" );
4027 }
4028 return $result;
4029 }
4030
4031 /**
4032 * Determine if an image exists on the 'bad image list'.
4033 *
4034 * The format of MediaWiki:Bad_image_list is as follows:
4035 * * Only list items (lines starting with "*") are considered
4036 * * The first link on a line must be a link to a bad image
4037 * * Any subsequent links on the same line are considered to be exceptions,
4038 * i.e. articles where the image may occur inline.
4039 *
4040 * @param string $name The image name to check
4041 * @param Title|bool $contextTitle The page on which the image occurs, if known
4042 * @param string $blacklist Wikitext of a file blacklist
4043 * @return bool
4044 */
4045 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4046 static $badImageCache = null; // based on bad_image_list msg
4047 wfProfileIn( __METHOD__ );
4048
4049 # Handle redirects
4050 $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) );
4051 if ( $redirectTitle ) {
4052 $name = $redirectTitle->getDBkey();
4053 }
4054
4055 # Run the extension hook
4056 $bad = false;
4057 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
4058 wfProfileOut( __METHOD__ );
4059 return $bad;
4060 }
4061
4062 $cacheable = ( $blacklist === null );
4063 if ( $cacheable && $badImageCache !== null ) {
4064 $badImages = $badImageCache;
4065 } else { // cache miss
4066 if ( $blacklist === null ) {
4067 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4068 }
4069 # Build the list now
4070 $badImages = array();
4071 $lines = explode( "\n", $blacklist );
4072 foreach ( $lines as $line ) {
4073 # List items only
4074 if ( substr( $line, 0, 1 ) !== '*' ) {
4075 continue;
4076 }
4077
4078 # Find all links
4079 $m = array();
4080 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4081 continue;
4082 }
4083
4084 $exceptions = array();
4085 $imageDBkey = false;
4086 foreach ( $m[1] as $i => $titleText ) {
4087 $title = Title::newFromText( $titleText );
4088 if ( !is_null( $title ) ) {
4089 if ( $i == 0 ) {
4090 $imageDBkey = $title->getDBkey();
4091 } else {
4092 $exceptions[$title->getPrefixedDBkey()] = true;
4093 }
4094 }
4095 }
4096
4097 if ( $imageDBkey !== false ) {
4098 $badImages[$imageDBkey] = $exceptions;
4099 }
4100 }
4101 if ( $cacheable ) {
4102 $badImageCache = $badImages;
4103 }
4104 }
4105
4106 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
4107 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4108 wfProfileOut( __METHOD__ );
4109 return $bad;
4110 }
4111
4112 /**
4113 * Determine whether the client at a given source IP is likely to be able to
4114 * access the wiki via HTTPS.
4115 *
4116 * @param string $ip The IPv4/6 address in the normal human-readable form
4117 * @return bool
4118 */
4119 function wfCanIPUseHTTPS( $ip ) {
4120 $canDo = true;
4121 wfRunHooks( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4122 return !!$canDo;
4123 }
4124
4125 /**
4126 * Work out the IP address based on various globals
4127 * For trusted proxies, use the XFF client IP (first of the chain)
4128 *
4129 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4130 * @return string
4131 */
4132 function wfGetIP() {
4133 wfDeprecated( __METHOD__, '1.19' );
4134 global $wgRequest;
4135 return $wgRequest->getIP();
4136 }
4137
4138 /**
4139 * Checks if an IP is a trusted proxy provider.
4140 * Useful to tell if X-Forwarded-For data is possibly bogus.
4141 * Squid cache servers for the site are whitelisted.
4142 * @deprecated Since 1.24, use IP::isTrustedProxy()
4143 *
4144 * @param string $ip
4145 * @return bool
4146 */
4147 function wfIsTrustedProxy( $ip ) {
4148 return IP::isTrustedProxy( $ip );
4149 }
4150
4151 /**
4152 * Checks if an IP matches a proxy we've configured.
4153 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4154 *
4155 * @param string $ip
4156 * @return bool
4157 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4158 */
4159 function wfIsConfiguredProxy( $ip ) {
4160 return IP::isConfiguredProxy( $ip );
4161 }