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