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