Use addQuotes() consistently when building lists of group and user names.
[mediawiki.git] / includes / GlobalFunctions.php
blobe70bc46082ecd6b8583c19872bd11b9176fc8eb7
1 <?php
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
7 /**
8 * Global functions used everywhere
9 */
11 require_once dirname(__FILE__) . '/LogPage.php';
12 require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__) . '/XmlFunctions.php';
15 /**
16 * Compatibility functions
18 * We more or less support PHP 5.0.x and up.
19 * Re-implementations of newer functions or functions in non-standard
20 * PHP extensions may be included here.
22 if( !function_exists('iconv') ) {
23 # iconv support is not in the default configuration and so may not be present.
24 # Assume will only ever use utf-8 and iso-8859-1.
25 # This will *not* work in all circumstances.
26 function iconv( $from, $to, $string ) {
27 if(strcasecmp( $from, $to ) == 0) return $string;
28 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
29 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
30 return $string;
34 # UTF-8 substr function based on a PHP manual comment
35 if ( !function_exists( 'mb_substr' ) ) {
36 function mb_substr( $str, $start ) {
37 $ar = array();
38 preg_match_all( '/./us', $str, $ar );
40 if( func_num_args() >= 3 ) {
41 $end = func_get_arg( 2 );
42 return join( '', array_slice( $ar[0], $start, $end ) );
43 } else {
44 return join( '', array_slice( $ar[0], $start ) );
49 if ( !function_exists( 'mb_strlen' ) ) {
50 /**
51 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
52 * @param string $str
53 * @param string $enc optional encoding; ignored
54 * @return int
56 function mb_strlen( $str, $enc="" ) {
57 $counts = count_chars( $str );
58 $total = 0;
60 // Count ASCII bytes
61 for( $i = 0; $i < 0x80; $i++ ) {
62 $total += $counts[$i];
65 // Count multibyte sequence heads
66 for( $i = 0xc0; $i < 0xff; $i++ ) {
67 $total += $counts[$i];
69 return $total;
73 if ( !function_exists( 'array_diff_key' ) ) {
74 /**
75 * Exists in PHP 5.1.0+
76 * Not quite compatible, two-argument version only
77 * Null values will cause problems due to this use of isset()
79 function array_diff_key( $left, $right ) {
80 $result = $left;
81 foreach ( $left as $key => $unused ) {
82 if ( isset( $right[$key] ) ) {
83 unset( $result[$key] );
86 return $result;
91 /**
92 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
93 * PHP 5 won't let you declare a 'clone' function, even conditionally,
94 * so it has to be a wrapper with a different name.
96 function wfClone( $object ) {
97 return clone( $object );
101 * Seed Mersenne Twister
102 * No-op for compatibility; only necessary in PHP < 4.2.0
104 function wfSeedRandom() {
105 /* No-op */
109 * Get a random decimal value between 0 and 1, in a way
110 * not likely to give duplicate values for any realistic
111 * number of articles.
113 * @return string
115 function wfRandom() {
116 # The maximum random value is "only" 2^31-1, so get two random
117 # values to reduce the chance of dupes
118 $max = mt_getrandmax() + 1;
119 $rand = number_format( (mt_rand() * $max + mt_rand())
120 / $max / $max, 12, '.', '' );
121 return $rand;
125 * We want / and : to be included as literal characters in our title URLs.
126 * %2F in the page titles seems to fatally break for some reason.
128 * @param $s String:
129 * @return string
131 function wfUrlencode ( $s ) {
132 $s = urlencode( $s );
133 $s = preg_replace( '/%3[Aa]/', ':', $s );
134 $s = preg_replace( '/%2[Ff]/', '/', $s );
136 return $s;
140 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
141 * In normal operation this is a NOP.
143 * Controlling globals:
144 * $wgDebugLogFile - points to the log file
145 * $wgProfileOnly - if set, normal debug messages will not be recorded.
146 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
147 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
149 * @param $text String
150 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
152 function wfDebug( $text, $logonly = false ) {
153 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
154 static $recursion = 0;
156 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
157 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
158 return;
161 if ( $wgDebugComments && !$logonly ) {
162 if ( !isset( $wgOut ) ) {
163 return;
165 if ( !StubObject::isRealObject( $wgOut ) ) {
166 if ( $recursion ) {
167 return;
169 $recursion++;
170 $wgOut->_unstub();
171 $recursion--;
173 $wgOut->debug( $text );
175 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
176 # Strip unprintables; they can switch terminal modes when binary data
177 # gets dumped, which is pretty annoying.
178 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
179 wfErrorLog( $text, $wgDebugLogFile );
184 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
185 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
187 * @param $logGroup String
188 * @param $text String
189 * @param $public Bool: whether to log the event in the public log if no private
190 * log file is specified, (default true)
192 function wfDebugLog( $logGroup, $text, $public = true ) {
193 global $wgDebugLogGroups;
194 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
195 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
196 $time = wfTimestamp( TS_DB );
197 $wiki = wfWikiID();
198 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
199 } else if ( $public === true ) {
200 wfDebug( $text, true );
205 * Log for database errors
206 * @param $text String: database error message.
208 function wfLogDBError( $text ) {
209 global $wgDBerrorLog, $wgDBname;
210 if ( $wgDBerrorLog ) {
211 $host = trim(`hostname`);
212 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
213 wfErrorLog( $text, $wgDBerrorLog );
218 * Log to a file without getting "file size exceeded" signals
220 function wfErrorLog( $text, $file ) {
221 wfSuppressWarnings();
222 $exists = file_exists( $file );
223 $size = $exists ? filesize( $file ) : false;
224 if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
225 error_log( $text, 3, $file );
227 wfRestoreWarnings();
231 * @todo document
233 function wfLogProfilingData() {
234 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
235 global $wgProfiling, $wgUser;
236 if ( $wgProfiling ) {
237 $now = wfTime();
238 $elapsed = $now - $wgRequestTime;
239 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
240 $forward = '';
241 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
242 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
243 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
244 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
245 if( !empty( $_SERVER['HTTP_FROM'] ) )
246 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
247 if( $forward )
248 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
249 // Don't unstub $wgUser at this late stage just for statistics purposes
250 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
251 $forward .= ' anon';
252 $log = sprintf( "%s\t%04.3f\t%s\n",
253 gmdate( 'YmdHis' ), $elapsed,
254 urldecode( $wgRequest->getRequestURL() . $forward ) );
255 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
256 wfErrorLog( $log . $prof, $wgDebugLogFile );
262 * Check if the wiki read-only lock file is present. This can be used to lock
263 * off editing functions, but doesn't guarantee that the database will not be
264 * modified.
265 * @return bool
267 function wfReadOnly() {
268 global $wgReadOnlyFile, $wgReadOnly;
270 if ( !is_null( $wgReadOnly ) ) {
271 return (bool)$wgReadOnly;
273 if ( '' == $wgReadOnlyFile ) {
274 return false;
276 // Set $wgReadOnly for faster access next time
277 if ( is_file( $wgReadOnlyFile ) ) {
278 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
279 } else {
280 $wgReadOnly = false;
282 return (bool)$wgReadOnly;
287 * Get a message from anywhere, for the current user language.
289 * Use wfMsgForContent() instead if the message should NOT
290 * change depending on the user preferences.
292 * Note that the message may contain HTML, and is therefore
293 * not safe for insertion anywhere. Some functions such as
294 * addWikiText will do the escaping for you. Use wfMsgHtml()
295 * if you need an escaped message.
297 * @param $key String: lookup key for the message, usually
298 * defined in languages/Language.php
300 * This function also takes extra optional parameters (not
301 * shown in the function definition), which can by used to
302 * insert variable text into the predefined message.
304 function wfMsg( $key ) {
305 $args = func_get_args();
306 array_shift( $args );
307 return wfMsgReal( $key, $args, true );
311 * Same as above except doesn't transform the message
313 function wfMsgNoTrans( $key ) {
314 $args = func_get_args();
315 array_shift( $args );
316 return wfMsgReal( $key, $args, true, false, false );
320 * Get a message from anywhere, for the current global language
321 * set with $wgLanguageCode.
323 * Use this if the message should NOT change dependent on the
324 * language set in the user's preferences. This is the case for
325 * most text written into logs, as well as link targets (such as
326 * the name of the copyright policy page). Link titles, on the
327 * other hand, should be shown in the UI language.
329 * Note that MediaWiki allows users to change the user interface
330 * language in their preferences, but a single installation
331 * typically only contains content in one language.
333 * Be wary of this distinction: If you use wfMsg() where you should
334 * use wfMsgForContent(), a user of the software may have to
335 * customize over 70 messages in order to, e.g., fix a link in every
336 * possible language.
338 * @param $key String: lookup key for the message, usually
339 * defined in languages/Language.php
341 function wfMsgForContent( $key ) {
342 global $wgForceUIMsgAsContentMsg;
343 $args = func_get_args();
344 array_shift( $args );
345 $forcontent = true;
346 if( is_array( $wgForceUIMsgAsContentMsg ) &&
347 in_array( $key, $wgForceUIMsgAsContentMsg ) )
348 $forcontent = false;
349 return wfMsgReal( $key, $args, true, $forcontent );
353 * Same as above except doesn't transform the message
355 function wfMsgForContentNoTrans( $key ) {
356 global $wgForceUIMsgAsContentMsg;
357 $args = func_get_args();
358 array_shift( $args );
359 $forcontent = true;
360 if( is_array( $wgForceUIMsgAsContentMsg ) &&
361 in_array( $key, $wgForceUIMsgAsContentMsg ) )
362 $forcontent = false;
363 return wfMsgReal( $key, $args, true, $forcontent, false );
367 * Get a message from the language file, for the UI elements
369 function wfMsgNoDB( $key ) {
370 $args = func_get_args();
371 array_shift( $args );
372 return wfMsgReal( $key, $args, false );
376 * Get a message from the language file, for the content
378 function wfMsgNoDBForContent( $key ) {
379 global $wgForceUIMsgAsContentMsg;
380 $args = func_get_args();
381 array_shift( $args );
382 $forcontent = true;
383 if( is_array( $wgForceUIMsgAsContentMsg ) &&
384 in_array( $key, $wgForceUIMsgAsContentMsg ) )
385 $forcontent = false;
386 return wfMsgReal( $key, $args, false, $forcontent );
391 * Really get a message
392 * @param $key String: key to get.
393 * @param $args
394 * @param $useDB Boolean
395 * @param $transform Boolean: Whether or not to transform the message.
396 * @param $forContent Boolean
397 * @return String: the requested message.
399 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
400 wfProfileIn( __METHOD__ );
401 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
402 $message = wfMsgReplaceArgs( $message, $args );
403 wfProfileOut( __METHOD__ );
404 return $message;
408 * This function provides the message source for messages to be edited which are *not* stored in the database.
409 * @param $key String:
411 function wfMsgWeirdKey ( $key ) {
412 $source = wfMsgGetKey( $key, false, true, false );
413 if ( wfEmptyMsg( $key, $source ) )
414 return "";
415 else
416 return $source;
420 * Fetch a message string value, but don't replace any keys yet.
421 * @param string $key
422 * @param bool $useDB
423 * @param bool $forContent
424 * @return string
425 * @private
427 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
428 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
430 /* <Vyznev> btw, is all that code in wfMsgGetKey() that check
431 * if the message cache exists of not really necessary, or is
432 * it just paranoia?
433 * <TimStarling> Vyznev: it's probably not necessary
434 * <TimStarling> I think I wrote it in an attempt to report DB
435 * connection errors properly
436 * <TimStarling> but eventually we gave up on using the
437 * message cache for that and just hard-coded the strings
438 * <TimStarling> it may have other uses, it's not mere paranoia
441 if ( is_object( $wgMessageCache ) )
442 $transstat = $wgMessageCache->getTransform();
444 if( is_object( $wgMessageCache ) ) {
445 if ( ! $transform )
446 $wgMessageCache->disableTransform();
447 $message = $wgMessageCache->get( $key, $useDB, $forContent );
448 } else {
449 if( $forContent ) {
450 $lang = &$wgContLang;
451 } else {
452 $lang = &$wgLang;
455 # MessageCache::get() does this already, Language::getMessage() doesn't
456 # ISSUE: Should we try to handle "message/lang" here too?
457 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
459 wfSuppressWarnings();
460 if( is_object( $lang ) ) {
461 $message = $lang->getMessage( $key );
462 } else {
463 $message = false;
465 wfRestoreWarnings();
467 if ( $transform && strstr( $message, '{{' ) !== false ) {
468 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
472 if ( is_object( $wgMessageCache ) && ! $transform )
473 $wgMessageCache->setTransform( $transstat );
475 return $message;
479 * Replace message parameter keys on the given formatted output.
481 * @param string $message
482 * @param array $args
483 * @return string
484 * @private
486 function wfMsgReplaceArgs( $message, $args ) {
487 # Fix windows line-endings
488 # Some messages are split with explode("\n", $msg)
489 $message = str_replace( "\r", '', $message );
491 // Replace arguments
492 if ( count( $args ) ) {
493 if ( is_array( $args[0] ) ) {
494 foreach ( $args[0] as $key => $val ) {
495 $message = str_replace( '$' . $key, $val, $message );
497 } else {
498 foreach( $args as $n => $param ) {
499 $replacementKeys['$' . ($n + 1)] = $param;
501 $message = strtr( $message, $replacementKeys );
505 return $message;
509 * Return an HTML-escaped version of a message.
510 * Parameter replacements, if any, are done *after* the HTML-escaping,
511 * so parameters may contain HTML (eg links or form controls). Be sure
512 * to pre-escape them if you really do want plaintext, or just wrap
513 * the whole thing in htmlspecialchars().
515 * @param string $key
516 * @param string ... parameters
517 * @return string
519 function wfMsgHtml( $key ) {
520 $args = func_get_args();
521 array_shift( $args );
522 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
526 * Return an HTML version of message
527 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
528 * so parameters may contain HTML (eg links or form controls). Be sure
529 * to pre-escape them if you really do want plaintext, or just wrap
530 * the whole thing in htmlspecialchars().
532 * @param string $key
533 * @param string ... parameters
534 * @return string
536 function wfMsgWikiHtml( $key ) {
537 global $wgOut;
538 $args = func_get_args();
539 array_shift( $args );
540 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
544 * Returns message in the requested format
545 * @param string $key Key of the message
546 * @param array $options Processing rules:
547 * <i>parse</i>: parses wikitext to html
548 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
549 * <i>escape</i>: filters message through htmlspecialchars
550 * <i>escapenoentities</i>: same, but allows entity references like &nbsp; through
551 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
552 * <i>parsemag</i>: transform the message using magic phrases
553 * <i>content</i>: fetch message for content language instead of interface
554 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
556 function wfMsgExt( $key, $options ) {
557 global $wgOut, $wgParser;
559 $args = func_get_args();
560 array_shift( $args );
561 array_shift( $args );
563 if( !is_array($options) ) {
564 $options = array($options);
567 $forContent = false;
568 if( in_array('content', $options) ) {
569 $forContent = true;
572 $string = wfMsgGetKey( $key, /*DB*/true, $forContent, /*Transform*/false );
574 if( !in_array('replaceafter', $options) ) {
575 $string = wfMsgReplaceArgs( $string, $args );
578 if( in_array('parse', $options) ) {
579 $string = $wgOut->parse( $string, true, !$forContent );
580 } elseif ( in_array('parseinline', $options) ) {
581 $string = $wgOut->parse( $string, true, !$forContent );
582 $m = array();
583 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
584 $string = $m[1];
586 } elseif ( in_array('parsemag', $options) ) {
587 global $wgMessageCache;
588 if ( isset( $wgMessageCache ) ) {
589 $string = $wgMessageCache->transform( $string, !$forContent );
593 if ( in_array('escape', $options) ) {
594 $string = htmlspecialchars ( $string );
595 } elseif ( in_array( 'escapenoentities', $options ) ) {
596 $string = htmlspecialchars( $string );
597 $string = str_replace( '&amp;', '&', $string );
598 $string = Sanitizer::normalizeCharReferences( $string );
601 if( in_array('replaceafter', $options) ) {
602 $string = wfMsgReplaceArgs( $string, $args );
605 return $string;
610 * Just like exit() but makes a note of it.
611 * Commits open transactions except if the error parameter is set
613 * @deprecated Please return control to the caller or throw an exception
615 function wfAbruptExit( $error = false ){
616 global $wgLoadBalancer;
617 static $called = false;
618 if ( $called ){
619 exit( -1 );
621 $called = true;
623 $bt = wfDebugBacktrace();
624 if( $bt ) {
625 for($i = 0; $i < count($bt) ; $i++){
626 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
627 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
628 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
630 } else {
631 wfDebug('WARNING: Abrupt exit\n');
634 wfLogProfilingData();
636 if ( !$error ) {
637 $wgLoadBalancer->closeAll();
639 exit( -1 );
643 * @deprecated Please return control the caller or throw an exception
645 function wfErrorExit() {
646 wfAbruptExit( true );
650 * Print a simple message and die, returning nonzero to the shell if any.
651 * Plain die() fails to return nonzero to the shell if you pass a string.
652 * @param string $msg
654 function wfDie( $msg='' ) {
655 echo $msg;
656 die( 1 );
660 * Throw a debugging exception. This function previously once exited the process,
661 * but now throws an exception instead, with similar results.
663 * @param string $msg Message shown when dieing.
665 function wfDebugDieBacktrace( $msg = '' ) {
666 throw new MWException( $msg );
670 * Fetch server name for use in error reporting etc.
671 * Use real server name if available, so we know which machine
672 * in a server farm generated the current page.
673 * @return string
675 function wfHostname() {
676 if ( function_exists( 'posix_uname' ) ) {
677 // This function not present on Windows
678 $uname = @posix_uname();
679 } else {
680 $uname = false;
682 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
683 return $uname['nodename'];
684 } else {
685 # This may be a virtual server.
686 return $_SERVER['SERVER_NAME'];
691 * Returns a HTML comment with the elapsed time since request.
692 * This method has no side effects.
693 * @return string
695 function wfReportTime() {
696 global $wgRequestTime, $wgShowHostnames;
698 $now = wfTime();
699 $elapsed = $now - $wgRequestTime;
701 return $wgShowHostnames
702 ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
703 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
707 * Safety wrapper for debug_backtrace().
709 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
710 * murky circumstances, which may be triggered in part by stub objects
711 * or other fancy talkin'.
713 * Will return an empty array if Zend Optimizer is detected, otherwise
714 * the output from debug_backtrace() (trimmed).
716 * @return array of backtrace information
718 function wfDebugBacktrace() {
719 if( extension_loaded( 'Zend Optimizer' ) ) {
720 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
721 return array();
722 } else {
723 return array_slice( debug_backtrace(), 1 );
727 function wfBacktrace() {
728 global $wgCommandLineMode;
730 if ( $wgCommandLineMode ) {
731 $msg = '';
732 } else {
733 $msg = "<ul>\n";
735 $backtrace = wfDebugBacktrace();
736 foreach( $backtrace as $call ) {
737 if( isset( $call['file'] ) ) {
738 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
739 $file = $f[count($f)-1];
740 } else {
741 $file = '-';
743 if( isset( $call['line'] ) ) {
744 $line = $call['line'];
745 } else {
746 $line = '-';
748 if ( $wgCommandLineMode ) {
749 $msg .= "$file line $line calls ";
750 } else {
751 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
753 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
754 $msg .= $call['function'] . '()';
756 if ( $wgCommandLineMode ) {
757 $msg .= "\n";
758 } else {
759 $msg .= "</li>\n";
762 if ( $wgCommandLineMode ) {
763 $msg .= "\n";
764 } else {
765 $msg .= "</ul>\n";
768 return $msg;
772 /* Some generic result counters, pulled out of SearchEngine */
776 * @todo document
778 function wfShowingResults( $offset, $limit ) {
779 global $wgLang;
780 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
784 * @todo document
786 function wfShowingResultsNum( $offset, $limit, $num ) {
787 global $wgLang;
788 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
792 * @todo document
794 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
795 global $wgLang;
796 $fmtLimit = $wgLang->formatNum( $limit );
797 $prev = wfMsg( 'prevn', $fmtLimit );
798 $next = wfMsg( 'nextn', $fmtLimit );
800 if( is_object( $link ) ) {
801 $title =& $link;
802 } else {
803 $title = Title::newFromText( $link );
804 if( is_null( $title ) ) {
805 return false;
809 if ( 0 != $offset ) {
810 $po = $offset - $limit;
811 if ( $po < 0 ) { $po = 0; }
812 $q = "limit={$limit}&offset={$po}";
813 if ( '' != $query ) { $q .= '&'.$query; }
814 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
815 } else { $plink = $prev; }
817 $no = $offset + $limit;
818 $q = 'limit='.$limit.'&offset='.$no;
819 if ( '' != $query ) { $q .= '&'.$query; }
821 if ( $atend ) {
822 $nlink = $next;
823 } else {
824 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
826 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
827 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
828 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
829 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
830 wfNumLink( $offset, 500, $title, $query );
832 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
836 * @todo document
838 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
839 global $wgLang;
840 if ( '' == $query ) { $q = ''; }
841 else { $q = $query.'&'; }
842 $q .= 'limit='.$limit.'&offset='.$offset;
844 $fmtLimit = $wgLang->formatNum( $limit );
845 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
846 return $s;
850 * @todo document
851 * @todo FIXME: we may want to blacklist some broken browsers
853 * @return bool Whereas client accept gzip compression
855 function wfClientAcceptsGzip() {
856 global $wgUseGzip;
857 if( $wgUseGzip ) {
858 # FIXME: we may want to blacklist some broken browsers
859 $m = array();
860 if( preg_match(
861 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
862 $_SERVER['HTTP_ACCEPT_ENCODING'],
863 $m ) ) {
864 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
865 wfDebug( " accepts gzip\n" );
866 return true;
869 return false;
873 * Obtain the offset and limit values from the request string;
874 * used in special pages
876 * @param $deflimit Default limit if none supplied
877 * @param $optionname Name of a user preference to check against
878 * @return array
881 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
882 global $wgRequest;
883 return $wgRequest->getLimitOffset( $deflimit, $optionname );
887 * Escapes the given text so that it may be output using addWikiText()
888 * without any linking, formatting, etc. making its way through. This
889 * is achieved by substituting certain characters with HTML entities.
890 * As required by the callers, <nowiki> is not used. It currently does
891 * not filter out characters which have special meaning only at the
892 * start of a line, such as "*".
894 * @param string $text Text to be escaped
896 function wfEscapeWikiText( $text ) {
897 $text = str_replace(
898 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
899 array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
900 htmlspecialchars($text) );
901 return $text;
905 * @todo document
907 function wfQuotedPrintable( $string, $charset = '' ) {
908 # Probably incomplete; see RFC 2045
909 if( empty( $charset ) ) {
910 global $wgInputEncoding;
911 $charset = $wgInputEncoding;
913 $charset = strtoupper( $charset );
914 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
916 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
917 $replace = $illegal . '\t ?_';
918 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
919 $out = "=?$charset?Q?";
920 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
921 $out .= '?=';
922 return $out;
927 * @todo document
928 * @return float
930 function wfTime() {
931 return microtime(true);
935 * Sets dest to source and returns the original value of dest
936 * If source is NULL, it just returns the value, it doesn't set the variable
938 function wfSetVar( &$dest, $source ) {
939 $temp = $dest;
940 if ( !is_null( $source ) ) {
941 $dest = $source;
943 return $temp;
947 * As for wfSetVar except setting a bit
949 function wfSetBit( &$dest, $bit, $state = true ) {
950 $temp = (bool)($dest & $bit );
951 if ( !is_null( $state ) ) {
952 if ( $state ) {
953 $dest |= $bit;
954 } else {
955 $dest &= ~$bit;
958 return $temp;
962 * This function takes two arrays as input, and returns a CGI-style string, e.g.
963 * "days=7&limit=100". Options in the first array override options in the second.
964 * Options set to "" will not be output.
966 function wfArrayToCGI( $array1, $array2 = NULL )
968 if ( !is_null( $array2 ) ) {
969 $array1 = $array1 + $array2;
972 $cgi = '';
973 foreach ( $array1 as $key => $value ) {
974 if ( '' !== $value ) {
975 if ( '' != $cgi ) {
976 $cgi .= '&';
978 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
981 return $cgi;
985 * Append a query string to an existing URL, which may or may not already
986 * have query string parameters already. If so, they will be combined.
988 * @param string $url
989 * @param string $query
990 * @return string
992 function wfAppendQuery( $url, $query ) {
993 if( $query != '' ) {
994 if( false === strpos( $url, '?' ) ) {
995 $url .= '?';
996 } else {
997 $url .= '&';
999 $url .= $query;
1001 return $url;
1005 * This is obsolete, use SquidUpdate::purge()
1006 * @deprecated
1008 function wfPurgeSquidServers ($urlArr) {
1009 SquidUpdate::purge( $urlArr );
1013 * Windows-compatible version of escapeshellarg()
1014 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1015 * function puts single quotes in regardless of OS
1017 function wfEscapeShellArg( ) {
1018 $args = func_get_args();
1019 $first = true;
1020 $retVal = '';
1021 foreach ( $args as $arg ) {
1022 if ( !$first ) {
1023 $retVal .= ' ';
1024 } else {
1025 $first = false;
1028 if ( wfIsWindows() ) {
1029 // Escaping for an MSVC-style command line parser
1030 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1031 // Double the backslashes before any double quotes. Escape the double quotes.
1032 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
1033 $arg = '';
1034 $delim = false;
1035 foreach ( $tokens as $token ) {
1036 if ( $delim ) {
1037 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1038 } else {
1039 $arg .= $token;
1041 $delim = !$delim;
1043 // Double the backslashes before the end of the string, because
1044 // we will soon add a quote
1045 $m = array();
1046 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1047 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1050 // Add surrounding quotes
1051 $retVal .= '"' . $arg . '"';
1052 } else {
1053 $retVal .= escapeshellarg( $arg );
1056 return $retVal;
1060 * wfMerge attempts to merge differences between three texts.
1061 * Returns true for a clean merge and false for failure or a conflict.
1063 function wfMerge( $old, $mine, $yours, &$result ){
1064 global $wgDiff3;
1066 # This check may also protect against code injection in
1067 # case of broken installations.
1068 if(! file_exists( $wgDiff3 ) ){
1069 wfDebug( "diff3 not found\n" );
1070 return false;
1073 # Make temporary files
1074 $td = wfTempDir();
1075 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1076 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1077 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1079 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1080 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1081 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1083 # Check for a conflict
1084 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1085 wfEscapeShellArg( $mytextName ) . ' ' .
1086 wfEscapeShellArg( $oldtextName ) . ' ' .
1087 wfEscapeShellArg( $yourtextName );
1088 $handle = popen( $cmd, 'r' );
1090 if( fgets( $handle, 1024 ) ){
1091 $conflict = true;
1092 } else {
1093 $conflict = false;
1095 pclose( $handle );
1097 # Merge differences
1098 $cmd = $wgDiff3 . ' -a -e --merge ' .
1099 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1100 $handle = popen( $cmd, 'r' );
1101 $result = '';
1102 do {
1103 $data = fread( $handle, 8192 );
1104 if ( strlen( $data ) == 0 ) {
1105 break;
1107 $result .= $data;
1108 } while ( true );
1109 pclose( $handle );
1110 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1112 if ( $result === '' && $old !== '' && $conflict == false ) {
1113 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1114 $conflict = true;
1116 return ! $conflict;
1120 * @todo document
1122 function wfVarDump( $var ) {
1123 global $wgOut;
1124 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1125 if ( headers_sent() || !@is_object( $wgOut ) ) {
1126 print $s;
1127 } else {
1128 $wgOut->addHTML( $s );
1133 * Provide a simple HTTP error.
1135 function wfHttpError( $code, $label, $desc ) {
1136 global $wgOut;
1137 $wgOut->disable();
1138 header( "HTTP/1.0 $code $label" );
1139 header( "Status: $code $label" );
1140 $wgOut->sendCacheControl();
1142 header( 'Content-type: text/html; charset=utf-8' );
1143 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1144 "<html><head><title>" .
1145 htmlspecialchars( $label ) .
1146 "</title></head><body><h1>" .
1147 htmlspecialchars( $label ) .
1148 "</h1><p>" .
1149 nl2br( htmlspecialchars( $desc ) ) .
1150 "</p></body></html>\n";
1154 * Clear away any user-level output buffers, discarding contents.
1156 * Suitable for 'starting afresh', for instance when streaming
1157 * relatively large amounts of data without buffering, or wanting to
1158 * output image files without ob_gzhandler's compression.
1160 * The optional $resetGzipEncoding parameter controls suppression of
1161 * the Content-Encoding header sent by ob_gzhandler; by default it
1162 * is left. See comments for wfClearOutputBuffers() for why it would
1163 * be used.
1165 * Note that some PHP configuration options may add output buffer
1166 * layers which cannot be removed; these are left in place.
1168 * @param bool $resetGzipEncoding
1170 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1171 if( $resetGzipEncoding ) {
1172 // Suppress Content-Encoding and Content-Length
1173 // headers from 1.10+s wfOutputHandler
1174 global $wgDisableOutputCompression;
1175 $wgDisableOutputCompression = true;
1177 while( $status = ob_get_status() ) {
1178 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1179 // Probably from zlib.output_compression or other
1180 // PHP-internal setting which can't be removed.
1182 // Give up, and hope the result doesn't break
1183 // output behavior.
1184 break;
1186 if( !ob_end_clean() ) {
1187 // Could not remove output buffer handler; abort now
1188 // to avoid getting in some kind of infinite loop.
1189 break;
1191 if( $resetGzipEncoding ) {
1192 if( $status['name'] == 'ob_gzhandler' ) {
1193 // Reset the 'Content-Encoding' field set by this handler
1194 // so we can start fresh.
1195 header( 'Content-Encoding:' );
1202 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1204 * Clear away output buffers, but keep the Content-Encoding header
1205 * produced by ob_gzhandler, if any.
1207 * This should be used for HTTP 304 responses, where you need to
1208 * preserve the Content-Encoding header of the real result, but
1209 * also need to suppress the output of ob_gzhandler to keep to spec
1210 * and avoid breaking Firefox in rare cases where the headers and
1211 * body are broken over two packets.
1213 function wfClearOutputBuffers() {
1214 wfResetOutputBuffers( false );
1218 * Converts an Accept-* header into an array mapping string values to quality
1219 * factors
1221 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1222 # No arg means accept anything (per HTTP spec)
1223 if( !$accept ) {
1224 return array( $def => 1 );
1227 $prefs = array();
1229 $parts = explode( ',', $accept );
1231 foreach( $parts as $part ) {
1232 # FIXME: doesn't deal with params like 'text/html; level=1'
1233 @list( $value, $qpart ) = explode( ';', $part );
1234 $match = array();
1235 if( !isset( $qpart ) ) {
1236 $prefs[$value] = 1;
1237 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1238 $prefs[$value] = $match[1];
1242 return $prefs;
1246 * Checks if a given MIME type matches any of the keys in the given
1247 * array. Basic wildcards are accepted in the array keys.
1249 * Returns the matching MIME type (or wildcard) if a match, otherwise
1250 * NULL if no match.
1252 * @param string $type
1253 * @param array $avail
1254 * @return string
1255 * @private
1257 function mimeTypeMatch( $type, $avail ) {
1258 if( array_key_exists($type, $avail) ) {
1259 return $type;
1260 } else {
1261 $parts = explode( '/', $type );
1262 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1263 return $parts[0] . '/*';
1264 } elseif( array_key_exists( '*/*', $avail ) ) {
1265 return '*/*';
1266 } else {
1267 return NULL;
1273 * Returns the 'best' match between a client's requested internet media types
1274 * and the server's list of available types. Each list should be an associative
1275 * array of type to preference (preference is a float between 0.0 and 1.0).
1276 * Wildcards in the types are acceptable.
1278 * @param array $cprefs Client's acceptable type list
1279 * @param array $sprefs Server's offered types
1280 * @return string
1282 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1283 * XXX: generalize to negotiate other stuff
1285 function wfNegotiateType( $cprefs, $sprefs ) {
1286 $combine = array();
1288 foreach( array_keys($sprefs) as $type ) {
1289 $parts = explode( '/', $type );
1290 if( $parts[1] != '*' ) {
1291 $ckey = mimeTypeMatch( $type, $cprefs );
1292 if( $ckey ) {
1293 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1298 foreach( array_keys( $cprefs ) as $type ) {
1299 $parts = explode( '/', $type );
1300 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1301 $skey = mimeTypeMatch( $type, $sprefs );
1302 if( $skey ) {
1303 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1308 $bestq = 0;
1309 $besttype = NULL;
1311 foreach( array_keys( $combine ) as $type ) {
1312 if( $combine[$type] > $bestq ) {
1313 $besttype = $type;
1314 $bestq = $combine[$type];
1318 return $besttype;
1322 * Array lookup
1323 * Returns an array where the values in the first array are replaced by the
1324 * values in the second array with the corresponding keys
1326 * @return array
1328 function wfArrayLookup( $a, $b ) {
1329 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1333 * Convenience function; returns MediaWiki timestamp for the present time.
1334 * @return string
1336 function wfTimestampNow() {
1337 # return NOW
1338 return wfTimestamp( TS_MW, time() );
1342 * Reference-counted warning suppression
1344 function wfSuppressWarnings( $end = false ) {
1345 static $suppressCount = 0;
1346 static $originalLevel = false;
1348 if ( $end ) {
1349 if ( $suppressCount ) {
1350 --$suppressCount;
1351 if ( !$suppressCount ) {
1352 error_reporting( $originalLevel );
1355 } else {
1356 if ( !$suppressCount ) {
1357 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1359 ++$suppressCount;
1364 * Restore error level to previous value
1366 function wfRestoreWarnings() {
1367 wfSuppressWarnings( true );
1370 # Autodetect, convert and provide timestamps of various types
1373 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1375 define('TS_UNIX', 0);
1378 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1380 define('TS_MW', 1);
1383 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1385 define('TS_DB', 2);
1388 * RFC 2822 format, for E-mail and HTTP headers
1390 define('TS_RFC2822', 3);
1393 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1395 * This is used by Special:Export
1397 define('TS_ISO_8601', 4);
1400 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1402 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1403 * DateTime tag and page 36 for the DateTimeOriginal and
1404 * DateTimeDigitized tags.
1406 define('TS_EXIF', 5);
1409 * Oracle format time.
1411 define('TS_ORACLE', 6);
1414 * Postgres format time.
1416 define('TS_POSTGRES', 7);
1419 * @param mixed $outputtype A timestamp in one of the supported formats, the
1420 * function will autodetect which format is supplied
1421 * and act accordingly.
1422 * @return string Time in the format specified in $outputtype
1424 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1425 $uts = 0;
1426 $da = array();
1427 if ($ts==0) {
1428 $uts=time();
1429 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1430 # TS_DB
1431 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1432 (int)$da[2],(int)$da[3],(int)$da[1]);
1433 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1434 # TS_EXIF
1435 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1436 (int)$da[2],(int)$da[3],(int)$da[1]);
1437 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1438 # TS_MW
1439 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1440 (int)$da[2],(int)$da[3],(int)$da[1]);
1441 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1442 # TS_UNIX
1443 $uts = $ts;
1444 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1445 # TS_ORACLE
1446 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1447 str_replace("+00:00", "UTC", $ts)));
1448 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1449 # TS_ISO_8601
1450 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1451 (int)$da[2],(int)$da[3],(int)$da[1]);
1452 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1453 # TS_POSTGRES
1454 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1455 (int)$da[2],(int)$da[3],(int)$da[1]);
1456 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1457 # TS_POSTGRES
1458 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1459 (int)$da[2],(int)$da[3],(int)$da[1]);
1460 } else {
1461 # Bogus value; fall back to the epoch...
1462 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1463 $uts = 0;
1467 switch($outputtype) {
1468 case TS_UNIX:
1469 return $uts;
1470 case TS_MW:
1471 return gmdate( 'YmdHis', $uts );
1472 case TS_DB:
1473 return gmdate( 'Y-m-d H:i:s', $uts );
1474 case TS_ISO_8601:
1475 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1476 // This shouldn't ever be used, but is included for completeness
1477 case TS_EXIF:
1478 return gmdate( 'Y:m:d H:i:s', $uts );
1479 case TS_RFC2822:
1480 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1481 case TS_ORACLE:
1482 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1483 case TS_POSTGRES:
1484 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1485 default:
1486 throw new MWException( 'wfTimestamp() called with illegal output type.');
1491 * Return a formatted timestamp, or null if input is null.
1492 * For dealing with nullable timestamp columns in the database.
1493 * @param int $outputtype
1494 * @param string $ts
1495 * @return string
1497 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1498 if( is_null( $ts ) ) {
1499 return null;
1500 } else {
1501 return wfTimestamp( $outputtype, $ts );
1506 * Check if the operating system is Windows
1508 * @return bool True if it's Windows, False otherwise.
1510 function wfIsWindows() {
1511 if (substr(php_uname(), 0, 7) == 'Windows') {
1512 return true;
1513 } else {
1514 return false;
1519 * Swap two variables
1521 function swap( &$x, &$y ) {
1522 $z = $x;
1523 $x = $y;
1524 $y = $z;
1527 function wfGetCachedNotice( $name ) {
1528 global $wgOut, $parserMemc;
1529 $fname = 'wfGetCachedNotice';
1530 wfProfileIn( $fname );
1532 $needParse = false;
1534 if( $name === 'default' ) {
1535 // special case
1536 global $wgSiteNotice;
1537 $notice = $wgSiteNotice;
1538 if( empty( $notice ) ) {
1539 wfProfileOut( $fname );
1540 return false;
1542 } else {
1543 $notice = wfMsgForContentNoTrans( $name );
1544 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1545 wfProfileOut( $fname );
1546 return( false );
1550 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1551 if( is_array( $cachedNotice ) ) {
1552 if( md5( $notice ) == $cachedNotice['hash'] ) {
1553 $notice = $cachedNotice['html'];
1554 } else {
1555 $needParse = true;
1557 } else {
1558 $needParse = true;
1561 if( $needParse ) {
1562 if( is_object( $wgOut ) ) {
1563 $parsed = $wgOut->parse( $notice );
1564 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1565 $notice = $parsed;
1566 } else {
1567 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1568 $notice = '';
1572 wfProfileOut( $fname );
1573 return $notice;
1576 function wfGetNamespaceNotice() {
1577 global $wgTitle;
1579 # Paranoia
1580 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1581 return "";
1583 $fname = 'wfGetNamespaceNotice';
1584 wfProfileIn( $fname );
1586 $key = "namespacenotice-" . $wgTitle->getNsText();
1587 $namespaceNotice = wfGetCachedNotice( $key );
1588 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1589 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1590 } else {
1591 $namespaceNotice = "";
1594 wfProfileOut( $fname );
1595 return $namespaceNotice;
1598 function wfGetSiteNotice() {
1599 global $wgUser, $wgSiteNotice;
1600 $fname = 'wfGetSiteNotice';
1601 wfProfileIn( $fname );
1602 $siteNotice = '';
1604 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1605 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1606 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1607 } else {
1608 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1609 if( !$anonNotice ) {
1610 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1611 } else {
1612 $siteNotice = $anonNotice;
1615 if( !$siteNotice ) {
1616 $siteNotice = wfGetCachedNotice( 'default' );
1620 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1621 wfProfileOut( $fname );
1622 return $siteNotice;
1625 /**
1626 * BC wrapper for MimeMagic::singleton()
1627 * @deprecated
1629 function &wfGetMimeMagic() {
1630 return MimeMagic::singleton();
1634 * Tries to get the system directory for temporary files.
1635 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1636 * and if none are set /tmp is returned as the generic Unix default.
1638 * NOTE: When possible, use the tempfile() function to create temporary
1639 * files to avoid race conditions on file creation, etc.
1641 * @return string
1643 function wfTempDir() {
1644 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1645 $tmp = getenv( $var );
1646 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1647 return $tmp;
1650 # Hope this is Unix of some kind!
1651 return '/tmp';
1655 * Make directory, and make all parent directories if they don't exist
1657 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1658 if( strval( $fullDir ) === '' )
1659 return true;
1660 if( file_exists( $fullDir ) )
1661 return true;
1662 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR, $fullDir ), $mode, true );
1666 * Increment a statistics counter
1668 function wfIncrStats( $key ) {
1669 global $wgMemc;
1670 $key = wfMemcKey( 'stats', $key );
1671 if ( is_null( $wgMemc->incr( $key ) ) ) {
1672 $wgMemc->add( $key, 1 );
1677 * @param mixed $nr The number to format
1678 * @param int $acc The number of digits after the decimal point, default 2
1679 * @param bool $round Whether or not to round the value, default true
1680 * @return float
1682 function wfPercent( $nr, $acc = 2, $round = true ) {
1683 $ret = sprintf( "%.${acc}f", $nr );
1684 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1688 * Encrypt a username/password.
1690 * @param string $userid ID of the user
1691 * @param string $password Password of the user
1692 * @return string Hashed password
1694 function wfEncryptPassword( $userid, $password ) {
1695 global $wgPasswordSalt;
1696 $p = md5( $password);
1698 if($wgPasswordSalt)
1699 return md5( "{$userid}-{$p}" );
1700 else
1701 return $p;
1705 * Appends to second array if $value differs from that in $default
1707 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1708 if ( is_null( $changed ) ) {
1709 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1711 if ( $default[$key] !== $value ) {
1712 $changed[$key] = $value;
1717 * Since wfMsg() and co suck, they don't return false if the message key they
1718 * looked up didn't exist but a XHTML string, this function checks for the
1719 * nonexistance of messages by looking at wfMsg() output
1721 * @param $msg The message key looked up
1722 * @param $wfMsgOut The output of wfMsg*()
1723 * @return bool
1725 function wfEmptyMsg( $msg, $wfMsgOut ) {
1726 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1730 * Find out whether or not a mixed variable exists in a string
1732 * @param mixed needle
1733 * @param string haystack
1734 * @return bool
1736 function in_string( $needle, $str ) {
1737 return strpos( $str, $needle ) !== false;
1740 function wfSpecialList( $page, $details ) {
1741 global $wgContLang;
1742 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1743 return $page . $details;
1747 * Returns a regular expression of url protocols
1749 * @return string
1751 function wfUrlProtocols() {
1752 global $wgUrlProtocols;
1754 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1755 // with LocalSettings files from 1.5
1756 if ( is_array( $wgUrlProtocols ) ) {
1757 $protocols = array();
1758 foreach ($wgUrlProtocols as $protocol)
1759 $protocols[] = preg_quote( $protocol, '/' );
1761 return implode( '|', $protocols );
1762 } else {
1763 return $wgUrlProtocols;
1768 * Safety wrapper around ini_get() for boolean settings.
1769 * The values returned from ini_get() are pre-normalized for settings
1770 * set via php.ini or php_flag/php_admin_flag... but *not*
1771 * for those set via php_value/php_admin_value.
1773 * It's fairly common for people to use php_value instead of php_flag,
1774 * which can leave you with an 'off' setting giving a false positive
1775 * for code that just takes the ini_get() return value as a boolean.
1777 * To make things extra interesting, setting via php_value accepts
1778 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1779 * Unrecognized values go false... again opposite PHP's own coercion
1780 * from string to bool.
1782 * Luckily, 'properly' set settings will always come back as '0' or '1',
1783 * so we only have to worry about them and the 'improper' settings.
1785 * I frickin' hate PHP... :P
1787 * @param string $setting
1788 * @return bool
1790 function wfIniGetBool( $setting ) {
1791 $val = ini_get( $setting );
1792 // 'on' and 'true' can't have whitespace around them, but '1' can.
1793 return strtolower( $val ) == 'on'
1794 || strtolower( $val ) == 'true'
1795 || strtolower( $val ) == 'yes'
1796 || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1800 * Execute a shell command, with time and memory limits mirrored from the PHP
1801 * configuration if supported.
1802 * @param $cmd Command line, properly escaped for shell.
1803 * @param &$retval optional, will receive the program's exit code.
1804 * (non-zero is usually failure)
1805 * @return collected stdout as a string (trailing newlines stripped)
1807 function wfShellExec( $cmd, &$retval=null ) {
1808 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1810 if( wfIniGetBool( 'safe_mode' ) ) {
1811 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1812 $retval = 1;
1813 return "Unable to run external programs in safe mode.";
1816 if ( php_uname( 's' ) == 'Linux' ) {
1817 $time = intval( ini_get( 'max_execution_time' ) );
1818 $mem = intval( $wgMaxShellMemory );
1819 $filesize = intval( $wgMaxShellFileSize );
1821 if ( $time > 0 && $mem > 0 ) {
1822 $script = "$IP/bin/ulimit4.sh";
1823 if ( is_executable( $script ) ) {
1824 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1827 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1828 # This is a hack to work around PHP's flawed invocation of cmd.exe
1829 # http://news.php.net/php.internals/21796
1830 $cmd = '"' . $cmd . '"';
1832 wfDebug( "wfShellExec: $cmd\n" );
1834 $output = array();
1835 $retval = 1; // error by default?
1836 exec( $cmd, $output, $retval ); // returns the last line of output.
1837 return implode( "\n", $output );
1842 * This function works like "use VERSION" in Perl, the program will die with a
1843 * backtrace if the current version of PHP is less than the version provided
1845 * This is useful for extensions which due to their nature are not kept in sync
1846 * with releases, and might depend on other versions of PHP than the main code
1848 * Note: PHP might die due to parsing errors in some cases before it ever
1849 * manages to call this function, such is life
1851 * @see perldoc -f use
1853 * @param mixed $version The version to check, can be a string, an integer, or
1854 * a float
1856 function wfUsePHP( $req_ver ) {
1857 $php_ver = PHP_VERSION;
1859 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1860 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1864 * This function works like "use VERSION" in Perl except it checks the version
1865 * of MediaWiki, the program will die with a backtrace if the current version
1866 * of MediaWiki is less than the version provided.
1868 * This is useful for extensions which due to their nature are not kept in sync
1869 * with releases
1871 * @see perldoc -f use
1873 * @param mixed $version The version to check, can be a string, an integer, or
1874 * a float
1876 function wfUseMW( $req_ver ) {
1877 global $wgVersion;
1879 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1880 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1884 * @deprecated use StringUtils::escapeRegexReplacement
1886 function wfRegexReplacement( $string ) {
1887 return StringUtils::escapeRegexReplacement( $string );
1891 * Return the final portion of a pathname.
1892 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1893 * http://bugs.php.net/bug.php?id=33898
1895 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1896 * We'll consider it so always, as we don't want \s in our Unix paths either.
1898 * @param string $path
1899 * @param string $suffix to remove if present
1900 * @return string
1902 function wfBaseName( $path, $suffix='' ) {
1903 $encSuffix = ($suffix == '')
1904 ? ''
1905 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1906 $matches = array();
1907 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1908 return $matches[1];
1909 } else {
1910 return '';
1915 * Generate a relative path name to the given file.
1916 * May explode on non-matching case-insensitive paths,
1917 * funky symlinks, etc.
1919 * @param string $path Absolute destination path including target filename
1920 * @param string $from Absolute source path, directory only
1921 * @return string
1923 function wfRelativePath( $path, $from ) {
1924 // Normalize mixed input on Windows...
1925 $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
1926 $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
1928 $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
1929 $against = explode( DIRECTORY_SEPARATOR, $from );
1931 // Trim off common prefix
1932 while( count( $pieces ) && count( $against )
1933 && $pieces[0] == $against[0] ) {
1934 array_shift( $pieces );
1935 array_shift( $against );
1938 // relative dots to bump us to the parent
1939 while( count( $against ) ) {
1940 array_unshift( $pieces, '..' );
1941 array_shift( $against );
1944 array_push( $pieces, wfBaseName( $path ) );
1946 return implode( DIRECTORY_SEPARATOR, $pieces );
1950 * Make a URL index, appropriate for the el_index field of externallinks.
1952 function wfMakeUrlIndex( $url ) {
1953 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1954 $bits = parse_url( $url );
1955 wfSuppressWarnings();
1956 wfRestoreWarnings();
1957 if ( !$bits ) {
1958 return false;
1960 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1961 $delimiter = '';
1962 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1963 $delimiter = '://';
1964 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1965 $delimiter = ':';
1966 // parse_url detects for news: and mailto: the host part of an url as path
1967 // We have to correct this wrong detection
1968 if ( isset ( $bits['path'] ) ) {
1969 $bits['host'] = $bits['path'];
1970 $bits['path'] = '';
1972 } else {
1973 return false;
1976 // Reverse the labels in the hostname, convert to lower case
1977 // For emails reverse domainpart only
1978 if ( $bits['scheme'] == 'mailto' ) {
1979 $mailparts = explode( '@', $bits['host'], 2 );
1980 if ( count($mailparts) === 2 ) {
1981 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1982 } else {
1983 // No domain specified, don't mangle it
1984 $domainpart = '';
1986 $reversedHost = $domainpart . '@' . $mailparts[0];
1987 } else {
1988 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1990 // Add an extra dot to the end
1991 // Why? Is it in wrong place in mailto links?
1992 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1993 $reversedHost .= '.';
1995 // Reconstruct the pseudo-URL
1996 $prot = $bits['scheme'];
1997 $index = "$prot$delimiter$reversedHost";
1998 // Leave out user and password. Add the port, path, query and fragment
1999 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2000 if ( isset( $bits['path'] ) ) {
2001 $index .= $bits['path'];
2002 } else {
2003 $index .= '/';
2005 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2006 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2007 return $index;
2011 * Do any deferred updates and clear the list
2012 * TODO: This could be in Wiki.php if that class made any sense at all
2014 function wfDoUpdates()
2016 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2017 foreach ( $wgDeferredUpdateList as $update ) {
2018 $update->doUpdate();
2020 foreach ( $wgPostCommitUpdateList as $update ) {
2021 $update->doUpdate();
2023 $wgDeferredUpdateList = array();
2024 $wgPostCommitUpdateList = array();
2028 * @deprecated use StringUtils::explodeMarkup
2030 function wfExplodeMarkup( $separator, $text ) {
2031 return StringUtils::explodeMarkup( $separator, $text );
2035 * Convert an arbitrarily-long digit string from one numeric base
2036 * to another, optionally zero-padding to a minimum column width.
2038 * Supports base 2 through 36; digit values 10-36 are represented
2039 * as lowercase letters a-z. Input is case-insensitive.
2041 * @param $input string of digits
2042 * @param $sourceBase int 2-36
2043 * @param $destBase int 2-36
2044 * @param $pad int 1 or greater
2045 * @param $lowercase bool
2046 * @return string or false on invalid input
2048 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2049 $input = strval( $input );
2050 if( $sourceBase < 2 ||
2051 $sourceBase > 36 ||
2052 $destBase < 2 ||
2053 $destBase > 36 ||
2054 $pad < 1 ||
2055 $sourceBase != intval( $sourceBase ) ||
2056 $destBase != intval( $destBase ) ||
2057 $pad != intval( $pad ) ||
2058 !is_string( $input ) ||
2059 $input == '' ) {
2060 return false;
2062 $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2063 $inDigits = array();
2064 $outChars = '';
2066 // Decode and validate input string
2067 $input = strtolower( $input );
2068 for( $i = 0; $i < strlen( $input ); $i++ ) {
2069 $n = strpos( $digitChars, $input{$i} );
2070 if( $n === false || $n > $sourceBase ) {
2071 return false;
2073 $inDigits[] = $n;
2076 // Iterate over the input, modulo-ing out an output digit
2077 // at a time until input is gone.
2078 while( count( $inDigits ) ) {
2079 $work = 0;
2080 $workDigits = array();
2082 // Long division...
2083 foreach( $inDigits as $digit ) {
2084 $work *= $sourceBase;
2085 $work += $digit;
2087 if( $work < $destBase ) {
2088 // Gonna need to pull another digit.
2089 if( count( $workDigits ) ) {
2090 // Avoid zero-padding; this lets us find
2091 // the end of the input very easily when
2092 // length drops to zero.
2093 $workDigits[] = 0;
2095 } else {
2096 // Finally! Actual division!
2097 $workDigits[] = intval( $work / $destBase );
2099 // Isn't it annoying that most programming languages
2100 // don't have a single divide-and-remainder operator,
2101 // even though the CPU implements it that way?
2102 $work = $work % $destBase;
2106 // All that division leaves us with a remainder,
2107 // which is conveniently our next output digit.
2108 $outChars .= $digitChars[$work];
2110 // And we continue!
2111 $inDigits = $workDigits;
2114 while( strlen( $outChars ) < $pad ) {
2115 $outChars .= '0';
2118 return strrev( $outChars );
2122 * Create an object with a given name and an array of construct parameters
2123 * @param string $name
2124 * @param array $p parameters
2126 function wfCreateObject( $name, $p ){
2127 $p = array_values( $p );
2128 switch ( count( $p ) ) {
2129 case 0:
2130 return new $name;
2131 case 1:
2132 return new $name( $p[0] );
2133 case 2:
2134 return new $name( $p[0], $p[1] );
2135 case 3:
2136 return new $name( $p[0], $p[1], $p[2] );
2137 case 4:
2138 return new $name( $p[0], $p[1], $p[2], $p[3] );
2139 case 5:
2140 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2141 case 6:
2142 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2143 default:
2144 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2149 * Aliases for modularized functions
2151 function wfGetHTTP( $url, $timeout = 'default' ) {
2152 return Http::get( $url, $timeout );
2154 function wfIsLocalURL( $url ) {
2155 return Http::isLocalURL( $url );
2159 * Initialise php session
2161 function wfSetupSession() {
2162 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2163 if( $wgSessionsInMemcached ) {
2164 require_once( 'MemcachedSessions.php' );
2165 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2166 # If it's left on 'user' or another setting from another
2167 # application, it will end up failing. Try to recover.
2168 ini_set ( 'session.save_handler', 'files' );
2170 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2171 session_cache_limiter( 'private, must-revalidate' );
2172 @session_start();
2176 * Get an object from the precompiled serialized directory
2178 * @return mixed The variable on success, false on failure
2180 function wfGetPrecompiledData( $name ) {
2181 global $IP;
2183 $file = "$IP/serialized/$name";
2184 if ( file_exists( $file ) ) {
2185 $blob = file_get_contents( $file );
2186 if ( $blob ) {
2187 return unserialize( $blob );
2190 return false;
2193 function wfGetCaller( $level = 2 ) {
2194 $backtrace = wfDebugBacktrace();
2195 if ( isset( $backtrace[$level] ) ) {
2196 return wfFormatStackFrame($backtrace[$level]);
2197 } else {
2198 $caller = 'unknown';
2200 return $caller;
2203 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2204 function wfGetAllCallers() {
2205 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2208 /** Return a string representation of frame */
2209 function wfFormatStackFrame($frame) {
2210 return isset( $frame["class"] )?
2211 $frame["class"]."::".$frame["function"]:
2212 $frame["function"];
2216 * Get a cache key
2218 function wfMemcKey( /*... */ ) {
2219 global $wgDBprefix, $wgDBname;
2220 $args = func_get_args();
2221 if ( $wgDBprefix ) {
2222 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2223 } else {
2224 $key = $wgDBname . ':' . implode( ':', $args );
2226 return $key;
2230 * Get a cache key for a foreign DB
2232 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2233 $args = array_slice( func_get_args(), 2 );
2234 if ( $prefix ) {
2235 $key = "$db-$prefix:" . implode( ':', $args );
2236 } else {
2237 $key = $db . ':' . implode( ':', $args );
2239 return $key;
2243 * Get an ASCII string identifying this wiki
2244 * This is used as a prefix in memcached keys
2246 function wfWikiID() {
2247 global $wgDBprefix, $wgDBname;
2248 if ( $wgDBprefix ) {
2249 return "$wgDBname-$wgDBprefix";
2250 } else {
2251 return $wgDBname;
2256 * Get a Database object
2257 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2258 * master (for write queries), DB_SLAVE for potentially lagged
2259 * read queries, or an integer >= 0 for a particular server.
2261 * @param mixed $groups Query groups. An array of group names that this query
2262 * belongs to. May contain a single string if the query is only
2263 * in one group.
2265 function &wfGetDB( $db = DB_LAST, $groups = array() ) {
2266 global $wgLoadBalancer;
2267 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2268 return $ret;
2272 * Find a file.
2273 * Shortcut for RepoGroup::singleton()->findFile()
2274 * @param mixed $title Title object or string. May be interwiki.
2275 * @param mixed $time Requested time for an archived image, or false for the
2276 * current version. An image object will be returned which
2277 * existed at or before the specified time.
2278 * @return File, or false if the file does not exist
2280 function wfFindFile( $title, $time = false ) {
2281 return RepoGroup::singleton()->findFile( $title, $time );
2285 * Get an object referring to a locally registered file.
2286 * Returns a valid placeholder object if the file does not exist.
2288 function wfLocalFile( $title ) {
2289 return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
2293 * Should low-performance queries be disabled?
2295 * @return bool
2297 function wfQueriesMustScale() {
2298 global $wgMiserMode;
2299 return $wgMiserMode
2300 || ( SiteStats::pages() > 100000
2301 && SiteStats::edits() > 1000000
2302 && SiteStats::users() > 10000 );
2306 * Get the path to a specified script file, respecting file
2307 * extensions; this is a wrapper around $wgScriptExtension etc.
2309 * @param string $script Script filename, sans extension
2310 * @return string
2312 function wfScript( $script = 'index' ) {
2313 global $wgScriptPath, $wgScriptExtension;
2314 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2318 * Convenience function converts boolean values into "true"
2319 * or "false" (string) values
2321 * @param bool $value
2322 * @return string
2324 function wfBoolToStr( $value ) {
2325 return $value ? 'true' : 'false';
2329 * Load an extension messages file
2331 function wfLoadExtensionMessages( $extensionName ) {
2332 global $wgExtensionMessagesFiles, $wgMessageCache;
2333 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2334 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2335 // Prevent double-loading
2336 $wgExtensionMessagesFiles[$extensionName] = false;
2341 * Get a platform-independent path to the null file, e.g.
2342 * /dev/null
2344 * @return string
2346 function wfGetNull() {
2347 return wfIsWindows()
2348 ? 'NUL'
2349 : '/dev/null';
2353 * Displays a maxlag error
2355 * @param string $host Server that lags the most
2356 * @param int $lag Maxlag (actual)
2357 * @param int $maxLag Maxlag (requested)
2359 function wfMaxlagError( $host, $lag, $maxLag ) {
2360 global $wgShowHostnames;
2361 header( 'HTTP/1.1 503 Service Unavailable' );
2362 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2363 header( 'X-Database-Lag: ' . intval( $lag ) );
2364 header( 'Content-Type: text/plain' );
2365 if( $wgShowHostnames ) {
2366 echo "Waiting for $host: $lag seconds lagged\n";
2367 } else {
2368 echo "Waiting for a database server: $lag seconds lagged\n";