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