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