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