Apply changes made live on Wikimedia cluster related to preprocessor caching to subve...
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
5 }
6
7 /**
8 * Global functions used everywhere
9 */
10
11 require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
12 require_once dirname(__FILE__) . '/XmlFunctions.php';
13
14 // Hide compatibility functions from Doxygen
15 /// @cond
16
17 /**
18 * Compatibility functions
19 *
20 * We more or less support PHP 5.0.x and up.
21 * Re-implementations of newer functions or functions in non-standard
22 * PHP extensions may be included here.
23 */
24 if( !function_exists('iconv') ) {
25 # iconv support is not in the default configuration and so may not be present.
26 # Assume will only ever use utf-8 and iso-8859-1.
27 # This will *not* work in all circumstances.
28 function iconv( $from, $to, $string ) {
29 if(strcasecmp( $from, $to ) == 0) return $string;
30 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
31 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
32 return $string;
33 }
34 }
35
36 # UTF-8 substr function based on a PHP manual comment
37 if ( !function_exists( 'mb_substr' ) ) {
38 function mb_substr( $str, $start ) {
39 $ar = array();
40 preg_match_all( '/./us', $str, $ar );
41
42 if( func_num_args() >= 3 ) {
43 $end = func_get_arg( 2 );
44 return join( '', array_slice( $ar[0], $start, $end ) );
45 } else {
46 return join( '', array_slice( $ar[0], $start ) );
47 }
48 }
49 }
50
51 if ( !function_exists( 'mb_strlen' ) ) {
52 /**
53 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
54 * @param string $str
55 * @param string $enc optional encoding; ignored
56 * @return int
57 */
58 function mb_strlen( $str, $enc="" ) {
59 $counts = count_chars( $str );
60 $total = 0;
61
62 // Count ASCII bytes
63 for( $i = 0; $i < 0x80; $i++ ) {
64 $total += $counts[$i];
65 }
66
67 // Count multibyte sequence heads
68 for( $i = 0xc0; $i < 0xff; $i++ ) {
69 $total += $counts[$i];
70 }
71 return $total;
72 }
73 }
74
75 if ( !function_exists( 'array_diff_key' ) ) {
76 /**
77 * Exists in PHP 5.1.0+
78 * Not quite compatible, two-argument version only
79 * Null values will cause problems due to this use of isset()
80 */
81 function array_diff_key( $left, $right ) {
82 $result = $left;
83 foreach ( $left as $key => $unused ) {
84 if ( isset( $right[$key] ) ) {
85 unset( $result[$key] );
86 }
87 }
88 return $result;
89 }
90 }
91
92 // Support for Wietse Venema's taint feature
93 if ( !function_exists( 'istainted' ) ) {
94 function istainted( $var ) {
95 return 0;
96 }
97 function taint( $var, $level = 0 ) {}
98 function untaint( $var, $level = 0 ) {}
99 define( 'TC_HTML', 1 );
100 define( 'TC_SHELL', 1 );
101 define( 'TC_MYSQL', 1 );
102 define( 'TC_PCRE', 1 );
103 define( 'TC_SELF', 1 );
104 }
105 /// @endcond
106
107
108 /**
109 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
110 */
111 function wfArrayDiff2( $a, $b ) {
112 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
113 }
114 function wfArrayDiff2_cmp( $a, $b ) {
115 if ( !is_array( $a ) ) {
116 return strcmp( $a, $b );
117 } elseif ( count( $a ) !== count( $b ) ) {
118 return count( $a ) < count( $b ) ? -1 : 1;
119 } else {
120 reset( $a );
121 reset( $b );
122 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
123 $cmp = strcmp( $valueA, $valueB );
124 if ( $cmp !== 0 ) {
125 return $cmp;
126 }
127 }
128 return 0;
129 }
130 }
131
132 /**
133 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
134 * PHP 5 won't let you declare a 'clone' function, even conditionally,
135 * so it has to be a wrapper with a different name.
136 */
137 function wfClone( $object ) {
138 return clone( $object );
139 }
140
141 /**
142 * Seed Mersenne Twister
143 * No-op for compatibility; only necessary in PHP < 4.2.0
144 */
145 function wfSeedRandom() {
146 /* No-op */
147 }
148
149 /**
150 * Get a random decimal value between 0 and 1, in a way
151 * not likely to give duplicate values for any realistic
152 * number of articles.
153 *
154 * @return string
155 */
156 function wfRandom() {
157 # The maximum random value is "only" 2^31-1, so get two random
158 # values to reduce the chance of dupes
159 $max = mt_getrandmax() + 1;
160 $rand = number_format( (mt_rand() * $max + mt_rand())
161 / $max / $max, 12, '.', '' );
162 return $rand;
163 }
164
165 /**
166 * We want some things to be included as literal characters in our title URLs
167 * for prettiness, which urlencode encodes by default. According to RFC 1738,
168 * all of the following should be safe:
169 *
170 * ;:@&=$-_.+!*'(),
171 *
172 * But + is not safe because it's used to indicate a space; &= are only safe in
173 * paths and not in queries (and we don't distinguish here); ' seems kind of
174 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
175 * is reserved, we don't care. So the list we unescape is:
176 *
177 * ;:@$!*(),/
178 *
179 * %2F in the page titles seems to fatally break for some reason.
180 *
181 * @param $s String:
182 * @return string
183 */
184 function wfUrlencode( $s ) {
185 $s = urlencode( $s );
186 $s = str_ireplace(
187 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
188 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
189 $s
190 );
191
192 return $s;
193 }
194
195 /**
196 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
197 * In normal operation this is a NOP.
198 *
199 * Controlling globals:
200 * $wgDebugLogFile - points to the log file
201 * $wgProfileOnly - if set, normal debug messages will not be recorded.
202 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
203 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
204 *
205 * @param $text String
206 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
207 */
208 function wfDebug( $text, $logonly = false ) {
209 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
210 global $wgDebugLogPrefix;
211 static $recursion = 0;
212
213 static $cache = array(); // Cache of unoutputted messages
214
215 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
216 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
217 return;
218 }
219
220 if ( $wgDebugComments && !$logonly ) {
221 $cache[] = $text;
222
223 if ( !isset( $wgOut ) ) {
224 return;
225 }
226 if ( !StubObject::isRealObject( $wgOut ) ) {
227 if ( $recursion ) {
228 return;
229 }
230 $recursion++;
231 $wgOut->_unstub();
232 $recursion--;
233 }
234
235 // add the message and possible cached ones to the output
236 array_map( array( $wgOut, 'debug' ), $cache );
237 $cache = array();
238 }
239 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
240 # Strip unprintables; they can switch terminal modes when binary data
241 # gets dumped, which is pretty annoying.
242 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
243 $text = $wgDebugLogPrefix . $text;
244 wfErrorLog( $text, $wgDebugLogFile );
245 }
246 }
247
248 /**
249 * Send a line giving PHP memory usage.
250 * @param $exact Bool : print exact values instead of kilobytes (default: false)
251 */
252 function wfDebugMem( $exact = false ) {
253 $mem = memory_get_usage();
254 if( !$exact ) {
255 $mem = floor( $mem / 1024 ) . ' kilobytes';
256 } else {
257 $mem .= ' bytes';
258 }
259 wfDebug( "Memory usage: $mem\n" );
260 }
261
262 /**
263 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
264 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
265 *
266 * @param $logGroup String
267 * @param $text String
268 * @param $public Bool: whether to log the event in the public log if no private
269 * log file is specified, (default true)
270 */
271 function wfDebugLog( $logGroup, $text, $public = true ) {
272 global $wgDebugLogGroups, $wgShowHostnames;
273 $text = trim($text)."\n";
274 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
275 $time = wfTimestamp( TS_DB );
276 $wiki = wfWikiID();
277 if ( $wgShowHostnames ) {
278 $host = wfHostname();
279 } else {
280 $host = '';
281 }
282 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
283 } else if ( $public === true ) {
284 wfDebug( $text, true );
285 }
286 }
287
288 /**
289 * Log for database errors
290 * @param $text String: database error message.
291 */
292 function wfLogDBError( $text ) {
293 global $wgDBerrorLog, $wgDBname;
294 if ( $wgDBerrorLog ) {
295 $host = trim(`hostname`);
296 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
297 wfErrorLog( $text, $wgDBerrorLog );
298 }
299 }
300
301 /**
302 * Log to a file without getting "file size exceeded" signals.
303 *
304 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
305 * send lines to the specified port, prefixed by the specified prefix and a space.
306 */
307 function wfErrorLog( $text, $file ) {
308 if ( substr( $file, 0, 4 ) == 'udp:' ) {
309 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
310 // IPv6 bracketed host
311 $protocol = $m[1];
312 $host = $m[2];
313 $port = $m[3];
314 $prefix = isset( $m[4] ) ? $m[4] : false;
315 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
316 $protocol = $m[1];
317 $host = $m[2];
318 $port = $m[3];
319 $prefix = isset( $m[4] ) ? $m[4] : false;
320 } else {
321 throw new MWException( __METHOD__.": Invalid UDP specification" );
322 }
323 // Clean it up for the multiplexer
324 if ( strval( $prefix ) !== '' ) {
325 $text = preg_replace( '/^/m', $prefix . ' ', $text );
326 if ( substr( $text, -1 ) != "\n" ) {
327 $text .= "\n";
328 }
329 }
330
331 $sock = fsockopen( "$protocol://$host", $port );
332 if ( !$sock ) {
333 return;
334 }
335 fwrite( $sock, $text );
336 fclose( $sock );
337 } else {
338 wfSuppressWarnings();
339 $exists = file_exists( $file );
340 $size = $exists ? filesize( $file ) : false;
341 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
342 error_log( $text, 3, $file );
343 }
344 wfRestoreWarnings();
345 }
346 }
347
348 /**
349 * @todo document
350 */
351 function wfLogProfilingData() {
352 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
353 global $wgProfiler, $wgUser;
354 if ( !isset( $wgProfiler ) )
355 return;
356
357 $now = wfTime();
358 $elapsed = $now - $wgRequestTime;
359 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
360 $forward = '';
361 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
362 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
363 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
364 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
365 if( !empty( $_SERVER['HTTP_FROM'] ) )
366 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
367 if( $forward )
368 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
369 // Don't unstub $wgUser at this late stage just for statistics purposes
370 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
371 $forward .= ' anon';
372 $log = sprintf( "%s\t%04.3f\t%s\n",
373 gmdate( 'YmdHis' ), $elapsed,
374 urldecode( $wgRequest->getRequestURL() . $forward ) );
375 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
376 wfErrorLog( $log . $prof, $wgDebugLogFile );
377 }
378 }
379
380 /**
381 * Check if the wiki read-only lock file is present. This can be used to lock
382 * off editing functions, but doesn't guarantee that the database will not be
383 * modified.
384 * @return bool
385 */
386 function wfReadOnly() {
387 global $wgReadOnlyFile, $wgReadOnly;
388
389 if ( !is_null( $wgReadOnly ) ) {
390 return (bool)$wgReadOnly;
391 }
392 if ( '' == $wgReadOnlyFile ) {
393 return false;
394 }
395 // Set $wgReadOnly for faster access next time
396 if ( is_file( $wgReadOnlyFile ) ) {
397 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
398 } else {
399 $wgReadOnly = false;
400 }
401 return (bool)$wgReadOnly;
402 }
403
404 function wfReadOnlyReason() {
405 global $wgReadOnly;
406 wfReadOnly();
407 return $wgReadOnly;
408 }
409
410 /**
411 * Return a Language object from $langcode
412 * @param $langcode Mixed: either:
413 * - a Language object
414 * - code of the language to get the message for, if it is
415 * a valid code create a language for that language, if
416 * it is a string but not a valid code then make a basic
417 * language object
418 * - a boolean: if it's false then use the current users
419 * language (as a fallback for the old parameter
420 * functionality), or if it is true then use the wikis
421 * @return Language object
422 */
423 function wfGetLangObj( $langcode = false ){
424 # Identify which language to get or create a language object for.
425 if( $langcode instanceof Language )
426 # Great, we already have the object!
427 return $langcode;
428
429 global $wgContLang;
430 if( $langcode === $wgContLang->getCode() || $langcode === true )
431 # $langcode is the language code of the wikis content language object.
432 # or it is a boolean and value is true
433 return $wgContLang;
434
435 global $wgLang;
436 if( $langcode === $wgLang->getCode() || $langcode === false )
437 # $langcode is the language code of user language object.
438 # or it was a boolean and value is false
439 return $wgLang;
440
441 $validCodes = array_keys( Language::getLanguageNames() );
442 if( in_array( $langcode, $validCodes ) )
443 # $langcode corresponds to a valid language.
444 return Language::factory( $langcode );
445
446 # $langcode is a string, but not a valid language code; use content language.
447 wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
448 return $wgContLang;
449 }
450
451 /**
452 * Get a message from anywhere, for the current user language.
453 *
454 * Use wfMsgForContent() instead if the message should NOT
455 * change depending on the user preferences.
456 *
457 * @param $key String: lookup key for the message, usually
458 * defined in languages/Language.php
459 *
460 * This function also takes extra optional parameters (not
461 * shown in the function definition), which can by used to
462 * insert variable text into the predefined message.
463 */
464 function wfMsg( $key ) {
465 $args = func_get_args();
466 array_shift( $args );
467 return wfMsgReal( $key, $args, true );
468 }
469
470 /**
471 * Same as above except doesn't transform the message
472 */
473 function wfMsgNoTrans( $key ) {
474 $args = func_get_args();
475 array_shift( $args );
476 return wfMsgReal( $key, $args, true, false, false );
477 }
478
479 /**
480 * Get a message from anywhere, for the current global language
481 * set with $wgLanguageCode.
482 *
483 * Use this if the message should NOT change dependent on the
484 * language set in the user's preferences. This is the case for
485 * most text written into logs, as well as link targets (such as
486 * the name of the copyright policy page). Link titles, on the
487 * other hand, should be shown in the UI language.
488 *
489 * Note that MediaWiki allows users to change the user interface
490 * language in their preferences, but a single installation
491 * typically only contains content in one language.
492 *
493 * Be wary of this distinction: If you use wfMsg() where you should
494 * use wfMsgForContent(), a user of the software may have to
495 * customize over 70 messages in order to, e.g., fix a link in every
496 * possible language.
497 *
498 * @param $key String: lookup key for the message, usually
499 * defined in languages/Language.php
500 */
501 function wfMsgForContent( $key ) {
502 global $wgForceUIMsgAsContentMsg;
503 $args = func_get_args();
504 array_shift( $args );
505 $forcontent = true;
506 if( is_array( $wgForceUIMsgAsContentMsg ) &&
507 in_array( $key, $wgForceUIMsgAsContentMsg ) )
508 $forcontent = false;
509 return wfMsgReal( $key, $args, true, $forcontent );
510 }
511
512 /**
513 * Same as above except doesn't transform the message
514 */
515 function wfMsgForContentNoTrans( $key ) {
516 global $wgForceUIMsgAsContentMsg;
517 $args = func_get_args();
518 array_shift( $args );
519 $forcontent = true;
520 if( is_array( $wgForceUIMsgAsContentMsg ) &&
521 in_array( $key, $wgForceUIMsgAsContentMsg ) )
522 $forcontent = false;
523 return wfMsgReal( $key, $args, true, $forcontent, false );
524 }
525
526 /**
527 * Get a message from the language file, for the UI elements
528 */
529 function wfMsgNoDB( $key ) {
530 $args = func_get_args();
531 array_shift( $args );
532 return wfMsgReal( $key, $args, false );
533 }
534
535 /**
536 * Get a message from the language file, for the content
537 */
538 function wfMsgNoDBForContent( $key ) {
539 global $wgForceUIMsgAsContentMsg;
540 $args = func_get_args();
541 array_shift( $args );
542 $forcontent = true;
543 if( is_array( $wgForceUIMsgAsContentMsg ) &&
544 in_array( $key, $wgForceUIMsgAsContentMsg ) )
545 $forcontent = false;
546 return wfMsgReal( $key, $args, false, $forcontent );
547 }
548
549
550 /**
551 * Really get a message
552 * @param $key String: key to get.
553 * @param $args
554 * @param $useDB Boolean
555 * @param $transform Boolean: Whether or not to transform the message.
556 * @param $forContent Boolean
557 * @return String: the requested message.
558 */
559 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
560 wfProfileIn( __METHOD__ );
561 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
562 $message = wfMsgReplaceArgs( $message, $args );
563 wfProfileOut( __METHOD__ );
564 return $message;
565 }
566
567 /**
568 * This function provides the message source for messages to be edited which are *not* stored in the database.
569 * @param $key String:
570 */
571 function wfMsgWeirdKey ( $key ) {
572 $source = wfMsgGetKey( $key, false, true, false );
573 if ( wfEmptyMsg( $key, $source ) )
574 return "";
575 else
576 return $source;
577 }
578
579 /**
580 * Fetch a message string value, but don't replace any keys yet.
581 * @param string $key
582 * @param bool $useDB
583 * @param string $langcode Code of the language to get the message for, or
584 * behaves as a content language switch if it is a
585 * boolean.
586 * @return string
587 * @private
588 */
589 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
590 global $wgContLang, $wgMessageCache;
591
592 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
593
594 # If $wgMessageCache isn't initialised yet, try to return something sensible.
595 if( is_object( $wgMessageCache ) ) {
596 $message = $wgMessageCache->get( $key, $useDB, $langCode );
597 if ( $transform ) {
598 $message = $wgMessageCache->transform( $message );
599 }
600 } else {
601 $lang = wfGetLangObj( $langCode );
602
603 # MessageCache::get() does this already, Language::getMessage() doesn't
604 # ISSUE: Should we try to handle "message/lang" here too?
605 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
606
607 if( is_object( $lang ) ) {
608 $message = $lang->getMessage( $key );
609 } else {
610 $message = false;
611 }
612 }
613
614 return $message;
615 }
616
617 /**
618 * Replace message parameter keys on the given formatted output.
619 *
620 * @param string $message
621 * @param array $args
622 * @return string
623 * @private
624 */
625 function wfMsgReplaceArgs( $message, $args ) {
626 # Fix windows line-endings
627 # Some messages are split with explode("\n", $msg)
628 $message = str_replace( "\r", '', $message );
629
630 // Replace arguments
631 if ( count( $args ) ) {
632 if ( is_array( $args[0] ) ) {
633 $args = array_values( $args[0] );
634 }
635 $replacementKeys = array();
636 foreach( $args as $n => $param ) {
637 $replacementKeys['$' . ($n + 1)] = $param;
638 }
639 $message = strtr( $message, $replacementKeys );
640 }
641
642 return $message;
643 }
644
645 /**
646 * Return an HTML-escaped version of a message.
647 * Parameter replacements, if any, are done *after* the HTML-escaping,
648 * so parameters may contain HTML (eg links or form controls). Be sure
649 * to pre-escape them if you really do want plaintext, or just wrap
650 * the whole thing in htmlspecialchars().
651 *
652 * @param string $key
653 * @param string ... parameters
654 * @return string
655 */
656 function wfMsgHtml( $key ) {
657 $args = func_get_args();
658 array_shift( $args );
659 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
660 }
661
662 /**
663 * Return an HTML version of message
664 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
665 * so parameters may contain HTML (eg links or form controls). Be sure
666 * to pre-escape them if you really do want plaintext, or just wrap
667 * the whole thing in htmlspecialchars().
668 *
669 * @param string $key
670 * @param string ... parameters
671 * @return string
672 */
673 function wfMsgWikiHtml( $key ) {
674 global $wgOut;
675 $args = func_get_args();
676 array_shift( $args );
677 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
678 }
679
680 /**
681 * Returns message in the requested format
682 * @param string $key Key of the message
683 * @param array $options Processing rules. Can take the following options:
684 * <i>parse</i>: parses wikitext to html
685 * <i>parseinline</i>: parses wikitext to html and removes the surrounding
686 * p's added by parser or tidy
687 * <i>escape</i>: filters message through htmlspecialchars
688 * <i>escapenoentities</i>: same, but allows entity references like &nbsp; through
689 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
690 * <i>parsemag</i>: transform the message using magic phrases
691 * <i>content</i>: fetch message for content language instead of interface
692 * Also can accept a single associative argument, of the form 'language' => 'xx':
693 * <i>language</i>: Language object or language code to fetch message for
694 * (overriden by <i>content</i>), its behaviour with parser, parseinline
695 * and parsemag is undefined.
696 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
697 */
698 function wfMsgExt( $key, $options ) {
699 global $wgOut;
700
701 $args = func_get_args();
702 array_shift( $args );
703 array_shift( $args );
704 $options = (array)$options;
705
706 foreach( $options as $arrayKey => $option ) {
707 if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
708 # An unknown index, neither numeric nor "language"
709 trigger_error( "wfMsgExt called with incorrect parameter key $arrayKey", E_USER_WARNING );
710 } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
711 array( 'parse', 'parseinline', 'escape', 'escapenoentities',
712 'replaceafter', 'parsemag', 'content' ) ) ) {
713 # A numeric index with unknown value
714 trigger_error( "wfMsgExt called with incorrect parameter $option", E_USER_WARNING );
715 }
716 }
717
718 if( in_array('content', $options, true ) ) {
719 $forContent = true;
720 $langCode = true;
721 } elseif( array_key_exists('language', $options) ) {
722 $forContent = false;
723 $langCode = wfGetLangObj( $options['language'] );
724 } else {
725 $forContent = false;
726 $langCode = false;
727 }
728
729 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
730
731 if( !in_array('replaceafter', $options, true ) ) {
732 $string = wfMsgReplaceArgs( $string, $args );
733 }
734
735 if( in_array('parse', $options, true ) ) {
736 $string = $wgOut->parse( $string, true, !$forContent );
737 } elseif ( in_array('parseinline', $options, true ) ) {
738 $string = $wgOut->parse( $string, true, !$forContent );
739 $m = array();
740 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
741 $string = $m[1];
742 }
743 } elseif ( in_array('parsemag', $options, true ) ) {
744 global $wgMessageCache;
745 if ( isset( $wgMessageCache ) ) {
746 $string = $wgMessageCache->transform( $string,
747 !$forContent,
748 is_object( $langCode ) ? $langCode : null );
749 }
750 }
751
752 if ( in_array('escape', $options, true ) ) {
753 $string = htmlspecialchars ( $string );
754 } elseif ( in_array( 'escapenoentities', $options, true ) ) {
755 $string = Sanitizer::escapeHtmlAllowEntities( $string );
756 }
757
758 if( in_array('replaceafter', $options, true ) ) {
759 $string = wfMsgReplaceArgs( $string, $args );
760 }
761
762 return $string;
763 }
764
765
766 /**
767 * Just like exit() but makes a note of it.
768 * Commits open transactions except if the error parameter is set
769 *
770 * @deprecated Please return control to the caller or throw an exception
771 */
772 function wfAbruptExit( $error = false ){
773 static $called = false;
774 if ( $called ){
775 exit( -1 );
776 }
777 $called = true;
778
779 $bt = wfDebugBacktrace();
780 if( $bt ) {
781 for($i = 0; $i < count($bt) ; $i++){
782 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
783 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
784 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
785 }
786 } else {
787 wfDebug("WARNING: Abrupt exit\n");
788 }
789
790 wfLogProfilingData();
791
792 if ( !$error ) {
793 wfGetLB()->closeAll();
794 }
795 exit( -1 );
796 }
797
798 /**
799 * @deprecated Please return control the caller or throw an exception
800 */
801 function wfErrorExit() {
802 wfAbruptExit( true );
803 }
804
805 /**
806 * Print a simple message and die, returning nonzero to the shell if any.
807 * Plain die() fails to return nonzero to the shell if you pass a string.
808 * @param string $msg
809 */
810 function wfDie( $msg='' ) {
811 echo $msg;
812 die( 1 );
813 }
814
815 /**
816 * Throw a debugging exception. This function previously once exited the process,
817 * but now throws an exception instead, with similar results.
818 *
819 * @param string $msg Message shown when dieing.
820 */
821 function wfDebugDieBacktrace( $msg = '' ) {
822 throw new MWException( $msg );
823 }
824
825 /**
826 * Fetch server name for use in error reporting etc.
827 * Use real server name if available, so we know which machine
828 * in a server farm generated the current page.
829 * @return string
830 */
831 function wfHostname() {
832 static $host;
833 if ( is_null( $host ) ) {
834 if ( function_exists( 'posix_uname' ) ) {
835 // This function not present on Windows
836 $uname = @posix_uname();
837 } else {
838 $uname = false;
839 }
840 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
841 $host = $uname['nodename'];
842 } elseif ( getenv( 'COMPUTERNAME' ) ) {
843 # Windows computer name
844 $host = getenv( 'COMPUTERNAME' );
845 } else {
846 # This may be a virtual server.
847 $host = $_SERVER['SERVER_NAME'];
848 }
849 }
850 return $host;
851 }
852
853 /**
854 * Returns a HTML comment with the elapsed time since request.
855 * This method has no side effects.
856 * @return string
857 */
858 function wfReportTime() {
859 global $wgRequestTime, $wgShowHostnames;
860
861 $now = wfTime();
862 $elapsed = $now - $wgRequestTime;
863
864 return $wgShowHostnames
865 ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
866 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
867 }
868
869 /**
870 * Safety wrapper for debug_backtrace().
871 *
872 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
873 * murky circumstances, which may be triggered in part by stub objects
874 * or other fancy talkin'.
875 *
876 * Will return an empty array if Zend Optimizer is detected, otherwise
877 * the output from debug_backtrace() (trimmed).
878 *
879 * @return array of backtrace information
880 */
881 function wfDebugBacktrace() {
882 if( extension_loaded( 'Zend Optimizer' ) ) {
883 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
884 return array();
885 } else {
886 return array_slice( debug_backtrace(), 1 );
887 }
888 }
889
890 function wfBacktrace() {
891 global $wgCommandLineMode;
892
893 if ( $wgCommandLineMode ) {
894 $msg = '';
895 } else {
896 $msg = "<ul>\n";
897 }
898 $backtrace = wfDebugBacktrace();
899 foreach( $backtrace as $call ) {
900 if( isset( $call['file'] ) ) {
901 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
902 $file = $f[count($f)-1];
903 } else {
904 $file = '-';
905 }
906 if( isset( $call['line'] ) ) {
907 $line = $call['line'];
908 } else {
909 $line = '-';
910 }
911 if ( $wgCommandLineMode ) {
912 $msg .= "$file line $line calls ";
913 } else {
914 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
915 }
916 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
917 $msg .= $call['function'] . '()';
918
919 if ( $wgCommandLineMode ) {
920 $msg .= "\n";
921 } else {
922 $msg .= "</li>\n";
923 }
924 }
925 if ( $wgCommandLineMode ) {
926 $msg .= "\n";
927 } else {
928 $msg .= "</ul>\n";
929 }
930
931 return $msg;
932 }
933
934
935 /* Some generic result counters, pulled out of SearchEngine */
936
937
938 /**
939 * @todo document
940 */
941 function wfShowingResults( $offset, $limit ) {
942 global $wgLang;
943 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
944 }
945
946 /**
947 * @todo document
948 */
949 function wfShowingResultsNum( $offset, $limit, $num ) {
950 global $wgLang;
951 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
952 }
953
954 /**
955 * @todo document
956 */
957 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
958 global $wgLang;
959 $fmtLimit = $wgLang->formatNum( $limit );
960 $prev = wfMsg( 'prevn', $fmtLimit );
961 $next = wfMsg( 'nextn', $fmtLimit );
962
963 if( is_object( $link ) ) {
964 $title =& $link;
965 } else {
966 $title = Title::newFromText( $link );
967 if( is_null( $title ) ) {
968 return false;
969 }
970 }
971
972 if ( 0 != $offset ) {
973 $po = $offset - $limit;
974 if ( $po < 0 ) { $po = 0; }
975 $q = "limit={$limit}&offset={$po}";
976 if ( '' != $query ) { $q .= '&'.$query; }
977 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
978 } else { $plink = $prev; }
979
980 $no = $offset + $limit;
981 $q = 'limit='.$limit.'&offset='.$no;
982 if ( '' != $query ) { $q .= '&'.$query; }
983
984 if ( $atend ) {
985 $nlink = $next;
986 } else {
987 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
988 }
989 $nums = $wgLang->pipeList( array( wfNumLink( $offset, 20, $title, $query ),
990 wfNumLink( $offset, 50, $title, $query ),
991 wfNumLink( $offset, 100, $title, $query ),
992 wfNumLink( $offset, 250, $title, $query ),
993 wfNumLink( $offset, 500, $title, $query ) ) );
994
995 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
996 }
997
998 /**
999 * @todo document
1000 */
1001 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
1002 global $wgLang;
1003 if ( '' == $query ) { $q = ''; }
1004 else { $q = $query.'&'; }
1005 $q .= 'limit='.$limit.'&offset='.$offset;
1006
1007 $fmtLimit = $wgLang->formatNum( $limit );
1008 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
1009 return $s;
1010 }
1011
1012 /**
1013 * @todo document
1014 * @todo FIXME: we may want to blacklist some broken browsers
1015 *
1016 * @return bool Whereas client accept gzip compression
1017 */
1018 function wfClientAcceptsGzip() {
1019 global $wgUseGzip;
1020 if( $wgUseGzip ) {
1021 # FIXME: we may want to blacklist some broken browsers
1022 $m = array();
1023 if( preg_match(
1024 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
1025 $_SERVER['HTTP_ACCEPT_ENCODING'],
1026 $m ) ) {
1027 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
1028 wfDebug( " accepts gzip\n" );
1029 return true;
1030 }
1031 }
1032 return false;
1033 }
1034
1035 /**
1036 * Obtain the offset and limit values from the request string;
1037 * used in special pages
1038 *
1039 * @param $deflimit Default limit if none supplied
1040 * @param $optionname Name of a user preference to check against
1041 * @return array
1042 *
1043 */
1044 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1045 global $wgRequest;
1046 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1047 }
1048
1049 /**
1050 * Escapes the given text so that it may be output using addWikiText()
1051 * without any linking, formatting, etc. making its way through. This
1052 * is achieved by substituting certain characters with HTML entities.
1053 * As required by the callers, <nowiki> is not used. It currently does
1054 * not filter out characters which have special meaning only at the
1055 * start of a line, such as "*".
1056 *
1057 * @param string $text Text to be escaped
1058 */
1059 function wfEscapeWikiText( $text ) {
1060 $text = str_replace(
1061 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
1062 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
1063 htmlspecialchars($text) );
1064 return $text;
1065 }
1066
1067 /**
1068 * @todo document
1069 */
1070 function wfQuotedPrintable( $string, $charset = '' ) {
1071 # Probably incomplete; see RFC 2045
1072 if( empty( $charset ) ) {
1073 global $wgInputEncoding;
1074 $charset = $wgInputEncoding;
1075 }
1076 $charset = strtoupper( $charset );
1077 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1078
1079 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1080 $replace = $illegal . '\t ?_';
1081 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1082 $out = "=?$charset?Q?";
1083 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1084 $out .= '?=';
1085 return $out;
1086 }
1087
1088
1089 /**
1090 * @todo document
1091 * @return float
1092 */
1093 function wfTime() {
1094 return microtime(true);
1095 }
1096
1097 /**
1098 * Sets dest to source and returns the original value of dest
1099 * If source is NULL, it just returns the value, it doesn't set the variable
1100 */
1101 function wfSetVar( &$dest, $source ) {
1102 $temp = $dest;
1103 if ( !is_null( $source ) ) {
1104 $dest = $source;
1105 }
1106 return $temp;
1107 }
1108
1109 /**
1110 * As for wfSetVar except setting a bit
1111 */
1112 function wfSetBit( &$dest, $bit, $state = true ) {
1113 $temp = (bool)($dest & $bit );
1114 if ( !is_null( $state ) ) {
1115 if ( $state ) {
1116 $dest |= $bit;
1117 } else {
1118 $dest &= ~$bit;
1119 }
1120 }
1121 return $temp;
1122 }
1123
1124 /**
1125 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1126 * "days=7&limit=100". Options in the first array override options in the second.
1127 * Options set to "" will not be output.
1128 */
1129 function wfArrayToCGI( $array1, $array2 = NULL )
1130 {
1131 if ( !is_null( $array2 ) ) {
1132 $array1 = $array1 + $array2;
1133 }
1134
1135 $cgi = '';
1136 foreach ( $array1 as $key => $value ) {
1137 if ( '' !== $value ) {
1138 if ( '' != $cgi ) {
1139 $cgi .= '&';
1140 }
1141 if(is_array($value))
1142 {
1143 $firstTime = true;
1144 foreach($value as $v)
1145 {
1146 $cgi .= ($firstTime ? '' : '&') .
1147 urlencode( $key . '[]' ) . '=' .
1148 urlencode( $v );
1149 $firstTime = false;
1150 }
1151 }
1152 else
1153 $cgi .= urlencode( $key ) . '=' .
1154 urlencode( $value );
1155 }
1156 }
1157 return $cgi;
1158 }
1159
1160 /**
1161 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1162 * its argument and returns the same string in array form. This allows compa-
1163 * tibility with legacy functions that accept raw query strings instead of nice
1164 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1165 * valid query strings, or it will explode.
1166 *
1167 * @param $query string Query string
1168 * @return array Array version of input
1169 */
1170 function wfCgiToArray( $query ) {
1171 if( isset( $query[0] ) and $query[0] == '?' ) {
1172 $query = substr( $query, 1 );
1173 }
1174 $bits = explode( '&', $query );
1175 $ret = array();
1176 foreach( $bits as $bit ) {
1177 if( $bit === '' ) {
1178 continue;
1179 }
1180 list( $key, $value ) = explode( '=', $bit );
1181 $key = urldecode( $key );
1182 $value = urldecode( $value );
1183 $ret[$key] = $value;
1184 }
1185 return $ret;
1186 }
1187
1188 /**
1189 * Append a query string to an existing URL, which may or may not already
1190 * have query string parameters already. If so, they will be combined.
1191 *
1192 * @param string $url
1193 * @param string $query
1194 * @return string
1195 */
1196 function wfAppendQuery( $url, $query ) {
1197 if( $query != '' ) {
1198 if( false === strpos( $url, '?' ) ) {
1199 $url .= '?';
1200 } else {
1201 $url .= '&';
1202 }
1203 $url .= $query;
1204 }
1205 return $url;
1206 }
1207
1208 /**
1209 * Expand a potentially local URL to a fully-qualified URL.
1210 * Assumes $wgServer is correct. :)
1211 * @param string $url, either fully-qualified or a local path + query
1212 * @return string Fully-qualified URL
1213 */
1214 function wfExpandUrl( $url ) {
1215 if( substr( $url, 0, 1 ) == '/' ) {
1216 global $wgServer;
1217 return $wgServer . $url;
1218 } else {
1219 return $url;
1220 }
1221 }
1222
1223 /**
1224 * This is obsolete, use SquidUpdate::purge()
1225 * @deprecated
1226 */
1227 function wfPurgeSquidServers ($urlArr) {
1228 SquidUpdate::purge( $urlArr );
1229 }
1230
1231 /**
1232 * Windows-compatible version of escapeshellarg()
1233 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1234 * function puts single quotes in regardless of OS.
1235 *
1236 * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
1237 * earlier distro releases of PHP)
1238 */
1239 function wfEscapeShellArg( ) {
1240 wfInitShellLocale();
1241
1242 $args = func_get_args();
1243 $first = true;
1244 $retVal = '';
1245 foreach ( $args as $arg ) {
1246 if ( !$first ) {
1247 $retVal .= ' ';
1248 } else {
1249 $first = false;
1250 }
1251
1252 if ( wfIsWindows() ) {
1253 // Escaping for an MSVC-style command line parser
1254 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1255 // Double the backslashes before any double quotes. Escape the double quotes.
1256 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1257 $arg = '';
1258 $delim = false;
1259 foreach ( $tokens as $token ) {
1260 if ( $delim ) {
1261 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1262 } else {
1263 $arg .= $token;
1264 }
1265 $delim = !$delim;
1266 }
1267 // Double the backslashes before the end of the string, because
1268 // we will soon add a quote
1269 $m = array();
1270 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1271 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1272 }
1273
1274 // Add surrounding quotes
1275 $retVal .= '"' . $arg . '"';
1276 } else {
1277 $retVal .= escapeshellarg( $arg );
1278 }
1279 }
1280 return $retVal;
1281 }
1282
1283 /**
1284 * wfMerge attempts to merge differences between three texts.
1285 * Returns true for a clean merge and false for failure or a conflict.
1286 */
1287 function wfMerge( $old, $mine, $yours, &$result ){
1288 global $wgDiff3;
1289
1290 # This check may also protect against code injection in
1291 # case of broken installations.
1292 if( !$wgDiff3 || !file_exists( $wgDiff3 ) ) {
1293 wfDebug( "diff3 not found\n" );
1294 return false;
1295 }
1296
1297 # Make temporary files
1298 $td = wfTempDir();
1299 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1300 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1301 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1302
1303 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1304 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1305 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1306
1307 # Check for a conflict
1308 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1309 wfEscapeShellArg( $mytextName ) . ' ' .
1310 wfEscapeShellArg( $oldtextName ) . ' ' .
1311 wfEscapeShellArg( $yourtextName );
1312 $handle = popen( $cmd, 'r' );
1313
1314 if( fgets( $handle, 1024 ) ){
1315 $conflict = true;
1316 } else {
1317 $conflict = false;
1318 }
1319 pclose( $handle );
1320
1321 # Merge differences
1322 $cmd = $wgDiff3 . ' -a -e --merge ' .
1323 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1324 $handle = popen( $cmd, 'r' );
1325 $result = '';
1326 do {
1327 $data = fread( $handle, 8192 );
1328 if ( strlen( $data ) == 0 ) {
1329 break;
1330 }
1331 $result .= $data;
1332 } while ( true );
1333 pclose( $handle );
1334 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1335
1336 if ( $result === '' && $old !== '' && $conflict == false ) {
1337 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1338 $conflict = true;
1339 }
1340 return ! $conflict;
1341 }
1342
1343 /**
1344 * Returns unified plain-text diff of two texts.
1345 * Useful for machine processing of diffs.
1346 * @param $before string The text before the changes.
1347 * @param $after string The text after the changes.
1348 * @param $params string Command-line options for the diff command.
1349 * @return string Unified diff of $before and $after
1350 */
1351 function wfDiff( $before, $after, $params = '-u' ) {
1352 global $wgDiff;
1353
1354 # This check may also protect against code injection in
1355 # case of broken installations.
1356 if( !file_exists( $wgDiff ) ){
1357 wfDebug( "diff executable not found\n" );
1358 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1359 $format = new UnifiedDiffFormatter();
1360 return $format->format( $diffs );
1361 }
1362
1363 # Make temporary files
1364 $td = wfTempDir();
1365 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1366 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1367
1368 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1369 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1370
1371 // Get the diff of the two files
1372 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1373
1374 $h = popen( $cmd, 'r' );
1375
1376 $diff = '';
1377
1378 do {
1379 $data = fread( $h, 8192 );
1380 if ( strlen( $data ) == 0 ) {
1381 break;
1382 }
1383 $diff .= $data;
1384 } while ( true );
1385
1386 // Clean up
1387 pclose( $h );
1388 unlink( $oldtextName );
1389 unlink( $newtextName );
1390
1391 // Kill the --- and +++ lines. They're not useful.
1392 $diff_lines = explode( "\n", $diff );
1393 if (strpos( $diff_lines[0], '---' ) === 0) {
1394 unset($diff_lines[0]);
1395 }
1396 if (strpos( $diff_lines[1], '+++' ) === 0) {
1397 unset($diff_lines[1]);
1398 }
1399
1400 $diff = implode( "\n", $diff_lines );
1401
1402 return $diff;
1403 }
1404
1405 /**
1406 * A wrapper around the PHP function var_export().
1407 * Either print it or add it to the regular output ($wgOut).
1408 *
1409 * @param $var A PHP variable to dump.
1410 */
1411 function wfVarDump( $var ) {
1412 global $wgOut;
1413 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1414 if ( headers_sent() || !@is_object( $wgOut ) ) {
1415 print $s;
1416 } else {
1417 $wgOut->addHTML( $s );
1418 }
1419 }
1420
1421 /**
1422 * Provide a simple HTTP error.
1423 */
1424 function wfHttpError( $code, $label, $desc ) {
1425 global $wgOut;
1426 $wgOut->disable();
1427 header( "HTTP/1.0 $code $label" );
1428 header( "Status: $code $label" );
1429 $wgOut->sendCacheControl();
1430
1431 header( 'Content-type: text/html; charset=utf-8' );
1432 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1433 "<html><head><title>" .
1434 htmlspecialchars( $label ) .
1435 "</title></head><body><h1>" .
1436 htmlspecialchars( $label ) .
1437 "</h1><p>" .
1438 nl2br( htmlspecialchars( $desc ) ) .
1439 "</p></body></html>\n";
1440 }
1441
1442 /**
1443 * Clear away any user-level output buffers, discarding contents.
1444 *
1445 * Suitable for 'starting afresh', for instance when streaming
1446 * relatively large amounts of data without buffering, or wanting to
1447 * output image files without ob_gzhandler's compression.
1448 *
1449 * The optional $resetGzipEncoding parameter controls suppression of
1450 * the Content-Encoding header sent by ob_gzhandler; by default it
1451 * is left. See comments for wfClearOutputBuffers() for why it would
1452 * be used.
1453 *
1454 * Note that some PHP configuration options may add output buffer
1455 * layers which cannot be removed; these are left in place.
1456 *
1457 * @param bool $resetGzipEncoding
1458 */
1459 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1460 if( $resetGzipEncoding ) {
1461 // Suppress Content-Encoding and Content-Length
1462 // headers from 1.10+s wfOutputHandler
1463 global $wgDisableOutputCompression;
1464 $wgDisableOutputCompression = true;
1465 }
1466 while( $status = ob_get_status() ) {
1467 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1468 // Probably from zlib.output_compression or other
1469 // PHP-internal setting which can't be removed.
1470 //
1471 // Give up, and hope the result doesn't break
1472 // output behavior.
1473 break;
1474 }
1475 if( !ob_end_clean() ) {
1476 // Could not remove output buffer handler; abort now
1477 // to avoid getting in some kind of infinite loop.
1478 break;
1479 }
1480 if( $resetGzipEncoding ) {
1481 if( $status['name'] == 'ob_gzhandler' ) {
1482 // Reset the 'Content-Encoding' field set by this handler
1483 // so we can start fresh.
1484 header( 'Content-Encoding:' );
1485 break;
1486 }
1487 }
1488 }
1489 }
1490
1491 /**
1492 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1493 *
1494 * Clear away output buffers, but keep the Content-Encoding header
1495 * produced by ob_gzhandler, if any.
1496 *
1497 * This should be used for HTTP 304 responses, where you need to
1498 * preserve the Content-Encoding header of the real result, but
1499 * also need to suppress the output of ob_gzhandler to keep to spec
1500 * and avoid breaking Firefox in rare cases where the headers and
1501 * body are broken over two packets.
1502 */
1503 function wfClearOutputBuffers() {
1504 wfResetOutputBuffers( false );
1505 }
1506
1507 /**
1508 * Converts an Accept-* header into an array mapping string values to quality
1509 * factors
1510 */
1511 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1512 # No arg means accept anything (per HTTP spec)
1513 if( !$accept ) {
1514 return array( $def => 1.0 );
1515 }
1516
1517 $prefs = array();
1518
1519 $parts = explode( ',', $accept );
1520
1521 foreach( $parts as $part ) {
1522 # FIXME: doesn't deal with params like 'text/html; level=1'
1523 @list( $value, $qpart ) = explode( ';', trim( $part ) );
1524 $match = array();
1525 if( !isset( $qpart ) ) {
1526 $prefs[$value] = 1.0;
1527 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1528 $prefs[$value] = floatval($match[1]);
1529 }
1530 }
1531
1532 return $prefs;
1533 }
1534
1535 /**
1536 * Checks if a given MIME type matches any of the keys in the given
1537 * array. Basic wildcards are accepted in the array keys.
1538 *
1539 * Returns the matching MIME type (or wildcard) if a match, otherwise
1540 * NULL if no match.
1541 *
1542 * @param string $type
1543 * @param array $avail
1544 * @return string
1545 * @private
1546 */
1547 function mimeTypeMatch( $type, $avail ) {
1548 if( array_key_exists($type, $avail) ) {
1549 return $type;
1550 } else {
1551 $parts = explode( '/', $type );
1552 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1553 return $parts[0] . '/*';
1554 } elseif( array_key_exists( '*/*', $avail ) ) {
1555 return '*/*';
1556 } else {
1557 return NULL;
1558 }
1559 }
1560 }
1561
1562 /**
1563 * Returns the 'best' match between a client's requested internet media types
1564 * and the server's list of available types. Each list should be an associative
1565 * array of type to preference (preference is a float between 0.0 and 1.0).
1566 * Wildcards in the types are acceptable.
1567 *
1568 * @param array $cprefs Client's acceptable type list
1569 * @param array $sprefs Server's offered types
1570 * @return string
1571 *
1572 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1573 * XXX: generalize to negotiate other stuff
1574 */
1575 function wfNegotiateType( $cprefs, $sprefs ) {
1576 $combine = array();
1577
1578 foreach( array_keys($sprefs) as $type ) {
1579 $parts = explode( '/', $type );
1580 if( $parts[1] != '*' ) {
1581 $ckey = mimeTypeMatch( $type, $cprefs );
1582 if( $ckey ) {
1583 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1584 }
1585 }
1586 }
1587
1588 foreach( array_keys( $cprefs ) as $type ) {
1589 $parts = explode( '/', $type );
1590 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1591 $skey = mimeTypeMatch( $type, $sprefs );
1592 if( $skey ) {
1593 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1594 }
1595 }
1596 }
1597
1598 $bestq = 0;
1599 $besttype = NULL;
1600
1601 foreach( array_keys( $combine ) as $type ) {
1602 if( $combine[$type] > $bestq ) {
1603 $besttype = $type;
1604 $bestq = $combine[$type];
1605 }
1606 }
1607
1608 return $besttype;
1609 }
1610
1611 /**
1612 * Array lookup
1613 * Returns an array where the values in the first array are replaced by the
1614 * values in the second array with the corresponding keys
1615 *
1616 * @return array
1617 */
1618 function wfArrayLookup( $a, $b ) {
1619 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1620 }
1621
1622 /**
1623 * Convenience function; returns MediaWiki timestamp for the present time.
1624 * @return string
1625 */
1626 function wfTimestampNow() {
1627 # return NOW
1628 return wfTimestamp( TS_MW, time() );
1629 }
1630
1631 /**
1632 * Reference-counted warning suppression
1633 */
1634 function wfSuppressWarnings( $end = false ) {
1635 static $suppressCount = 0;
1636 static $originalLevel = false;
1637
1638 if ( $end ) {
1639 if ( $suppressCount ) {
1640 --$suppressCount;
1641 if ( !$suppressCount ) {
1642 error_reporting( $originalLevel );
1643 }
1644 }
1645 } else {
1646 if ( !$suppressCount ) {
1647 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1648 }
1649 ++$suppressCount;
1650 }
1651 }
1652
1653 /**
1654 * Restore error level to previous value
1655 */
1656 function wfRestoreWarnings() {
1657 wfSuppressWarnings( true );
1658 }
1659
1660 # Autodetect, convert and provide timestamps of various types
1661
1662 /**
1663 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1664 */
1665 define('TS_UNIX', 0);
1666
1667 /**
1668 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1669 */
1670 define('TS_MW', 1);
1671
1672 /**
1673 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1674 */
1675 define('TS_DB', 2);
1676
1677 /**
1678 * RFC 2822 format, for E-mail and HTTP headers
1679 */
1680 define('TS_RFC2822', 3);
1681
1682 /**
1683 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1684 *
1685 * This is used by Special:Export
1686 */
1687 define('TS_ISO_8601', 4);
1688
1689 /**
1690 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1691 *
1692 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1693 * DateTime tag and page 36 for the DateTimeOriginal and
1694 * DateTimeDigitized tags.
1695 */
1696 define('TS_EXIF', 5);
1697
1698 /**
1699 * Oracle format time.
1700 */
1701 define('TS_ORACLE', 6);
1702
1703 /**
1704 * Postgres format time.
1705 */
1706 define('TS_POSTGRES', 7);
1707
1708 /**
1709 * DB2 format time
1710 */
1711 define('TS_DB2', 8);
1712
1713 /**
1714 * @param mixed $outputtype A timestamp in one of the supported formats, the
1715 * function will autodetect which format is supplied
1716 * and act accordingly.
1717 * @return string Time in the format specified in $outputtype
1718 */
1719 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1720 $uts = 0;
1721 $da = array();
1722 if ($ts==0) {
1723 $uts=time();
1724 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1725 # TS_DB
1726 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1727 # TS_EXIF
1728 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1729 # TS_MW
1730 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1731 # TS_UNIX
1732 $uts = $ts;
1733 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1734 # TS_ORACLE
1735 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1736 str_replace("+00:00", "UTC", $ts)));
1737 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
1738 # TS_ISO_8601
1739 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
1740 # TS_POSTGRES
1741 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
1742 # TS_POSTGRES
1743 } else {
1744 # Bogus value; fall back to the epoch...
1745 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1746 $uts = 0;
1747 }
1748
1749 if (count( $da ) ) {
1750 // Warning! gmmktime() acts oddly if the month or day is set to 0
1751 // We may want to handle that explicitly at some point
1752 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1753 (int)$da[2],(int)$da[3],(int)$da[1]);
1754 }
1755
1756 switch($outputtype) {
1757 case TS_UNIX:
1758 return $uts;
1759 case TS_MW:
1760 return gmdate( 'YmdHis', $uts );
1761 case TS_DB:
1762 return gmdate( 'Y-m-d H:i:s', $uts );
1763 case TS_ISO_8601:
1764 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1765 // This shouldn't ever be used, but is included for completeness
1766 case TS_EXIF:
1767 return gmdate( 'Y:m:d H:i:s', $uts );
1768 case TS_RFC2822:
1769 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1770 case TS_ORACLE:
1771 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1772 case TS_POSTGRES:
1773 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1774 case TS_DB2:
1775 return gmdate( 'Y-m-d H:i:s', $uts);
1776 default:
1777 throw new MWException( 'wfTimestamp() called with illegal output type.');
1778 }
1779 }
1780
1781 /**
1782 * Return a formatted timestamp, or null if input is null.
1783 * For dealing with nullable timestamp columns in the database.
1784 * @param int $outputtype
1785 * @param string $ts
1786 * @return string
1787 */
1788 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1789 if( is_null( $ts ) ) {
1790 return null;
1791 } else {
1792 return wfTimestamp( $outputtype, $ts );
1793 }
1794 }
1795
1796 /**
1797 * Check if the operating system is Windows
1798 *
1799 * @return bool True if it's Windows, False otherwise.
1800 */
1801 function wfIsWindows() {
1802 if (substr(php_uname(), 0, 7) == 'Windows') {
1803 return true;
1804 } else {
1805 return false;
1806 }
1807 }
1808
1809 /**
1810 * Swap two variables
1811 */
1812 function swap( &$x, &$y ) {
1813 $z = $x;
1814 $x = $y;
1815 $y = $z;
1816 }
1817
1818 function wfGetCachedNotice( $name ) {
1819 global $wgOut, $wgRenderHashAppend, $parserMemc;
1820 $fname = 'wfGetCachedNotice';
1821 wfProfileIn( $fname );
1822
1823 $needParse = false;
1824
1825 if( $name === 'default' ) {
1826 // special case
1827 global $wgSiteNotice;
1828 $notice = $wgSiteNotice;
1829 if( empty( $notice ) ) {
1830 wfProfileOut( $fname );
1831 return false;
1832 }
1833 } else {
1834 $notice = wfMsgForContentNoTrans( $name );
1835 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1836 wfProfileOut( $fname );
1837 return( false );
1838 }
1839 }
1840
1841 // Use the extra hash appender to let eg SSL variants separately cache.
1842 $key = wfMemcKey( $name . $wgRenderHashAppend );
1843 $cachedNotice = $parserMemc->get( $key );
1844 if( is_array( $cachedNotice ) ) {
1845 if( md5( $notice ) == $cachedNotice['hash'] ) {
1846 $notice = $cachedNotice['html'];
1847 } else {
1848 $needParse = true;
1849 }
1850 } else {
1851 $needParse = true;
1852 }
1853
1854 if( $needParse ) {
1855 if( is_object( $wgOut ) ) {
1856 $parsed = $wgOut->parse( $notice );
1857 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1858 $notice = $parsed;
1859 } else {
1860 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
1861 $notice = '';
1862 }
1863 }
1864
1865 wfProfileOut( $fname );
1866 return $notice;
1867 }
1868
1869 function wfGetNamespaceNotice() {
1870 global $wgTitle;
1871
1872 # Paranoia
1873 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1874 return "";
1875
1876 $fname = 'wfGetNamespaceNotice';
1877 wfProfileIn( $fname );
1878
1879 $key = "namespacenotice-" . $wgTitle->getNsText();
1880 $namespaceNotice = wfGetCachedNotice( $key );
1881 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1882 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1883 } else {
1884 $namespaceNotice = "";
1885 }
1886
1887 wfProfileOut( $fname );
1888 return $namespaceNotice;
1889 }
1890
1891 function wfGetSiteNotice() {
1892 global $wgUser, $wgSiteNotice;
1893 $fname = 'wfGetSiteNotice';
1894 wfProfileIn( $fname );
1895 $siteNotice = '';
1896
1897 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1898 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1899 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1900 } else {
1901 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1902 if( !$anonNotice ) {
1903 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1904 } else {
1905 $siteNotice = $anonNotice;
1906 }
1907 }
1908 if( !$siteNotice ) {
1909 $siteNotice = wfGetCachedNotice( 'default' );
1910 }
1911 }
1912
1913 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1914 wfProfileOut( $fname );
1915 return $siteNotice;
1916 }
1917
1918 /**
1919 * BC wrapper for MimeMagic::singleton()
1920 * @deprecated
1921 */
1922 function &wfGetMimeMagic() {
1923 return MimeMagic::singleton();
1924 }
1925
1926 /**
1927 * Tries to get the system directory for temporary files.
1928 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1929 * and if none are set /tmp is returned as the generic Unix default.
1930 *
1931 * NOTE: When possible, use the tempfile() function to create temporary
1932 * files to avoid race conditions on file creation, etc.
1933 *
1934 * @return string
1935 */
1936 function wfTempDir() {
1937 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1938 $tmp = getenv( $var );
1939 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1940 return $tmp;
1941 }
1942 }
1943 # Hope this is Unix of some kind!
1944 return '/tmp';
1945 }
1946
1947 /**
1948 * Make directory, and make all parent directories if they don't exist
1949 *
1950 * @param string $dir Full path to directory to create
1951 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1952 * @return bool
1953 */
1954 function wfMkdirParents( $dir, $mode = null ) {
1955 global $wgDirectoryMode;
1956
1957 if( strval( $dir ) === '' || file_exists( $dir ) )
1958 return true;
1959
1960 if ( is_null( $mode ) )
1961 $mode = $wgDirectoryMode;
1962
1963 return mkdir( $dir, $mode, true ); // PHP5 <3
1964 }
1965
1966 /**
1967 * Increment a statistics counter
1968 */
1969 function wfIncrStats( $key ) {
1970 global $wgStatsMethod;
1971
1972 if( $wgStatsMethod == 'udp' ) {
1973 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1974 static $socket;
1975 if (!$socket) {
1976 $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
1977 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1978 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1979 }
1980 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1981 @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1982 } elseif( $wgStatsMethod == 'cache' ) {
1983 global $wgMemc;
1984 $key = wfMemcKey( 'stats', $key );
1985 if ( is_null( $wgMemc->incr( $key ) ) ) {
1986 $wgMemc->add( $key, 1 );
1987 }
1988 } else {
1989 // Disabled
1990 }
1991 }
1992
1993 /**
1994 * @param mixed $nr The number to format
1995 * @param int $acc The number of digits after the decimal point, default 2
1996 * @param bool $round Whether or not to round the value, default true
1997 * @return float
1998 */
1999 function wfPercent( $nr, $acc = 2, $round = true ) {
2000 $ret = sprintf( "%.${acc}f", $nr );
2001 return $round ? round( $ret, $acc ) . '%' : "$ret%";
2002 }
2003
2004 /**
2005 * Encrypt a username/password.
2006 *
2007 * @param string $userid ID of the user
2008 * @param string $password Password of the user
2009 * @return string Hashed password
2010 * @deprecated Use User::crypt() or User::oldCrypt() instead
2011 */
2012 function wfEncryptPassword( $userid, $password ) {
2013 wfDeprecated(__FUNCTION__);
2014 # Just wrap around User::oldCrypt()
2015 return User::oldCrypt($password, $userid);
2016 }
2017
2018 /**
2019 * Appends to second array if $value differs from that in $default
2020 */
2021 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2022 if ( is_null( $changed ) ) {
2023 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2024 }
2025 if ( $default[$key] !== $value ) {
2026 $changed[$key] = $value;
2027 }
2028 }
2029
2030 /**
2031 * Since wfMsg() and co suck, they don't return false if the message key they
2032 * looked up didn't exist but a XHTML string, this function checks for the
2033 * nonexistance of messages by looking at wfMsg() output
2034 *
2035 * @param $msg The message key looked up
2036 * @param $wfMsgOut The output of wfMsg*()
2037 * @return bool
2038 */
2039 function wfEmptyMsg( $msg, $wfMsgOut ) {
2040 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2041 }
2042
2043 /**
2044 * Find out whether or not a mixed variable exists in a string
2045 *
2046 * @param mixed needle
2047 * @param string haystack
2048 * @return bool
2049 */
2050 function in_string( $needle, $str ) {
2051 return strpos( $str, $needle ) !== false;
2052 }
2053
2054 function wfSpecialList( $page, $details ) {
2055 global $wgContLang;
2056 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
2057 return $page . $details;
2058 }
2059
2060 /**
2061 * Returns a regular expression of url protocols
2062 *
2063 * @return string
2064 */
2065 function wfUrlProtocols() {
2066 global $wgUrlProtocols;
2067
2068 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2069 // with LocalSettings files from 1.5
2070 if ( is_array( $wgUrlProtocols ) ) {
2071 $protocols = array();
2072 foreach ($wgUrlProtocols as $protocol)
2073 $protocols[] = preg_quote( $protocol, '/' );
2074
2075 return implode( '|', $protocols );
2076 } else {
2077 return $wgUrlProtocols;
2078 }
2079 }
2080
2081 /**
2082 * Safety wrapper around ini_get() for boolean settings.
2083 * The values returned from ini_get() are pre-normalized for settings
2084 * set via php.ini or php_flag/php_admin_flag... but *not*
2085 * for those set via php_value/php_admin_value.
2086 *
2087 * It's fairly common for people to use php_value instead of php_flag,
2088 * which can leave you with an 'off' setting giving a false positive
2089 * for code that just takes the ini_get() return value as a boolean.
2090 *
2091 * To make things extra interesting, setting via php_value accepts
2092 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2093 * Unrecognized values go false... again opposite PHP's own coercion
2094 * from string to bool.
2095 *
2096 * Luckily, 'properly' set settings will always come back as '0' or '1',
2097 * so we only have to worry about them and the 'improper' settings.
2098 *
2099 * I frickin' hate PHP... :P
2100 *
2101 * @param string $setting
2102 * @return bool
2103 */
2104 function wfIniGetBool( $setting ) {
2105 $val = ini_get( $setting );
2106 // 'on' and 'true' can't have whitespace around them, but '1' can.
2107 return strtolower( $val ) == 'on'
2108 || strtolower( $val ) == 'true'
2109 || strtolower( $val ) == 'yes'
2110 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2111 }
2112
2113 /**
2114 * Execute a shell command, with time and memory limits mirrored from the PHP
2115 * configuration if supported.
2116 * @param $cmd Command line, properly escaped for shell.
2117 * @param &$retval optional, will receive the program's exit code.
2118 * (non-zero is usually failure)
2119 * @return collected stdout as a string (trailing newlines stripped)
2120 */
2121 function wfShellExec( $cmd, &$retval=null ) {
2122 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
2123
2124 static $disabled;
2125 if ( is_null( $disabled ) ) {
2126 $disabled = false;
2127 if( wfIniGetBool( 'safe_mode' ) ) {
2128 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2129 $disabled = true;
2130 }
2131 $functions = explode( ',', ini_get( 'disable_functions' ) );
2132 $functions = array_map( 'trim', $functions );
2133 $functions = array_map( 'strtolower', $functions );
2134 if ( in_array( 'passthru', $functions ) ) {
2135 wfDebug( "passthru is in disabled_functions\n" );
2136 $disabled = true;
2137 }
2138 }
2139 if ( $disabled ) {
2140 $retval = 1;
2141 return "Unable to run external programs in safe mode.";
2142 }
2143
2144 wfInitShellLocale();
2145
2146 if ( php_uname( 's' ) == 'Linux' ) {
2147 $time = intval( $wgMaxShellTime );
2148 $mem = intval( $wgMaxShellMemory );
2149 $filesize = intval( $wgMaxShellFileSize );
2150
2151 if ( $time > 0 && $mem > 0 ) {
2152 $script = "$IP/bin/ulimit4.sh";
2153 if ( is_executable( $script ) ) {
2154 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2155 }
2156 }
2157 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2158 # This is a hack to work around PHP's flawed invocation of cmd.exe
2159 # http://news.php.net/php.internals/21796
2160 $cmd = '"' . $cmd . '"';
2161 }
2162 wfDebug( "wfShellExec: $cmd\n" );
2163
2164 $retval = 1; // error by default?
2165 ob_start();
2166 passthru( $cmd, $retval );
2167 $output = ob_get_contents();
2168 ob_end_clean();
2169
2170 if ( $retval == 127 ) {
2171 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2172 }
2173 return $output;
2174 }
2175
2176 /**
2177 * Workaround for http://bugs.php.net/bug.php?id=45132
2178 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
2179 */
2180 function wfInitShellLocale() {
2181 static $done = false;
2182 if ( $done ) return;
2183 $done = true;
2184 global $wgShellLocale;
2185 if ( !wfIniGetBool( 'safe_mode' ) ) {
2186 putenv( "LC_CTYPE=$wgShellLocale" );
2187 setlocale( LC_CTYPE, $wgShellLocale );
2188 }
2189 }
2190
2191 /**
2192 * This function works like "use VERSION" in Perl, the program will die with a
2193 * backtrace if the current version of PHP is less than the version provided
2194 *
2195 * This is useful for extensions which due to their nature are not kept in sync
2196 * with releases, and might depend on other versions of PHP than the main code
2197 *
2198 * Note: PHP might die due to parsing errors in some cases before it ever
2199 * manages to call this function, such is life
2200 *
2201 * @see perldoc -f use
2202 *
2203 * @param mixed $version The version to check, can be a string, an integer, or
2204 * a float
2205 */
2206 function wfUsePHP( $req_ver ) {
2207 $php_ver = PHP_VERSION;
2208
2209 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2210 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2211 }
2212
2213 /**
2214 * This function works like "use VERSION" in Perl except it checks the version
2215 * of MediaWiki, the program will die with a backtrace if the current version
2216 * of MediaWiki is less than the version provided.
2217 *
2218 * This is useful for extensions which due to their nature are not kept in sync
2219 * with releases
2220 *
2221 * @see perldoc -f use
2222 *
2223 * @param mixed $version The version to check, can be a string, an integer, or
2224 * a float
2225 */
2226 function wfUseMW( $req_ver ) {
2227 global $wgVersion;
2228
2229 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2230 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2231 }
2232
2233 /**
2234 * @deprecated use StringUtils::escapeRegexReplacement
2235 */
2236 function wfRegexReplacement( $string ) {
2237 return StringUtils::escapeRegexReplacement( $string );
2238 }
2239
2240 /**
2241 * Return the final portion of a pathname.
2242 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2243 * http://bugs.php.net/bug.php?id=33898
2244 *
2245 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2246 * We'll consider it so always, as we don't want \s in our Unix paths either.
2247 *
2248 * @param string $path
2249 * @param string $suffix to remove if present
2250 * @return string
2251 */
2252 function wfBaseName( $path, $suffix='' ) {
2253 $encSuffix = ($suffix == '')
2254 ? ''
2255 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2256 $matches = array();
2257 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2258 return $matches[1];
2259 } else {
2260 return '';
2261 }
2262 }
2263
2264 /**
2265 * Generate a relative path name to the given file.
2266 * May explode on non-matching case-insensitive paths,
2267 * funky symlinks, etc.
2268 *
2269 * @param string $path Absolute destination path including target filename
2270 * @param string $from Absolute source path, directory only
2271 * @return string
2272 */
2273 function wfRelativePath( $path, $from ) {
2274 // Normalize mixed input on Windows...
2275 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
2276 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
2277
2278 // Trim trailing slashes -- fix for drive root
2279 $path = rtrim( $path, DIRECTORY_SEPARATOR );
2280 $from = rtrim( $from, DIRECTORY_SEPARATOR );
2281
2282 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
2283 $against = explode( DIRECTORY_SEPARATOR, $from );
2284
2285 if( $pieces[0] !== $against[0] ) {
2286 // Non-matching Windows drive letters?
2287 // Return a full path.
2288 return $path;
2289 }
2290
2291 // Trim off common prefix
2292 while( count( $pieces ) && count( $against )
2293 && $pieces[0] == $against[0] ) {
2294 array_shift( $pieces );
2295 array_shift( $against );
2296 }
2297
2298 // relative dots to bump us to the parent
2299 while( count( $against ) ) {
2300 array_unshift( $pieces, '..' );
2301 array_shift( $against );
2302 }
2303
2304 array_push( $pieces, wfBaseName( $path ) );
2305
2306 return implode( DIRECTORY_SEPARATOR, $pieces );
2307 }
2308
2309 /**
2310 * Backwards array plus for people who haven't bothered to read the PHP manual
2311 * XXX: will not darn your socks for you.
2312 *
2313 * @param array $array1, [$array2, [...]]
2314 * @return array
2315 */
2316 function wfArrayMerge( $array1/* ... */ ) {
2317 $args = func_get_args();
2318 $args = array_reverse( $args, true );
2319 $out = array();
2320 foreach ( $args as $arg ) {
2321 $out += $arg;
2322 }
2323 return $out;
2324 }
2325
2326 /**
2327 * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
2328 * e.g.
2329 * wfMergeErrorArrays(
2330 * array( array( 'x' ) ),
2331 * array( array( 'x', '2' ) ),
2332 * array( array( 'x' ) ),
2333 * array( array( 'y') )
2334 * );
2335 * returns:
2336 * array(
2337 * array( 'x', '2' ),
2338 * array( 'x' ),
2339 * array( 'y' )
2340 * )
2341 */
2342 function wfMergeErrorArrays(/*...*/) {
2343 $args = func_get_args();
2344 $out = array();
2345 foreach ( $args as $errors ) {
2346 foreach ( $errors as $params ) {
2347 $spec = implode( "\t", $params );
2348 $out[$spec] = $params;
2349 }
2350 }
2351 return array_values( $out );
2352 }
2353
2354 /**
2355 * parse_url() work-alike, but non-broken. Differences:
2356 *
2357 * 1) Does not raise warnings on bad URLs (just returns false)
2358 * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
2359 * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
2360 *
2361 * @param string $url A URL to parse
2362 * @return array Bits of the URL in an associative array, per PHP docs
2363 */
2364 function wfParseUrl( $url ) {
2365 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2366 wfSuppressWarnings();
2367 $bits = parse_url( $url );
2368 wfRestoreWarnings();
2369 if ( !$bits ) {
2370 return false;
2371 }
2372
2373 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2374 if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
2375 $bits['delimiter'] = '://';
2376 } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
2377 $bits['delimiter'] = ':';
2378 // parse_url detects for news: and mailto: the host part of an url as path
2379 // We have to correct this wrong detection
2380 if ( isset ( $bits['path'] ) ) {
2381 $bits['host'] = $bits['path'];
2382 $bits['path'] = '';
2383 }
2384 } else {
2385 return false;
2386 }
2387
2388 return $bits;
2389 }
2390
2391 /**
2392 * Make a URL index, appropriate for the el_index field of externallinks.
2393 */
2394 function wfMakeUrlIndex( $url ) {
2395 $bits = wfParseUrl( $url );
2396
2397 // Reverse the labels in the hostname, convert to lower case
2398 // For emails reverse domainpart only
2399 if ( $bits['scheme'] == 'mailto' ) {
2400 $mailparts = explode( '@', $bits['host'], 2 );
2401 if ( count($mailparts) === 2 ) {
2402 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2403 } else {
2404 // No domain specified, don't mangle it
2405 $domainpart = '';
2406 }
2407 $reversedHost = $domainpart . '@' . $mailparts[0];
2408 } else {
2409 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2410 }
2411 // Add an extra dot to the end
2412 // Why? Is it in wrong place in mailto links?
2413 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2414 $reversedHost .= '.';
2415 }
2416 // Reconstruct the pseudo-URL
2417 $prot = $bits['scheme'];
2418 $index = $prot . $bits['delimiter'] . $reversedHost;
2419 // Leave out user and password. Add the port, path, query and fragment
2420 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2421 if ( isset( $bits['path'] ) ) {
2422 $index .= $bits['path'];
2423 } else {
2424 $index .= '/';
2425 }
2426 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2427 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2428 return $index;
2429 }
2430
2431 /**
2432 * Do any deferred updates and clear the list
2433 * TODO: This could be in Wiki.php if that class made any sense at all
2434 */
2435 function wfDoUpdates()
2436 {
2437 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2438 foreach ( $wgDeferredUpdateList as $update ) {
2439 $update->doUpdate();
2440 }
2441 foreach ( $wgPostCommitUpdateList as $update ) {
2442 $update->doUpdate();
2443 }
2444 $wgDeferredUpdateList = array();
2445 $wgPostCommitUpdateList = array();
2446 }
2447
2448 /**
2449 * @deprecated use StringUtils::explodeMarkup
2450 */
2451 function wfExplodeMarkup( $separator, $text ) {
2452 return StringUtils::explodeMarkup( $separator, $text );
2453 }
2454
2455 /**
2456 * Convert an arbitrarily-long digit string from one numeric base
2457 * to another, optionally zero-padding to a minimum column width.
2458 *
2459 * Supports base 2 through 36; digit values 10-36 are represented
2460 * as lowercase letters a-z. Input is case-insensitive.
2461 *
2462 * @param $input string of digits
2463 * @param $sourceBase int 2-36
2464 * @param $destBase int 2-36
2465 * @param $pad int 1 or greater
2466 * @param $lowercase bool
2467 * @return string or false on invalid input
2468 */
2469 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2470 $input = strval( $input );
2471 if( $sourceBase < 2 ||
2472 $sourceBase > 36 ||
2473 $destBase < 2 ||
2474 $destBase > 36 ||
2475 $pad < 1 ||
2476 $sourceBase != intval( $sourceBase ) ||
2477 $destBase != intval( $destBase ) ||
2478 $pad != intval( $pad ) ||
2479 !is_string( $input ) ||
2480 $input == '' ) {
2481 return false;
2482 }
2483 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2484 $inDigits = array();
2485 $outChars = '';
2486
2487 // Decode and validate input string
2488 $input = strtolower( $input );
2489 for( $i = 0; $i < strlen( $input ); $i++ ) {
2490 $n = strpos( $digitChars, $input{$i} );
2491 if( $n === false || $n > $sourceBase ) {
2492 return false;
2493 }
2494 $inDigits[] = $n;
2495 }
2496
2497 // Iterate over the input, modulo-ing out an output digit
2498 // at a time until input is gone.
2499 while( count( $inDigits ) ) {
2500 $work = 0;
2501 $workDigits = array();
2502
2503 // Long division...
2504 foreach( $inDigits as $digit ) {
2505 $work *= $sourceBase;
2506 $work += $digit;
2507
2508 if( $work < $destBase ) {
2509 // Gonna need to pull another digit.
2510 if( count( $workDigits ) ) {
2511 // Avoid zero-padding; this lets us find
2512 // the end of the input very easily when
2513 // length drops to zero.
2514 $workDigits[] = 0;
2515 }
2516 } else {
2517 // Finally! Actual division!
2518 $workDigits[] = intval( $work / $destBase );
2519
2520 // Isn't it annoying that most programming languages
2521 // don't have a single divide-and-remainder operator,
2522 // even though the CPU implements it that way?
2523 $work = $work % $destBase;
2524 }
2525 }
2526
2527 // All that division leaves us with a remainder,
2528 // which is conveniently our next output digit.
2529 $outChars .= $digitChars[$work];
2530
2531 // And we continue!
2532 $inDigits = $workDigits;
2533 }
2534
2535 while( strlen( $outChars ) < $pad ) {
2536 $outChars .= '0';
2537 }
2538
2539 return strrev( $outChars );
2540 }
2541
2542 /**
2543 * Create an object with a given name and an array of construct parameters
2544 * @param string $name
2545 * @param array $p parameters
2546 */
2547 function wfCreateObject( $name, $p ){
2548 $p = array_values( $p );
2549 switch ( count( $p ) ) {
2550 case 0:
2551 return new $name;
2552 case 1:
2553 return new $name( $p[0] );
2554 case 2:
2555 return new $name( $p[0], $p[1] );
2556 case 3:
2557 return new $name( $p[0], $p[1], $p[2] );
2558 case 4:
2559 return new $name( $p[0], $p[1], $p[2], $p[3] );
2560 case 5:
2561 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2562 case 6:
2563 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2564 default:
2565 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2566 }
2567 }
2568
2569 /**
2570 * Alias for modularized function
2571 * @deprecated Use Http::get() instead
2572 */
2573 function wfGetHTTP( $url, $timeout = 'default' ) {
2574 wfDeprecated(__FUNCTION__);
2575 return Http::get( $url, $timeout );
2576 }
2577
2578 /**
2579 * Alias for modularized function
2580 * @deprecated Use Http::isLocalURL() instead
2581 */
2582 function wfIsLocalURL( $url ) {
2583 wfDeprecated(__FUNCTION__);
2584 return Http::isLocalURL( $url );
2585 }
2586
2587 function wfHttpOnlySafe() {
2588 global $wgHttpOnlyBlacklist;
2589 if( !version_compare("5.2", PHP_VERSION, "<") )
2590 return false;
2591
2592 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2593 foreach( $wgHttpOnlyBlacklist as $regex ) {
2594 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2595 return false;
2596 }
2597 }
2598 }
2599
2600 return true;
2601 }
2602
2603 /**
2604 * Initialise php session
2605 */
2606 function wfSetupSession() {
2607 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2608 if( $wgSessionsInMemcached ) {
2609 require_once( 'MemcachedSessions.php' );
2610 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2611 # If it's left on 'user' or another setting from another
2612 # application, it will end up failing. Try to recover.
2613 ini_set ( 'session.save_handler', 'files' );
2614 }
2615 $httpOnlySafe = wfHttpOnlySafe();
2616 wfDebugLog( 'cookie',
2617 'session_set_cookie_params: "' . implode( '", "',
2618 array(
2619 0,
2620 $wgCookiePath,
2621 $wgCookieDomain,
2622 $wgCookieSecure,
2623 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2624 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2625 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2626 } else {
2627 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2628 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2629 }
2630 session_cache_limiter( 'private, must-revalidate' );
2631 wfSuppressWarnings();
2632 session_start();
2633 wfRestoreWarnings();
2634 }
2635
2636 /**
2637 * Get an object from the precompiled serialized directory
2638 *
2639 * @return mixed The variable on success, false on failure
2640 */
2641 function wfGetPrecompiledData( $name ) {
2642 global $IP;
2643
2644 $file = "$IP/serialized/$name";
2645 if ( file_exists( $file ) ) {
2646 $blob = file_get_contents( $file );
2647 if ( $blob ) {
2648 return unserialize( $blob );
2649 }
2650 }
2651 return false;
2652 }
2653
2654 function wfGetCaller( $level = 2 ) {
2655 $backtrace = wfDebugBacktrace();
2656 if ( isset( $backtrace[$level] ) ) {
2657 return wfFormatStackFrame($backtrace[$level]);
2658 } else {
2659 $caller = 'unknown';
2660 }
2661 return $caller;
2662 }
2663
2664 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2665 function wfGetAllCallers() {
2666 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2667 }
2668
2669 /** Return a string representation of frame */
2670 function wfFormatStackFrame($frame) {
2671 return isset( $frame["class"] )?
2672 $frame["class"]."::".$frame["function"]:
2673 $frame["function"];
2674 }
2675
2676 /**
2677 * Get a cache key
2678 */
2679 function wfMemcKey( /*... */ ) {
2680 $args = func_get_args();
2681 $key = wfWikiID() . ':' . implode( ':', $args );
2682 return $key;
2683 }
2684
2685 /**
2686 * Get a cache key for a foreign DB
2687 */
2688 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2689 $args = array_slice( func_get_args(), 2 );
2690 if ( $prefix ) {
2691 $key = "$db-$prefix:" . implode( ':', $args );
2692 } else {
2693 $key = $db . ':' . implode( ':', $args );
2694 }
2695 return $key;
2696 }
2697
2698 /**
2699 * Get an ASCII string identifying this wiki
2700 * This is used as a prefix in memcached keys
2701 */
2702 function wfWikiID( $db = null ) {
2703 if( $db instanceof Database ) {
2704 return $db->getWikiID();
2705 } else {
2706 global $wgDBprefix, $wgDBname;
2707 if ( $wgDBprefix ) {
2708 return "$wgDBname-$wgDBprefix";
2709 } else {
2710 return $wgDBname;
2711 }
2712 }
2713 }
2714
2715 /**
2716 * Split a wiki ID into DB name and table prefix
2717 */
2718 function wfSplitWikiID( $wiki ) {
2719 $bits = explode( '-', $wiki, 2 );
2720 if ( count( $bits ) < 2 ) {
2721 $bits[] = '';
2722 }
2723 return $bits;
2724 }
2725
2726 /*
2727 * Get a Database object.
2728 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2729 * master (for write queries), DB_SLAVE for potentially lagged
2730 * read queries, or an integer >= 0 for a particular server.
2731 *
2732 * @param mixed $groups Query groups. An array of group names that this query
2733 * belongs to. May contain a single string if the query is only
2734 * in one group.
2735 *
2736 * @param string $wiki The wiki ID, or false for the current wiki
2737 *
2738 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2739 * will always return the same object, unless the underlying connection or load
2740 * balancer is manually destroyed.
2741 */
2742 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2743 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2744 }
2745
2746 /**
2747 * Get a load balancer object.
2748 *
2749 * @param array $groups List of query groups
2750 * @param string $wiki Wiki ID, or false for the current wiki
2751 * @return LoadBalancer
2752 */
2753 function wfGetLB( $wiki = false ) {
2754 return wfGetLBFactory()->getMainLB( $wiki );
2755 }
2756
2757 /**
2758 * Get the load balancer factory object
2759 */
2760 function &wfGetLBFactory() {
2761 return LBFactory::singleton();
2762 }
2763
2764 /**
2765 * Find a file.
2766 * Shortcut for RepoGroup::singleton()->findFile()
2767 * @param mixed $title Title object or string. May be interwiki.
2768 * @param mixed $time Requested time for an archived image, or false for the
2769 * current version. An image object will be returned which
2770 * was created at the specified time.
2771 * @param mixed $flags FileRepo::FIND_ flags
2772 * @param boolean $bypass Bypass the file cache even if it could be used
2773 * @return File, or false if the file does not exist
2774 */
2775 function wfFindFile( $title, $time = false, $flags = 0, $bypass = false ) {
2776 if( !$time && !$flags && !$bypass ) {
2777 return FileCache::singleton()->findFile( $title );
2778 } else {
2779 return RepoGroup::singleton()->findFile( $title, $time, $flags );
2780 }
2781 }
2782
2783 /**
2784 * Get an object referring to a locally registered file.
2785 * Returns a valid placeholder object if the file does not exist.
2786 */
2787 function wfLocalFile( $title ) {
2788 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2789 }
2790
2791 /**
2792 * Should low-performance queries be disabled?
2793 *
2794 * @return bool
2795 */
2796 function wfQueriesMustScale() {
2797 global $wgMiserMode;
2798 return $wgMiserMode
2799 || ( SiteStats::pages() > 100000
2800 && SiteStats::edits() > 1000000
2801 && SiteStats::users() > 10000 );
2802 }
2803
2804 /**
2805 * Get the path to a specified script file, respecting file
2806 * extensions; this is a wrapper around $wgScriptExtension etc.
2807 *
2808 * @param string $script Script filename, sans extension
2809 * @return string
2810 */
2811 function wfScript( $script = 'index' ) {
2812 global $wgScriptPath, $wgScriptExtension;
2813 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2814 }
2815
2816 /**
2817 * Convenience function converts boolean values into "true"
2818 * or "false" (string) values
2819 *
2820 * @param bool $value
2821 * @return string
2822 */
2823 function wfBoolToStr( $value ) {
2824 return $value ? 'true' : 'false';
2825 }
2826
2827 /**
2828 * Load an extension messages file
2829 *
2830 * @param string $extensionName Name of extension to load messages from\for.
2831 * @param string $langcode Language to load messages for, or false for default
2832 * behvaiour (en, content language and user language).
2833 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2834 * on MediaWiki prior to that
2835 */
2836 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2837 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2838
2839 #For recording whether extension message files have been loaded in a given language.
2840 static $loaded = array();
2841
2842 if( !array_key_exists( $extensionName, $loaded ) ) {
2843 $loaded[$extensionName] = array();
2844 }
2845
2846 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2847 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2848 }
2849
2850 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2851 # Just do en, content language and user language.
2852 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2853 # Mark that they have been loaded.
2854 $loaded[$extensionName]['en'] = true;
2855 $loaded[$extensionName][$wgLang->getCode()] = true;
2856 $loaded[$extensionName][$wgContLang->getCode()] = true;
2857 # Mark that this part has been done to avoid weird if statements.
2858 $loaded[$extensionName]['*'] = true;
2859 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2860 # Load messages for specified language.
2861 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2862 # Mark that they have been loaded.
2863 $loaded[$extensionName][$langcode] = true;
2864 }
2865 }
2866
2867 /**
2868 * Get a platform-independent path to the null file, e.g.
2869 * /dev/null
2870 *
2871 * @return string
2872 */
2873 function wfGetNull() {
2874 return wfIsWindows()
2875 ? 'NUL'
2876 : '/dev/null';
2877 }
2878
2879 /**
2880 * Displays a maxlag error
2881 *
2882 * @param string $host Server that lags the most
2883 * @param int $lag Maxlag (actual)
2884 * @param int $maxLag Maxlag (requested)
2885 */
2886 function wfMaxlagError( $host, $lag, $maxLag ) {
2887 global $wgShowHostnames;
2888 header( 'HTTP/1.1 503 Service Unavailable' );
2889 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2890 header( 'X-Database-Lag: ' . intval( $lag ) );
2891 header( 'Content-Type: text/plain' );
2892 if( $wgShowHostnames ) {
2893 echo "Waiting for $host: $lag seconds lagged\n";
2894 } else {
2895 echo "Waiting for a database server: $lag seconds lagged\n";
2896 }
2897 }
2898
2899 /**
2900 * Throws an E_USER_NOTICE saying that $function is deprecated
2901 * @param string $function
2902 * @return null
2903 */
2904 function wfDeprecated( $function ) {
2905 global $wgDebugLogFile;
2906 if ( !$wgDebugLogFile ) {
2907 return;
2908 }
2909 $callers = wfDebugBacktrace();
2910 if( isset( $callers[2] ) ){
2911 $callerfunc = $callers[2];
2912 $callerfile = $callers[1];
2913 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2914 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2915 } else {
2916 $file = '(internal function)';
2917 }
2918 $func = '';
2919 if( isset( $callerfunc['class'] ) )
2920 $func .= $callerfunc['class'] . '::';
2921 $func .= @$callerfunc['function'];
2922 $msg = "Use of $function is deprecated. Called from $func in $file";
2923 } else {
2924 $msg = "Use of $function is deprecated.";
2925 }
2926 wfDebug( "$msg\n" );
2927 }
2928
2929 /**
2930 * Sleep until the worst slave's replication lag is less than or equal to
2931 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2932 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2933 * a no-op if there are no slaves.
2934 *
2935 * Every time the function has to wait for a slave, it will print a message to
2936 * that effect (and then sleep for a little while), so it's probably not best
2937 * to use this outside maintenance scripts in its present form.
2938 *
2939 * @param int $maxLag
2940 * @return null
2941 */
2942 function wfWaitForSlaves( $maxLag ) {
2943 if( $maxLag ) {
2944 $lb = wfGetLB();
2945 list( $host, $lag ) = $lb->getMaxLag();
2946 while( $lag > $maxLag ) {
2947 $name = @gethostbyaddr( $host );
2948 if( $name !== false ) {
2949 $host = $name;
2950 }
2951 print "Waiting for $host (lagged $lag seconds)...\n";
2952 sleep($maxLag);
2953 list( $host, $lag ) = $lb->getMaxLag();
2954 }
2955 }
2956 }
2957
2958 /**
2959 * Output some plain text in command-line mode or in the installer (updaters.inc).
2960 * Do not use it in any other context, its behaviour is subject to change.
2961 */
2962 function wfOut( $s ) {
2963 static $lineStarted = false;
2964 global $wgCommandLineMode;
2965 if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
2966 echo $s;
2967 } else {
2968 echo htmlspecialchars( $s );
2969 }
2970 flush();
2971 }
2972
2973 /** Generate a random 32-character hexadecimal token.
2974 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2975 */
2976 function wfGenerateToken( $salt = '' ) {
2977 $salt = serialize($salt);
2978
2979 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2980 }
2981
2982 /**
2983 * Replace all invalid characters with -
2984 * @param mixed $title Filename to process
2985 */
2986 function wfStripIllegalFilenameChars( $name ) {
2987 $name = wfBaseName( $name );
2988 $name = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $name );
2989 return $name;
2990 }