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