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