Fixed spacing
[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|string[] $cmd if string, a properly shell-escaped command line,
2789 * or an array of unescaped arguments, in which case each value will be escaped
2790 * Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
2791 * @param null|mixed &$retval Optional, will receive the program's exit code.
2792 * (non-zero is usually failure). If there is an error from
2793 * read, select, or proc_open(), this will be set to -1.
2794 * @param array $environ Optional environment variables which should be
2795 * added to the executed command environment.
2796 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
2797 * this overwrites the global wgMaxShell* limits.
2798 * @param array $options Array of options:
2799 * - duplicateStderr: Set this to true to duplicate stderr to stdout,
2800 * including errors from limit.sh
2801 *
2802 * @return string Collected stdout as a string
2803 */
2804 function wfShellExec( $cmd, &$retval = null, $environ = array(),
2805 $limits = array(), $options = array()
2806 ) {
2807 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime,
2808 $wgMaxShellWallClockTime, $wgShellCgroup;
2809
2810 $disabled = wfShellExecDisabled();
2811 if ( $disabled ) {
2812 $retval = 1;
2813 return $disabled == 'safemode' ?
2814 'Unable to run external programs in safe mode.' :
2815 'Unable to run external programs, proc_open() is disabled.';
2816 }
2817
2818 $includeStderr = isset( $options['duplicateStderr'] ) && $options['duplicateStderr'];
2819
2820 wfInitShellLocale();
2821
2822 $envcmd = '';
2823 foreach ( $environ as $k => $v ) {
2824 if ( wfIsWindows() ) {
2825 /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
2826 * appear in the environment variable, so we must use carat escaping as documented in
2827 * http://technet.microsoft.com/en-us/library/cc723564.aspx
2828 * Note however that the quote isn't listed there, but is needed, and the parentheses
2829 * are listed there but doesn't appear to need it.
2830 */
2831 $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
2832 } else {
2833 /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
2834 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
2835 */
2836 $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
2837 }
2838 }
2839 if ( is_array( $cmd ) ) {
2840 // Command line may be given as an array, escape each value and glue them together with a space
2841 $cmdVals = array();
2842 foreach ( $cmd as $val ) {
2843 $cmdVals[] = wfEscapeShellArg( $val );
2844 }
2845 $cmd = implode( ' ', $cmdVals );
2846 }
2847
2848 $cmd = $envcmd . $cmd;
2849
2850 $useLogPipe = false;
2851 if ( is_executable( '/bin/bash' ) ) {
2852 $time = intval ( isset( $limits['time'] ) ? $limits['time'] : $wgMaxShellTime );
2853 if ( isset( $limits['walltime'] ) ) {
2854 $wallTime = intval( $limits['walltime'] );
2855 } elseif ( isset( $limits['time'] ) ) {
2856 $wallTime = $time;
2857 } else {
2858 $wallTime = intval( $wgMaxShellWallClockTime );
2859 }
2860 $mem = intval ( isset( $limits['memory'] ) ? $limits['memory'] : $wgMaxShellMemory );
2861 $filesize = intval ( isset( $limits['filesize'] ) ? $limits['filesize'] : $wgMaxShellFileSize );
2862
2863 if ( $time > 0 || $mem > 0 || $filesize > 0 || $wallTime > 0 ) {
2864 $cmd = '/bin/bash ' . escapeshellarg( "$IP/includes/limit.sh" ) . ' ' .
2865 escapeshellarg( $cmd ) . ' ' .
2866 escapeshellarg(
2867 "MW_INCLUDE_STDERR=" . ( $includeStderr ? '1' : '' ) . ';' .
2868 "MW_CPU_LIMIT=$time; " .
2869 'MW_CGROUP=' . escapeshellarg( $wgShellCgroup ) . '; ' .
2870 "MW_MEM_LIMIT=$mem; " .
2871 "MW_FILE_SIZE_LIMIT=$filesize; " .
2872 "MW_WALL_CLOCK_LIMIT=$wallTime; " .
2873 "MW_USE_LOG_PIPE=yes"
2874 );
2875 $useLogPipe = true;
2876 } elseif ( $includeStderr ) {
2877 $cmd .= ' 2>&1';
2878 }
2879 } elseif ( $includeStderr ) {
2880 $cmd .= ' 2>&1';
2881 }
2882 wfDebug( "wfShellExec: $cmd\n" );
2883
2884 $desc = array(
2885 0 => array( 'file', 'php://stdin', 'r' ),
2886 1 => array( 'pipe', 'w' ),
2887 2 => array( 'file', 'php://stderr', 'w' ) );
2888 if ( $useLogPipe ) {
2889 $desc[3] = array( 'pipe', 'w' );
2890 }
2891 $pipes = null;
2892 $proc = proc_open( $cmd, $desc, $pipes );
2893 if ( !$proc ) {
2894 wfDebugLog( 'exec', "proc_open() failed: $cmd" );
2895 $retval = -1;
2896 return '';
2897 }
2898 $outBuffer = $logBuffer = '';
2899 $emptyArray = array();
2900 $status = false;
2901 $logMsg = false;
2902
2903 // According to the documentation, it is possible for stream_select()
2904 // to fail due to EINTR. I haven't managed to induce this in testing
2905 // despite sending various signals. If it did happen, the error
2906 // message would take the form:
2907 //
2908 // stream_select(): unable to select [4]: Interrupted system call (max_fd=5)
2909 //
2910 // where [4] is the value of the macro EINTR and "Interrupted system
2911 // call" is string which according to the Linux manual is "possibly"
2912 // localised according to LC_MESSAGES.
2913 $eintr = defined( 'SOCKET_EINTR' ) ? SOCKET_EINTR : 4;
2914 $eintrMessage = "stream_select(): unable to select [$eintr]";
2915
2916 // Build a table mapping resource IDs to pipe FDs to work around a
2917 // PHP 5.3 issue in which stream_select() does not preserve array keys
2918 // <https://bugs.php.net/bug.php?id=53427>.
2919 $fds = array();
2920 foreach ( $pipes as $fd => $pipe ) {
2921 $fds[(int)$pipe] = $fd;
2922 }
2923
2924 $running = true;
2925 $timeout = null;
2926 $numReadyPipes = 0;
2927
2928 while ( $running === true || $numReadyPipes !== 0 ) {
2929 if ( $running ) {
2930 $status = proc_get_status( $proc );
2931 // If the process has terminated, switch to nonblocking selects
2932 // for getting any data still waiting to be read.
2933 if ( !$status['running'] ) {
2934 $running = false;
2935 $timeout = 0;
2936 }
2937 }
2938
2939 $readyPipes = $pipes;
2940
2941 // Clear last error
2942 // @codingStandardsIgnoreStart Generic.PHP.NoSilencedErrors.Discouraged
2943 @trigger_error( '' );
2944 $numReadyPipes = @stream_select( $readyPipes, $emptyArray, $emptyArray, $timeout );
2945 if ( $numReadyPipes === false ) {
2946 // @codingStandardsIgnoreEnd
2947 $error = error_get_last();
2948 if ( strncmp( $error['message'], $eintrMessage, strlen( $eintrMessage ) ) == 0 ) {
2949 continue;
2950 } else {
2951 trigger_error( $error['message'], E_USER_WARNING );
2952 $logMsg = $error['message'];
2953 break;
2954 }
2955 }
2956 foreach ( $readyPipes as $pipe ) {
2957 $block = fread( $pipe, 65536 );
2958 $fd = $fds[(int)$pipe];
2959 if ( $block === '' ) {
2960 // End of file
2961 fclose( $pipes[$fd] );
2962 unset( $pipes[$fd] );
2963 if ( !$pipes ) {
2964 break 2;
2965 }
2966 } elseif ( $block === false ) {
2967 // Read error
2968 $logMsg = "Error reading from pipe";
2969 break 2;
2970 } elseif ( $fd == 1 ) {
2971 // From stdout
2972 $outBuffer .= $block;
2973 } elseif ( $fd == 3 ) {
2974 // From log FD
2975 $logBuffer .= $block;
2976 if ( strpos( $block, "\n" ) !== false ) {
2977 $lines = explode( "\n", $logBuffer );
2978 $logBuffer = array_pop( $lines );
2979 foreach ( $lines as $line ) {
2980 wfDebugLog( 'exec', $line );
2981 }
2982 }
2983 }
2984 }
2985 }
2986
2987 foreach ( $pipes as $pipe ) {
2988 fclose( $pipe );
2989 }
2990
2991 // Use the status previously collected if possible, since proc_get_status()
2992 // just calls waitpid() which will not return anything useful the second time.
2993 if ( $running ) {
2994 $status = proc_get_status( $proc );
2995 }
2996
2997 if ( $logMsg !== false ) {
2998 // Read/select error
2999 $retval = -1;
3000 proc_close( $proc );
3001 } elseif ( $status['signaled'] ) {
3002 $logMsg = "Exited with signal {$status['termsig']}";
3003 $retval = 128 + $status['termsig'];
3004 proc_close( $proc );
3005 } else {
3006 if ( $status['running'] ) {
3007 $retval = proc_close( $proc );
3008 } else {
3009 $retval = $status['exitcode'];
3010 proc_close( $proc );
3011 }
3012 if ( $retval == 127 ) {
3013 $logMsg = "Possibly missing executable file";
3014 } elseif ( $retval >= 129 && $retval <= 192 ) {
3015 $logMsg = "Probably exited with signal " . ( $retval - 128 );
3016 }
3017 }
3018
3019 if ( $logMsg !== false ) {
3020 wfDebugLog( 'exec', "$logMsg: $cmd" );
3021 }
3022
3023 return $outBuffer;
3024 }
3025
3026 /**
3027 * Execute a shell command, returning both stdout and stderr. Convenience
3028 * function, as all the arguments to wfShellExec can become unwieldy.
3029 *
3030 * @note This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
3031 * @param string $cmd Command line, properly escaped for shell.
3032 * @param null|mixed &$retval Optional, will receive the program's exit code.
3033 * (non-zero is usually failure)
3034 * @param array $environ optional environment variables which should be
3035 * added to the executed command environment.
3036 * @param array $limits Optional array with limits(filesize, memory, time, walltime)
3037 * this overwrites the global wgMaxShell* limits.
3038 * @return string Collected stdout and stderr as a string
3039 */
3040 function wfShellExecWithStderr( $cmd, &$retval = null, $environ = array(), $limits = array() ) {
3041 return wfShellExec( $cmd, $retval, $environ, $limits, array( 'duplicateStderr' => true ) );
3042 }
3043
3044 /**
3045 * Workaround for http://bugs.php.net/bug.php?id=45132
3046 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
3047 */
3048 function wfInitShellLocale() {
3049 static $done = false;
3050 if ( $done ) {
3051 return;
3052 }
3053 $done = true;
3054 global $wgShellLocale;
3055 if ( !wfIniGetBool( 'safe_mode' ) ) {
3056 putenv( "LC_CTYPE=$wgShellLocale" );
3057 setlocale( LC_CTYPE, $wgShellLocale );
3058 }
3059 }
3060
3061 /**
3062 * Alias to wfShellWikiCmd()
3063 *
3064 * @see wfShellWikiCmd()
3065 */
3066 function wfShellMaintenanceCmd( $script, array $parameters = array(), array $options = array() ) {
3067 return wfShellWikiCmd( $script, $parameters, $options );
3068 }
3069
3070 /**
3071 * Generate a shell-escaped command line string to run a MediaWiki cli script.
3072 * Note that $parameters should be a flat array and an option with an argument
3073 * should consist of two consecutive items in the array (do not use "--option value").
3074 *
3075 * @param string $script MediaWiki cli script path
3076 * @param array $parameters Arguments and options to the script
3077 * @param array $options Associative array of options:
3078 * 'php': The path to the php executable
3079 * 'wrapper': Path to a PHP wrapper to handle the maintenance script
3080 * @return string
3081 */
3082 function wfShellWikiCmd( $script, array $parameters = array(), array $options = array() ) {
3083 global $wgPhpCli;
3084 // Give site config file a chance to run the script in a wrapper.
3085 // The caller may likely want to call wfBasename() on $script.
3086 wfRunHooks( 'wfShellWikiCmd', array( &$script, &$parameters, &$options ) );
3087 $cmd = isset( $options['php'] ) ? array( $options['php'] ) : array( $wgPhpCli );
3088 if ( isset( $options['wrapper'] ) ) {
3089 $cmd[] = $options['wrapper'];
3090 }
3091 $cmd[] = $script;
3092 // Escape each parameter for shell
3093 return implode( " ", array_map( 'wfEscapeShellArg', array_merge( $cmd, $parameters ) ) );
3094 }
3095
3096 /**
3097 * wfMerge attempts to merge differences between three texts.
3098 * Returns true for a clean merge and false for failure or a conflict.
3099 *
3100 * @param string $old
3101 * @param string $mine
3102 * @param string $yours
3103 * @param string $result
3104 * @return bool
3105 */
3106 function wfMerge( $old, $mine, $yours, &$result ) {
3107 global $wgDiff3;
3108
3109 # This check may also protect against code injection in
3110 # case of broken installations.
3111 wfSuppressWarnings();
3112 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
3113 wfRestoreWarnings();
3114
3115 if ( !$haveDiff3 ) {
3116 wfDebug( "diff3 not found\n" );
3117 return false;
3118 }
3119
3120 # Make temporary files
3121 $td = wfTempDir();
3122 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3123 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
3124 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
3125
3126 # NOTE: diff3 issues a warning to stderr if any of the files does not end with
3127 # a newline character. To avoid this, we normalize the trailing whitespace before
3128 # creating the diff.
3129
3130 fwrite( $oldtextFile, rtrim( $old ) . "\n" );
3131 fclose( $oldtextFile );
3132 fwrite( $mytextFile, rtrim( $mine ) . "\n" );
3133 fclose( $mytextFile );
3134 fwrite( $yourtextFile, rtrim( $yours ) . "\n" );
3135 fclose( $yourtextFile );
3136
3137 # Check for a conflict
3138 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
3139 wfEscapeShellArg( $mytextName ) . ' ' .
3140 wfEscapeShellArg( $oldtextName ) . ' ' .
3141 wfEscapeShellArg( $yourtextName );
3142 $handle = popen( $cmd, 'r' );
3143
3144 if ( fgets( $handle, 1024 ) ) {
3145 $conflict = true;
3146 } else {
3147 $conflict = false;
3148 }
3149 pclose( $handle );
3150
3151 # Merge differences
3152 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
3153 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
3154 $handle = popen( $cmd, 'r' );
3155 $result = '';
3156 do {
3157 $data = fread( $handle, 8192 );
3158 if ( strlen( $data ) == 0 ) {
3159 break;
3160 }
3161 $result .= $data;
3162 } while ( true );
3163 pclose( $handle );
3164 unlink( $mytextName );
3165 unlink( $oldtextName );
3166 unlink( $yourtextName );
3167
3168 if ( $result === '' && $old !== '' && !$conflict ) {
3169 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
3170 $conflict = true;
3171 }
3172 return !$conflict;
3173 }
3174
3175 /**
3176 * Returns unified plain-text diff of two texts.
3177 * Useful for machine processing of diffs.
3178 *
3179 * @param string $before The text before the changes.
3180 * @param string $after The text after the changes.
3181 * @param string $params Command-line options for the diff command.
3182 * @return string Unified diff of $before and $after
3183 */
3184 function wfDiff( $before, $after, $params = '-u' ) {
3185 if ( $before == $after ) {
3186 return '';
3187 }
3188
3189 global $wgDiff;
3190 wfSuppressWarnings();
3191 $haveDiff = $wgDiff && file_exists( $wgDiff );
3192 wfRestoreWarnings();
3193
3194 # This check may also protect against code injection in
3195 # case of broken installations.
3196 if ( !$haveDiff ) {
3197 wfDebug( "diff executable not found\n" );
3198 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
3199 $format = new UnifiedDiffFormatter();
3200 return $format->format( $diffs );
3201 }
3202
3203 # Make temporary files
3204 $td = wfTempDir();
3205 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
3206 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
3207
3208 fwrite( $oldtextFile, $before );
3209 fclose( $oldtextFile );
3210 fwrite( $newtextFile, $after );
3211 fclose( $newtextFile );
3212
3213 // Get the diff of the two files
3214 $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
3215
3216 $h = popen( $cmd, 'r' );
3217
3218 $diff = '';
3219
3220 do {
3221 $data = fread( $h, 8192 );
3222 if ( strlen( $data ) == 0 ) {
3223 break;
3224 }
3225 $diff .= $data;
3226 } while ( true );
3227
3228 // Clean up
3229 pclose( $h );
3230 unlink( $oldtextName );
3231 unlink( $newtextName );
3232
3233 // Kill the --- and +++ lines. They're not useful.
3234 $diff_lines = explode( "\n", $diff );
3235 if ( strpos( $diff_lines[0], '---' ) === 0 ) {
3236 unset( $diff_lines[0] );
3237 }
3238 if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
3239 unset( $diff_lines[1] );
3240 }
3241
3242 $diff = implode( "\n", $diff_lines );
3243
3244 return $diff;
3245 }
3246
3247 /**
3248 * This function works like "use VERSION" in Perl, the program will die with a
3249 * backtrace if the current version of PHP is less than the version provided
3250 *
3251 * This is useful for extensions which due to their nature are not kept in sync
3252 * with releases, and might depend on other versions of PHP than the main code
3253 *
3254 * Note: PHP might die due to parsing errors in some cases before it ever
3255 * manages to call this function, such is life
3256 *
3257 * @see perldoc -f use
3258 *
3259 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3260 * @throws MWException
3261 */
3262 function wfUsePHP( $req_ver ) {
3263 $php_ver = PHP_VERSION;
3264
3265 if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
3266 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
3267 }
3268 }
3269
3270 /**
3271 * This function works like "use VERSION" in Perl except it checks the version
3272 * of MediaWiki, the program will die with a backtrace if the current version
3273 * of MediaWiki is less than the version provided.
3274 *
3275 * This is useful for extensions which due to their nature are not kept in sync
3276 * with releases
3277 *
3278 * Note: Due to the behavior of PHP's version_compare() which is used in this
3279 * function, if you want to allow the 'wmf' development versions add a 'c' (or
3280 * any single letter other than 'a', 'b' or 'p') as a post-fix to your
3281 * targeted version number. For example if you wanted to allow any variation
3282 * of 1.22 use `wfUseMW( '1.22c' )`. Using an 'a' or 'b' instead of 'c' will
3283 * not result in the same comparison due to the internal logic of
3284 * version_compare().
3285 *
3286 * @see perldoc -f use
3287 *
3288 * @param string|int|float $req_ver The version to check, can be a string, an integer, or a float
3289 * @throws MWException
3290 */
3291 function wfUseMW( $req_ver ) {
3292 global $wgVersion;
3293
3294 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
3295 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
3296 }
3297 }
3298
3299 /**
3300 * Return the final portion of a pathname.
3301 * Reimplemented because PHP5's "basename()" is buggy with multibyte text.
3302 * http://bugs.php.net/bug.php?id=33898
3303 *
3304 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
3305 * We'll consider it so always, as we don't want '\s' in our Unix paths either.
3306 *
3307 * @param string $path
3308 * @param string $suffix String to remove if present
3309 * @return string
3310 */
3311 function wfBaseName( $path, $suffix = '' ) {
3312 if ( $suffix == '' ) {
3313 $encSuffix = '';
3314 } else {
3315 $encSuffix = '(?:' . preg_quote( $suffix, '#' ) . ')?';
3316 }
3317
3318 $matches = array();
3319 if ( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
3320 return $matches[1];
3321 } else {
3322 return '';
3323 }
3324 }
3325
3326 /**
3327 * Generate a relative path name to the given file.
3328 * May explode on non-matching case-insensitive paths,
3329 * funky symlinks, etc.
3330 *
3331 * @param string $path Absolute destination path including target filename
3332 * @param string $from Absolute source path, directory only
3333 * @return string
3334 */
3335 function wfRelativePath( $path, $from ) {
3336 // Normalize mixed input on Windows...
3337 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
3338 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
3339
3340 // Trim trailing slashes -- fix for drive root
3341 $path = rtrim( $path, DIRECTORY_SEPARATOR );
3342 $from = rtrim( $from, DIRECTORY_SEPARATOR );
3343
3344 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
3345 $against = explode( DIRECTORY_SEPARATOR, $from );
3346
3347 if ( $pieces[0] !== $against[0] ) {
3348 // Non-matching Windows drive letters?
3349 // Return a full path.
3350 return $path;
3351 }
3352
3353 // Trim off common prefix
3354 while ( count( $pieces ) && count( $against )
3355 && $pieces[0] == $against[0] ) {
3356 array_shift( $pieces );
3357 array_shift( $against );
3358 }
3359
3360 // relative dots to bump us to the parent
3361 while ( count( $against ) ) {
3362 array_unshift( $pieces, '..' );
3363 array_shift( $against );
3364 }
3365
3366 array_push( $pieces, wfBaseName( $path ) );
3367
3368 return implode( DIRECTORY_SEPARATOR, $pieces );
3369 }
3370
3371 /**
3372 * Convert an arbitrarily-long digit string from one numeric base
3373 * to another, optionally zero-padding to a minimum column width.
3374 *
3375 * Supports base 2 through 36; digit values 10-36 are represented
3376 * as lowercase letters a-z. Input is case-insensitive.
3377 *
3378 * @param string $input Input number
3379 * @param int $sourceBase Base of the input number
3380 * @param int $destBase Desired base of the output
3381 * @param int $pad Minimum number of digits in the output (pad with zeroes)
3382 * @param bool $lowercase Whether to output in lowercase or uppercase
3383 * @param string $engine Either "gmp", "bcmath", or "php"
3384 * @return string|bool The output number as a string, or false on error
3385 */
3386 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1,
3387 $lowercase = true, $engine = 'auto'
3388 ) {
3389 $input = (string)$input;
3390 if (
3391 $sourceBase < 2 ||
3392 $sourceBase > 36 ||
3393 $destBase < 2 ||
3394 $destBase > 36 ||
3395 $sourceBase != (int)$sourceBase ||
3396 $destBase != (int)$destBase ||
3397 $pad != (int)$pad ||
3398 !preg_match(
3399 "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
3400 $input
3401 )
3402 ) {
3403 return false;
3404 }
3405
3406 static $baseChars = array(
3407 10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
3408 16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
3409 22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
3410 28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
3411 34 => 'y', 35 => 'z',
3412
3413 '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
3414 '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
3415 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
3416 'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
3417 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
3418 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
3419 );
3420
3421 if ( extension_loaded( 'gmp' ) && ( $engine == 'auto' || $engine == 'gmp' ) ) {
3422 $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
3423 } elseif ( extension_loaded( 'bcmath' ) && ( $engine == 'auto' || $engine == 'bcmath' ) ) {
3424 $decimal = '0';
3425 foreach ( str_split( strtolower( $input ) ) as $char ) {
3426 $decimal = bcmul( $decimal, $sourceBase );
3427 $decimal = bcadd( $decimal, $baseChars[$char] );
3428 }
3429
3430 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
3431 for ( $result = ''; bccomp( $decimal, 0 ); $decimal = bcdiv( $decimal, $destBase, 0 ) ) {
3432 $result .= $baseChars[bcmod( $decimal, $destBase )];
3433 }
3434 // @codingStandardsIgnoreEnd
3435
3436 $result = strrev( $result );
3437 } else {
3438 $inDigits = array();
3439 foreach ( str_split( strtolower( $input ) ) as $char ) {
3440 $inDigits[] = $baseChars[$char];
3441 }
3442
3443 // Iterate over the input, modulo-ing out an output digit
3444 // at a time until input is gone.
3445 $result = '';
3446 while ( $inDigits ) {
3447 $work = 0;
3448 $workDigits = array();
3449
3450 // Long division...
3451 foreach ( $inDigits as $digit ) {
3452 $work *= $sourceBase;
3453 $work += $digit;
3454
3455 if ( $workDigits || $work >= $destBase ) {
3456 $workDigits[] = (int)( $work / $destBase );
3457 }
3458 $work %= $destBase;
3459 }
3460
3461 // All that division leaves us with a remainder,
3462 // which is conveniently our next output digit.
3463 $result .= $baseChars[$work];
3464
3465 // And we continue!
3466 $inDigits = $workDigits;
3467 }
3468
3469 $result = strrev( $result );
3470 }
3471
3472 if ( !$lowercase ) {
3473 $result = strtoupper( $result );
3474 }
3475
3476 return str_pad( $result, $pad, '0', STR_PAD_LEFT );
3477 }
3478
3479 /**
3480 * Check if there is sufficient entropy in php's built-in session generation
3481 *
3482 * @return bool true = there is sufficient entropy
3483 */
3484 function wfCheckEntropy() {
3485 return (
3486 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
3487 || ini_get( 'session.entropy_file' )
3488 )
3489 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3490 }
3491
3492 /**
3493 * Override session_id before session startup if php's built-in
3494 * session generation code is not secure.
3495 */
3496 function wfFixSessionID() {
3497 // If the cookie or session id is already set we already have a session and should abort
3498 if ( isset( $_COOKIE[session_name()] ) || session_id() ) {
3499 return;
3500 }
3501
3502 // PHP's built-in session entropy is enabled if:
3503 // - entropy_file is set or you're on Windows with php 5.3.3+
3504 // - AND entropy_length is > 0
3505 // We treat it as disabled if it doesn't have an entropy length of at least 32
3506 $entropyEnabled = wfCheckEntropy();
3507
3508 // If built-in entropy is not enabled or not sufficient override PHP's
3509 // built in session id generation code
3510 if ( !$entropyEnabled ) {
3511 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, " .
3512 "overriding session id generation using our cryptrand source.\n" );
3513 session_id( MWCryptRand::generateHex( 32 ) );
3514 }
3515 }
3516
3517 /**
3518 * Reset the session_id
3519 *
3520 * @since 1.22
3521 */
3522 function wfResetSessionID() {
3523 global $wgCookieSecure;
3524 $oldSessionId = session_id();
3525 $cookieParams = session_get_cookie_params();
3526 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
3527 session_regenerate_id( false );
3528 } else {
3529 $tmp = $_SESSION;
3530 session_destroy();
3531 wfSetupSession( MWCryptRand::generateHex( 32 ) );
3532 $_SESSION = $tmp;
3533 }
3534 $newSessionId = session_id();
3535 wfRunHooks( 'ResetSessionID', array( $oldSessionId, $newSessionId ) );
3536 }
3537
3538 /**
3539 * Initialise php session
3540 *
3541 * @param bool $sessionId
3542 */
3543 function wfSetupSession( $sessionId = false ) {
3544 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3545 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3546 if ( $wgSessionsInObjectCache || $wgSessionsInMemcached ) {
3547 ObjectCacheSessionHandler::install();
3548 } elseif ( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3549 # Only set this if $wgSessionHandler isn't null and session.save_handler
3550 # hasn't already been set to the desired value (that causes errors)
3551 ini_set( 'session.save_handler', $wgSessionHandler );
3552 }
3553 session_set_cookie_params(
3554 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
3555 session_cache_limiter( 'private, must-revalidate' );
3556 if ( $sessionId ) {
3557 session_id( $sessionId );
3558 } else {
3559 wfFixSessionID();
3560 }
3561 wfSuppressWarnings();
3562 session_start();
3563 wfRestoreWarnings();
3564 }
3565
3566 /**
3567 * Get an object from the precompiled serialized directory
3568 *
3569 * @param string $name
3570 * @return mixed The variable on success, false on failure
3571 */
3572 function wfGetPrecompiledData( $name ) {
3573 global $IP;
3574
3575 $file = "$IP/serialized/$name";
3576 if ( file_exists( $file ) ) {
3577 $blob = file_get_contents( $file );
3578 if ( $blob ) {
3579 return unserialize( $blob );
3580 }
3581 }
3582 return false;
3583 }
3584
3585 /**
3586 * Get a cache key
3587 *
3588 * @param string [$args,...]
3589 * @return string
3590 */
3591 function wfMemcKey( /*...*/ ) {
3592 global $wgCachePrefix;
3593 $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix;
3594 $args = func_get_args();
3595 $key = $prefix . ':' . implode( ':', $args );
3596 $key = str_replace( ' ', '_', $key );
3597 return $key;
3598 }
3599
3600 /**
3601 * Get a cache key for a foreign DB
3602 *
3603 * @param string $db
3604 * @param string $prefix
3605 * @param string [$args,...]
3606 * @return string
3607 */
3608 function wfForeignMemcKey( $db, $prefix /*...*/ ) {
3609 $args = array_slice( func_get_args(), 2 );
3610 if ( $prefix ) {
3611 $key = "$db-$prefix:" . implode( ':', $args );
3612 } else {
3613 $key = $db . ':' . implode( ':', $args );
3614 }
3615 return str_replace( ' ', '_', $key );
3616 }
3617
3618 /**
3619 * Get an ASCII string identifying this wiki
3620 * This is used as a prefix in memcached keys
3621 *
3622 * @return string
3623 */
3624 function wfWikiID() {
3625 global $wgDBprefix, $wgDBname;
3626 if ( $wgDBprefix ) {
3627 return "$wgDBname-$wgDBprefix";
3628 } else {
3629 return $wgDBname;
3630 }
3631 }
3632
3633 /**
3634 * Split a wiki ID into DB name and table prefix
3635 *
3636 * @param string $wiki
3637 *
3638 * @return array
3639 */
3640 function wfSplitWikiID( $wiki ) {
3641 $bits = explode( '-', $wiki, 2 );
3642 if ( count( $bits ) < 2 ) {
3643 $bits[] = '';
3644 }
3645 return $bits;
3646 }
3647
3648 /**
3649 * Get a Database object.
3650 *
3651 * @param int $db Index of the connection to get. May be DB_MASTER for the
3652 * master (for write queries), DB_SLAVE for potentially lagged read
3653 * queries, or an integer >= 0 for a particular server.
3654 *
3655 * @param string|string[] $groups Query groups. An array of group names that this query
3656 * belongs to. May contain a single string if the query is only
3657 * in one group.
3658 *
3659 * @param string|bool $wiki The wiki ID, or false for the current wiki
3660 *
3661 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3662 * will always return the same object, unless the underlying connection or load
3663 * balancer is manually destroyed.
3664 *
3665 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3666 * updater to ensure that a proper database is being updated.
3667 *
3668 * @return DatabaseBase
3669 */
3670 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3671 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3672 }
3673
3674 /**
3675 * Get a load balancer object.
3676 *
3677 * @param string|bool $wiki wiki ID, or false for the current wiki
3678 * @return LoadBalancer
3679 */
3680 function wfGetLB( $wiki = false ) {
3681 return wfGetLBFactory()->getMainLB( $wiki );
3682 }
3683
3684 /**
3685 * Get the load balancer factory object
3686 *
3687 * @return LBFactory
3688 */
3689 function &wfGetLBFactory() {
3690 return LBFactory::singleton();
3691 }
3692
3693 /**
3694 * Find a file.
3695 * Shortcut for RepoGroup::singleton()->findFile()
3696 *
3697 * @param string $title or Title object
3698 * @param array $options Associative array of options:
3699 * time: requested time for an archived image, or false for the
3700 * current version. An image object will be returned which was
3701 * created at the specified time.
3702 *
3703 * ignoreRedirect: If true, do not follow file redirects
3704 *
3705 * private: If true, return restricted (deleted) files if the current
3706 * user is allowed to view them. Otherwise, such files will not
3707 * be found.
3708 *
3709 * bypassCache: If true, do not use the process-local cache of File objects
3710 *
3711 * @return File|bool File, or false if the file does not exist
3712 */
3713 function wfFindFile( $title, $options = array() ) {
3714 return RepoGroup::singleton()->findFile( $title, $options );
3715 }
3716
3717 /**
3718 * Get an object referring to a locally registered file.
3719 * Returns a valid placeholder object if the file does not exist.
3720 *
3721 * @param Title|string $title
3722 * @return LocalFile|null A File, or null if passed an invalid Title
3723 */
3724 function wfLocalFile( $title ) {
3725 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3726 }
3727
3728 /**
3729 * Should low-performance queries be disabled?
3730 *
3731 * @return bool
3732 * @codeCoverageIgnore
3733 */
3734 function wfQueriesMustScale() {
3735 global $wgMiserMode;
3736 return $wgMiserMode
3737 || ( SiteStats::pages() > 100000
3738 && SiteStats::edits() > 1000000
3739 && SiteStats::users() > 10000 );
3740 }
3741
3742 /**
3743 * Get the path to a specified script file, respecting file
3744 * extensions; this is a wrapper around $wgScriptExtension etc.
3745 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3746 *
3747 * @param string $script Script filename, sans extension
3748 * @return string
3749 */
3750 function wfScript( $script = 'index' ) {
3751 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3752 if ( $script === 'index' ) {
3753 return $wgScript;
3754 } elseif ( $script === 'load' ) {
3755 return $wgLoadScript;
3756 } else {
3757 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3758 }
3759 }
3760
3761 /**
3762 * Get the script URL.
3763 *
3764 * @return string script URL
3765 */
3766 function wfGetScriptUrl() {
3767 if ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3768 #
3769 # as it was called, minus the query string.
3770 #
3771 # Some sites use Apache rewrite rules to handle subdomains,
3772 # and have PHP set up in a weird way that causes PHP_SELF
3773 # to contain the rewritten URL instead of the one that the
3774 # outside world sees.
3775 #
3776 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3777 # provides containing the "before" URL.
3778 return $_SERVER['SCRIPT_NAME'];
3779 } else {
3780 return $_SERVER['URL'];
3781 }
3782 }
3783
3784 /**
3785 * Convenience function converts boolean values into "true"
3786 * or "false" (string) values
3787 *
3788 * @param bool $value
3789 * @return string
3790 */
3791 function wfBoolToStr( $value ) {
3792 return $value ? 'true' : 'false';
3793 }
3794
3795 /**
3796 * Get a platform-independent path to the null file, e.g. /dev/null
3797 *
3798 * @return string
3799 */
3800 function wfGetNull() {
3801 return wfIsWindows() ? 'NUL' : '/dev/null';
3802 }
3803
3804 /**
3805 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3806 * and waiting for it to go down, this waits for the slaves to catch up to the
3807 * master position. Use this when updating very large numbers of rows, as
3808 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3809 * a no-op if there are no slaves.
3810 *
3811 * @param float|null $ifWritesSince Only wait if writes were done since this UNIX timestamp
3812 * @param string|bool $wiki Wiki identifier accepted by wfGetLB
3813 * @param string|bool $cluster Cluster name accepted by LBFactory. Default: false.
3814 */
3815 function wfWaitForSlaves( $ifWritesSince = false, $wiki = false, $cluster = false ) {
3816 // B/C: first argument used to be "max seconds of lag"; ignore such values
3817 $ifWritesSince = ( $ifWritesSince > 1e9 ) ? $ifWritesSince : false;
3818
3819 if ( $cluster !== false ) {
3820 $lb = wfGetLBFactory()->getExternalLB( $cluster );
3821 } else {
3822 $lb = wfGetLB( $wiki );
3823 }
3824
3825 // bug 27975 - Don't try to wait for slaves if there are none
3826 // Prevents permission error when getting master position
3827 if ( $lb->getServerCount() > 1 ) {
3828 if ( $ifWritesSince && !$lb->hasMasterConnection() ) {
3829 return; // assume no writes done
3830 }
3831 $dbw = $lb->getConnection( DB_MASTER, array(), $wiki );
3832 if ( $ifWritesSince && $dbw->lastDoneWrites() < $ifWritesSince ) {
3833 return; // no writes since the last wait
3834 }
3835 $pos = $dbw->getMasterPos();
3836 // The DBMS may not support getMasterPos() or the whole
3837 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
3838 if ( $pos !== false ) {
3839 $lb->waitForAll( $pos );
3840 }
3841 }
3842 }
3843
3844 /**
3845 * Count down from $seconds to zero on the terminal, with a one-second pause
3846 * between showing each number. For use in command-line scripts.
3847 *
3848 * @codeCoverageIgnore
3849 * @param int $seconds
3850 */
3851 function wfCountDown( $seconds ) {
3852 for ( $i = $seconds; $i >= 0; $i-- ) {
3853 if ( $i != $seconds ) {
3854 echo str_repeat( "\x08", strlen( $i + 1 ) );
3855 }
3856 echo $i;
3857 flush();
3858 if ( $i ) {
3859 sleep( 1 );
3860 }
3861 }
3862 echo "\n";
3863 }
3864
3865 /**
3866 * Replace all invalid characters with -
3867 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3868 * By default, $wgIllegalFileChars = ':'
3869 *
3870 * @param string $name Filename to process
3871 * @return string
3872 */
3873 function wfStripIllegalFilenameChars( $name ) {
3874 global $wgIllegalFileChars;
3875 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
3876 $name = wfBaseName( $name );
3877 $name = preg_replace(
3878 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
3879 '-',
3880 $name
3881 );
3882 return $name;
3883 }
3884
3885 /**
3886 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3887 *
3888 * @return int Value the memory limit was set to.
3889 */
3890 function wfMemoryLimit() {
3891 global $wgMemoryLimit;
3892 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3893 if ( $memlimit != -1 ) {
3894 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3895 if ( $conflimit == -1 ) {
3896 wfDebug( "Removing PHP's memory limit\n" );
3897 wfSuppressWarnings();
3898 ini_set( 'memory_limit', $conflimit );
3899 wfRestoreWarnings();
3900 return $conflimit;
3901 } elseif ( $conflimit > $memlimit ) {
3902 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3903 wfSuppressWarnings();
3904 ini_set( 'memory_limit', $conflimit );
3905 wfRestoreWarnings();
3906 return $conflimit;
3907 }
3908 }
3909 return $memlimit;
3910 }
3911
3912 /**
3913 * Converts shorthand byte notation to integer form
3914 *
3915 * @param string $string
3916 * @return int
3917 */
3918 function wfShorthandToInteger( $string = '' ) {
3919 $string = trim( $string );
3920 if ( $string === '' ) {
3921 return -1;
3922 }
3923 $last = $string[strlen( $string ) - 1];
3924 $val = intval( $string );
3925 switch ( $last ) {
3926 case 'g':
3927 case 'G':
3928 $val *= 1024;
3929 // break intentionally missing
3930 case 'm':
3931 case 'M':
3932 $val *= 1024;
3933 // break intentionally missing
3934 case 'k':
3935 case 'K':
3936 $val *= 1024;
3937 }
3938
3939 return $val;
3940 }
3941
3942 /**
3943 * Get the normalised IETF language tag
3944 * See unit test for examples.
3945 *
3946 * @param string $code The language code.
3947 * @return string The language code which complying with BCP 47 standards.
3948 */
3949 function wfBCP47( $code ) {
3950 $codeSegment = explode( '-', $code );
3951 $codeBCP = array();
3952 foreach ( $codeSegment as $segNo => $seg ) {
3953 // when previous segment is x, it is a private segment and should be lc
3954 if ( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3955 $codeBCP[$segNo] = strtolower( $seg );
3956 // ISO 3166 country code
3957 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3958 $codeBCP[$segNo] = strtoupper( $seg );
3959 // ISO 15924 script code
3960 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3961 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3962 // Use lowercase for other cases
3963 } else {
3964 $codeBCP[$segNo] = strtolower( $seg );
3965 }
3966 }
3967 $langCode = implode( '-', $codeBCP );
3968 return $langCode;
3969 }
3970
3971 /**
3972 * Get a cache object.
3973 *
3974 * @param int $inputType Cache type, one the the CACHE_* constants.
3975 * @return BagOStuff
3976 */
3977 function wfGetCache( $inputType ) {
3978 return ObjectCache::getInstance( $inputType );
3979 }
3980
3981 /**
3982 * Get the main cache object
3983 *
3984 * @return BagOStuff
3985 */
3986 function wfGetMainCache() {
3987 global $wgMainCacheType;
3988 return ObjectCache::getInstance( $wgMainCacheType );
3989 }
3990
3991 /**
3992 * Get the cache object used by the message cache
3993 *
3994 * @return BagOStuff
3995 */
3996 function wfGetMessageCacheStorage() {
3997 global $wgMessageCacheType;
3998 return ObjectCache::getInstance( $wgMessageCacheType );
3999 }
4000
4001 /**
4002 * Get the cache object used by the parser cache
4003 *
4004 * @return BagOStuff
4005 */
4006 function wfGetParserCacheStorage() {
4007 global $wgParserCacheType;
4008 return ObjectCache::getInstance( $wgParserCacheType );
4009 }
4010
4011 /**
4012 * Get the cache object used by the language converter
4013 *
4014 * @return BagOStuff
4015 */
4016 function wfGetLangConverterCacheStorage() {
4017 global $wgLanguageConverterCacheType;
4018 return ObjectCache::getInstance( $wgLanguageConverterCacheType );
4019 }
4020
4021 /**
4022 * Call hook functions defined in $wgHooks
4023 *
4024 * @param string $event Event name
4025 * @param array $args Parameters passed to hook functions
4026 * @param string|null $deprecatedVersion Optionally mark hook as deprecated with version number
4027 *
4028 * @return bool True if no handler aborted the hook
4029 */
4030 function wfRunHooks( $event, array $args = array(), $deprecatedVersion = null ) {
4031 return Hooks::run( $event, $args, $deprecatedVersion );
4032 }
4033
4034 /**
4035 * Wrapper around php's unpack.
4036 *
4037 * @param string $format The format string (See php's docs)
4038 * @param string $data A binary string of binary data
4039 * @param int|bool $length The minimum length of $data or false. This is to
4040 * prevent reading beyond the end of $data. false to disable the check.
4041 *
4042 * Also be careful when using this function to read unsigned 32 bit integer
4043 * because php might make it negative.
4044 *
4045 * @throws MWException if $data not long enough, or if unpack fails
4046 * @return array Associative array of the extracted data
4047 */
4048 function wfUnpack( $format, $data, $length = false ) {
4049 if ( $length !== false ) {
4050 $realLen = strlen( $data );
4051 if ( $realLen < $length ) {
4052 throw new MWException( "Tried to use wfUnpack on a "
4053 . "string of length $realLen, but needed one "
4054 . "of at least length $length."
4055 );
4056 }
4057 }
4058
4059 wfSuppressWarnings();
4060 $result = unpack( $format, $data );
4061 wfRestoreWarnings();
4062
4063 if ( $result === false ) {
4064 // If it cannot extract the packed data.
4065 throw new MWException( "unpack could not unpack binary data" );
4066 }
4067 return $result;
4068 }
4069
4070 /**
4071 * Determine if an image exists on the 'bad image list'.
4072 *
4073 * The format of MediaWiki:Bad_image_list is as follows:
4074 * * Only list items (lines starting with "*") are considered
4075 * * The first link on a line must be a link to a bad image
4076 * * Any subsequent links on the same line are considered to be exceptions,
4077 * i.e. articles where the image may occur inline.
4078 *
4079 * @param string $name The image name to check
4080 * @param Title|bool $contextTitle The page on which the image occurs, if known
4081 * @param string $blacklist Wikitext of a file blacklist
4082 * @return bool
4083 */
4084 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
4085 static $badImageCache = null; // based on bad_image_list msg
4086 wfProfileIn( __METHOD__ );
4087
4088 # Handle redirects
4089 $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) );
4090 if ( $redirectTitle ) {
4091 $name = $redirectTitle->getDBkey();
4092 }
4093
4094 # Run the extension hook
4095 $bad = false;
4096 if ( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
4097 wfProfileOut( __METHOD__ );
4098 return $bad;
4099 }
4100
4101 $cacheable = ( $blacklist === null );
4102 if ( $cacheable && $badImageCache !== null ) {
4103 $badImages = $badImageCache;
4104 } else { // cache miss
4105 if ( $blacklist === null ) {
4106 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
4107 }
4108 # Build the list now
4109 $badImages = array();
4110 $lines = explode( "\n", $blacklist );
4111 foreach ( $lines as $line ) {
4112 # List items only
4113 if ( substr( $line, 0, 1 ) !== '*' ) {
4114 continue;
4115 }
4116
4117 # Find all links
4118 $m = array();
4119 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
4120 continue;
4121 }
4122
4123 $exceptions = array();
4124 $imageDBkey = false;
4125 foreach ( $m[1] as $i => $titleText ) {
4126 $title = Title::newFromText( $titleText );
4127 if ( !is_null( $title ) ) {
4128 if ( $i == 0 ) {
4129 $imageDBkey = $title->getDBkey();
4130 } else {
4131 $exceptions[$title->getPrefixedDBkey()] = true;
4132 }
4133 }
4134 }
4135
4136 if ( $imageDBkey !== false ) {
4137 $badImages[$imageDBkey] = $exceptions;
4138 }
4139 }
4140 if ( $cacheable ) {
4141 $badImageCache = $badImages;
4142 }
4143 }
4144
4145 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
4146 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
4147 wfProfileOut( __METHOD__ );
4148 return $bad;
4149 }
4150
4151 /**
4152 * Determine whether the client at a given source IP is likely to be able to
4153 * access the wiki via HTTPS.
4154 *
4155 * @param string $ip The IPv4/6 address in the normal human-readable form
4156 * @return bool
4157 */
4158 function wfCanIPUseHTTPS( $ip ) {
4159 $canDo = true;
4160 wfRunHooks( 'CanIPUseHTTPS', array( $ip, &$canDo ) );
4161 return !!$canDo;
4162 }
4163
4164 /**
4165 * Work out the IP address based on various globals
4166 * For trusted proxies, use the XFF client IP (first of the chain)
4167 *
4168 * @deprecated since 1.19; call $wgRequest->getIP() directly.
4169 * @return string
4170 */
4171 function wfGetIP() {
4172 wfDeprecated( __METHOD__, '1.19' );
4173 global $wgRequest;
4174 return $wgRequest->getIP();
4175 }
4176
4177 /**
4178 * Checks if an IP is a trusted proxy provider.
4179 * Useful to tell if X-Forwarded-For data is possibly bogus.
4180 * Squid cache servers for the site are whitelisted.
4181 * @deprecated Since 1.24, use IP::isTrustedProxy()
4182 *
4183 * @param string $ip
4184 * @return bool
4185 */
4186 function wfIsTrustedProxy( $ip ) {
4187 return IP::isTrustedProxy( $ip );
4188 }
4189
4190 /**
4191 * Checks if an IP matches a proxy we've configured.
4192 * @deprecated Since 1.24, use IP::isConfiguredProxy()
4193 *
4194 * @param string $ip
4195 * @return bool
4196 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
4197 */
4198 function wfIsConfiguredProxy( $ip ) {
4199 return IP::isConfiguredProxy( $ip );
4200 }