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