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