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