Merge "mw.ui: button: Update focus state"
[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 Destination of the message:
1034 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1035 * - 'log': only to the log and not in HTML
1036 * For backward compatibility, it can also take a boolean:
1037 * - true: same as 'all'
1038 * - false: same as 'log'
1039 * @param array $context Additional logging context data
1040 */
1041 function wfDebug( $text, $dest = 'all', array $context = array() ) {
1042 global $wgDebugRawPage, $wgDebugLogPrefix;
1043 global $wgDebugTimestamps, $wgRequestTime;
1044
1045 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1046 return;
1047 }
1048
1049 // Turn $dest into a string if it's a boolean (for b/c)
1050 if ( $dest === true ) {
1051 $dest = 'all';
1052 } elseif ( $dest === false ) {
1053 $dest = 'log';
1054 }
1055
1056 $text = trim( $text );
1057
1058 // Inline logic from deprecated wfDebugTimer()
1059 if ( $wgDebugTimestamps ) {
1060 $context['seconds_elapsed'] = sprintf(
1061 '%6.4f',
1062 microtime( true ) - $wgRequestTime
1063 );
1064 $context['memory_used'] = sprintf(
1065 '%5.1fM',
1066 ( memory_get_usage( true ) / ( 1024 * 1024 ) )
1067 );
1068 }
1069
1070 if ( $dest === 'all' ) {
1071 $prefix = '';
1072 if ( $wgDebugTimestamps ) {
1073 // Prepend elapsed request time and real memory usage with two
1074 // trailing spaces.
1075 $prefix = "{$context['seconds_elapsed']} {$context['memory_used']} ";
1076 }
1077 MWDebug::debugMsg( "{$prefix}{$text}" );
1078 }
1079
1080 if ( $wgDebugLogPrefix !== '' ) {
1081 $context['prefix'] = $wgDebugLogPrefix;
1082 }
1083
1084 $logger = MWLoggerFactory::getInstance( 'wfDebug' );
1085 $logger->debug( $text, $context );
1086 }
1087
1088 /**
1089 * Returns true if debug logging should be suppressed if $wgDebugRawPage = false
1090 * @return bool
1091 */
1092 function wfIsDebugRawPage() {
1093 static $cache;
1094 if ( $cache !== null ) {
1095 return $cache;
1096 }
1097 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
1098 if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
1099 || (
1100 isset( $_SERVER['SCRIPT_NAME'] )
1101 && substr( $_SERVER['SCRIPT_NAME'], -8 ) == 'load.php'
1102 )
1103 ) {
1104 $cache = true;
1105 } else {
1106 $cache = false;
1107 }
1108 return $cache;
1109 }
1110
1111 /**
1112 * Get microsecond timestamps for debug logs
1113 *
1114 * @deprecated since 1.25
1115 * @return string
1116 */
1117 function wfDebugTimer() {
1118 global $wgDebugTimestamps, $wgRequestTime;
1119
1120 wfDeprecated( __METHOD__, '1.25' );
1121
1122 if ( !$wgDebugTimestamps ) {
1123 return '';
1124 }
1125
1126 $prefix = sprintf( "%6.4f", microtime( true ) - $wgRequestTime );
1127 $mem = sprintf( "%5.1fM", ( memory_get_usage( true ) / ( 1024 * 1024 ) ) );
1128 return "$prefix $mem ";
1129 }
1130
1131 /**
1132 * Send a line giving PHP memory usage.
1133 *
1134 * @param bool $exact Print exact byte values instead of kibibytes (default: false)
1135 */
1136 function wfDebugMem( $exact = false ) {
1137 $mem = memory_get_usage();
1138 if ( !$exact ) {
1139 $mem = floor( $mem / 1024 ) . ' KiB';
1140 } else {
1141 $mem .= ' B';
1142 }
1143 wfDebug( "Memory usage: $mem\n" );
1144 }
1145
1146 /**
1147 * Send a line to a supplementary debug log file, if configured, or main debug
1148 * log if not.
1149 *
1150 * To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
1151 * a string filename or an associative array mapping 'destination' to the
1152 * desired filename. The associative array may also contain a 'sample' key
1153 * with an integer value, specifying a sampling factor. Sampled log events
1154 * will be emitted with a 1 in N random chance.
1155 *
1156 * @since 1.23 support for sampling log messages via $wgDebugLogGroups.
1157 * @since 1.25 support for additional context data
1158 * @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
1159 *
1160 * @param string $logGroup
1161 * @param string $text
1162 * @param string|bool $dest Destination of the message:
1163 * - 'all': both to the log and HTML (debug toolbar or HTML comments)
1164 * - 'log': only to the log and not in HTML
1165 * - 'private': only to the specific log if set in $wgDebugLogGroups and
1166 * discarded otherwise
1167 * For backward compatibility, it can also take a boolean:
1168 * - true: same as 'all'
1169 * - false: same as 'private'
1170 * @param array $context Additional logging context data
1171 */
1172 function wfDebugLog(
1173 $logGroup, $text, $dest = 'all', array $context = array()
1174 ) {
1175 // Turn $dest into a string if it's a boolean (for b/c)
1176 if ( $dest === true ) {
1177 $dest = 'all';
1178 } elseif ( $dest === false ) {
1179 $dest = 'private';
1180 }
1181
1182 $text = trim( $text );
1183
1184 if ( $dest === 'all' ) {
1185 MWDebug::debugMsg( "[{$logGroup}] {$text}\n" );
1186 }
1187
1188 $logger = MWLoggerFactory::getInstance( $logGroup );
1189 $context['private'] = ( $dest === 'private' );
1190 $logger->info( $text, $context );
1191 }
1192
1193 /**
1194 * Log for database errors
1195 *
1196 * @since 1.25 support for additional context data
1197 *
1198 * @param string $text Database error message.
1199 * @param array $context Additional logging context data
1200 */
1201 function wfLogDBError( $text, array $context = array() ) {
1202 $logger = MWLoggerFactory::getInstance( 'wfLogDBError' );
1203 $logger->error( trim( $text ), $context );
1204 }
1205
1206 /**
1207 * Throws a warning that $function is deprecated
1208 *
1209 * @param string $function
1210 * @param string|bool $version Version of MediaWiki that the function
1211 * was deprecated in (Added in 1.19).
1212 * @param string|bool $component Added in 1.19.
1213 * @param int $callerOffset How far up the call stack is the original
1214 * caller. 2 = function that called the function that called
1215 * wfDeprecated (Added in 1.20)
1216 *
1217 * @return null
1218 */
1219 function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
1220 MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
1221 }
1222
1223 /**
1224 * Send a warning either to the debug log or in a PHP error depending on
1225 * $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
1226 *
1227 * @param string $msg Message to send
1228 * @param int $callerOffset Number of items to go back in the backtrace to
1229 * find the correct caller (1 = function calling wfWarn, ...)
1230 * @param int $level PHP error level; defaults to E_USER_NOTICE;
1231 * only used when $wgDevelopmentWarnings is true
1232 */
1233 function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
1234 MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
1235 }
1236
1237 /**
1238 * Send a warning as a PHP error and the debug log. This is intended for logging
1239 * warnings in production. For logging development warnings, use WfWarn instead.
1240 *
1241 * @param string $msg Message to send
1242 * @param int $callerOffset Number of items to go back in the backtrace to
1243 * find the correct caller (1 = function calling wfLogWarning, ...)
1244 * @param int $level PHP error level; defaults to E_USER_WARNING
1245 */
1246 function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
1247 MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
1248 }
1249
1250 /**
1251 * Log to a file without getting "file size exceeded" signals.
1252 *
1253 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
1254 * send lines to the specified port, prefixed by the specified prefix and a space.
1255 * @since 1.25 support for additional context data
1256 *
1257 * @param string $text
1258 * @param string $file Filename
1259 * @param array $context Additional logging context data
1260 * @throws MWException
1261 * @deprecated since 1.25 Use MWLoggerLegacyLogger::emit or UDPTransport
1262 */
1263 function wfErrorLog( $text, $file, array $context = array() ) {
1264 wfDeprecated( __METHOD__, '1.25' );
1265 $logger = MWLoggerFactory::getInstance( 'wfErrorLog' );
1266 $context['destination'] = $file;
1267 $logger->info( trim( $text ), $context );
1268 }
1269
1270 /**
1271 * @todo document
1272 */
1273 function wfLogProfilingData() {
1274 global $wgRequestTime, $wgDebugLogGroups, $wgDebugRawPage;
1275 global $wgProfileLimit, $wgUser, $wgRequest;
1276
1277 $context = RequestContext::getMain();
1278 $config = $context->getConfig();
1279 if ( $config->has( 'StatsdServer' ) ) {
1280 $statsdServer = explode( ':', $config->get( 'StatsdServer' ) );
1281 $statsdHost = $statsdServer[0];
1282 $statsdPort = isset( $statsdServer[1] ) ? $statsdServer[1] : 8125;
1283 $statsdSender = new SocketSender( $statsdHost, $statsdPort );
1284 $statsdClient = new StatsdClient( $statsdSender );
1285 $statsdClient->send( $context->getStats()->getBuffer() );
1286 }
1287
1288 $profiler = Profiler::instance();
1289
1290 # Profiling must actually be enabled...
1291 if ( $profiler instanceof ProfilerStub ) {
1292 return;
1293 }
1294
1295 // Get total page request time and only show pages that longer than
1296 // $wgProfileLimit time (default is 0)
1297 $elapsed = microtime( true ) - $wgRequestTime;
1298 if ( $elapsed <= $wgProfileLimit ) {
1299 return;
1300 }
1301
1302 $profiler->logData();
1303
1304 if ( isset( $wgDebugLogGroups['profileoutput'] )
1305 && $wgDebugLogGroups['profileoutput'] === false
1306 ) {
1307 // Explicitly disabled
1308 return;
1309 }
1310 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
1311 return;
1312 }
1313
1314 $ctx = array( 'elapsed' => $elapsed );
1315 if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
1316 $ctx['forwarded_for'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
1317 }
1318 if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
1319 $ctx['client_ip'] = $_SERVER['HTTP_CLIENT_IP'];
1320 }
1321 if ( !empty( $_SERVER['HTTP_FROM'] ) ) {
1322 $ctx['from'] = $_SERVER['HTTP_FROM'];
1323 }
1324 if ( isset( $ctx['forwarded_for'] ) ||
1325 isset( $ctx['client_ip'] ) ||
1326 isset( $ctx['from'] ) ) {
1327 $ctx['proxy'] = $_SERVER['REMOTE_ADDR'];
1328 }
1329
1330 // Don't load $wgUser at this late stage just for statistics purposes
1331 // @todo FIXME: We can detect some anons even if it is not loaded.
1332 // See User::getId()
1333 if ( $wgUser->isItemLoaded( 'id' ) && $wgUser->isAnon() ) {
1334 $ctx['anon'] = true;
1335 } else {
1336 $ctx['anon'] = false;
1337 }
1338
1339 // Command line script uses a FauxRequest object which does not have
1340 // any knowledge about an URL and throw an exception instead.
1341 try {
1342 $ctx['url'] = urldecode( $wgRequest->getRequestURL() );
1343 } catch ( Exception $ignored ) {
1344 // no-op
1345 }
1346
1347 $ctx['output'] = $profiler->getOutput();
1348
1349 $log = MWLoggerFactory::getInstance( 'profileoutput' );
1350 $log->info( "Elapsed: {elapsed}; URL: <{url}>\n{output}", $ctx );
1351 }
1352
1353 /**
1354 * Increment a statistics counter
1355 *
1356 * @param string $key
1357 * @param int $count
1358 * @return void
1359 */
1360 function wfIncrStats( $key, $count = 1 ) {
1361 $stats = RequestContext::getMain()->getStats();
1362 $stats->updateCount( $key, $count );
1363 }
1364
1365 /**
1366 * Check whether the wiki is in read-only mode.
1367 *
1368 * @return bool
1369 */
1370 function wfReadOnly() {
1371 return wfReadOnlyReason() !== false;
1372 }
1373
1374 /**
1375 * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
1376 *
1377 * @return string|bool String when in read-only mode; false otherwise
1378 */
1379 function wfReadOnlyReason() {
1380 global $wgReadOnly, $wgReadOnlyFile;
1381
1382 if ( $wgReadOnly === null ) {
1383 // Set $wgReadOnly for faster access next time
1384 if ( is_file( $wgReadOnlyFile ) && filesize( $wgReadOnlyFile ) > 0 ) {
1385 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
1386 } else {
1387 $wgReadOnly = false;
1388 }
1389 }
1390
1391 return $wgReadOnly;
1392 }
1393
1394 /**
1395 * Return a Language object from $langcode
1396 *
1397 * @param Language|string|bool $langcode Either:
1398 * - a Language object
1399 * - code of the language to get the message for, if it is
1400 * a valid code create a language for that language, if
1401 * it is a string but not a valid code then make a basic
1402 * language object
1403 * - a boolean: if it's false then use the global object for
1404 * the current user's language (as a fallback for the old parameter
1405 * functionality), or if it is true then use global object
1406 * for the wiki's content language.
1407 * @return Language
1408 */
1409 function wfGetLangObj( $langcode = false ) {
1410 # Identify which language to get or create a language object for.
1411 # Using is_object here due to Stub objects.
1412 if ( is_object( $langcode ) ) {
1413 # Great, we already have the object (hopefully)!
1414 return $langcode;
1415 }
1416
1417 global $wgContLang, $wgLanguageCode;
1418 if ( $langcode === true || $langcode === $wgLanguageCode ) {
1419 # $langcode is the language code of the wikis content language object.
1420 # or it is a boolean and value is true
1421 return $wgContLang;
1422 }
1423
1424 global $wgLang;
1425 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1426 # $langcode is the language code of user language object.
1427 # or it was a boolean and value is false
1428 return $wgLang;
1429 }
1430
1431 $validCodes = array_keys( Language::fetchLanguageNames() );
1432 if ( in_array( $langcode, $validCodes ) ) {
1433 # $langcode corresponds to a valid language.
1434 return Language::factory( $langcode );
1435 }
1436
1437 # $langcode is a string, but not a valid language code; use content language.
1438 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
1439 return $wgContLang;
1440 }
1441
1442 /**
1443 * This is the function for getting translated interface messages.
1444 *
1445 * @see Message class for documentation how to use them.
1446 * @see https://www.mediawiki.org/wiki/Manual:Messages_API
1447 *
1448 * This function replaces all old wfMsg* functions.
1449 *
1450 * @param string|string[] $key Message key, or array of keys
1451 * @param mixed $params,... Normal message parameters
1452 * @return Message
1453 *
1454 * @since 1.17
1455 *
1456 * @see Message::__construct
1457 */
1458 function wfMessage( $key /*...*/ ) {
1459 $params = func_get_args();
1460 array_shift( $params );
1461 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
1462 $params = $params[0];
1463 }
1464 return new Message( $key, $params );
1465 }
1466
1467 /**
1468 * This function accepts multiple message keys and returns a message instance
1469 * for the first message which is non-empty. If all messages are empty then an
1470 * instance of the first message key is returned.
1471 *
1472 * @param string|string[] $keys,... Message keys
1473 * @return Message
1474 *
1475 * @since 1.18
1476 *
1477 * @see Message::newFallbackSequence
1478 */
1479 function wfMessageFallback( /*...*/ ) {
1480 $args = func_get_args();
1481 return call_user_func_array( 'Message::newFallbackSequence', $args );
1482 }
1483
1484 /**
1485 * Get a message from anywhere, for the current user language.
1486 *
1487 * Use wfMsgForContent() instead if the message should NOT
1488 * change depending on the user preferences.
1489 *
1490 * @deprecated since 1.18
1491 *
1492 * @param string $key Lookup key for the message, usually
1493 * defined in languages/Language.php
1494 *
1495 * Parameters to the message, which can be used to insert variable text into
1496 * it, can be passed to this function in the following formats:
1497 * - One per argument, starting at the second parameter
1498 * - As an array in the second parameter
1499 * These are not shown in the function definition.
1500 *
1501 * @return string
1502 */
1503 function wfMsg( $key ) {
1504 wfDeprecated( __METHOD__, '1.21' );
1505
1506 $args = func_get_args();
1507 array_shift( $args );
1508 return wfMsgReal( $key, $args );
1509 }
1510
1511 /**
1512 * Same as above except doesn't transform the message
1513 *
1514 * @deprecated since 1.18
1515 *
1516 * @param string $key
1517 * @return string
1518 */
1519 function wfMsgNoTrans( $key ) {
1520 wfDeprecated( __METHOD__, '1.21' );
1521
1522 $args = func_get_args();
1523 array_shift( $args );
1524 return wfMsgReal( $key, $args, true, false, false );
1525 }
1526
1527 /**
1528 * Get a message from anywhere, for the current global language
1529 * set with $wgLanguageCode.
1530 *
1531 * Use this if the message should NOT change dependent on the
1532 * language set in the user's preferences. This is the case for
1533 * most text written into logs, as well as link targets (such as
1534 * the name of the copyright policy page). Link titles, on the
1535 * other hand, should be shown in the UI language.
1536 *
1537 * Note that MediaWiki allows users to change the user interface
1538 * language in their preferences, but a single installation
1539 * typically only contains content in one language.
1540 *
1541 * Be wary of this distinction: If you use wfMsg() where you should
1542 * use wfMsgForContent(), a user of the software may have to
1543 * customize potentially hundreds of messages in
1544 * order to, e.g., fix a link in every possible language.
1545 *
1546 * @deprecated since 1.18
1547 *
1548 * @param string $key Lookup key for the message, usually
1549 * defined in languages/Language.php
1550 * @return string
1551 */
1552 function wfMsgForContent( $key ) {
1553 wfDeprecated( __METHOD__, '1.21' );
1554
1555 global $wgForceUIMsgAsContentMsg;
1556 $args = func_get_args();
1557 array_shift( $args );
1558 $forcontent = true;
1559 if ( is_array( $wgForceUIMsgAsContentMsg )
1560 && in_array( $key, $wgForceUIMsgAsContentMsg )
1561 ) {
1562 $forcontent = false;
1563 }
1564 return wfMsgReal( $key, $args, true, $forcontent );
1565 }
1566
1567 /**
1568 * Same as above except doesn't transform the message
1569 *
1570 * @deprecated since 1.18
1571 *
1572 * @param string $key
1573 * @return string
1574 */
1575 function wfMsgForContentNoTrans( $key ) {
1576 wfDeprecated( __METHOD__, '1.21' );
1577
1578 global $wgForceUIMsgAsContentMsg;
1579 $args = func_get_args();
1580 array_shift( $args );
1581 $forcontent = true;
1582 if ( is_array( $wgForceUIMsgAsContentMsg )
1583 && in_array( $key, $wgForceUIMsgAsContentMsg )
1584 ) {
1585 $forcontent = false;
1586 }
1587 return wfMsgReal( $key, $args, true, $forcontent, false );
1588 }
1589
1590 /**
1591 * Really get a message
1592 *
1593 * @deprecated since 1.18
1594 *
1595 * @param string $key Key to get.
1596 * @param array $args
1597 * @param bool $useDB
1598 * @param string|bool $forContent Language code, or false for user lang, true for content lang.
1599 * @param bool $transform Whether or not to transform the message.
1600 * @return string The requested message.
1601 */
1602 function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
1603 wfDeprecated( __METHOD__, '1.21' );
1604
1605 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
1606 $message = wfMsgReplaceArgs( $message, $args );
1607 return $message;
1608 }
1609
1610 /**
1611 * Fetch a message string value, but don't replace any keys yet.
1612 *
1613 * @deprecated since 1.18
1614 *
1615 * @param string $key
1616 * @param bool $useDB
1617 * @param string|bool $langCode Code of the language to get the message for, or
1618 * behaves as a content language switch if it is a boolean.
1619 * @param bool $transform Whether to parse magic words, etc.
1620 * @return string
1621 */
1622 function wfMsgGetKey( $key, $useDB = true, $langCode = false, $transform = true ) {
1623 wfDeprecated( __METHOD__, '1.21' );
1624
1625 Hooks::run( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
1626
1627 $cache = MessageCache::singleton();
1628 $message = $cache->get( $key, $useDB, $langCode );
1629 if ( $message === false ) {
1630 $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
1631 } elseif ( $transform ) {
1632 $message = $cache->transform( $message );
1633 }
1634 return $message;
1635 }
1636
1637 /**
1638 * Replace message parameter keys on the given formatted output.
1639 *
1640 * @param string $message
1641 * @param array $args
1642 * @return string
1643 * @private
1644 */
1645 function wfMsgReplaceArgs( $message, $args ) {
1646 # Fix windows line-endings
1647 # Some messages are split with explode("\n", $msg)
1648 $message = str_replace( "\r", '', $message );
1649
1650 // Replace arguments
1651 if ( count( $args ) ) {
1652 if ( is_array( $args[0] ) ) {
1653 $args = array_values( $args[0] );
1654 }
1655 $replacementKeys = array();
1656 foreach ( $args as $n => $param ) {
1657 $replacementKeys['$' . ( $n + 1 )] = $param;
1658 }
1659 $message = strtr( $message, $replacementKeys );
1660 }
1661
1662 return $message;
1663 }
1664
1665 /**
1666 * Return an HTML-escaped version of a message.
1667 * Parameter replacements, if any, are done *after* the HTML-escaping,
1668 * so parameters may contain HTML (eg links or form controls). Be sure
1669 * to pre-escape them if you really do want plaintext, or just wrap
1670 * the whole thing in htmlspecialchars().
1671 *
1672 * @deprecated since 1.18
1673 *
1674 * @param string $key
1675 * @param string $args,... Parameters
1676 * @return string
1677 */
1678 function wfMsgHtml( $key ) {
1679 wfDeprecated( __METHOD__, '1.21' );
1680
1681 $args = func_get_args();
1682 array_shift( $args );
1683 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key ) ), $args );
1684 }
1685
1686 /**
1687 * Return an HTML version of message
1688 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
1689 * so parameters may contain HTML (eg links or form controls). Be sure
1690 * to pre-escape them if you really do want plaintext, or just wrap
1691 * the whole thing in htmlspecialchars().
1692 *
1693 * @deprecated since 1.18
1694 *
1695 * @param string $key
1696 * @param string $args,... Parameters
1697 * @return string
1698 */
1699 function wfMsgWikiHtml( $key ) {
1700 wfDeprecated( __METHOD__, '1.21' );
1701
1702 $args = func_get_args();
1703 array_shift( $args );
1704 return wfMsgReplaceArgs(
1705 MessageCache::singleton()->parse( wfMsgGetKey( $key ), null,
1706 /* can't be set to false */ true, /* interface */ true )->getText(),
1707 $args );
1708 }
1709
1710 /**
1711 * Returns message in the requested format
1712 *
1713 * @deprecated since 1.18
1714 *
1715 * @param string $key Key of the message
1716 * @param array $options Processing rules.
1717 * Can take the following options:
1718 * parse: parses wikitext to HTML
1719 * parseinline: parses wikitext to HTML and removes the surrounding
1720 * p's added by parser or tidy
1721 * escape: filters message through htmlspecialchars
1722 * escapenoentities: same, but allows entity references like &#160; through
1723 * replaceafter: parameters are substituted after parsing or escaping
1724 * parsemag: transform the message using magic phrases
1725 * content: fetch message for content language instead of interface
1726 * Also can accept a single associative argument, of the form 'language' => 'xx':
1727 * language: Language object or language code to fetch message for
1728 * (overridden by content).
1729 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
1730 *
1731 * @return string
1732 */
1733 function wfMsgExt( $key, $options ) {
1734 wfDeprecated( __METHOD__, '1.21' );
1735
1736 $args = func_get_args();
1737 array_shift( $args );
1738 array_shift( $args );
1739 $options = (array)$options;
1740 $validOptions = array( 'parse', 'parseinline', 'escape', 'escapenoentities', 'replaceafter',
1741 'parsemag', 'content' );
1742
1743 foreach ( $options as $arrayKey => $option ) {
1744 if ( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
1745 // An unknown index, neither numeric nor "language"
1746 wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
1747 } elseif ( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option, $validOptions ) ) {
1748 // A numeric index with unknown value
1749 wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
1750 }
1751 }
1752
1753 if ( in_array( 'content', $options, true ) ) {
1754 $forContent = true;
1755 $langCode = true;
1756 $langCodeObj = null;
1757 } elseif ( array_key_exists( 'language', $options ) ) {
1758 $forContent = false;
1759 $langCode = wfGetLangObj( $options['language'] );
1760 $langCodeObj = $langCode;
1761 } else {
1762 $forContent = false;
1763 $langCode = false;
1764 $langCodeObj = null;
1765 }
1766
1767 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
1768
1769 if ( !in_array( 'replaceafter', $options, true ) ) {
1770 $string = wfMsgReplaceArgs( $string, $args );
1771 }
1772
1773 $messageCache = MessageCache::singleton();
1774 $parseInline = in_array( 'parseinline', $options, true );
1775 if ( in_array( 'parse', $options, true ) || $parseInline ) {
1776 $string = $messageCache->parse( $string, null, true, !$forContent, $langCodeObj );
1777 if ( $string instanceof ParserOutput ) {
1778 $string = $string->getText();
1779 }
1780
1781 if ( $parseInline ) {
1782 $string = Parser::stripOuterParagraph( $string );
1783 }
1784 } elseif ( in_array( 'parsemag', $options, true ) ) {
1785 $string = $messageCache->transform( $string,
1786 !$forContent, $langCodeObj );
1787 }
1788
1789 if ( in_array( 'escape', $options, true ) ) {
1790 $string = htmlspecialchars ( $string );
1791 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
1792 $string = Sanitizer::escapeHtmlAllowEntities( $string );
1793 }
1794
1795 if ( in_array( 'replaceafter', $options, true ) ) {
1796 $string = wfMsgReplaceArgs( $string, $args );
1797 }
1798
1799 return $string;
1800 }
1801
1802 /**
1803 * Since wfMsg() and co suck, they don't return false if the message key they
1804 * looked up didn't exist but instead the key wrapped in <>'s, this function checks for the
1805 * nonexistence of messages by checking the MessageCache::get() result directly.
1806 *
1807 * @deprecated since 1.18. Use Message::isDisabled().
1808 *
1809 * @param string $key The message key looked up
1810 * @return bool True if the message *doesn't* exist.
1811 */
1812 function wfEmptyMsg( $key ) {
1813 wfDeprecated( __METHOD__, '1.21' );
1814
1815 return MessageCache::singleton()->get( $key, /*useDB*/true, /*content*/false ) === false;
1816 }
1817
1818 /**
1819 * Fetch server name for use in error reporting etc.
1820 * Use real server name if available, so we know which machine
1821 * in a server farm generated the current page.
1822 *
1823 * @return string
1824 */
1825 function wfHostname() {
1826 static $host;
1827 if ( is_null( $host ) ) {
1828
1829 # Hostname overriding
1830 global $wgOverrideHostname;
1831 if ( $wgOverrideHostname !== false ) {
1832 # Set static and skip any detection
1833 $host = $wgOverrideHostname;
1834 return $host;
1835 }
1836
1837 if ( function_exists( 'posix_uname' ) ) {
1838 // This function not present on Windows
1839 $uname = posix_uname();
1840 } else {
1841 $uname = false;
1842 }
1843 if ( is_array( $uname ) && isset( $uname['nodename'] ) ) {
1844 $host = $uname['nodename'];
1845 } elseif ( getenv( 'COMPUTERNAME' ) ) {
1846 # Windows computer name
1847 $host = getenv( 'COMPUTERNAME' );
1848 } else {
1849 # This may be a virtual server.
1850 $host = $_SERVER['SERVER_NAME'];
1851 }
1852 }
1853 return $host;
1854 }
1855
1856 /**
1857 * Returns a script tag that stores the amount of time it took MediaWiki to
1858 * handle the request in milliseconds as 'wgBackendResponseTime'.
1859 *
1860 * If $wgShowHostnames is true, the script will also set 'wgHostname' to the
1861 * hostname of the server handling the request.
1862 *
1863 * @return string
1864 */
1865 function wfReportTime() {
1866 global $wgRequestTime, $wgShowHostnames;
1867
1868 $responseTime = round( ( microtime( true ) - $wgRequestTime ) * 1000 );
1869 $reportVars = array( 'wgBackendResponseTime' => $responseTime );
1870 if ( $wgShowHostnames ) {
1871 $reportVars['wgHostname'] = wfHostname();
1872 }
1873 return Skin::makeVariablesScript( $reportVars );
1874 }
1875
1876 /**
1877 * Safety wrapper for debug_backtrace().
1878 *
1879 * Will return an empty array if debug_backtrace is disabled, otherwise
1880 * the output from debug_backtrace() (trimmed).
1881 *
1882 * @param int $limit This parameter can be used to limit the number of stack frames returned
1883 *
1884 * @return array Array of backtrace information
1885 */
1886 function wfDebugBacktrace( $limit = 0 ) {
1887 static $disabled = null;
1888
1889 if ( is_null( $disabled ) ) {
1890 $disabled = !function_exists( 'debug_backtrace' );
1891 if ( $disabled ) {
1892 wfDebug( "debug_backtrace() is disabled\n" );
1893 }
1894 }
1895 if ( $disabled ) {
1896 return array();
1897 }
1898
1899 if ( $limit && version_compare( PHP_VERSION, '5.4.0', '>=' ) ) {
1900 return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
1901 } else {
1902 return array_slice( debug_backtrace(), 1 );
1903 }
1904 }
1905
1906 /**
1907 * Get a debug backtrace as a string
1908 *
1909 * @param bool|null $raw If true, the return value is plain text. If false, HTML.
1910 * Defaults to $wgCommandLineMode if unset.
1911 * @return string
1912 * @since 1.25 Supports $raw parameter.
1913 */
1914 function wfBacktrace( $raw = null ) {
1915 global $wgCommandLineMode;
1916
1917 if ( $raw === null ) {
1918 $raw = $wgCommandLineMode;
1919 }
1920
1921 if ( $raw ) {
1922 $frameFormat = "%s line %s calls %s()\n";
1923 $traceFormat = "%s";
1924 } else {
1925 $frameFormat = "<li>%s line %s calls %s()</li>\n";
1926 $traceFormat = "<ul>\n%s</ul>\n";
1927 }
1928
1929 $frames = array_map( function ( $frame ) use ( $frameFormat ) {
1930 $file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
1931 $line = isset( $frame['line'] ) ? $frame['line'] : '-';
1932 $call = $frame['function'];
1933 if ( !empty( $frame['class'] ) ) {
1934 $call = $frame['class'] . $frame['type'] . $call;
1935 }
1936 return sprintf( $frameFormat, $file, $line, $call );
1937 }, wfDebugBacktrace() );
1938
1939 return sprintf( $traceFormat, implode( '', $frames ) );
1940 }
1941
1942 /**
1943 * Get the name of the function which called this function
1944 * wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
1945 * wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
1946 * wfGetCaller( 3 ) is the parent of that.
1947 *
1948 * @param int $level
1949 * @return string
1950 */
1951 function wfGetCaller( $level = 2 ) {
1952 $backtrace = wfDebugBacktrace( $level + 1 );
1953 if ( isset( $backtrace[$level] ) ) {
1954 return wfFormatStackFrame( $backtrace[$level] );
1955 } else {
1956 return 'unknown';
1957 }
1958 }
1959
1960 /**
1961 * Return a string consisting of callers in the stack. Useful sometimes
1962 * for profiling specific points.
1963 *
1964 * @param int $limit The maximum depth of the stack frame to return, or false for the entire stack.
1965 * @return string
1966 */
1967 function wfGetAllCallers( $limit = 3 ) {
1968 $trace = array_reverse( wfDebugBacktrace() );
1969 if ( !$limit || $limit > count( $trace ) - 1 ) {
1970 $limit = count( $trace ) - 1;
1971 }
1972 $trace = array_slice( $trace, -$limit - 1, $limit );
1973 return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
1974 }
1975
1976 /**
1977 * Return a string representation of frame
1978 *
1979 * @param array $frame
1980 * @return string
1981 */
1982 function wfFormatStackFrame( $frame ) {
1983 return isset( $frame['class'] ) ?
1984 $frame['class'] . '::' . $frame['function'] :
1985 $frame['function'];
1986 }
1987
1988 /* Some generic result counters, pulled out of SearchEngine */
1989
1990 /**
1991 * @todo document
1992 *
1993 * @param int $offset
1994 * @param int $limit
1995 * @return string
1996 */
1997 function wfShowingResults( $offset, $limit ) {
1998 return wfMessage( 'showingresults' )->numParams( $limit, $offset + 1 )->parse();
1999 }
2000
2001 /**
2002 * @todo document
2003 * @todo FIXME: We may want to blacklist some broken browsers
2004 *
2005 * @param bool $force
2006 * @return bool Whereas client accept gzip compression
2007 */
2008 function wfClientAcceptsGzip( $force = false ) {
2009 static $result = null;
2010 if ( $result === null || $force ) {
2011 $result = false;
2012 if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
2013 # @todo FIXME: We may want to blacklist some broken browsers
2014 $m = array();
2015 if ( preg_match(
2016 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
2017 $_SERVER['HTTP_ACCEPT_ENCODING'],
2018 $m
2019 )
2020 ) {
2021 if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
2022 $result = false;
2023 return $result;
2024 }
2025 wfDebug( "wfClientAcceptsGzip: client accepts gzip.\n" );
2026 $result = true;
2027 }
2028 }
2029 }
2030 return $result;
2031 }
2032
2033 /**
2034 * Obtain the offset and limit values from the request string;
2035 * used in special pages
2036 *
2037 * @param int $deflimit Default limit if none supplied
2038 * @param string $optionname Name of a user preference to check against
2039 * @return array
2040 * @deprecated since 1.24, just call WebRequest::getLimitOffset() directly
2041 */
2042 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
2043 global $wgRequest;
2044 wfDeprecated( __METHOD__, '1.24' );
2045 return $wgRequest->getLimitOffset( $deflimit, $optionname );
2046 }
2047
2048 /**
2049 * Escapes the given text so that it may be output using addWikiText()
2050 * without any linking, formatting, etc. making its way through. This
2051 * is achieved by substituting certain characters with HTML entities.
2052 * As required by the callers, "<nowiki>" is not used.
2053 *
2054 * @param string $text Text to be escaped
2055 * @return string
2056 */
2057 function wfEscapeWikiText( $text ) {
2058 static $repl = null, $repl2 = null;
2059 if ( $repl === null ) {
2060 $repl = array(
2061 '"' => '&#34;', '&' => '&#38;', "'" => '&#39;', '<' => '&#60;',
2062 '=' => '&#61;', '>' => '&#62;', '[' => '&#91;', ']' => '&#93;',
2063 '{' => '&#123;', '|' => '&#124;', '}' => '&#125;', ';' => '&#59;',
2064 "\n#" => "\n&#35;", "\r#" => "\r&#35;",
2065 "\n*" => "\n&#42;", "\r*" => "\r&#42;",
2066 "\n:" => "\n&#58;", "\r:" => "\r&#58;",
2067 "\n " => "\n&#32;", "\r " => "\r&#32;",
2068 "\n\n" => "\n&#10;", "\r\n" => "&#13;\n",
2069 "\n\r" => "\n&#13;", "\r\r" => "\r&#13;",
2070 "\n\t" => "\n&#9;", "\r\t" => "\r&#9;", // "\n\t\n" is treated like "\n\n"
2071 "\n----" => "\n&#45;---", "\r----" => "\r&#45;---",
2072 '__' => '_&#95;', '://' => '&#58;//',
2073 );
2074
2075 // We have to catch everything "\s" matches in PCRE
2076 foreach ( array( 'ISBN', 'RFC', 'PMID' ) as $magic ) {
2077 $repl["$magic "] = "$magic&#32;";
2078 $repl["$magic\t"] = "$magic&#9;";
2079 $repl["$magic\r"] = "$magic&#13;";
2080 $repl["$magic\n"] = "$magic&#10;";
2081 $repl["$magic\f"] = "$magic&#12;";
2082 }
2083
2084 // And handle protocols that don't use "://"
2085 global $wgUrlProtocols;
2086 $repl2 = array();
2087 foreach ( $wgUrlProtocols as $prot ) {
2088 if ( substr( $prot, -1 ) === ':' ) {
2089 $repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
2090 }
2091 }
2092 $repl2 = $repl2 ? '/\b(' . join( '|', $repl2 ) . '):/i' : '/^(?!)/';
2093 }
2094 $text = substr( strtr( "\n$text", $repl ), 1 );
2095 $text = preg_replace( $repl2, '$1&#58;', $text );
2096 return $text;
2097 }
2098
2099 /**
2100 * Sets dest to source and returns the original value of dest
2101 * If source is NULL, it just returns the value, it doesn't set the variable
2102 * If force is true, it will set the value even if source is NULL
2103 *
2104 * @param mixed $dest
2105 * @param mixed $source
2106 * @param bool $force
2107 * @return mixed
2108 */
2109 function wfSetVar( &$dest, $source, $force = false ) {
2110 $temp = $dest;
2111 if ( !is_null( $source ) || $force ) {
2112 $dest = $source;
2113 }
2114 return $temp;
2115 }
2116
2117 /**
2118 * As for wfSetVar except setting a bit
2119 *
2120 * @param int $dest
2121 * @param int $bit
2122 * @param bool $state
2123 *
2124 * @return bool
2125 */
2126 function wfSetBit( &$dest, $bit, $state = true ) {
2127 $temp = (bool)( $dest & $bit );
2128 if ( !is_null( $state ) ) {
2129 if ( $state ) {
2130 $dest |= $bit;
2131 } else {
2132 $dest &= ~$bit;
2133 }
2134 }
2135 return $temp;
2136 }
2137
2138 /**
2139 * A wrapper around the PHP function var_export().
2140 * Either print it or add it to the regular output ($wgOut).
2141 *
2142 * @param mixed $var A PHP variable to dump.
2143 */
2144 function wfVarDump( $var ) {
2145 global $wgOut;
2146 $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
2147 if ( headers_sent() || !isset( $wgOut ) || !is_object( $wgOut ) ) {
2148 print $s;
2149 } else {
2150 $wgOut->addHTML( $s );
2151 }
2152 }
2153
2154 /**
2155 * Provide a simple HTTP error.
2156 *
2157 * @param int|string $code
2158 * @param string $label
2159 * @param string $desc
2160 */
2161 function wfHttpError( $code, $label, $desc ) {
2162 global $wgOut;
2163 header( "HTTP/1.0 $code $label" );
2164 header( "Status: $code $label" );
2165 if ( $wgOut ) {
2166 $wgOut->disable();
2167 $wgOut->sendCacheControl();
2168 }
2169
2170 header( 'Content-type: text/html; charset=utf-8' );
2171 print "<!doctype html>" .
2172 '<html><head><title>' .
2173 htmlspecialchars( $label ) .
2174 '</title></head><body><h1>' .
2175 htmlspecialchars( $label ) .
2176 '</h1><p>' .
2177 nl2br( htmlspecialchars( $desc ) ) .
2178 "</p></body></html>\n";
2179 }
2180
2181 /**
2182 * Clear away any user-level output buffers, discarding contents.
2183 *
2184 * Suitable for 'starting afresh', for instance when streaming
2185 * relatively large amounts of data without buffering, or wanting to
2186 * output image files without ob_gzhandler's compression.
2187 *
2188 * The optional $resetGzipEncoding parameter controls suppression of
2189 * the Content-Encoding header sent by ob_gzhandler; by default it
2190 * is left. See comments for wfClearOutputBuffers() for why it would
2191 * be used.
2192 *
2193 * Note that some PHP configuration options may add output buffer
2194 * layers which cannot be removed; these are left in place.
2195 *
2196 * @param bool $resetGzipEncoding
2197 */
2198 function wfResetOutputBuffers( $resetGzipEncoding = true ) {
2199 if ( $resetGzipEncoding ) {
2200 // Suppress Content-Encoding and Content-Length
2201 // headers from 1.10+s wfOutputHandler
2202 global $wgDisableOutputCompression;
2203 $wgDisableOutputCompression = true;
2204 }
2205 while ( $status = ob_get_status() ) {
2206 if ( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
2207 // Probably from zlib.output_compression or other
2208 // PHP-internal setting which can't be removed.
2209 //
2210 // Give up, and hope the result doesn't break
2211 // output behavior.
2212 break;
2213 }
2214 if ( !ob_end_clean() ) {
2215 // Could not remove output buffer handler; abort now
2216 // to avoid getting in some kind of infinite loop.
2217 break;
2218 }
2219 if ( $resetGzipEncoding ) {
2220 if ( $status['name'] == 'ob_gzhandler' ) {
2221 // Reset the 'Content-Encoding' field set by this handler
2222 // so we can start fresh.
2223 header_remove( 'Content-Encoding' );
2224 break;
2225 }
2226 }
2227 }
2228 }
2229
2230 /**
2231 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
2232 *
2233 * Clear away output buffers, but keep the Content-Encoding header
2234 * produced by ob_gzhandler, if any.
2235 *
2236 * This should be used for HTTP 304 responses, where you need to
2237 * preserve the Content-Encoding header of the real result, but
2238 * also need to suppress the output of ob_gzhandler to keep to spec
2239 * and avoid breaking Firefox in rare cases where the headers and
2240 * body are broken over two packets.
2241 */
2242 function wfClearOutputBuffers() {
2243 wfResetOutputBuffers( false );
2244 }
2245
2246 /**
2247 * Converts an Accept-* header into an array mapping string values to quality
2248 * factors
2249 *
2250 * @param string $accept
2251 * @param string $def Default
2252 * @return float[] Associative array of string => float pairs
2253 */
2254 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
2255 # No arg means accept anything (per HTTP spec)
2256 if ( !$accept ) {
2257 return array( $def => 1.0 );
2258 }
2259
2260 $prefs = array();
2261
2262 $parts = explode( ',', $accept );
2263
2264 foreach ( $parts as $part ) {
2265 # @todo FIXME: Doesn't deal with params like 'text/html; level=1'
2266 $values = explode( ';', trim( $part ) );
2267 $match = array();
2268 if ( count( $values ) == 1 ) {
2269 $prefs[$values[0]] = 1.0;
2270 } elseif ( preg_match( '/q\s*=\s*(\d*\.\d+)/', $values[1], $match ) ) {
2271 $prefs[$values[0]] = floatval( $match[1] );
2272 }
2273 }
2274
2275 return $prefs;
2276 }
2277
2278 /**
2279 * Checks if a given MIME type matches any of the keys in the given
2280 * array. Basic wildcards are accepted in the array keys.
2281 *
2282 * Returns the matching MIME type (or wildcard) if a match, otherwise
2283 * NULL if no match.
2284 *
2285 * @param string $type
2286 * @param array $avail
2287 * @return string
2288 * @private
2289 */
2290 function mimeTypeMatch( $type, $avail ) {
2291 if ( array_key_exists( $type, $avail ) ) {
2292 return $type;
2293 } else {
2294 $parts = explode( '/', $type );
2295 if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
2296 return $parts[0] . '/*';
2297 } elseif ( array_key_exists( '*/*', $avail ) ) {
2298 return '*/*';
2299 } else {
2300 return null;
2301 }
2302 }
2303 }
2304
2305 /**
2306 * Returns the 'best' match between a client's requested internet media types
2307 * and the server's list of available types. Each list should be an associative
2308 * array of type to preference (preference is a float between 0.0 and 1.0).
2309 * Wildcards in the types are acceptable.
2310 *
2311 * @param array $cprefs Client's acceptable type list
2312 * @param array $sprefs Server's offered types
2313 * @return string
2314 *
2315 * @todo FIXME: Doesn't handle params like 'text/plain; charset=UTF-8'
2316 * XXX: generalize to negotiate other stuff
2317 */
2318 function wfNegotiateType( $cprefs, $sprefs ) {
2319 $combine = array();
2320
2321 foreach ( array_keys( $sprefs ) as $type ) {
2322 $parts = explode( '/', $type );
2323 if ( $parts[1] != '*' ) {
2324 $ckey = mimeTypeMatch( $type, $cprefs );
2325 if ( $ckey ) {
2326 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
2327 }
2328 }
2329 }
2330
2331 foreach ( array_keys( $cprefs ) as $type ) {
2332 $parts = explode( '/', $type );
2333 if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
2334 $skey = mimeTypeMatch( $type, $sprefs );
2335 if ( $skey ) {
2336 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
2337 }
2338 }
2339 }
2340
2341 $bestq = 0;
2342 $besttype = null;
2343
2344 foreach ( array_keys( $combine ) as $type ) {
2345 if ( $combine[$type] > $bestq ) {
2346 $besttype = $type;
2347 $bestq = $combine[$type];
2348 }
2349 }
2350
2351 return $besttype;
2352 }
2353
2354 /**
2355 * Reference-counted warning suppression
2356 *
2357 * @param bool $end
2358 */
2359 function wfSuppressWarnings( $end = false ) {
2360 static $suppressCount = 0;
2361 static $originalLevel = false;
2362
2363 if ( $end ) {
2364 if ( $suppressCount ) {
2365 --$suppressCount;
2366 if ( !$suppressCount ) {
2367 error_reporting( $originalLevel );
2368 }
2369 }
2370 } else {
2371 if ( !$suppressCount ) {
2372 $originalLevel = error_reporting( E_ALL & ~(
2373 E_WARNING |
2374 E_NOTICE |
2375 E_USER_WARNING |
2376 E_USER_NOTICE |
2377 E_DEPRECATED |
2378 E_USER_DEPRECATED |
2379 E_STRICT
2380 ) );
2381 }
2382 ++$suppressCount;
2383 }
2384 }
2385
2386 /**
2387 * Restore error level to previous value
2388 */
2389 function wfRestoreWarnings() {
2390 wfSuppressWarnings( true );
2391 }
2392
2393 # Autodetect, convert and provide timestamps of various types
2394
2395 /**
2396 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
2397 */
2398 define( 'TS_UNIX', 0 );
2399
2400 /**
2401 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
2402 */
2403 define( 'TS_MW', 1 );
2404
2405 /**
2406 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
2407 */
2408 define( 'TS_DB', 2 );
2409
2410 /**
2411 * RFC 2822 format, for E-mail and HTTP headers
2412 */
2413 define( 'TS_RFC2822', 3 );
2414
2415 /**
2416 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
2417 *
2418 * This is used by Special:Export
2419 */
2420 define( 'TS_ISO_8601', 4 );
2421
2422 /**
2423 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
2424 *
2425 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
2426 * DateTime tag and page 36 for the DateTimeOriginal and
2427 * DateTimeDigitized tags.
2428 */
2429 define( 'TS_EXIF', 5 );
2430
2431 /**
2432 * Oracle format time.
2433 */
2434 define( 'TS_ORACLE', 6 );
2435
2436 /**
2437 * Postgres format time.
2438 */
2439 define( 'TS_POSTGRES', 7 );
2440
2441 /**
2442 * ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader
2443 */
2444 define( 'TS_ISO_8601_BASIC', 9 );
2445
2446 /**
2447 * Get a timestamp string in one of various formats
2448 *
2449 * @param mixed $outputtype A timestamp in one of the supported formats, the
2450 * function will autodetect which format is supplied and act accordingly.
2451 * @param mixed $ts Optional timestamp to convert, default 0 for the current time
2452 * @return string|bool String / false The same date in the format specified in $outputtype or false
2453 */
2454 function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
2455 try {
2456 $timestamp = new MWTimestamp( $ts );
2457 return $timestamp->getTimestamp( $outputtype );
2458 } catch ( TimestampException $e ) {
2459 wfDebug( "wfTimestamp() fed bogus time value: TYPE=$outputtype; VALUE=$ts\n" );
2460 return false;
2461 }
2462 }
2463
2464 /**
2465 * Return a formatted timestamp, or null if input is null.
2466 * For dealing with nullable timestamp columns in the database.
2467 *
2468 * @param int $outputtype
2469 * @param string $ts
2470 * @return string
2471 */
2472 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
2473 if ( is_null( $ts ) ) {
2474 return null;
2475 } else {
2476 return wfTimestamp( $outputtype, $ts );
2477 }
2478 }
2479
2480 /**
2481 * Convenience function; returns MediaWiki timestamp for the present time.
2482 *
2483 * @return string
2484 */
2485 function wfTimestampNow() {
2486 # return NOW
2487 return wfTimestamp( TS_MW, time() );
2488 }
2489
2490 /**
2491 * Check if the operating system is Windows
2492 *
2493 * @return bool True if it's Windows, false otherwise.
2494 */
2495 function wfIsWindows() {
2496 static $isWindows = null;
2497 if ( $isWindows === null ) {
2498 $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
2499 }
2500 return $isWindows;
2501 }
2502
2503 /**
2504 * Check if we are running under HHVM
2505 *
2506 * @return bool
2507 */
2508 function wfIsHHVM() {
2509 return defined( 'HHVM_VERSION' );
2510 }
2511
2512 /**
2513 * Swap two variables
2514 *
2515 * @deprecated since 1.24
2516 * @param mixed $x
2517 * @param mixed $y
2518 */
2519 function swap( &$x, &$y ) {
2520 wfDeprecated( __FUNCTION__, '1.24' );
2521 $z = $x;
2522 $x = $y;
2523 $y = $z;
2524 }
2525
2526 /**
2527 * Tries to get the system directory for temporary files. First
2528 * $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP
2529 * environment variables are then checked in sequence, and if none are
2530 * set try sys_get_temp_dir().
2531 *
2532 * NOTE: When possible, use instead the tmpfile() function to create
2533 * temporary files to avoid race conditions on file creation, etc.
2534 *
2535 * @return string
2536 */
2537 function wfTempDir() {
2538 global $wgTmpDirectory;
2539
2540 if ( $wgTmpDirectory !== false ) {
2541 return $wgTmpDirectory;
2542 }
2543
2544 $tmpDir = array_map( "getenv", array( 'TMPDIR', 'TMP', 'TEMP' ) );
2545
2546 foreach ( $tmpDir as $tmp ) {
2547 if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
2548 return $tmp;
2549 }
2550 }
2551 return sys_get_temp_dir();
2552 }
2553
2554 /**
2555 * Make directory, and make all parent directories if they don't exist
2556 *
2557 * @param string $dir Full path to directory to create
2558 * @param int $mode Chmod value to use, default is $wgDirectoryMode
2559 * @param string $caller Optional caller param for debugging.
2560 * @throws MWException
2561 * @return bool
2562 */
2563 function wfMkdirParents( $dir, $mode = null, $caller = null ) {
2564 global $wgDirectoryMode;
2565
2566 if ( FileBackend::isStoragePath( $dir ) ) { // sanity
2567 throw new MWException( __FUNCTION__ . " given storage path '$dir'." );
2568 }
2569
2570 if ( !is_null( $caller ) ) {
2571 wfDebug( "$caller: called wfMkdirParents($dir)\n" );
2572 }
2573
2574 if ( strval( $dir ) === '' || ( file_exists( $dir ) && is_dir( $dir ) ) ) {
2575 return true;
2576 }
2577
2578 $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
2579
2580 if ( is_null( $mode ) ) {
2581 $mode = $wgDirectoryMode;
2582 }
2583
2584 // Turn off the normal warning, we're doing our own below
2585 wfSuppressWarnings();
2586 $ok = mkdir( $dir, $mode, true ); // PHP5 <3
2587 wfRestoreWarnings();
2588
2589 if ( !$ok ) {
2590 //directory may have been created on another request since we last checked
2591 if ( is_dir( $dir ) ) {
2592 return true;
2593 }
2594
2595 // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
2596 wfLogWarning( sprintf( "failed to mkdir \"%s\" mode 0%o", $dir, $mode ) );
2597 }
2598 return $ok;
2599 }
2600
2601 /**
2602 * Remove a directory and all its content.
2603 * Does not hide error.
2604 * @param string $dir
2605 */
2606 function wfRecursiveRemoveDir( $dir ) {
2607 wfDebug( __FUNCTION__ . "( $dir )\n" );
2608 // taken from http://de3.php.net/manual/en/function.rmdir.php#98622
2609 if ( is_dir( $dir ) ) {
2610 $objects = scandir( $dir );
2611 foreach ( $objects as $object ) {
2612 if ( $object != "." && $object != ".." ) {
2613 if ( filetype( $dir . '/' . $object ) == "dir" ) {
2614 wfRecursiveRemoveDir( $dir . '/' . $object );
2615 } else {
2616 unlink( $dir . '/' . $object );
2617 }
2618 }
2619 }
2620 reset( $objects );
2621 rmdir( $dir );
2622 }
2623 }
2624
2625 /**
2626 * @param int $nr The number to format
2627 * @param int $acc The number of digits after the decimal point, default 2
2628 * @param bool $round Whether or not to round the value, default true
2629 * @return string
2630 */
2631 function wfPercent( $nr, $acc = 2, $round = true ) {
2632 $ret = sprintf( "%.${acc}f", $nr );
2633 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2634 }
2635
2636 /**
2637 * Safety wrapper around ini_get() for boolean settings.
2638 * The values returned from ini_get() are pre-normalized for settings
2639 * set via php.ini or php_flag/php_admin_flag... but *not*
2640 * for those set via php_value/php_admin_value.
2641 *
2642 * It's fairly common for people to use php_value instead of php_flag,
2643 * which can leave you with an 'off' setting giving a false positive
2644 * for code that just takes the ini_get() return value as a boolean.
2645 *
2646 * To make things extra interesting, setting via php_value accepts
2647 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2648 * Unrecognized values go false... again opposite PHP's own coercion
2649 * from string to bool.
2650 *
2651 * Luckily, 'properly' set settings will always come back as '0' or '1',
2652 * so we only have to worry about them and the 'improper' settings.
2653 *
2654 * I frickin' hate PHP... :P
2655 *
2656 * @param string $setting
2657 * @return bool
2658 */
2659 function wfIniGetBool( $setting ) {
2660 $val = strtolower( ini_get( $setting ) );
2661 // 'on' and 'true' can't have whitespace around them, but '1' can.
2662 return $val == 'on'
2663 || $val == 'true'
2664 || $val == 'yes'
2665 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2666 }
2667
2668 /**
2669 * Windows-compatible version of escapeshellarg()
2670 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
2671 * function puts single quotes in regardless of OS.
2672 *
2673 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
2674 * earlier distro releases of PHP)
2675 *
2676 * @param string ... strings to escape and glue together, or a single array of strings parameter
2677 * @return string
2678 */
2679 function wfEscapeShellArg( /*...*/ ) {
2680 wfInitShellLocale();
2681
2682 $args = func_get_args();
2683 if ( count( $args ) === 1 && is_array( reset( $args ) ) ) {
2684 // If only one argument has been passed, and that argument is an array,
2685 // treat it as a list of arguments
2686 $args = reset( $args );
2687 }
2688
2689 $first = true;
2690 $retVal = '';
2691 foreach ( $args as $arg ) {
2692 if ( !$first ) {
2693 $retVal .= ' ';
2694 } else {
2695 $first = false;
2696 }
2697
2698 if ( wfIsWindows() ) {
2699 // Escaping for an MSVC-style command line parser and CMD.EXE
2700 // @codingStandardsIgnoreStart For long URLs
2701 // Refs:
2702 // * http://web.archive.org/web/20020708081031/http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
2703 // * http://technet.microsoft.com/en-us/library/cc723564.aspx
2704 // * Bug #13518
2705 // * CR r63214
2706 // Double the backslashes before any double quotes. Escape the double quotes.
2707 // @codingStandardsIgnoreEnd
2708 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
2709 $arg = '';
2710 $iteration = 0;
2711 foreach ( $tokens as $token ) {
2712 if ( $iteration % 2 == 1 ) {
2713 // Delimiter, a double quote preceded by zero or more slashes
2714 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
2715 } elseif ( $iteration % 4 == 2 ) {
2716 // ^ in $token will be outside quotes, need to be escaped
2717 $arg .= str_replace( '^', '^^', $token );
2718 } else { // $iteration % 4 == 0
2719 // ^ in $token will appear inside double quotes, so leave as is
2720 $arg .= $token;
2721 }
2722 $iteration++;
2723 }
2724 // Double the backslashes before the end of the string, because
2725 // we will soon add a quote
2726 $m = array();
2727 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
2728 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
2729 }
2730
2731 // Add surrounding quotes
2732 $retVal .= '"' . $arg . '"';
2733 } else {
2734 $retVal .= escapeshellarg( $arg );
2735 }
2736 }
2737 return $retVal;
2738 }
2739
2740 /**
2741 * Check if wfShellExec() is effectively disabled via php.ini config
2742 *
2743 * @return bool|string False or one of (safemode,disabled)
2744 * @since 1.22
2745 */
2746 function wfShellExecDisabled() {
2747 static $disabled = null;
2748 if ( is_null( $disabled ) ) {
2749 if ( wfIniGetBool( 'safe_mode' ) ) {
2750 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2751 $disabled = 'safemode';
2752 } elseif ( !function_exists( 'proc_open' ) ) {
2753 wfDebug( "proc_open() is disabled\n" );
2754 $disabled = 'disabled';
2755 } else {
2756 $disabled = false;
2757 }
2758 }
2759 return $disabled;
2760 }
2761
2762 /**
2763 * Execute a shell command, with time and memory limits mirrored from the PHP
2764 * configuration if supported.
2765 *
2766 * @param string|string[] $cmd If string, a properly shell-escaped command line,
2767 * or an array of unescaped arguments, in which case each value will be escaped
2768 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2769 * @param null|mixed &$retval Optional, will receive the program's exit code.
2770 * (non-zero is usually failure). If there is an error from
2771 * read, select, or proc_open(), this will be set to -1.
2772 * @param array $environ Optional environment variables which should be
2773 * added to the executed command environment.
2774 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2775 * this overwrites the global wgMaxShell* limits.
2776 * @param array $options Array of options:
2777 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2778 * including errors from limit.sh
2779 * - profileMethod: By default this function will profile based on the calling
2780 * method. Set this to a string for an alternative method to profile from
2781 *
2782 * @return string Collected stdout as a string
2783 */
2784 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2785 $limits = array(), $options = array()
2786 ) {
2787 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2788 $wgMaxShellWallClockTime, $wgShellCgroup;
2789
2790 $disabled = wfShellExecDisabled();
2791 if ( $disabled ) {
2792 $retval = 1;
2793 return $disabled == 'safemode' ?
2794 'Unable to run external programs in safe mode.' :
2795 'Unable to run external programs, proc_open() is disabled.';
2796 }
2797
2798 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2799 $profileMethod = isset( $options['profileMethod'] ) ? $options['profileMethod'] : wfGetCaller();
2800
2801 wfInitShellLocale();
2802
2803 $envcmd = '';
2804 foreach ( $environ as $k => $v ) {
2805 if ( wfIsWindows() ) {
2806 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2807 * appear in the environment variable, so we must use carat escaping as documented in
2808 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2809 * Note however that the quote isn't listed there, but is needed, and the parentheses
2810 * are listed there but doesn't appear to need it.
2811 */
2812 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2813 } else {
2814 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2815 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2816 */
2817 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2818 }
2819 }
2820 if ( is_array( $cmd ) ) {
2821 $cmd = wfEscapeShellArg( $cmd );
2822 }
2823
2824 $cmd = $envcmd . $cmd;
2825
2826 $useLogPipe = false;
2827 if ( is_executable( '/bin/bash' ) ) {
2828 $time = intval ( isset( $limits['time'] ) ? $limits['time'] : $wgMaxShellTime );
2829 if ( isset( $limits['walltime'] ) ) {
2830 $wallTime = intval( $limits['walltime'] );
2831 } elseif ( isset( $limits['time'] ) ) {
2832 $wallTime = $time;
2833 } else {
2834 $wallTime = intval( $wgMaxShellWallClockTime );
2835 }
2836 $mem = intval ( isset( $limits['memory'] ) ? $limits['memory'] : $wgMaxShellMemory );
2837 $filesize = intval ( isset( $limits['filesize'] ) ? $limits['filesize'] : $wgMaxShellFileSize );
2838
2839 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
2840 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2841 escapeshellarg( $cmd ) . ' ' .
2842 escapeshellarg(
2843 "MW_INCLUDE_STDERR=" . ( $includeStderr ? '1' : '' ) . ';' .
2844 "MW_CPU_LIMIT=$time; " .
2845 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2846 "MW_MEM_LIMIT=$mem; " .
2847 "MW_FILE_SIZE_LIMIT=$filesize; " .
2848 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2849 "MW_USE_LOG_PIPE=yes"
2850 );
2851 $useLogPipe = true;
2852 } elseif ( $includeStderr ) {
2853 $cmd .= ' 2>&1';
2854 }
2855 } elseif ( $includeStderr ) {
2856 $cmd .= ' 2>&1';
2857 }
2858 wfDebug( "wfShellExec: $cmd\n" );
2859
2860 $desc = array(
2861 0 => array( 'file', 'php://stdin', 'r' ),
2862 1 => array( 'pipe', 'w' ),
2863 2 => array( 'file', 'php://stderr', 'w' ) );
2864 if ( $useLogPipe ) {
2865 $desc[3] = array( 'pipe', 'w' );
2866 }
2867 $pipes = null;
2868 $scoped = Profiler::instance()->scopedProfileIn( __FUNCTION__ . '-' . $profileMethod );
2869 $proc = proc_open( $cmd, $desc, $pipes );
2870 if ( !$proc ) {
2871 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2872 $retval = -1;
2873 return '';
2874 }
2875 $outBuffer = $logBuffer = '';
2876 $emptyArray = array();
2877 $status = false;
2878 $logMsg = false;
2879
2880 // According to the documentation, it is possible for stream_select()
2881 // to fail due to EINTR. I haven't managed to induce this in testing
2882 // despite sending various signals. If it did happen, the error
2883 // message would take the form:
2884 //
2885 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2886 //
2887 // where [4] is the value of the macro EINTR and "Interrupted system
2888 // call" is string which according to the Linux manual is "possibly"
2889 // localised according to LC_MESSAGES.
2890 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
2891 $eintrMessage = "stream_select(): unable to select [$eintr]";
2892
2893 // Build a table mapping resource IDs to pipe FDs to work around a
2894 // PHP 5.3 issue in which stream_select() does not preserve array keys
2895 // <https://bugs.php.net/bug.php?id=53427>.
2896 $fds = array();
2897 foreach ( $pipes as $fd => $pipe ) {
2898 $fds[(int)$pipe] = $fd;
2899 }
2900
2901 $running = true;
2902 $timeout = null;
2903 $numReadyPipes = 0;
2904
2905 while ( $running === true || $numReadyPipes !== 0 ) {
2906 if ( $running ) {
2907 $status = proc_get_status( $proc );
2908 // If the process has terminated, switch to nonblocking selects
2909 // for getting any data still waiting to be read.
2910 if ( !$status['running'] ) {
2911 $running = false;
2912 $timeout = 0;
2913 }
2914 }
2915
2916 $readyPipes = $pipes;
2917
2918 // Clear last error
2919 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2920 @trigger_error( '' );
2921 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
2922 if ( $numReadyPipes === false ) {
2923 // @codingStandardsIgnoreEnd
2924 $error = error_get_last();
2925 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2926 continue;
2927 } else {
2928 trigger_error( $error['message'], E_USER_WARNING );
2929 $logMsg = $error['message'];
2930 break;
2931 }
2932 }
2933 foreach ( $readyPipes as $pipe ) {
2934 $block = fread( $pipe, 65536 );
2935 $fd = $fds[(int)$pipe];
2936 if ( $block === '' ) {
2937 // End of file
2938 fclose( $pipes[$fd] );
2939 unset( $pipes[$fd] );
2940 if ( !$pipes ) {
2941 break 2;
2942 }
2943 } elseif ( $block === false ) {
2944 // Read error
2945 $logMsg = "Error reading from pipe";
2946 break 2;
2947 } elseif ( $fd == 1 ) {
2948 // From stdout
2949 $outBuffer .= $block;
2950 } elseif ( $fd == 3 ) {
2951 // From log FD
2952 $logBuffer .= $block;
2953 if ( strpos( $block, "\n" ) !== false ) {
2954 $lines = explode( "\n", $logBuffer );
2955 $logBuffer = array_pop( $lines );
2956 foreach ( $lines as $line ) {
2957 wfDebugLog( 'exec', $line );
2958 }
2959 }
2960 }
2961 }
2962 }
2963
2964 foreach ( $pipes as $pipe ) {
2965 fclose( $pipe );
2966 }
2967
2968 // Use the status previously collected if possible, since proc_get_status()
2969 // just calls waitpid() which will not return anything useful the second time.
2970 if ( $running ) {
2971 $status = proc_get_status( $proc );
2972 }
2973
2974 if ( $logMsg !== false ) {
2975 // Read/select error
2976 $retval = -1;
2977 proc_close( $proc );
2978 } elseif ( $status['signaled'] ) {
2979 $logMsg = "Exited with signal {$status['termsig']}";
2980 $retval = 128 + $status['termsig'];
2981 proc_close( $proc );
2982 } else {
2983 if ( $status['running'] ) {
2984 $retval = proc_close( $proc );
2985 } else {
2986 $retval = $status['exitcode'];
2987 proc_close( $proc );
2988 }
2989 if ( $retval == 127 ) {
2990 $logMsg = "Possibly missing executable file";
2991 } elseif ( $retval >= 129 && $retval <= 192 ) {
2992 $logMsg = "Probably exited with signal " . ( $retval - 128 );
2993 }
2994 }
2995
2996 if ( $logMsg !== false ) {
2997 wfDebugLog( 'exec', "$logMsg: $cmd" );
2998 }
2999
3000 return $outBuffer;
3001 }
3002
3003 /**
3004 * Execute a shell command, returning both stdout and stderr. Convenience
3005 * function, as all the arguments to wfShellExec can become unwieldy.
3006 *
3007 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
3008 * @param string|string[] $cmd If string, a properly shell-escaped command line,
3009 * or an array of unescaped arguments, in which case each value will be escaped
3010 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
3011 * @param null|mixed &$retval Optional, will receive the program's exit code.
3012 * (non-zero is usually failure)
3013 * @param array $environ Optional environment variables which should be
3014 * added to the executed command environment.
3015 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
3016 * this overwrites the global wgMaxShell* limits.
3017 * @return string Collected stdout and stderr as a string
3018 */
3019 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
3020 return wfShellExec( $cmd, $retval, $environ, $limits,
3021 array( 'duplicateStderr' => true, 'profileMethod' => wfGetCaller() ) );
3022 }
3023
3024 /**
3025 * Workaround for http://bugs.php.net/bug.php?id=45132
3026 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
3027 */
3028 function wfInitShellLocale() {
3029 static $done = false;
3030 if ( $done ) {
3031 return;
3032 }
3033 $done = true;
3034 global $wgShellLocale;
3035 if ( !wfIniGetBool( 'safe_mode' ) ) {
3036 putenv( "LC_CTYPE=$wgShellLocale" );
3037 setlocale( LC_CTYPE, $wgShellLocale );
3038 }
3039 }
3040
3041 /**
3042 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3043 * Note that $parameters should be a flat array and an option with an argument
3044 * should consist of two consecutive items in the array (do not use "--option value").
3045 *
3046 * @param string $script MediaWiki cli script path
3047 * @param array $parameters Arguments and options to the script
3048 * @param array $options Associative array of options:
3049 * 'php': The path to the php executable
3050 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3051 * @return string
3052 */
3053 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3054 global $wgPhpCli;
3055 // Give site config file a chance to run the script in a wrapper.
3056 // The caller may likely want to call wfBasename() on $script.
3057 Hooks::run( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3058 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
3059 if ( isset( $options['wrapper'] ) ) {
3060 $cmd[] = $options['wrapper'];
3061 }
3062 $cmd[] = $script;
3063 // Escape each parameter for shell
3064 return wfEscapeShellArg( array_merge( $cmd, $parameters ) );
3065 }
3066
3067 /**
3068 * wfMerge attempts to merge differences between three texts.
3069 * Returns true for a clean merge and false for failure or a conflict.
3070 *
3071 * @param string $old
3072 * @param string $mine
3073 * @param string $yours
3074 * @param string $result
3075 * @return bool
3076 */
3077 function wfMerge( $old, $mine, $yours, &$result ) {
3078 global $wgDiff3;
3079
3080 # This check may also protect against code injection in
3081 # case of broken installations.
3082 wfSuppressWarnings();
3083 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3084 wfRestoreWarnings();
3085
3086 if ( !$haveDiff3 ) {
3087 wfDebug( "diff3 not found\n" );
3088 return false;
3089 }
3090
3091 # Make temporary files
3092 $td = wfTempDir();
3093 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3094 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3095 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3096
3097 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3098 # a newline character. To avoid this, we normalize the trailing whitespace before
3099 # creating the diff.
3100
3101 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3102 fclose( $oldtextFile );
3103 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3104 fclose( $mytextFile );
3105 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3106 fclose( $yourtextFile );
3107
3108 # Check for a conflict
3109 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '--overlap-only', $mytextName, $oldtextName, $yourtextName );
3110 $handle = popen( $cmd, 'r' );
3111
3112 if ( fgets( $handle, 1024 ) ) {
3113 $conflict = true;
3114 } else {
3115 $conflict = false;
3116 }
3117 pclose( $handle );
3118
3119 # Merge differences
3120 $cmd = wfEscapeShellArg( $wgDiff3, '-a', '-e', '--merge', $mytextName, $oldtextName, $yourtextName );
3121 $handle = popen( $cmd, 'r' );
3122 $result = '';
3123 do {
3124 $data = fread( $handle, 8192 );
3125 if ( strlen( $data ) == 0 ) {
3126 break;
3127 }
3128 $result .= $data;
3129 } while ( true );
3130 pclose( $handle );
3131 unlink( $mytextName );
3132 unlink( $oldtextName );
3133 unlink( $yourtextName );
3134
3135 if ( $result === '' && $old !== '' && !$conflict ) {
3136 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3137 $conflict = true;
3138 }
3139 return !$conflict;
3140 }
3141
3142 /**
3143 * Returns unified plain-text diff of two texts.
3144 * Useful for machine processing of diffs.
3145 *
3146 * @param string $before The text before the changes.
3147 * @param string $after The text after the changes.
3148 * @param string $params Command-line options for the diff command.
3149 * @return string Unified diff of $before and $after
3150 */
3151 function wfDiff( $before, $after, $params = '-u' ) {
3152 if ( $before == $after ) {
3153 return '';
3154 }
3155
3156 global $wgDiff;
3157 wfSuppressWarnings();
3158 $haveDiff = $wgDiff && file_exists( $wgDiff );
3159 wfRestoreWarnings();
3160
3161 # This check may also protect against code injection in
3162 # case of broken installations.
3163 if ( !$haveDiff ) {
3164 wfDebug( "diff executable not found\n" );
3165 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3166 $format = new UnifiedDiffFormatter();
3167 return $format->format( $diffs );
3168 }
3169
3170 # Make temporary files
3171 $td = wfTempDir();
3172 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3173 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3174
3175 fwrite( $oldtextFile, $before );
3176 fclose( $oldtextFile );
3177 fwrite( $newtextFile, $after );
3178 fclose( $newtextFile );
3179
3180 // Get the diff of the two files
3181 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3182
3183 $h = popen( $cmd, 'r' );
3184
3185 $diff = '';
3186
3187 do {
3188 $data = fread( $h, 8192 );
3189 if ( strlen( $data ) == 0 ) {
3190 break;
3191 }
3192 $diff .= $data;
3193 } while ( true );
3194
3195 // Clean up
3196 pclose( $h );
3197 unlink( $oldtextName );
3198 unlink( $newtextName );
3199
3200 // Kill the --- and +++ lines. They're not useful.
3201 $diff_lines = explode( "\n", $diff );
3202 if ( isset( $diff_lines[0] ) && strpos( $diff_lines[0], '---' ) === 0 ) {
3203 unset( $diff_lines[0] );
3204 }
3205 if ( isset( $diff_lines[1] ) && strpos( $diff_lines[1], '+++' ) === 0 ) {
3206 unset( $diff_lines[1] );
3207 }
3208
3209 $diff = implode( "\n", $diff_lines );
3210
3211 return $diff;
3212 }
3213
3214 /**
3215 * This function works like "use VERSION" in Perl, the program will die with a
3216 * backtrace if the current version of PHP is less than the version provided
3217 *
3218 * This is useful for extensions which due to their nature are not kept in sync
3219 * with releases, and might depend on other versions of PHP than the main code
3220 *
3221 * Note: PHP might die due to parsing errors in some cases before it ever
3222 * manages to call this function, such is life
3223 *
3224 * @see perldoc -f use
3225 *
3226 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3227 * @throws MWException
3228 */
3229 function wfUsePHP( $req_ver ) {
3230 $php_ver = PHP_VERSION;
3231
3232 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3233 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3234 }
3235 }
3236
3237 /**
3238 * This function works like "use VERSION" in Perl except it checks the version
3239 * of MediaWiki, the program will die with a backtrace if the current version
3240 * of MediaWiki is less than the version provided.
3241 *
3242 * This is useful for extensions which due to their nature are not kept in sync
3243 * with releases
3244 *
3245 * Note: Due to the behavior of PHP's version_compare() which is used in this
3246 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3247 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3248 * targeted version number. For example if you wanted to allow any variation
3249 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3250 * not result in the same comparison due to the internal logic of
3251 * version_compare().
3252 *
3253 * @see perldoc -f use
3254 *
3255 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3256 * @throws MWException
3257 */
3258 function wfUseMW( $req_ver ) {
3259 global $wgVersion;
3260
3261 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3262 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3263 }
3264 }
3265
3266 /**
3267 * Return the final portion of a pathname.
3268 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3269 * http://bugs.php.net/bug.php?id=33898
3270 *
3271 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3272 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3273 *
3274 * @param string $path
3275 * @param string $suffix String to remove if present
3276 * @return string
3277 */
3278 function wfBaseName( $path, $suffix = '' ) {
3279 if ( $suffix == '' ) {
3280 $encSuffix = '';
3281 } else {
3282 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3283 }
3284
3285 $matches = array();
3286 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3287 return $matches[1];
3288 } else {
3289 return '';
3290 }
3291 }
3292
3293 /**
3294 * Generate a relative path name to the given file.
3295 * May explode on non-matching case-insensitive paths,
3296 * funky symlinks, etc.
3297 *
3298 * @param string $path Absolute destination path including target filename
3299 * @param string $from Absolute source path, directory only
3300 * @return string
3301 */
3302 function wfRelativePath( $path, $from ) {
3303 // Normalize mixed input on Windows...
3304 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
3305 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
3306
3307 // Trim trailing slashes -- fix for drive root
3308 $path = rtrim( $path, DIRECTORY_SEPARATOR );
3309 $from = rtrim( $from, DIRECTORY_SEPARATOR );
3310
3311 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
3312 $against = explode( DIRECTORY_SEPARATOR, $from );
3313
3314 if ( $pieces[0] !== $against[0] ) {
3315 // Non-matching Windows drive letters?
3316 // Return a full path.
3317 return $path;
3318 }
3319
3320 // Trim off common prefix
3321 while ( count( $pieces ) && count( $against )
3322 && $pieces[0] == $against[0] ) {
3323 array_shift( $pieces );
3324 array_shift( $against );
3325 }
3326
3327 // relative dots to bump us to the parent
3328 while ( count( $against ) ) {
3329 array_unshift( $pieces, '..' );
3330 array_shift( $against );
3331 }
3332
3333 array_push( $pieces, wfBaseName( $path ) );
3334
3335 return implode( DIRECTORY_SEPARATOR, $pieces );
3336 }
3337
3338 /**
3339 * Convert an arbitrarily-long digit string from one numeric base
3340 * to another, optionally zero-padding to a minimum column width.
3341 *
3342 * Supports base 2 through 36; digit values 10-36 are represented
3343 * as lowercase letters a-z. Input is case-insensitive.
3344 *
3345 * @param string $input Input number
3346 * @param int $sourceBase Base of the input number
3347 * @param int $destBase Desired base of the output
3348 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3349 * @param bool $lowercase Whether to output in lowercase or uppercase
3350 * @param string $engine Either "gmp", "bcmath", or "php"
3351 * @return string|bool The output number as a string, or false on error
3352 */
3353 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3354 $lowercase = true, $engine = 'auto'
3355 ) {
3356 $input = (string)$input;
3357 if (
3358 $sourceBase < 2 ||
3359 $sourceBase > 36 ||
3360 $destBase < 2 ||
3361 $destBase > 36 ||
3362 $sourceBase != (int)$sourceBase ||
3363 $destBase != (int)$destBase ||
3364 $pad != (int)$pad ||
3365 !preg_match(
3366 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3367 $input
3368 )
3369 ) {
3370 return false;
3371 }
3372
3373 static $baseChars = array(
3374 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3375 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3376 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3377 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3378 34 => 'y', 35 => 'z',
3379
3380 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3381 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3382 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3383 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3384 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3385 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3386 );
3387
3388 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' || $engine == 'gmp' ) ) {
3389 // Removing leading zeros works around broken base detection code in
3390 // some PHP versions (see <https://bugs.php.net/bug.php?id=50175> and
3391 // <https://bugs.php.net/bug.php?id=55398>).
3392 $result = gmp_strval( gmp_init( ltrim( $input, '0' ), $sourceBase ), $destBase );
3393 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' || $engine == 'bcmath' ) ) {
3394 $decimal = '0';
3395 foreach ( str_split( strtolower( $input ) ) as $char ) {
3396 $decimal = bcmul( $decimal, $sourceBase );
3397 $decimal = bcadd( $decimal, $baseChars[$char] );
3398 }
3399
3400 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3401 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3402 $result .= $baseChars[bcmod( $decimal, $destBase )];
3403 }
3404 // @codingStandardsIgnoreEnd
3405
3406 $result = strrev( $result );
3407 } else {
3408 $inDigits = array();
3409 foreach ( str_split( strtolower( $input ) ) as $char ) {
3410 $inDigits[] = $baseChars[$char];
3411 }
3412
3413 // Iterate over the input, modulo-ing out an output digit
3414 // at a time until input is gone.
3415 $result = '';
3416 while ( $inDigits ) {
3417 $work = 0;
3418 $workDigits = array();
3419
3420 // Long division...
3421 foreach ( $inDigits as $digit ) {
3422 $work *= $sourceBase;
3423 $work += $digit;
3424
3425 if ( $workDigits || $work >= $destBase ) {
3426 $workDigits[] = (int)( $work / $destBase );
3427 }
3428 $work %= $destBase;
3429 }
3430
3431 // All that division leaves us with a remainder,
3432 // which is conveniently our next output digit.
3433 $result .= $baseChars[$work];
3434
3435 // And we continue!
3436 $inDigits = $workDigits;
3437 }
3438
3439 $result = strrev( $result );
3440 }
3441
3442 if ( !$lowercase ) {
3443 $result = strtoupper( $result );
3444 }
3445
3446 return str_pad( $result, $pad, '0', STR_PAD_LEFT );
3447 }
3448
3449 /**
3450 * Check if there is sufficient entropy in php's built-in session generation
3451 *
3452 * @return bool True = there is sufficient entropy
3453 */
3454 function wfCheckEntropy() {
3455 return (
3456 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
3457 || ini_get( 'session.entropy_file' )
3458 )
3459 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3460 }
3461
3462 /**
3463 * Override session_id before session startup if php's built-in
3464 * session generation code is not secure.
3465 */
3466 function wfFixSessionID() {
3467 // If the cookie or session id is already set we already have a session and should abort
3468 if ( isset( $_COOKIE[session_name()] ) || session_id() ) {
3469 return;
3470 }
3471
3472 // PHP's built-in session entropy is enabled if:
3473 // - entropy_file is set or you're on Windows with php 5.3.3+
3474 // - AND entropy_length is > 0
3475 // We treat it as disabled if it doesn't have an entropy length of at least 32
3476 $entropyEnabled = wfCheckEntropy();
3477
3478 // If built-in entropy is not enabled or not sufficient override PHP's
3479 // built in session id generation code
3480 if ( !$entropyEnabled ) {
3481 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, " .
3482 "overriding session id generation using our cryptrand source.\n" );
3483 session_id( MWCryptRand::generateHex( 32 ) );
3484 }
3485 }
3486
3487 /**
3488 * Reset the session_id
3489 *
3490 * @since 1.22
3491 */
3492 function wfResetSessionID() {
3493 global $wgCookieSecure;
3494 $oldSessionId = session_id();
3495 $cookieParams = session_get_cookie_params();
3496 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3497 session_regenerate_id( false );
3498 } else {
3499 $tmp = $_SESSION;
3500 session_destroy();
3501 wfSetupSession( MWCryptRand::generateHex( 32 ) );
3502 $_SESSION = $tmp;
3503 }
3504 $newSessionId = session_id();
3505 Hooks::run( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3506 }
3507
3508 /**
3509 * Initialise php session
3510 *
3511 * @param bool $sessionId
3512 */
3513 function wfSetupSession( $sessionId = false ) {
3514 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3515 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3516 if ( $wgSessionsInObjectCache || $wgSessionsInMemcached ) {
3517 ObjectCacheSessionHandler::install();
3518 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3519 # Only set this if $wgSessionHandler isn't null and session.save_handler
3520 # hasn't already been set to the desired value (that causes errors)
3521 ini_set( 'session.save_handler', $wgSessionHandler );
3522 }
3523 session_set_cookie_params(
3524 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3525 session_cache_limiter( 'private, must-revalidate' );
3526 if ( $sessionId ) {
3527 session_id( $sessionId );
3528 } else {
3529 wfFixSessionID();
3530 }
3531 wfSuppressWarnings();
3532 session_start();
3533 wfRestoreWarnings();
3534 }
3535
3536 /**
3537 * Get an object from the precompiled serialized directory
3538 *
3539 * @param string $name
3540 * @return mixed The variable on success, false on failure
3541 */
3542 function wfGetPrecompiledData( $name ) {
3543 global $IP;
3544
3545 $file = "$IP/serialized/$name";
3546 if ( file_exists( $file ) ) {
3547 $blob = file_get_contents( $file );
3548 if ( $blob ) {
3549 return unserialize( $blob );
3550 }
3551 }
3552 return false;
3553 }
3554
3555 /**
3556 * Get a cache key
3557 *
3558 * @param string $args,...
3559 * @return string
3560 */
3561 function wfMemcKey( /*...*/ ) {
3562 global $wgCachePrefix;
3563 $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix;
3564 $args = func_get_args();
3565 $key = $prefix . ':' . implode( ':', $args );
3566 $key = str_replace( ' ', '_', $key );
3567 return $key;
3568 }
3569
3570 /**
3571 * Get a cache key for a foreign DB
3572 *
3573 * @param string $db
3574 * @param string $prefix
3575 * @param string $args,...
3576 * @return string
3577 */
3578 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3579 $args = array_slice( func_get_args(), 2 );
3580 if ( $prefix ) {
3581 $key = "$db-$prefix:" . implode( ':', $args );
3582 } else {
3583 $key = $db . ':' . implode( ':', $args );
3584 }
3585 return str_replace( ' ', '_', $key );
3586 }
3587
3588 /**
3589 * Get an ASCII string identifying this wiki
3590 * This is used as a prefix in memcached keys
3591 *
3592 * @return string
3593 */
3594 function wfWikiID() {
3595 global $wgDBprefix, $wgDBname;
3596 if ( $wgDBprefix ) {
3597 return "$wgDBname-$wgDBprefix";
3598 } else {
3599 return $wgDBname;
3600 }
3601 }
3602
3603 /**
3604 * Split a wiki ID into DB name and table prefix
3605 *
3606 * @param string $wiki
3607 *
3608 * @return array
3609 */
3610 function wfSplitWikiID( $wiki ) {
3611 $bits = explode( '-', $wiki, 2 );
3612 if ( count( $bits ) < 2 ) {
3613 $bits[] = '';
3614 }
3615 return $bits;
3616 }
3617
3618 /**
3619 * Get a Database object.
3620 *
3621 * @param int $db Index of the connection to get. May be DB_MASTER for the
3622 * master (for write queries), DB_SLAVE for potentially lagged read
3623 * queries, or an integer >= 0 for a particular server.
3624 *
3625 * @param string|string[] $groups Query groups. An array of group names that this query
3626 * belongs to. May contain a single string if the query is only
3627 * in one group.
3628 *
3629 * @param string|bool $wiki The wiki ID, or false for the current wiki
3630 *
3631 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3632 * will always return the same object, unless the underlying connection or load
3633 * balancer is manually destroyed.
3634 *
3635 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3636 * updater to ensure that a proper database is being updated.
3637 *
3638 * @return DatabaseBase
3639 */
3640 function wfGetDB( $db, $groups = array(), $wiki = false ) {
3641 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3642 }
3643
3644 /**
3645 * Get a load balancer object.
3646 *
3647 * @param string|bool $wiki Wiki ID, or false for the current wiki
3648 * @return LoadBalancer
3649 */
3650 function wfGetLB( $wiki = false ) {
3651 return wfGetLBFactory()->getMainLB( $wiki );
3652 }
3653
3654 /**
3655 * Get the load balancer factory object
3656 *
3657 * @return LBFactory
3658 */
3659 function wfGetLBFactory() {
3660 return LBFactory::singleton();
3661 }
3662
3663 /**
3664 * Find a file.
3665 * Shortcut for RepoGroup::singleton()->findFile()
3666 *
3667 * @param string $title String or Title object
3668 * @param array $options Associative array of options (see RepoGroup::findFile)
3669 * @return File|bool File, or false if the file does not exist
3670 */
3671 function wfFindFile( $title, $options = array() ) {
3672 return RepoGroup::singleton()->findFile( $title, $options );
3673 }
3674
3675 /**
3676 * Get an object referring to a locally registered file.
3677 * Returns a valid placeholder object if the file does not exist.
3678 *
3679 * @param Title|string $title
3680 * @return LocalFile|null A File, or null if passed an invalid Title
3681 */
3682 function wfLocalFile( $title ) {
3683 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3684 }
3685
3686 /**
3687 * Should low-performance queries be disabled?
3688 *
3689 * @return bool
3690 * @codeCoverageIgnore
3691 */
3692 function wfQueriesMustScale() {
3693 global $wgMiserMode;
3694 return $wgMiserMode
3695 || ( SiteStats::pages() > 100000
3696 && SiteStats::edits() > 1000000
3697 && SiteStats::users() > 10000 );
3698 }
3699
3700 /**
3701 * Get the path to a specified script file, respecting file
3702 * extensions; this is a wrapper around $wgScriptExtension etc.
3703 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3704 *
3705 * @param string $script Script filename, sans extension
3706 * @return string
3707 */
3708 function wfScript( $script = 'index' ) {
3709 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3710 if ( $script === 'index' ) {
3711 return $wgScript;
3712 } elseif ( $script === 'load' ) {
3713 return $wgLoadScript;
3714 } else {
3715 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3716 }
3717 }
3718
3719 /**
3720 * Get the script URL.
3721 *
3722 * @return string Script URL
3723 */
3724 function wfGetScriptUrl() {
3725 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3726 #
3727 # as it was called, minus the query string.
3728 #
3729 # Some sites use Apache rewrite rules to handle subdomains,
3730 # and have PHP set up in a weird way that causes PHP_SELF
3731 # to contain the rewritten URL instead of the one that the
3732 # outside world sees.
3733 #
3734 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3735 # provides containing the "before" URL.
3736 return $_SERVER['SCRIPT_NAME'];
3737 } else {
3738 return $_SERVER['URL'];
3739 }
3740 }
3741
3742 /**
3743 * Convenience function converts boolean values into "true"
3744 * or "false" (string) values
3745 *
3746 * @param bool $value
3747 * @return string
3748 */
3749 function wfBoolToStr( $value ) {
3750 return $value ? 'true' : 'false';
3751 }
3752
3753 /**
3754 * Get a platform-independent path to the null file, e.g. /dev/null
3755 *
3756 * @return string
3757 */
3758 function wfGetNull() {
3759 return wfIsWindows() ? 'NUL' : '/dev/null';
3760 }
3761
3762 /**
3763 * Waits for the slaves to catch up to the master position
3764 *
3765 * Use this when updating very large numbers of rows, as in maintenance scripts,
3766 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
3767 *
3768 * By default this waits on the main DB cluster of the current wiki.
3769 * If $cluster is set to "*" it will wait on all DB clusters, including
3770 * external ones. If the lag being waiting on is caused by the code that
3771 * does this check, it makes since to use $ifWritesSince, particularly if
3772 * cluster is "*", to avoid excess overhead.
3773 *
3774 * Never call this function after a big DB write that is still in a transaction.
3775 * This only makes sense after the possible lag inducing changes were committed.
3776 *
3777 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3778 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3779 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3780 * @param int|null $timeout Max wait time. Default: 1 day (cli), ~10 seconds (web)
3781 * @return bool Success (able to connect and no timeouts reached)
3782 */
3783 function wfWaitForSlaves(
3784 $ifWritesSince = null, $wiki = false, $cluster = false, $timeout = null
3785 ) {
3786 // B/C: first argument used to be "max seconds of lag"; ignore such values
3787 $ifWritesSince = ( $ifWritesSince > 1e9 ) ? $ifWritesSince : null;
3788
3789 if ( $timeout === null ) {
3790 $timeout = ( PHP_SAPI === 'cli' ) ? 86400 : 10;
3791 }
3792
3793 // Figure out which clusters need to be checked
3794 $lbs = array();
3795 if ( $cluster === '*' ) {
3796 wfGetLBFactory()->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
3797 $lbs[] = $lb;
3798 } );
3799 } elseif ( $cluster !== false ) {
3800 $lbs[] = wfGetLBFactory()->getExternalLB( $cluster );
3801 } else {
3802 $lbs[] = wfGetLB( $wiki );
3803 }
3804
3805 // Get all the master positions of applicable DBs right now.
3806 // This can be faster since waiting on one cluster reduces the
3807 // time needed to wait on the next clusters.
3808 $masterPositions = array_fill( 0, count( $lbs ), false );
3809 foreach ( $lbs as $i => $lb ) {
3810 // bug 27975 - Don't try to wait for slaves if there are none
3811 // Prevents permission error when getting master position
3812 if ( $lb->getServerCount() > 1 ) {
3813 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3814 continue; // assume no writes done
3815 }
3816 // Use the empty string to not trigger selectDB() since the connection
3817 // may have been to a server that does not have a DB for the current wiki.
3818 $dbw = $lb->getConnection( DB_MASTER, array(), '' );
3819 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3820 continue; // no writes since the last wait
3821 }
3822 $masterPositions[$i] = $dbw->getMasterPos();
3823 }
3824 }
3825
3826 $ok = true;
3827 foreach ( $lbs as $i => $lb ) {
3828 if ( $masterPositions[$i] ) {
3829 // The DBMS may not support getMasterPos() or the whole
3830 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3831 $ok = $lb->waitForAll( $masterPositions[$i], $timeout ) && $ok;
3832 }
3833 }
3834
3835 return $ok;
3836 }
3837
3838 /**
3839 * Count down from $seconds to zero on the terminal, with a one-second pause
3840 * between showing each number. For use in command-line scripts.
3841 *
3842 * @codeCoverageIgnore
3843 * @param int $seconds
3844 */
3845 function wfCountDown( $seconds ) {
3846 for ( $i = $seconds; $i >= 0; $i-- ) {
3847 if ( $i != $seconds ) {
3848 echo str_repeat( "\x08", strlen( $i + 1 ) );
3849 }
3850 echo $i;
3851 flush();
3852 if ( $i ) {
3853 sleep( 1 );
3854 }
3855 }
3856 echo "\n";
3857 }
3858
3859 /**
3860 * Replace all invalid characters with -
3861 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3862 * By default, $wgIllegalFileChars = ':'
3863 *
3864 * @param string $name Filename to process
3865 * @return string
3866 */
3867 function wfStripIllegalFilenameChars( $name ) {
3868 global $wgIllegalFileChars;
3869 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
3870 $name = wfBaseName( $name );
3871 $name = preg_replace(
3872 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
3873 '-',
3874 $name
3875 );
3876 return $name;
3877 }
3878
3879 /**
3880 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3881 *
3882 * @return int Value the memory limit was set to.
3883 */
3884 function wfMemoryLimit() {
3885 global $wgMemoryLimit;
3886 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3887 if ( $memlimit != -1 ) {
3888 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3889 if ( $conflimit == -1 ) {
3890 wfDebug( "Removing PHP's memory limit\n" );
3891 wfSuppressWarnings();
3892 ini_set( 'memory_limit', $conflimit );
3893 wfRestoreWarnings();
3894 return $conflimit;
3895 } elseif ( $conflimit > $memlimit ) {
3896 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3897 wfSuppressWarnings();
3898 ini_set( 'memory_limit', $conflimit );
3899 wfRestoreWarnings();
3900 return $conflimit;
3901 }
3902 }
3903 return $memlimit;
3904 }
3905
3906 /**
3907 * Converts shorthand byte notation to integer form
3908 *
3909 * @param string $string
3910 * @return int
3911 */
3912 function wfShorthandToInteger( $string = '' ) {
3913 $string = trim( $string );
3914 if ( $string === '' ) {
3915 return -1;
3916 }
3917 $last = $string[strlen( $string ) - 1];
3918 $val = intval( $string );
3919 switch ( $last ) {
3920 case 'g':
3921 case 'G':
3922 $val *= 1024;
3923 // break intentionally missing
3924 case 'm':
3925 case 'M':
3926 $val *= 1024;
3927 // break intentionally missing
3928 case 'k':
3929 case 'K':
3930 $val *= 1024;
3931 }
3932
3933 return $val;
3934 }
3935
3936 /**
3937 * Get the normalised IETF language tag
3938 * See unit test for examples.
3939 *
3940 * @param string $code The language code.
3941 * @return string The language code which complying with BCP 47 standards.
3942 */
3943 function wfBCP47( $code ) {
3944 $codeSegment = explode( '-', $code );
3945 $codeBCP = array();
3946 foreach ( $codeSegment as $segNo => $seg ) {
3947 // when previous segment is x, it is a private segment and should be lc
3948 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3949 $codeBCP[$segNo] = strtolower( $seg );
3950 // ISO 3166 country code
3951 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3952 $codeBCP[$segNo] = strtoupper( $seg );
3953 // ISO 15924 script code
3954 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3955 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3956 // Use lowercase for other cases
3957 } else {
3958 $codeBCP[$segNo] = strtolower( $seg );
3959 }
3960 }
3961 $langCode = implode( '-', $codeBCP );
3962 return $langCode;
3963 }
3964
3965 /**
3966 * Get a cache object.
3967 *
3968 * @param int $inputType Cache type, one of the CACHE_* constants.
3969 * @return BagOStuff
3970 */
3971 function wfGetCache( $inputType ) {
3972 return ObjectCache::getInstance( $inputType );
3973 }
3974
3975 /**
3976 * Get the main cache object
3977 *
3978 * @return BagOStuff
3979 */
3980 function wfGetMainCache() {
3981 global $wgMainCacheType;
3982 return ObjectCache::getInstance( $wgMainCacheType );
3983 }
3984
3985 /**
3986 * Get the cache object used by the message cache
3987 *
3988 * @return BagOStuff
3989 */
3990 function wfGetMessageCacheStorage() {
3991 global $wgMessageCacheType;
3992 return ObjectCache::getInstance( $wgMessageCacheType );
3993 }
3994
3995 /**
3996 * Get the cache object used by the parser cache
3997 *
3998 * @return BagOStuff
3999 */
4000 function wfGetParserCacheStorage() {
4001 global $wgParserCacheType;
4002 return ObjectCache::getInstance( $wgParserCacheType );
4003 }
4004
4005 /**
4006 * Call hook functions defined in $wgHooks
4007 *
4008 * @param string $event Event name
4009 * @param array $args Parameters passed to hook functions
4010 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
4011 *
4012 * @return bool True if no handler aborted the hook
4013 * @deprecated 1.25 - use Hooks::run
4014 */
4015 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
4016 return Hooks::run( $event, $args, $deprecatedVersion );
4017 }
4018
4019 /**
4020 * Wrapper around php's unpack.
4021 *
4022 * @param string $format The format string (See php's docs)
4023 * @param string $data A binary string of binary data
4024 * @param int|bool $length The minimum length of $data or false. This is to
4025 * prevent reading beyond the end of $data. false to disable the check.
4026 *
4027 * Also be careful when using this function to read unsigned 32 bit integer
4028 * because php might make it negative.
4029 *
4030 * @throws MWException If $data not long enough, or if unpack fails
4031 * @return array Associative array of the extracted data
4032 */
4033 function wfUnpack( $format, $data, $length = false ) {
4034 if ( $length !== false ) {
4035 $realLen = strlen( $data );
4036 if ( $realLen < $length ) {
4037 throw new MWException( "Tried to use wfUnpack on a "
4038 . "string of length $realLen, but needed one "
4039 . "of at least length $length."
4040 );
4041 }
4042 }
4043
4044 wfSuppressWarnings();
4045 $result = unpack( $format, $data );
4046 wfRestoreWarnings();
4047
4048 if ( $result === false ) {
4049 // If it cannot extract the packed data.
4050 throw new MWException( "unpack could not unpack binary data" );
4051 }
4052 return $result;
4053 }
4054
4055 /**
4056 * Determine if an image exists on the 'bad image list'.
4057 *
4058 * The format of MediaWiki:Bad_image_list is as follows:
4059 * * Only list items (lines starting with "*") are considered
4060 * * The first link on a line must be a link to a bad image
4061 * * Any subsequent links on the same line are considered to be exceptions,
4062 * i.e. articles where the image may occur inline.
4063 *
4064 * @param string $name The image name to check
4065 * @param Title|bool $contextTitle The page on which the image occurs, if known
4066 * @param string $blacklist Wikitext of a file blacklist
4067 * @return bool
4068 */
4069 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4070 static $badImageCache = null; // based on bad_image_list msg
4071
4072 # Handle redirects
4073 $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) );
4074 if ( $redirectTitle ) {
4075 $name = $redirectTitle->getDBkey();
4076 }
4077
4078 # Run the extension hook
4079 $bad = false;
4080 if ( !Hooks::run( 'BadImage', array( $name, &$bad ) ) ) {
4081 return $bad;
4082 }
4083
4084 $cacheable = ( $blacklist === null );
4085 if ( $cacheable && $badImageCache !== null ) {
4086 $badImages = $badImageCache;
4087 } else { // cache miss
4088 if ( $blacklist === null ) {
4089 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4090 }
4091 # Build the list now
4092 $badImages = array();
4093 $lines = explode( "\n", $blacklist );
4094 foreach ( $lines as $line ) {
4095 # List items only
4096 if ( substr( $line, 0, 1 ) !== '*' ) {
4097 continue;
4098 }
4099
4100 # Find all links
4101 $m = array();
4102 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4103 continue;
4104 }
4105
4106 $exceptions = array();
4107 $imageDBkey = false;
4108 foreach ( $m[1] as $i => $titleText ) {
4109 $title = Title::newFromText( $titleText );
4110 if ( !is_null( $title ) ) {
4111 if ( $i == 0 ) {
4112 $imageDBkey = $title->getDBkey();
4113 } else {
4114 $exceptions[$title->getPrefixedDBkey()] = true;
4115 }
4116 }
4117 }
4118
4119 if ( $imageDBkey !== false ) {
4120 $badImages[$imageDBkey] = $exceptions;
4121 }
4122 }
4123 if ( $cacheable ) {
4124 $badImageCache = $badImages;
4125 }
4126 }
4127
4128 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
4129 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4130 return $bad;
4131 }
4132
4133 /**
4134 * Determine whether the client at a given source IP is likely to be able to
4135 * access the wiki via HTTPS.
4136 *
4137 * @param string $ip The IPv4/6 address in the normal human-readable form
4138 * @return bool
4139 */
4140 function wfCanIPUseHTTPS( $ip ) {
4141 $canDo = true;
4142 Hooks::run( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4143 return !!$canDo;
4144 }
4145
4146 /**
4147 * Work out the IP address based on various globals
4148 * For trusted proxies, use the XFF client IP (first of the chain)
4149 *
4150 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4151 * @return string
4152 */
4153 function wfGetIP() {
4154 wfDeprecated( __METHOD__, '1.19' );
4155 global $wgRequest;
4156 return $wgRequest->getIP();
4157 }
4158
4159 /**
4160 * Checks if an IP is a trusted proxy provider.
4161 * Useful to tell if X-Forwarded-For data is possibly bogus.
4162 * Squid cache servers for the site are whitelisted.
4163 * @deprecated Since 1.24, use IP::isTrustedProxy()
4164 *
4165 * @param string $ip
4166 * @return bool
4167 */
4168 function wfIsTrustedProxy( $ip ) {
4169 wfDeprecated( __METHOD__, '1.24' );
4170 return IP::isTrustedProxy( $ip );
4171 }
4172
4173 /**
4174 * Checks if an IP matches a proxy we've configured.
4175 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4176 *
4177 * @param string $ip
4178 * @return bool
4179 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4180 */
4181 function wfIsConfiguredProxy( $ip ) {
4182 wfDeprecated( __METHOD__, '1.24' );
4183 return IP::isConfiguredProxy( $ip );
4184 }
4185
4186 /**
4187 * Returns true if these thumbnail parameters match one that MediaWiki
4188 * requests from file description pages and/or parser output.
4189 *
4190 * $params is considered non-standard if they involve a non-standard
4191 * width or any non-default parameters aside from width and page number.
4192 * The number of possible files with standard parameters is far less than
4193 * that of all combinations; rate-limiting for them can thus be more generious.
4194 *
4195 * @param File $file
4196 * @param array $params
4197 * @return bool
4198 * @since 1.24 Moved from thumb.php to GlobalFunctions in 1.25
4199 */
4200 function wfThumbIsStandard( File $file, array $params ) {
4201 global $wgThumbLimits, $wgImageLimits, $wgResponsiveImages;
4202
4203 $multipliers = array( 1 );
4204 if ( $wgResponsiveImages ) {
4205 // These available sizes are hardcoded currently elsewhere in MediaWiki.
4206 // @see Linker::processResponsiveImages
4207 $multipliers[] = 1.5;
4208 $multipliers[] = 2;
4209 }
4210
4211 $handler = $file->getHandler();
4212 if ( !$handler || !isset( $params['width'] ) ) {
4213 return false;
4214 }
4215
4216 $basicParams = array();
4217 if ( isset( $params['page'] ) ) {
4218 $basicParams['page'] = $params['page'];
4219 }
4220
4221 $thumbLimits = array();
4222 $imageLimits = array();
4223 // Expand limits to account for multipliers
4224 foreach ( $multipliers as $multiplier ) {
4225 $thumbLimits = array_merge( $thumbLimits, array_map(
4226 function ( $width ) use ( $multiplier ) {
4227 return round( $width * $multiplier );
4228 }, $wgThumbLimits )
4229 );
4230 $imageLimits = array_merge( $imageLimits, array_map(
4231 function ( $pair ) use ( $multiplier ) {
4232 return array(
4233 round( $pair[0] * $multiplier ),
4234 round( $pair[1] * $multiplier ),
4235 );
4236 }, $wgImageLimits )
4237 );
4238 }
4239
4240 // Check if the width matches one of $wgThumbLimits
4241 if ( in_array( $params['width'], $thumbLimits ) ) {
4242 $normalParams = $basicParams + array( 'width' => $params['width'] );
4243 // Append any default values to the map (e.g. "lossy", "lossless", ...)
4244 $handler->normaliseParams( $file, $normalParams );
4245 } else {
4246 // If not, then check if the width matchs one of $wgImageLimits
4247 $match = false;
4248 foreach ( $imageLimits as $pair ) {
4249 $normalParams = $basicParams + array( 'width' => $pair[0], 'height' => $pair[1] );
4250 // Decide whether the thumbnail should be scaled on width or height.
4251 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
4252 $handler->normaliseParams( $file, $normalParams );
4253 // Check if this standard thumbnail size maps to the given width
4254 if ( $normalParams['width'] == $params['width'] ) {
4255 $match = true;
4256 break;
4257 }
4258 }
4259 if ( !$match ) {
4260 return false; // not standard for description pages
4261 }
4262 }
4263
4264 // Check that the given values for non-page, non-width, params are just defaults
4265 foreach ( $params as $key => $value ) {
4266 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
4267 return false;
4268 }
4269 }
4270
4271 return true;
4272 }