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