Merge "misc style fix"
[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, $wgDBname, $wgAggregateStatsID;
1246 static $socket;
1247
1248 $id = $wgAggregateStatsID !== false ? $wgAggregateStatsID : $wgDBname;
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 = $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 = $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 $input String: of digits
3183 * @param $sourceBase Integer: 2-36
3184 * @param $destBase Integer: 2-36
3185 * @param $pad Integer: 1 or greater
3186 * @param $lowercase Boolean
3187 * @return String or false on invalid input
3188 */
3189 function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
3190 $input = strval( $input );
3191 if( $sourceBase < 2 ||
3192 $sourceBase > 36 ||
3193 $destBase < 2 ||
3194 $destBase > 36 ||
3195 $pad < 1 ||
3196 $sourceBase != intval( $sourceBase ) ||
3197 $destBase != intval( $destBase ) ||
3198 $pad != intval( $pad ) ||
3199 !is_string( $input ) ||
3200 $input == '' ) {
3201 return false;
3202 }
3203 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
3204 $inDigits = array();
3205 $outChars = '';
3206
3207 // Decode and validate input string
3208 $input = strtolower( $input );
3209 for( $i = 0; $i < strlen( $input ); $i++ ) {
3210 $n = strpos( $digitChars, $input[$i] );
3211 if( $n === false || $n > $sourceBase ) {
3212 return false;
3213 }
3214 $inDigits[] = $n;
3215 }
3216
3217 // Iterate over the input, modulo-ing out an output digit
3218 // at a time until input is gone.
3219 while( count( $inDigits ) ) {
3220 $work = 0;
3221 $workDigits = array();
3222
3223 // Long division...
3224 foreach( $inDigits as $digit ) {
3225 $work *= $sourceBase;
3226 $work += $digit;
3227
3228 if( $work < $destBase ) {
3229 // Gonna need to pull another digit.
3230 if( count( $workDigits ) ) {
3231 // Avoid zero-padding; this lets us find
3232 // the end of the input very easily when
3233 // length drops to zero.
3234 $workDigits[] = 0;
3235 }
3236 } else {
3237 // Finally! Actual division!
3238 $workDigits[] = intval( $work / $destBase );
3239
3240 // Isn't it annoying that most programming languages
3241 // don't have a single divide-and-remainder operator,
3242 // even though the CPU implements it that way?
3243 $work = $work % $destBase;
3244 }
3245 }
3246
3247 // All that division leaves us with a remainder,
3248 // which is conveniently our next output digit.
3249 $outChars .= $digitChars[$work];
3250
3251 // And we continue!
3252 $inDigits = $workDigits;
3253 }
3254
3255 while( strlen( $outChars ) < $pad ) {
3256 $outChars .= '0';
3257 }
3258
3259 return strrev( $outChars );
3260 }
3261
3262 /**
3263 * Create an object with a given name and an array of construct parameters
3264 *
3265 * @param $name String
3266 * @param $p Array: parameters
3267 * @return object
3268 * @deprecated since 1.18, warnings in 1.18, removal in 1.20
3269 */
3270 function wfCreateObject( $name, $p ) {
3271 wfDeprecated( __FUNCTION__, '1.18' );
3272 return MWFunction::newObj( $name, $p );
3273 }
3274
3275 /**
3276 * @return bool
3277 */
3278 function wfHttpOnlySafe() {
3279 global $wgHttpOnlyBlacklist;
3280
3281 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
3282 foreach( $wgHttpOnlyBlacklist as $regex ) {
3283 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
3284 return false;
3285 }
3286 }
3287 }
3288
3289 return true;
3290 }
3291
3292 /**
3293 * Check if there is sufficent entropy in php's built-in session generation
3294 * @return bool true = there is sufficient entropy
3295 */
3296 function wfCheckEntropy() {
3297 return (
3298 ( wfIsWindows() && version_compare( PHP_VERSION, '5.3.3', '>=' ) )
3299 || ini_get( 'session.entropy_file' )
3300 )
3301 && intval( ini_get( 'session.entropy_length' ) ) >= 32;
3302 }
3303
3304 /**
3305 * Override session_id before session startup if php's built-in
3306 * session generation code is not secure.
3307 */
3308 function wfFixSessionID() {
3309 // If the cookie or session id is already set we already have a session and should abort
3310 if ( isset( $_COOKIE[ session_name() ] ) || session_id() ) {
3311 return;
3312 }
3313
3314 // PHP's built-in session entropy is enabled if:
3315 // - entropy_file is set or you're on Windows with php 5.3.3+
3316 // - AND entropy_length is > 0
3317 // We treat it as disabled if it doesn't have an entropy length of at least 32
3318 $entropyEnabled = wfCheckEntropy();
3319
3320 // If built-in entropy is not enabled or not sufficient override php's built in session id generation code
3321 if ( !$entropyEnabled ) {
3322 wfDebug( __METHOD__ . ": PHP's built in entropy is disabled or not sufficient, overriding session id generation using our cryptrand source.\n" );
3323 session_id( MWCryptRand::generateHex( 32 ) );
3324 }
3325 }
3326
3327 /**
3328 * Initialise php session
3329 *
3330 * @param $sessionId Bool
3331 */
3332 function wfSetupSession( $sessionId = false ) {
3333 global $wgSessionsInMemcached, $wgSessionsInObjectCache, $wgCookiePath, $wgCookieDomain,
3334 $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
3335 if( $wgSessionsInObjectCache || $wgSessionsInMemcached ) {
3336 ObjectCacheSessionHandler::install();
3337 } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
3338 # Only set this if $wgSessionHandler isn't null and session.save_handler
3339 # hasn't already been set to the desired value (that causes errors)
3340 ini_set( 'session.save_handler', $wgSessionHandler );
3341 }
3342 $httpOnlySafe = wfHttpOnlySafe() && $wgCookieHttpOnly;
3343 wfDebugLog( 'cookie',
3344 'session_set_cookie_params: "' . implode( '", "',
3345 array(
3346 0,
3347 $wgCookiePath,
3348 $wgCookieDomain,
3349 $wgCookieSecure,
3350 $httpOnlySafe ) ) . '"' );
3351 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $httpOnlySafe );
3352 session_cache_limiter( 'private, must-revalidate' );
3353 if ( $sessionId ) {
3354 session_id( $sessionId );
3355 } else {
3356 wfFixSessionID();
3357 }
3358 wfSuppressWarnings();
3359 session_start();
3360 wfRestoreWarnings();
3361 }
3362
3363 /**
3364 * Get an object from the precompiled serialized directory
3365 *
3366 * @param $name String
3367 * @return Mixed: the variable on success, false on failure
3368 */
3369 function wfGetPrecompiledData( $name ) {
3370 global $IP;
3371
3372 $file = "$IP/serialized/$name";
3373 if ( file_exists( $file ) ) {
3374 $blob = file_get_contents( $file );
3375 if ( $blob ) {
3376 return unserialize( $blob );
3377 }
3378 }
3379 return false;
3380 }
3381
3382 /**
3383 * Get a cache key
3384 *
3385 * @param varargs
3386 * @return String
3387 */
3388 function wfMemcKey( /*... */ ) {
3389 global $wgCachePrefix;
3390 $prefix = $wgCachePrefix === false ? wfWikiID() : $wgCachePrefix;
3391 $args = func_get_args();
3392 $key = $prefix . ':' . implode( ':', $args );
3393 $key = str_replace( ' ', '_', $key );
3394 return $key;
3395 }
3396
3397 /**
3398 * Get a cache key for a foreign DB
3399 *
3400 * @param $db String
3401 * @param $prefix String
3402 * @param varargs String
3403 * @return String
3404 */
3405 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
3406 $args = array_slice( func_get_args(), 2 );
3407 if ( $prefix ) {
3408 $key = "$db-$prefix:" . implode( ':', $args );
3409 } else {
3410 $key = $db . ':' . implode( ':', $args );
3411 }
3412 return $key;
3413 }
3414
3415 /**
3416 * Get an ASCII string identifying this wiki
3417 * This is used as a prefix in memcached keys
3418 *
3419 * @return String
3420 */
3421 function wfWikiID() {
3422 global $wgDBprefix, $wgDBname;
3423 if ( $wgDBprefix ) {
3424 return "$wgDBname-$wgDBprefix";
3425 } else {
3426 return $wgDBname;
3427 }
3428 }
3429
3430 /**
3431 * Split a wiki ID into DB name and table prefix
3432 *
3433 * @param $wiki String
3434 *
3435 * @return array
3436 */
3437 function wfSplitWikiID( $wiki ) {
3438 $bits = explode( '-', $wiki, 2 );
3439 if ( count( $bits ) < 2 ) {
3440 $bits[] = '';
3441 }
3442 return $bits;
3443 }
3444
3445 /**
3446 * Get a Database object.
3447 *
3448 * @param $db Integer: index of the connection to get. May be DB_MASTER for the
3449 * master (for write queries), DB_SLAVE for potentially lagged read
3450 * queries, or an integer >= 0 for a particular server.
3451 *
3452 * @param $groups Mixed: query groups. An array of group names that this query
3453 * belongs to. May contain a single string if the query is only
3454 * in one group.
3455 *
3456 * @param $wiki String: the wiki ID, or false for the current wiki
3457 *
3458 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
3459 * will always return the same object, unless the underlying connection or load
3460 * balancer is manually destroyed.
3461 *
3462 * Note 2: use $this->getDB() in maintenance scripts that may be invoked by
3463 * updater to ensure that a proper database is being updated.
3464 *
3465 * @return DatabaseBase
3466 */
3467 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
3468 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
3469 }
3470
3471 /**
3472 * Get a load balancer object.
3473 *
3474 * @param $wiki String: wiki ID, or false for the current wiki
3475 * @return LoadBalancer
3476 */
3477 function wfGetLB( $wiki = false ) {
3478 return wfGetLBFactory()->getMainLB( $wiki );
3479 }
3480
3481 /**
3482 * Get the load balancer factory object
3483 *
3484 * @return LBFactory
3485 */
3486 function &wfGetLBFactory() {
3487 return LBFactory::singleton();
3488 }
3489
3490 /**
3491 * Find a file.
3492 * Shortcut for RepoGroup::singleton()->findFile()
3493 *
3494 * @param $title String or Title object
3495 * @param $options array Associative array of options:
3496 * time: requested time for an archived image, or false for the
3497 * current version. An image object will be returned which was
3498 * created at the specified time.
3499 *
3500 * ignoreRedirect: If true, do not follow file redirects
3501 *
3502 * private: If true, return restricted (deleted) files if the current
3503 * user is allowed to view them. Otherwise, such files will not
3504 * be found.
3505 *
3506 * bypassCache: If true, do not use the process-local cache of File objects
3507 *
3508 * @return File, or false if the file does not exist
3509 */
3510 function wfFindFile( $title, $options = array() ) {
3511 return RepoGroup::singleton()->findFile( $title, $options );
3512 }
3513
3514 /**
3515 * Get an object referring to a locally registered file.
3516 * Returns a valid placeholder object if the file does not exist.
3517 *
3518 * @param $title Title|String
3519 * @return LocalFile|null A File, or null if passed an invalid Title
3520 */
3521 function wfLocalFile( $title ) {
3522 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
3523 }
3524
3525 /**
3526 * Stream a file to the browser. Back-compat alias for StreamFile::stream()
3527 * @deprecated since 1.19
3528 */
3529 function wfStreamFile( $fname, $headers = array() ) {
3530 wfDeprecated( __FUNCTION__, '1.19' );
3531 StreamFile::stream( $fname, $headers );
3532 }
3533
3534 /**
3535 * Should low-performance queries be disabled?
3536 *
3537 * @return Boolean
3538 * @codeCoverageIgnore
3539 */
3540 function wfQueriesMustScale() {
3541 global $wgMiserMode;
3542 return $wgMiserMode
3543 || ( SiteStats::pages() > 100000
3544 && SiteStats::edits() > 1000000
3545 && SiteStats::users() > 10000 );
3546 }
3547
3548 /**
3549 * Get the path to a specified script file, respecting file
3550 * extensions; this is a wrapper around $wgScriptExtension etc.
3551 * except for 'index' and 'load' which use $wgScript/$wgLoadScript
3552 *
3553 * @param $script String: script filename, sans extension
3554 * @return String
3555 */
3556 function wfScript( $script = 'index' ) {
3557 global $wgScriptPath, $wgScriptExtension, $wgScript, $wgLoadScript;
3558 if ( $script === 'index' ) {
3559 return $wgScript;
3560 } else if ( $script === 'load' ) {
3561 return $wgLoadScript;
3562 } else {
3563 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
3564 }
3565 }
3566
3567 /**
3568 * Get the script URL.
3569 *
3570 * @return string script URL
3571 */
3572 function wfGetScriptUrl() {
3573 if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
3574 #
3575 # as it was called, minus the query string.
3576 #
3577 # Some sites use Apache rewrite rules to handle subdomains,
3578 # and have PHP set up in a weird way that causes PHP_SELF
3579 # to contain the rewritten URL instead of the one that the
3580 # outside world sees.
3581 #
3582 # If in this mode, use SCRIPT_URL instead, which mod_rewrite
3583 # provides containing the "before" URL.
3584 return $_SERVER['SCRIPT_NAME'];
3585 } else {
3586 return $_SERVER['URL'];
3587 }
3588 }
3589
3590 /**
3591 * Convenience function converts boolean values into "true"
3592 * or "false" (string) values
3593 *
3594 * @param $value Boolean
3595 * @return String
3596 */
3597 function wfBoolToStr( $value ) {
3598 return $value ? 'true' : 'false';
3599 }
3600
3601 /**
3602 * Get a platform-independent path to the null file, e.g. /dev/null
3603 *
3604 * @return string
3605 */
3606 function wfGetNull() {
3607 return wfIsWindows()
3608 ? 'NUL'
3609 : '/dev/null';
3610 }
3611
3612 /**
3613 * Modern version of wfWaitForSlaves(). Instead of looking at replication lag
3614 * and waiting for it to go down, this waits for the slaves to catch up to the
3615 * master position. Use this when updating very large numbers of rows, as
3616 * in maintenance scripts, to avoid causing too much lag. Of course, this is
3617 * a no-op if there are no slaves.
3618 *
3619 * @param $maxLag Integer (deprecated)
3620 * @param $wiki mixed Wiki identifier accepted by wfGetLB
3621 */
3622 function wfWaitForSlaves( $maxLag = false, $wiki = false ) {
3623 $lb = wfGetLB( $wiki );
3624 // bug 27975 - Don't try to wait for slaves if there are none
3625 // Prevents permission error when getting master position
3626 if ( $lb->getServerCount() > 1 ) {
3627 $dbw = $lb->getConnection( DB_MASTER );
3628 $pos = $dbw->getMasterPos();
3629 $lb->waitForAll( $pos );
3630 }
3631 }
3632
3633 /**
3634 * Used to be used for outputting text in the installer/updater
3635 * @deprecated since 1.18, warnings in 1.18, remove in 1.20
3636 */
3637 function wfOut( $s ) {
3638 wfDeprecated( __FUNCTION__, '1.18' );
3639 global $wgCommandLineMode;
3640 if ( $wgCommandLineMode ) {
3641 echo $s;
3642 } else {
3643 echo htmlspecialchars( $s );
3644 }
3645 flush();
3646 }
3647
3648 /**
3649 * Count down from $n to zero on the terminal, with a one-second pause
3650 * between showing each number. For use in command-line scripts.
3651 * @codeCoverageIgnore
3652 * @param $n int
3653 */
3654 function wfCountDown( $n ) {
3655 for ( $i = $n; $i >= 0; $i-- ) {
3656 if ( $i != $n ) {
3657 echo str_repeat( "\x08", strlen( $i + 1 ) );
3658 }
3659 echo $i;
3660 flush();
3661 if ( $i ) {
3662 sleep( 1 );
3663 }
3664 }
3665 echo "\n";
3666 }
3667
3668 /**
3669 * Generate a random 32-character hexadecimal token.
3670 * @param $salt Mixed: some sort of salt, if necessary, to add to random
3671 * characters before hashing.
3672 * @return string
3673 * @codeCoverageIgnore
3674 * @deprecated since 1.20; Please use MWCryptRand for security purposes and wfRandomString for pesudo-random strings
3675 * @warning This method is NOT secure. Additionally it has many callers that use it for pesudo-random purposes.
3676 */
3677 function wfGenerateToken( $salt = '' ) {
3678 wfDeprecated( __METHOD__, '1.20' );
3679 $salt = serialize( $salt );
3680 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
3681 }
3682
3683 /**
3684 * Replace all invalid characters with -
3685 * Additional characters can be defined in $wgIllegalFileChars (see bug 20489)
3686 * By default, $wgIllegalFileChars = ':'
3687 *
3688 * @param $name Mixed: filename to process
3689 * @return String
3690 */
3691 function wfStripIllegalFilenameChars( $name ) {
3692 global $wgIllegalFileChars;
3693 $illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
3694 $name = wfBaseName( $name );
3695 $name = preg_replace(
3696 "/[^" . Title::legalChars() . "]" . $illegalFileChars . "/",
3697 '-',
3698 $name
3699 );
3700 return $name;
3701 }
3702
3703 /**
3704 * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
3705 *
3706 * @return Integer value memory was set to.
3707 */
3708 function wfMemoryLimit() {
3709 global $wgMemoryLimit;
3710 $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
3711 if( $memlimit != -1 ) {
3712 $conflimit = wfShorthandToInteger( $wgMemoryLimit );
3713 if( $conflimit == -1 ) {
3714 wfDebug( "Removing PHP's memory limit\n" );
3715 wfSuppressWarnings();
3716 ini_set( 'memory_limit', $conflimit );
3717 wfRestoreWarnings();
3718 return $conflimit;
3719 } elseif ( $conflimit > $memlimit ) {
3720 wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
3721 wfSuppressWarnings();
3722 ini_set( 'memory_limit', $conflimit );
3723 wfRestoreWarnings();
3724 return $conflimit;
3725 }
3726 }
3727 return $memlimit;
3728 }
3729
3730 /**
3731 * Converts shorthand byte notation to integer form
3732 *
3733 * @param $string String
3734 * @return Integer
3735 */
3736 function wfShorthandToInteger( $string = '' ) {
3737 $string = trim( $string );
3738 if( $string === '' ) {
3739 return -1;
3740 }
3741 $last = $string[strlen( $string ) - 1];
3742 $val = intval( $string );
3743 switch( $last ) {
3744 case 'g':
3745 case 'G':
3746 $val *= 1024;
3747 // break intentionally missing
3748 case 'm':
3749 case 'M':
3750 $val *= 1024;
3751 // break intentionally missing
3752 case 'k':
3753 case 'K':
3754 $val *= 1024;
3755 }
3756
3757 return $val;
3758 }
3759
3760 /**
3761 * Get the normalised IETF language tag
3762 * See unit test for examples.
3763 *
3764 * @param $code String: The language code.
3765 * @return String: The language code which complying with BCP 47 standards.
3766 */
3767 function wfBCP47( $code ) {
3768 $codeSegment = explode( '-', $code );
3769 $codeBCP = array();
3770 foreach ( $codeSegment as $segNo => $seg ) {
3771 if ( count( $codeSegment ) > 0 ) {
3772 // when previous segment is x, it is a private segment and should be lc
3773 if( $segNo > 0 && strtolower( $codeSegment[( $segNo - 1 )] ) == 'x' ) {
3774 $codeBCP[$segNo] = strtolower( $seg );
3775 // ISO 3166 country code
3776 } elseif ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
3777 $codeBCP[$segNo] = strtoupper( $seg );
3778 // ISO 15924 script code
3779 } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
3780 $codeBCP[$segNo] = ucfirst( strtolower( $seg ) );
3781 // Use lowercase for other cases
3782 } else {
3783 $codeBCP[$segNo] = strtolower( $seg );
3784 }
3785 } else {
3786 // Use lowercase for single segment
3787 $codeBCP[$segNo] = strtolower( $seg );
3788 }
3789 }
3790 $langCode = implode( '-', $codeBCP );
3791 return $langCode;
3792 }
3793
3794 /**
3795 * Get a cache object.
3796 *
3797 * @param $inputType integer Cache type, one the the CACHE_* constants.
3798 * @return BagOStuff
3799 */
3800 function wfGetCache( $inputType ) {
3801 return ObjectCache::getInstance( $inputType );
3802 }
3803
3804 /**
3805 * Get the main cache object
3806 *
3807 * @return BagOStuff
3808 */
3809 function wfGetMainCache() {
3810 global $wgMainCacheType;
3811 return ObjectCache::getInstance( $wgMainCacheType );
3812 }
3813
3814 /**
3815 * Get the cache object used by the message cache
3816 *
3817 * @return BagOStuff
3818 */
3819 function wfGetMessageCacheStorage() {
3820 global $wgMessageCacheType;
3821 return ObjectCache::getInstance( $wgMessageCacheType );
3822 }
3823
3824 /**
3825 * Get the cache object used by the parser cache
3826 *
3827 * @return BagOStuff
3828 */
3829 function wfGetParserCacheStorage() {
3830 global $wgParserCacheType;
3831 return ObjectCache::getInstance( $wgParserCacheType );
3832 }
3833
3834 /**
3835 * Get the cache object used by the language converter
3836 *
3837 * @return BagOStuff
3838 */
3839 function wfGetLangConverterCacheStorage() {
3840 global $wgLanguageConverterCacheType;
3841 return ObjectCache::getInstance( $wgLanguageConverterCacheType );
3842 }
3843
3844 /**
3845 * Call hook functions defined in $wgHooks
3846 *
3847 * @param $event String: event name
3848 * @param $args Array: parameters passed to hook functions
3849 * @return Boolean True if no handler aborted the hook
3850 */
3851 function wfRunHooks( $event, $args = array() ) {
3852 return Hooks::run( $event, $args );
3853 }
3854
3855 /**
3856 * Wrapper around php's unpack.
3857 *
3858 * @param $format String: The format string (See php's docs)
3859 * @param $data: A binary string of binary data
3860 * @param $length integer or false: The minimun length of $data. This is to
3861 * prevent reading beyond the end of $data. false to disable the check.
3862 *
3863 * Also be careful when using this function to read unsigned 32 bit integer
3864 * because php might make it negative.
3865 *
3866 * @throws MWException if $data not long enough, or if unpack fails
3867 * @return array Associative array of the extracted data
3868 */
3869 function wfUnpack( $format, $data, $length=false ) {
3870 if ( $length !== false ) {
3871 $realLen = strlen( $data );
3872 if ( $realLen < $length ) {
3873 throw new MWException( "Tried to use wfUnpack on a "
3874 . "string of length $realLen, but needed one "
3875 . "of at least length $length."
3876 );
3877 }
3878 }
3879
3880 wfSuppressWarnings();
3881 $result = unpack( $format, $data );
3882 wfRestoreWarnings();
3883
3884 if ( $result === false ) {
3885 // If it cannot extract the packed data.
3886 throw new MWException( "unpack could not unpack binary data" );
3887 }
3888 return $result;
3889 }
3890
3891 /**
3892 * Determine if an image exists on the 'bad image list'.
3893 *
3894 * The format of MediaWiki:Bad_image_list is as follows:
3895 * * Only list items (lines starting with "*") are considered
3896 * * The first link on a line must be a link to a bad image
3897 * * Any subsequent links on the same line are considered to be exceptions,
3898 * i.e. articles where the image may occur inline.
3899 *
3900 * @param $name string the image name to check
3901 * @param $contextTitle Title|bool the page on which the image occurs, if known
3902 * @param $blacklist string wikitext of a file blacklist
3903 * @return bool
3904 */
3905 function wfIsBadImage( $name, $contextTitle = false, $blacklist = null ) {
3906 static $badImageCache = null; // based on bad_image_list msg
3907 wfProfileIn( __METHOD__ );
3908
3909 # Handle redirects
3910 $redirectTitle = RepoGroup::singleton()->checkRedirect( Title::makeTitle( NS_FILE, $name ) );
3911 if( $redirectTitle ) {
3912 $name = $redirectTitle->getDbKey();
3913 }
3914
3915 # Run the extension hook
3916 $bad = false;
3917 if( !wfRunHooks( 'BadImage', array( $name, &$bad ) ) ) {
3918 wfProfileOut( __METHOD__ );
3919 return $bad;
3920 }
3921
3922 $cacheable = ( $blacklist === null );
3923 if( $cacheable && $badImageCache !== null ) {
3924 $badImages = $badImageCache;
3925 } else { // cache miss
3926 if ( $blacklist === null ) {
3927 $blacklist = wfMessage( 'bad_image_list' )->inContentLanguage()->plain(); // site list
3928 }
3929 # Build the list now
3930 $badImages = array();
3931 $lines = explode( "\n", $blacklist );
3932 foreach( $lines as $line ) {
3933 # List items only
3934 if ( substr( $line, 0, 1 ) !== '*' ) {
3935 continue;
3936 }
3937
3938 # Find all links
3939 $m = array();
3940 if ( !preg_match_all( '/\[\[:?(.*?)\]\]/', $line, $m ) ) {
3941 continue;
3942 }
3943
3944 $exceptions = array();
3945 $imageDBkey = false;
3946 foreach ( $m[1] as $i => $titleText ) {
3947 $title = Title::newFromText( $titleText );
3948 if ( !is_null( $title ) ) {
3949 if ( $i == 0 ) {
3950 $imageDBkey = $title->getDBkey();
3951 } else {
3952 $exceptions[$title->getPrefixedDBkey()] = true;
3953 }
3954 }
3955 }
3956
3957 if ( $imageDBkey !== false ) {
3958 $badImages[$imageDBkey] = $exceptions;
3959 }
3960 }
3961 if ( $cacheable ) {
3962 $badImageCache = $badImages;
3963 }
3964 }
3965
3966 $contextKey = $contextTitle ? $contextTitle->getPrefixedDBkey() : false;
3967 $bad = isset( $badImages[$name] ) && !isset( $badImages[$name][$contextKey] );
3968 wfProfileOut( __METHOD__ );
3969 return $bad;
3970 }