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