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