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