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