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