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