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