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