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