3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
11 require_once dirname(__FILE__
) . '/LogPage.php';
12 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__
) . '/XmlFunctions.php';
15 // Hide compatibility functions from Doxygen
19 * Compatibility functions
21 * We more or less support PHP 5.0.x and up.
22 * Re-implementations of newer functions or functions in non-standard
23 * PHP extensions may be included here.
25 if( !function_exists('iconv') ) {
26 # iconv support is not in the default configuration and so may not be present.
27 # Assume will only ever use utf-8 and iso-8859-1.
28 # This will *not* work in all circumstances.
29 function iconv( $from, $to, $string ) {
30 if(strcasecmp( $from, $to ) == 0) return $string;
31 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
32 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
37 # UTF-8 substr function based on a PHP manual comment
38 if ( !function_exists( 'mb_substr' ) ) {
39 function mb_substr( $str, $start ) {
41 preg_match_all( '/./us', $str, $ar );
43 if( func_num_args() >= 3 ) {
44 $end = func_get_arg( 2 );
45 return join( '', array_slice( $ar[0], $start, $end ) );
47 return join( '', array_slice( $ar[0], $start ) );
52 if ( !function_exists( 'mb_strlen' ) ) {
54 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
56 * @param string $enc optional encoding; ignored
59 function mb_strlen( $str, $enc="" ) {
60 $counts = count_chars( $str );
64 for( $i = 0; $i < 0x80; $i++
) {
65 $total +
= $counts[$i];
68 // Count multibyte sequence heads
69 for( $i = 0xc0; $i < 0xff; $i++
) {
70 $total +
= $counts[$i];
76 if ( !function_exists( 'array_diff_key' ) ) {
78 * Exists in PHP 5.1.0+
79 * Not quite compatible, two-argument version only
80 * Null values will cause problems due to this use of isset()
82 function array_diff_key( $left, $right ) {
84 foreach ( $left as $key => $unused ) {
85 if ( isset( $right[$key] ) ) {
86 unset( $result[$key] );
97 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
99 function wfArrayDiff2( $a, $b ) {
100 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
102 function wfArrayDiff2_cmp( $a, $b ) {
103 if ( !is_array( $a ) ) {
104 return strcmp( $a, $b );
105 } elseif ( count( $a ) !== count( $b ) ) {
106 return count( $a ) < count( $b ) ?
-1 : 1;
110 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
111 $cmp = strcmp( $valueA, $valueB );
121 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
122 * PHP 5 won't let you declare a 'clone' function, even conditionally,
123 * so it has to be a wrapper with a different name.
125 function wfClone( $object ) {
126 return clone( $object );
130 * Seed Mersenne Twister
131 * No-op for compatibility; only necessary in PHP < 4.2.0
133 function wfSeedRandom() {
138 * Get a random decimal value between 0 and 1, in a way
139 * not likely to give duplicate values for any realistic
140 * number of articles.
144 function wfRandom() {
145 # The maximum random value is "only" 2^31-1, so get two random
146 # values to reduce the chance of dupes
147 $max = mt_getrandmax() +
1;
148 $rand = number_format( (mt_rand() * $max +
mt_rand())
149 / $max / $max, 12, '.', '' );
154 * We want some things to be included as literal characters in our title URLs
155 * for prettiness, which urlencode encodes by default. According to RFC 1738,
156 * all of the following should be safe:
160 * But + is not safe because it's used to indicate a space; &= are only safe in
161 * paths and not in queries (and we don't distinguish here); ' seems kind of
162 * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
163 * is reserved, we don't care. So the list we unescape is:
167 * %2F in the page titles seems to fatally break for some reason.
172 function wfUrlencode( $s ) {
173 $s = urlencode( $s );
175 array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
176 array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
184 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
185 * In normal operation this is a NOP.
187 * Controlling globals:
188 * $wgDebugLogFile - points to the log file
189 * $wgProfileOnly - if set, normal debug messages will not be recorded.
190 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
191 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
193 * @param $text String
194 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
196 function wfDebug( $text, $logonly = false ) {
197 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
198 static $recursion = 0;
200 static $cache = array(); // Cache of unoutputted messages
202 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
203 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
207 if ( $wgDebugComments && !$logonly ) {
210 if ( !isset( $wgOut ) ) {
213 if ( !StubObject
::isRealObject( $wgOut ) ) {
222 // add the message and possible cached ones to the output
223 array_map( array( $wgOut, 'debug' ), $cache );
226 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
227 # Strip unprintables; they can switch terminal modes when binary data
228 # gets dumped, which is pretty annoying.
229 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
230 wfErrorLog( $text, $wgDebugLogFile );
235 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
236 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
238 * @param $logGroup String
239 * @param $text String
240 * @param $public Bool: whether to log the event in the public log if no private
241 * log file is specified, (default true)
243 function wfDebugLog( $logGroup, $text, $public = true ) {
244 global $wgDebugLogGroups;
245 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
246 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
247 $time = wfTimestamp( TS_DB
);
249 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
250 } else if ( $public === true ) {
251 wfDebug( $text, true );
256 * Log for database errors
257 * @param $text String: database error message.
259 function wfLogDBError( $text ) {
260 global $wgDBerrorLog, $wgDBname;
261 if ( $wgDBerrorLog ) {
262 $host = trim(`hostname`
);
263 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
264 wfErrorLog( $text, $wgDBerrorLog );
269 * Log to a file without getting "file size exceeded" signals
271 function wfErrorLog( $text, $file ) {
272 wfSuppressWarnings();
273 $exists = file_exists( $file );
274 $size = $exists ?
filesize( $file ) : false;
275 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
276 error_log( $text, 3, $file );
284 function wfLogProfilingData() {
285 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
286 global $wgProfiler, $wgUser;
287 if ( !isset( $wgProfiler ) )
291 $elapsed = $now - $wgRequestTime;
292 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
294 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
295 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
296 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
297 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
298 if( !empty( $_SERVER['HTTP_FROM'] ) )
299 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
301 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
302 // Don't unstub $wgUser at this late stage just for statistics purposes
303 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
305 $log = sprintf( "%s\t%04.3f\t%s\n",
306 gmdate( 'YmdHis' ), $elapsed,
307 urldecode( $wgRequest->getRequestURL() . $forward ) );
308 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
309 wfErrorLog( $log . $prof, $wgDebugLogFile );
314 * Check if the wiki read-only lock file is present. This can be used to lock
315 * off editing functions, but doesn't guarantee that the database will not be
319 function wfReadOnly() {
320 global $wgReadOnlyFile, $wgReadOnly;
322 if ( !is_null( $wgReadOnly ) ) {
323 return (bool)$wgReadOnly;
325 if ( '' == $wgReadOnlyFile ) {
328 // Set $wgReadOnly for faster access next time
329 if ( is_file( $wgReadOnlyFile ) ) {
330 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
334 return (bool)$wgReadOnly;
337 function wfReadOnlyReason() {
344 * Return a Language object from $langcode
345 * @param $langcode Mixed: either:
346 * - a Language object
347 * - code of the language to get the message for, if it is
348 * a valid code create a language for that language, if
349 * it is a string but not a valid code then make a basic
351 * - a boolean: if it's false then use the current users
352 * language (as a fallback for the old parameter
353 * functionality), or if it is true then use the wikis
354 * @return Language object
356 function wfGetLangObj( $langcode = false ){
357 # Identify which language to get or create a language object for.
358 if( $langcode instanceof Language
)
359 # Great, we already have the object!
363 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
364 # $langcode is the language code of the wikis content language object.
365 # or it is a boolean and value is true
369 if( $langcode === $wgLang->getCode() ||
$langcode === false )
370 # $langcode is the language code of user language object.
371 # or it was a boolean and value is false
374 $validCodes = array_keys( Language
::getLanguageNames() );
375 if( in_array( $langcode, $validCodes ) )
376 # $langcode corresponds to a valid language.
377 return Language
::factory( $langcode );
379 # $langcode is a string, but not a valid language code; use content language.
380 wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
385 * Get a message from anywhere, for the current user language.
387 * Use wfMsgForContent() instead if the message should NOT
388 * change depending on the user preferences.
390 * @param $key String: lookup key for the message, usually
391 * defined in languages/Language.php
393 * This function also takes extra optional parameters (not
394 * shown in the function definition), which can by used to
395 * insert variable text into the predefined message.
397 function wfMsg( $key ) {
398 $args = func_get_args();
399 array_shift( $args );
400 return wfMsgReal( $key, $args, true );
404 * Same as above except doesn't transform the message
406 function wfMsgNoTrans( $key ) {
407 $args = func_get_args();
408 array_shift( $args );
409 return wfMsgReal( $key, $args, true, false, false );
413 * Get a message from anywhere, for the current global language
414 * set with $wgLanguageCode.
416 * Use this if the message should NOT change dependent on the
417 * language set in the user's preferences. This is the case for
418 * most text written into logs, as well as link targets (such as
419 * the name of the copyright policy page). Link titles, on the
420 * other hand, should be shown in the UI language.
422 * Note that MediaWiki allows users to change the user interface
423 * language in their preferences, but a single installation
424 * typically only contains content in one language.
426 * Be wary of this distinction: If you use wfMsg() where you should
427 * use wfMsgForContent(), a user of the software may have to
428 * customize over 70 messages in order to, e.g., fix a link in every
431 * @param $key String: lookup key for the message, usually
432 * defined in languages/Language.php
434 function wfMsgForContent( $key ) {
435 global $wgForceUIMsgAsContentMsg;
436 $args = func_get_args();
437 array_shift( $args );
439 if( is_array( $wgForceUIMsgAsContentMsg ) &&
440 in_array( $key, $wgForceUIMsgAsContentMsg ) )
442 return wfMsgReal( $key, $args, true, $forcontent );
446 * Same as above except doesn't transform the message
448 function wfMsgForContentNoTrans( $key ) {
449 global $wgForceUIMsgAsContentMsg;
450 $args = func_get_args();
451 array_shift( $args );
453 if( is_array( $wgForceUIMsgAsContentMsg ) &&
454 in_array( $key, $wgForceUIMsgAsContentMsg ) )
456 return wfMsgReal( $key, $args, true, $forcontent, false );
460 * Get a message from the language file, for the UI elements
462 function wfMsgNoDB( $key ) {
463 $args = func_get_args();
464 array_shift( $args );
465 return wfMsgReal( $key, $args, false );
469 * Get a message from the language file, for the content
471 function wfMsgNoDBForContent( $key ) {
472 global $wgForceUIMsgAsContentMsg;
473 $args = func_get_args();
474 array_shift( $args );
476 if( is_array( $wgForceUIMsgAsContentMsg ) &&
477 in_array( $key, $wgForceUIMsgAsContentMsg ) )
479 return wfMsgReal( $key, $args, false, $forcontent );
484 * Really get a message
485 * @param $key String: key to get.
487 * @param $useDB Boolean
488 * @param $transform Boolean: Whether or not to transform the message.
489 * @param $forContent Boolean
490 * @return String: the requested message.
492 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
493 wfProfileIn( __METHOD__
);
494 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
495 $message = wfMsgReplaceArgs( $message, $args );
496 wfProfileOut( __METHOD__
);
501 * This function provides the message source for messages to be edited which are *not* stored in the database.
502 * @param $key String:
504 function wfMsgWeirdKey ( $key ) {
505 $source = wfMsgGetKey( $key, false, true, false );
506 if ( wfEmptyMsg( $key, $source ) )
513 * Fetch a message string value, but don't replace any keys yet.
516 * @param string $langcode Code of the language to get the message for, or
517 * behaves as a content language switch if it is a
522 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
523 global $wgContLang, $wgMessageCache;
525 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
527 # If $wgMessageCache isn't initialised yet, try to return something sensible.
528 if( is_object( $wgMessageCache ) ) {
529 $message = $wgMessageCache->get( $key, $useDB, $langCode );
531 $message = $wgMessageCache->transform( $message );
534 $lang = wfGetLangObj( $langCode );
536 # MessageCache::get() does this already, Language::getMessage() doesn't
537 # ISSUE: Should we try to handle "message/lang" here too?
538 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
540 if( is_object( $lang ) ) {
541 $message = $lang->getMessage( $key );
551 * Replace message parameter keys on the given formatted output.
553 * @param string $message
558 function wfMsgReplaceArgs( $message, $args ) {
559 # Fix windows line-endings
560 # Some messages are split with explode("\n", $msg)
561 $message = str_replace( "\r", '', $message );
564 if ( count( $args ) ) {
565 if ( is_array( $args[0] ) ) {
566 $args = array_values( $args[0] );
568 $replacementKeys = array();
569 foreach( $args as $n => $param ) {
570 $replacementKeys['$' . ($n +
1)] = $param;
572 $message = strtr( $message, $replacementKeys );
579 * Return an HTML-escaped version of a message.
580 * Parameter replacements, if any, are done *after* the HTML-escaping,
581 * so parameters may contain HTML (eg links or form controls). Be sure
582 * to pre-escape them if you really do want plaintext, or just wrap
583 * the whole thing in htmlspecialchars().
586 * @param string ... parameters
589 function wfMsgHtml( $key ) {
590 $args = func_get_args();
591 array_shift( $args );
592 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
596 * Return an HTML version of message
597 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
598 * so parameters may contain HTML (eg links or form controls). Be sure
599 * to pre-escape them if you really do want plaintext, or just wrap
600 * the whole thing in htmlspecialchars().
603 * @param string ... parameters
606 function wfMsgWikiHtml( $key ) {
608 $args = func_get_args();
609 array_shift( $args );
610 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
614 * Returns message in the requested format
615 * @param string $key Key of the message
616 * @param array $options Processing rules:
617 * <i>parse</i>: parses wikitext to html
618 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
619 * <i>escape</i>: filters message through htmlspecialchars
620 * <i>escapenoentities</i>: same, but allows entity references like through
621 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
622 * <i>parsemag</i>: transform the message using magic phrases
623 * <i>content</i>: fetch message for content language instead of interface
624 * <i>language</i>: language code to fetch message for (overriden by <i>content</i>), its behaviour
625 * with parser, parseinline and parsemag is undefined.
626 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
628 function wfMsgExt( $key, $options ) {
629 global $wgOut, $wgParser;
631 $args = func_get_args();
632 array_shift( $args );
633 array_shift( $args );
635 if( !is_array($options) ) {
636 $options = array($options);
639 if( in_array('content', $options) ) {
642 } elseif( array_key_exists('language', $options) ) {
644 $langCode = $options['language'];
645 $validCodes = array_keys( Language
::getLanguageNames() );
646 if( !in_array($options['language'], $validCodes) ) {
647 # Fallback to en, instead of whatever interface language we might have
655 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
657 if( !in_array('replaceafter', $options) ) {
658 $string = wfMsgReplaceArgs( $string, $args );
661 if( in_array('parse', $options) ) {
662 $string = $wgOut->parse( $string, true, !$forContent );
663 } elseif ( in_array('parseinline', $options) ) {
664 $string = $wgOut->parse( $string, true, !$forContent );
666 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
669 } elseif ( in_array('parsemag', $options) ) {
670 global $wgMessageCache;
671 if ( isset( $wgMessageCache ) ) {
672 $string = $wgMessageCache->transform( $string, !$forContent );
676 if ( in_array('escape', $options) ) {
677 $string = htmlspecialchars ( $string );
678 } elseif ( in_array( 'escapenoentities', $options ) ) {
679 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
682 if( in_array('replaceafter', $options) ) {
683 $string = wfMsgReplaceArgs( $string, $args );
691 * Just like exit() but makes a note of it.
692 * Commits open transactions except if the error parameter is set
694 * @deprecated Please return control to the caller or throw an exception
696 function wfAbruptExit( $error = false ){
697 static $called = false;
703 $bt = wfDebugBacktrace();
705 for($i = 0; $i < count($bt) ; $i++
){
706 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
707 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
708 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
711 wfDebug('WARNING: Abrupt exit\n');
714 wfLogProfilingData();
717 wfGetLB()->closeAll();
723 * @deprecated Please return control the caller or throw an exception
725 function wfErrorExit() {
726 wfAbruptExit( true );
730 * Print a simple message and die, returning nonzero to the shell if any.
731 * Plain die() fails to return nonzero to the shell if you pass a string.
734 function wfDie( $msg='' ) {
740 * Throw a debugging exception. This function previously once exited the process,
741 * but now throws an exception instead, with similar results.
743 * @param string $msg Message shown when dieing.
745 function wfDebugDieBacktrace( $msg = '' ) {
746 throw new MWException( $msg );
750 * Fetch server name for use in error reporting etc.
751 * Use real server name if available, so we know which machine
752 * in a server farm generated the current page.
755 function wfHostname() {
756 if ( function_exists( 'posix_uname' ) ) {
757 // This function not present on Windows
758 $uname = @posix_uname
();
762 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
763 return $uname['nodename'];
765 # This may be a virtual server.
766 return $_SERVER['SERVER_NAME'];
771 * Returns a HTML comment with the elapsed time since request.
772 * This method has no side effects.
775 function wfReportTime() {
776 global $wgRequestTime, $wgShowHostnames;
779 $elapsed = $now - $wgRequestTime;
781 return $wgShowHostnames
782 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
783 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
787 * Safety wrapper for debug_backtrace().
789 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
790 * murky circumstances, which may be triggered in part by stub objects
791 * or other fancy talkin'.
793 * Will return an empty array if Zend Optimizer is detected, otherwise
794 * the output from debug_backtrace() (trimmed).
796 * @return array of backtrace information
798 function wfDebugBacktrace() {
799 if( extension_loaded( 'Zend Optimizer' ) ) {
800 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
803 return array_slice( debug_backtrace(), 1 );
807 function wfBacktrace() {
808 global $wgCommandLineMode;
810 if ( $wgCommandLineMode ) {
815 $backtrace = wfDebugBacktrace();
816 foreach( $backtrace as $call ) {
817 if( isset( $call['file'] ) ) {
818 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
819 $file = $f[count($f)-1];
823 if( isset( $call['line'] ) ) {
824 $line = $call['line'];
828 if ( $wgCommandLineMode ) {
829 $msg .= "$file line $line calls ";
831 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
833 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
834 $msg .= $call['function'] . '()';
836 if ( $wgCommandLineMode ) {
842 if ( $wgCommandLineMode ) {
852 /* Some generic result counters, pulled out of SearchEngine */
858 function wfShowingResults( $offset, $limit ) {
860 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
866 function wfShowingResultsNum( $offset, $limit, $num ) {
868 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
874 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
876 $fmtLimit = $wgLang->formatNum( $limit );
877 $prev = wfMsg( 'prevn', $fmtLimit );
878 $next = wfMsg( 'nextn', $fmtLimit );
880 if( is_object( $link ) ) {
883 $title = Title
::newFromText( $link );
884 if( is_null( $title ) ) {
889 if ( 0 != $offset ) {
890 $po = $offset - $limit;
891 if ( $po < 0 ) { $po = 0; }
892 $q = "limit={$limit}&offset={$po}";
893 if ( '' != $query ) { $q .= '&'.$query; }
894 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
895 } else { $plink = $prev; }
897 $no = $offset +
$limit;
898 $q = 'limit='.$limit.'&offset='.$no;
899 if ( '' != $query ) { $q .= '&'.$query; }
904 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
906 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
907 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
908 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
909 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
910 wfNumLink( $offset, 500, $title, $query );
912 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
918 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
920 if ( '' == $query ) { $q = ''; }
921 else { $q = $query.'&'; }
922 $q .= 'limit='.$limit.'&offset='.$offset;
924 $fmtLimit = $wgLang->formatNum( $limit );
925 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
931 * @todo FIXME: we may want to blacklist some broken browsers
933 * @return bool Whereas client accept gzip compression
935 function wfClientAcceptsGzip() {
938 # FIXME: we may want to blacklist some broken browsers
941 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
942 $_SERVER['HTTP_ACCEPT_ENCODING'],
944 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
945 wfDebug( " accepts gzip\n" );
953 * Obtain the offset and limit values from the request string;
954 * used in special pages
956 * @param $deflimit Default limit if none supplied
957 * @param $optionname Name of a user preference to check against
961 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
963 return $wgRequest->getLimitOffset( $deflimit, $optionname );
967 * Escapes the given text so that it may be output using addWikiText()
968 * without any linking, formatting, etc. making its way through. This
969 * is achieved by substituting certain characters with HTML entities.
970 * As required by the callers, <nowiki> is not used. It currently does
971 * not filter out characters which have special meaning only at the
972 * start of a line, such as "*".
974 * @param string $text Text to be escaped
976 function wfEscapeWikiText( $text ) {
978 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
979 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
980 htmlspecialchars($text) );
987 function wfQuotedPrintable( $string, $charset = '' ) {
988 # Probably incomplete; see RFC 2045
989 if( empty( $charset ) ) {
990 global $wgInputEncoding;
991 $charset = $wgInputEncoding;
993 $charset = strtoupper( $charset );
994 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
996 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
997 $replace = $illegal . '\t ?_';
998 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
999 $out = "=?$charset?Q?";
1000 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1011 return microtime(true);
1015 * Sets dest to source and returns the original value of dest
1016 * If source is NULL, it just returns the value, it doesn't set the variable
1018 function wfSetVar( &$dest, $source ) {
1020 if ( !is_null( $source ) ) {
1027 * As for wfSetVar except setting a bit
1029 function wfSetBit( &$dest, $bit, $state = true ) {
1030 $temp = (bool)($dest & $bit );
1031 if ( !is_null( $state ) ) {
1042 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1043 * "days=7&limit=100". Options in the first array override options in the second.
1044 * Options set to "" will not be output.
1046 function wfArrayToCGI( $array1, $array2 = NULL )
1048 if ( !is_null( $array2 ) ) {
1049 $array1 = $array1 +
$array2;
1053 foreach ( $array1 as $key => $value ) {
1054 if ( '' !== $value ) {
1058 if(is_array($value))
1061 foreach($value as $v)
1063 $cgi .= ($firstTime ?
'' : '&') .
1064 urlencode( $key . '[]' ) . '=' .
1070 $cgi .= urlencode( $key ) . '=' .
1071 urlencode( $value );
1078 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1079 * its argument and returns the same string in array form. This allows compa-
1080 * tibility with legacy functions that accept raw query strings instead of nice
1081 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1082 * valid query strings, or it will explode.
1084 * @param $query string Query string
1085 * @return array Array version of input
1087 function wfCgiToArray( $query ) {
1088 if( isset( $query[0] ) and $query[0] == '?' ) {
1089 $query = substr( $query, 1 );
1091 $bits = explode( '&', $query );
1093 foreach( $bits as $bit ) {
1097 list( $key, $value ) = explode( '=', $bit );
1098 $key = urldecode( $key );
1099 $value = urldecode( $value );
1100 $ret[$key] = $value;
1106 * Append a query string to an existing URL, which may or may not already
1107 * have query string parameters already. If so, they will be combined.
1109 * @param string $url
1110 * @param string $query
1113 function wfAppendQuery( $url, $query ) {
1114 if( $query != '' ) {
1115 if( false === strpos( $url, '?' ) ) {
1126 * Expand a potentially local URL to a fully-qualified URL.
1127 * Assumes $wgServer is correct. :)
1128 * @param string $url, either fully-qualified or a local path + query
1129 * @return string Fully-qualified URL
1131 function wfExpandUrl( $url ) {
1132 if( substr( $url, 0, 1 ) == '/' ) {
1134 return $wgServer . $url;
1141 * This is obsolete, use SquidUpdate::purge()
1144 function wfPurgeSquidServers ($urlArr) {
1145 SquidUpdate
::purge( $urlArr );
1149 * Windows-compatible version of escapeshellarg()
1150 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1151 * function puts single quotes in regardless of OS
1153 function wfEscapeShellArg( ) {
1154 $args = func_get_args();
1157 foreach ( $args as $arg ) {
1164 if ( wfIsWindows() ) {
1165 // Escaping for an MSVC-style command line parser
1166 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1167 // Double the backslashes before any double quotes. Escape the double quotes.
1168 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1171 foreach ( $tokens as $token ) {
1173 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1179 // Double the backslashes before the end of the string, because
1180 // we will soon add a quote
1182 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1183 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1186 // Add surrounding quotes
1187 $retVal .= '"' . $arg . '"';
1189 $retVal .= escapeshellarg( $arg );
1196 * wfMerge attempts to merge differences between three texts.
1197 * Returns true for a clean merge and false for failure or a conflict.
1199 function wfMerge( $old, $mine, $yours, &$result ){
1202 # This check may also protect against code injection in
1203 # case of broken installations.
1204 if(! file_exists( $wgDiff3 ) ){
1205 wfDebug( "diff3 not found\n" );
1209 # Make temporary files
1211 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1212 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1213 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1215 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1216 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1217 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1219 # Check for a conflict
1220 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1221 wfEscapeShellArg( $mytextName ) . ' ' .
1222 wfEscapeShellArg( $oldtextName ) . ' ' .
1223 wfEscapeShellArg( $yourtextName );
1224 $handle = popen( $cmd, 'r' );
1226 if( fgets( $handle, 1024 ) ){
1234 $cmd = $wgDiff3 . ' -a -e --merge ' .
1235 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1236 $handle = popen( $cmd, 'r' );
1239 $data = fread( $handle, 8192 );
1240 if ( strlen( $data ) == 0 ) {
1246 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1248 if ( $result === '' && $old !== '' && $conflict == false ) {
1249 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1256 * Returns unified plain-text diff of two texts.
1257 * Useful for machine processing of diffs.
1258 * @param $before string The text before the changes.
1259 * @param $after string The text after the changes.
1260 * @param $params string Command-line options for the diff command.
1261 * @return string Unified diff of $before and $after
1263 function wfDiff( $before, $after, $params = '-u' ) {
1266 # This check may also protect against code injection in
1267 # case of broken installations.
1268 if( !file_exists( $wgDiff ) ){
1269 wfDebug( "diff executable not found\n" );
1270 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1271 $format = new UnifiedDiffFormatter();
1272 return $format->format( $diffs );
1275 # Make temporary files
1277 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1278 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1280 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1281 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1283 // Get the diff of the two files
1284 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1286 $h = popen( $cmd, 'r' );
1291 $data = fread( $h, 8192 );
1292 if ( strlen( $data ) == 0 ) {
1300 unlink( $oldtextName );
1301 unlink( $newtextName );
1303 // Kill the --- and +++ lines. They're not useful.
1304 $diff_lines = explode( "\n", $diff );
1305 if (strpos( $diff_lines[0], '---' ) === 0) {
1306 unset($diff_lines[0]);
1308 if (strpos( $diff_lines[1], '+++' ) === 0) {
1309 unset($diff_lines[1]);
1312 $diff = implode( "\n", $diff_lines );
1320 function wfVarDump( $var ) {
1322 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1323 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1326 $wgOut->addHTML( $s );
1331 * Provide a simple HTTP error.
1333 function wfHttpError( $code, $label, $desc ) {
1336 header( "HTTP/1.0 $code $label" );
1337 header( "Status: $code $label" );
1338 $wgOut->sendCacheControl();
1340 header( 'Content-type: text/html; charset=utf-8' );
1341 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1342 "<html><head><title>" .
1343 htmlspecialchars( $label ) .
1344 "</title></head><body><h1>" .
1345 htmlspecialchars( $label ) .
1347 nl2br( htmlspecialchars( $desc ) ) .
1348 "</p></body></html>\n";
1352 * Clear away any user-level output buffers, discarding contents.
1354 * Suitable for 'starting afresh', for instance when streaming
1355 * relatively large amounts of data without buffering, or wanting to
1356 * output image files without ob_gzhandler's compression.
1358 * The optional $resetGzipEncoding parameter controls suppression of
1359 * the Content-Encoding header sent by ob_gzhandler; by default it
1360 * is left. See comments for wfClearOutputBuffers() for why it would
1363 * Note that some PHP configuration options may add output buffer
1364 * layers which cannot be removed; these are left in place.
1366 * @param bool $resetGzipEncoding
1368 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1369 if( $resetGzipEncoding ) {
1370 // Suppress Content-Encoding and Content-Length
1371 // headers from 1.10+s wfOutputHandler
1372 global $wgDisableOutputCompression;
1373 $wgDisableOutputCompression = true;
1375 while( $status = ob_get_status() ) {
1376 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1377 // Probably from zlib.output_compression or other
1378 // PHP-internal setting which can't be removed.
1380 // Give up, and hope the result doesn't break
1384 if( !ob_end_clean() ) {
1385 // Could not remove output buffer handler; abort now
1386 // to avoid getting in some kind of infinite loop.
1389 if( $resetGzipEncoding ) {
1390 if( $status['name'] == 'ob_gzhandler' ) {
1391 // Reset the 'Content-Encoding' field set by this handler
1392 // so we can start fresh.
1393 header( 'Content-Encoding:' );
1400 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1402 * Clear away output buffers, but keep the Content-Encoding header
1403 * produced by ob_gzhandler, if any.
1405 * This should be used for HTTP 304 responses, where you need to
1406 * preserve the Content-Encoding header of the real result, but
1407 * also need to suppress the output of ob_gzhandler to keep to spec
1408 * and avoid breaking Firefox in rare cases where the headers and
1409 * body are broken over two packets.
1411 function wfClearOutputBuffers() {
1412 wfResetOutputBuffers( false );
1416 * Converts an Accept-* header into an array mapping string values to quality
1419 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1420 # No arg means accept anything (per HTTP spec)
1422 return array( $def => 1.0 );
1427 $parts = explode( ',', $accept );
1429 foreach( $parts as $part ) {
1430 # FIXME: doesn't deal with params like 'text/html; level=1'
1431 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1433 if( !isset( $qpart ) ) {
1434 $prefs[$value] = 1.0;
1435 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1436 $prefs[$value] = floatval($match[1]);
1444 * Checks if a given MIME type matches any of the keys in the given
1445 * array. Basic wildcards are accepted in the array keys.
1447 * Returns the matching MIME type (or wildcard) if a match, otherwise
1450 * @param string $type
1451 * @param array $avail
1455 function mimeTypeMatch( $type, $avail ) {
1456 if( array_key_exists($type, $avail) ) {
1459 $parts = explode( '/', $type );
1460 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1461 return $parts[0] . '/*';
1462 } elseif( array_key_exists( '*/*', $avail ) ) {
1471 * Returns the 'best' match between a client's requested internet media types
1472 * and the server's list of available types. Each list should be an associative
1473 * array of type to preference (preference is a float between 0.0 and 1.0).
1474 * Wildcards in the types are acceptable.
1476 * @param array $cprefs Client's acceptable type list
1477 * @param array $sprefs Server's offered types
1480 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1481 * XXX: generalize to negotiate other stuff
1483 function wfNegotiateType( $cprefs, $sprefs ) {
1486 foreach( array_keys($sprefs) as $type ) {
1487 $parts = explode( '/', $type );
1488 if( $parts[1] != '*' ) {
1489 $ckey = mimeTypeMatch( $type, $cprefs );
1491 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1496 foreach( array_keys( $cprefs ) as $type ) {
1497 $parts = explode( '/', $type );
1498 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1499 $skey = mimeTypeMatch( $type, $sprefs );
1501 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1509 foreach( array_keys( $combine ) as $type ) {
1510 if( $combine[$type] > $bestq ) {
1512 $bestq = $combine[$type];
1521 * Returns an array where the values in the first array are replaced by the
1522 * values in the second array with the corresponding keys
1526 function wfArrayLookup( $a, $b ) {
1527 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1531 * Convenience function; returns MediaWiki timestamp for the present time.
1534 function wfTimestampNow() {
1536 return wfTimestamp( TS_MW
, time() );
1540 * Reference-counted warning suppression
1542 function wfSuppressWarnings( $end = false ) {
1543 static $suppressCount = 0;
1544 static $originalLevel = false;
1547 if ( $suppressCount ) {
1549 if ( !$suppressCount ) {
1550 error_reporting( $originalLevel );
1554 if ( !$suppressCount ) {
1555 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1562 * Restore error level to previous value
1564 function wfRestoreWarnings() {
1565 wfSuppressWarnings( true );
1568 # Autodetect, convert and provide timestamps of various types
1571 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1573 define('TS_UNIX', 0);
1576 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1581 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1586 * RFC 2822 format, for E-mail and HTTP headers
1588 define('TS_RFC2822', 3);
1591 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1593 * This is used by Special:Export
1595 define('TS_ISO_8601', 4);
1598 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1600 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1601 * DateTime tag and page 36 for the DateTimeOriginal and
1602 * DateTimeDigitized tags.
1604 define('TS_EXIF', 5);
1607 * Oracle format time.
1609 define('TS_ORACLE', 6);
1612 * Postgres format time.
1614 define('TS_POSTGRES', 7);
1617 * @param mixed $outputtype A timestamp in one of the supported formats, the
1618 * function will autodetect which format is supplied
1619 * and act accordingly.
1620 * @return string Time in the format specified in $outputtype
1622 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1627 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1629 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1631 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1633 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1636 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1638 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1639 str_replace("+00:00", "UTC", $ts)));
1640 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1642 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1644 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1647 # Bogus value; fall back to the epoch...
1648 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1652 if (count( $da ) ) {
1653 // Warning! gmmktime() acts oddly if the month or day is set to 0
1654 // We may want to handle that explicitly at some point
1655 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1656 (int)$da[2],(int)$da[3],(int)$da[1]);
1659 switch($outputtype) {
1663 return gmdate( 'YmdHis', $uts );
1665 return gmdate( 'Y-m-d H:i:s', $uts );
1667 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1668 // This shouldn't ever be used, but is included for completeness
1670 return gmdate( 'Y:m:d H:i:s', $uts );
1672 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1674 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1676 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1678 throw new MWException( 'wfTimestamp() called with illegal output type.');
1683 * Return a formatted timestamp, or null if input is null.
1684 * For dealing with nullable timestamp columns in the database.
1685 * @param int $outputtype
1689 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1690 if( is_null( $ts ) ) {
1693 return wfTimestamp( $outputtype, $ts );
1698 * Check if the operating system is Windows
1700 * @return bool True if it's Windows, False otherwise.
1702 function wfIsWindows() {
1703 if (substr(php_uname(), 0, 7) == 'Windows') {
1711 * Swap two variables
1713 function swap( &$x, &$y ) {
1719 function wfGetCachedNotice( $name ) {
1720 global $wgOut, $parserMemc;
1721 $fname = 'wfGetCachedNotice';
1722 wfProfileIn( $fname );
1726 if( $name === 'default' ) {
1728 global $wgSiteNotice;
1729 $notice = $wgSiteNotice;
1730 if( empty( $notice ) ) {
1731 wfProfileOut( $fname );
1735 $notice = wfMsgForContentNoTrans( $name );
1736 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1737 wfProfileOut( $fname );
1742 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1743 if( is_array( $cachedNotice ) ) {
1744 if( md5( $notice ) == $cachedNotice['hash'] ) {
1745 $notice = $cachedNotice['html'];
1754 if( is_object( $wgOut ) ) {
1755 $parsed = $wgOut->parse( $notice );
1756 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1759 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1764 wfProfileOut( $fname );
1768 function wfGetNamespaceNotice() {
1772 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1775 $fname = 'wfGetNamespaceNotice';
1776 wfProfileIn( $fname );
1778 $key = "namespacenotice-" . $wgTitle->getNsText();
1779 $namespaceNotice = wfGetCachedNotice( $key );
1780 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1781 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1783 $namespaceNotice = "";
1786 wfProfileOut( $fname );
1787 return $namespaceNotice;
1790 function wfGetSiteNotice() {
1791 global $wgUser, $wgSiteNotice;
1792 $fname = 'wfGetSiteNotice';
1793 wfProfileIn( $fname );
1796 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1797 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1798 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1800 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1801 if( !$anonNotice ) {
1802 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1804 $siteNotice = $anonNotice;
1807 if( !$siteNotice ) {
1808 $siteNotice = wfGetCachedNotice( 'default' );
1812 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1813 wfProfileOut( $fname );
1818 * BC wrapper for MimeMagic::singleton()
1821 function &wfGetMimeMagic() {
1822 return MimeMagic
::singleton();
1826 * Tries to get the system directory for temporary files.
1827 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1828 * and if none are set /tmp is returned as the generic Unix default.
1830 * NOTE: When possible, use the tempfile() function to create temporary
1831 * files to avoid race conditions on file creation, etc.
1835 function wfTempDir() {
1836 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1837 $tmp = getenv( $var );
1838 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1842 # Hope this is Unix of some kind!
1847 * Make directory, and make all parent directories if they don't exist
1849 * @param string $fullDir Full path to directory to create
1850 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1853 function wfMkdirParents( $fullDir, $mode = null ) {
1854 global $wgDirectoryMode;
1855 if( strval( $fullDir ) === '' )
1857 if( file_exists( $fullDir ) )
1859 // If not defined or isn't an int, set to default
1860 if ( is_null( $mode ) ) {
1861 $mode = $wgDirectoryMode;
1865 # Go back through the paths to find the first directory that exists
1866 $currentDir = $fullDir;
1867 $createList = array();
1868 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1869 # Strip trailing slashes
1870 $currentDir = rtrim( $currentDir, '/\\' );
1872 # Add to create list
1873 $createList[] = $currentDir;
1875 # Find next delimiter searching from the end
1876 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1877 if ( $p === false ) {
1878 $currentDir = false;
1880 $currentDir = substr( $currentDir, 0, $p );
1884 if ( count( $createList ) == 0 ) {
1885 # Directory specified already exists
1887 } elseif ( $currentDir === false ) {
1888 # Went all the way back to root and it apparently doesn't exist
1889 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1892 # Now go forward creating directories
1893 $createList = array_reverse( $createList );
1895 # Is the parent directory writable?
1896 if ( $currentDir === '' ) {
1899 if ( !is_writable( $currentDir ) ) {
1900 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1904 foreach ( $createList as $dir ) {
1905 # use chmod to override the umask, as suggested by the PHP manual
1906 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1907 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1915 * Increment a statistics counter
1917 function wfIncrStats( $key ) {
1918 global $wgStatsMethod;
1920 if( $wgStatsMethod == 'udp' ) {
1921 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1924 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1925 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1926 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1928 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1929 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1930 } elseif( $wgStatsMethod == 'cache' ) {
1932 $key = wfMemcKey( 'stats', $key );
1933 if ( is_null( $wgMemc->incr( $key ) ) ) {
1934 $wgMemc->add( $key, 1 );
1942 * @param mixed $nr The number to format
1943 * @param int $acc The number of digits after the decimal point, default 2
1944 * @param bool $round Whether or not to round the value, default true
1947 function wfPercent( $nr, $acc = 2, $round = true ) {
1948 $ret = sprintf( "%.${acc}f", $nr );
1949 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1953 * Encrypt a username/password.
1955 * @param string $userid ID of the user
1956 * @param string $password Password of the user
1957 * @return string Hashed password
1958 * @deprecated Use User::crypt() or User::oldCrypt() instead
1960 function wfEncryptPassword( $userid, $password ) {
1961 wfDeprecated(__FUNCTION__
);
1962 # Just wrap around User::oldCrypt()
1963 return User
::oldCrypt($password, $userid);
1967 * Appends to second array if $value differs from that in $default
1969 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1970 if ( is_null( $changed ) ) {
1971 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1973 if ( $default[$key] !== $value ) {
1974 $changed[$key] = $value;
1979 * Since wfMsg() and co suck, they don't return false if the message key they
1980 * looked up didn't exist but a XHTML string, this function checks for the
1981 * nonexistance of messages by looking at wfMsg() output
1983 * @param $msg The message key looked up
1984 * @param $wfMsgOut The output of wfMsg*()
1987 function wfEmptyMsg( $msg, $wfMsgOut ) {
1988 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1992 * Find out whether or not a mixed variable exists in a string
1994 * @param mixed needle
1995 * @param string haystack
1998 function in_string( $needle, $str ) {
1999 return strpos( $str, $needle ) !== false;
2002 function wfSpecialList( $page, $details ) {
2004 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2005 return $page . $details;
2009 * Returns a regular expression of url protocols
2013 function wfUrlProtocols() {
2014 global $wgUrlProtocols;
2016 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2017 // with LocalSettings files from 1.5
2018 if ( is_array( $wgUrlProtocols ) ) {
2019 $protocols = array();
2020 foreach ($wgUrlProtocols as $protocol)
2021 $protocols[] = preg_quote( $protocol, '/' );
2023 return implode( '|', $protocols );
2025 return $wgUrlProtocols;
2030 * Safety wrapper around ini_get() for boolean settings.
2031 * The values returned from ini_get() are pre-normalized for settings
2032 * set via php.ini or php_flag/php_admin_flag... but *not*
2033 * for those set via php_value/php_admin_value.
2035 * It's fairly common for people to use php_value instead of php_flag,
2036 * which can leave you with an 'off' setting giving a false positive
2037 * for code that just takes the ini_get() return value as a boolean.
2039 * To make things extra interesting, setting via php_value accepts
2040 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2041 * Unrecognized values go false... again opposite PHP's own coercion
2042 * from string to bool.
2044 * Luckily, 'properly' set settings will always come back as '0' or '1',
2045 * so we only have to worry about them and the 'improper' settings.
2047 * I frickin' hate PHP... :P
2049 * @param string $setting
2052 function wfIniGetBool( $setting ) {
2053 $val = ini_get( $setting );
2054 // 'on' and 'true' can't have whitespace around them, but '1' can.
2055 return strtolower( $val ) == 'on'
2056 ||
strtolower( $val ) == 'true'
2057 ||
strtolower( $val ) == 'yes'
2058 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2062 * Execute a shell command, with time and memory limits mirrored from the PHP
2063 * configuration if supported.
2064 * @param $cmd Command line, properly escaped for shell.
2065 * @param &$retval optional, will receive the program's exit code.
2066 * (non-zero is usually failure)
2067 * @return collected stdout as a string (trailing newlines stripped)
2069 function wfShellExec( $cmd, &$retval=null ) {
2070 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
2072 if( wfIniGetBool( 'safe_mode' ) ) {
2073 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2075 return "Unable to run external programs in safe mode.";
2078 if ( php_uname( 's' ) == 'Linux' ) {
2079 $time = intval( ini_get( 'max_execution_time' ) );
2080 $mem = intval( $wgMaxShellMemory );
2081 $filesize = intval( $wgMaxShellFileSize );
2083 if ( $time > 0 && $mem > 0 ) {
2084 $script = "$IP/bin/ulimit4.sh";
2085 if ( is_executable( $script ) ) {
2086 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2089 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2090 # This is a hack to work around PHP's flawed invocation of cmd.exe
2091 # http://news.php.net/php.internals/21796
2092 $cmd = '"' . $cmd . '"';
2094 wfDebug( "wfShellExec: $cmd\n" );
2096 $retval = 1; // error by default?
2098 passthru( $cmd, $retval );
2099 $output = ob_get_contents();
2106 * This function works like "use VERSION" in Perl, the program will die with a
2107 * backtrace if the current version of PHP is less than the version provided
2109 * This is useful for extensions which due to their nature are not kept in sync
2110 * with releases, and might depend on other versions of PHP than the main code
2112 * Note: PHP might die due to parsing errors in some cases before it ever
2113 * manages to call this function, such is life
2115 * @see perldoc -f use
2117 * @param mixed $version The version to check, can be a string, an integer, or
2120 function wfUsePHP( $req_ver ) {
2121 $php_ver = PHP_VERSION
;
2123 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2124 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2128 * This function works like "use VERSION" in Perl except it checks the version
2129 * of MediaWiki, the program will die with a backtrace if the current version
2130 * of MediaWiki is less than the version provided.
2132 * This is useful for extensions which due to their nature are not kept in sync
2135 * @see perldoc -f use
2137 * @param mixed $version The version to check, can be a string, an integer, or
2140 function wfUseMW( $req_ver ) {
2143 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2144 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2148 * @deprecated use StringUtils::escapeRegexReplacement
2150 function wfRegexReplacement( $string ) {
2151 return StringUtils
::escapeRegexReplacement( $string );
2155 * Return the final portion of a pathname.
2156 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2157 * http://bugs.php.net/bug.php?id=33898
2159 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2160 * We'll consider it so always, as we don't want \s in our Unix paths either.
2162 * @param string $path
2163 * @param string $suffix to remove if present
2166 function wfBaseName( $path, $suffix='' ) {
2167 $encSuffix = ($suffix == '')
2169 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2171 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2179 * Generate a relative path name to the given file.
2180 * May explode on non-matching case-insensitive paths,
2181 * funky symlinks, etc.
2183 * @param string $path Absolute destination path including target filename
2184 * @param string $from Absolute source path, directory only
2187 function wfRelativePath( $path, $from ) {
2188 // Normalize mixed input on Windows...
2189 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2190 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2192 // Trim trailing slashes -- fix for drive root
2193 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2194 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2196 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2197 $against = explode( DIRECTORY_SEPARATOR
, $from );
2199 if( $pieces[0] !== $against[0] ) {
2200 // Non-matching Windows drive letters?
2201 // Return a full path.
2205 // Trim off common prefix
2206 while( count( $pieces ) && count( $against )
2207 && $pieces[0] == $against[0] ) {
2208 array_shift( $pieces );
2209 array_shift( $against );
2212 // relative dots to bump us to the parent
2213 while( count( $against ) ) {
2214 array_unshift( $pieces, '..' );
2215 array_shift( $against );
2218 array_push( $pieces, wfBaseName( $path ) );
2220 return implode( DIRECTORY_SEPARATOR
, $pieces );
2224 * array_merge() does awful things with "numeric" indexes, including
2225 * string indexes when happen to look like integers. When we want
2226 * to merge arrays with arbitrary string indexes, we don't want our
2227 * arrays to be randomly corrupted just because some of them consist
2230 * Fuck you, PHP. Fuck you in the ear!
2232 * @param array $array1, [$array2, [...]]
2235 function wfArrayMerge( $array1/* ... */ ) {
2237 for( $i = 1; $i < func_num_args(); $i++
) {
2238 foreach( func_get_arg( $i ) as $key => $value ) {
2239 $out[$key] = $value;
2246 * Make a URL index, appropriate for the el_index field of externallinks.
2248 function wfMakeUrlIndex( $url ) {
2249 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2250 wfSuppressWarnings();
2251 $bits = parse_url( $url );
2252 wfRestoreWarnings();
2256 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2258 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2260 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2262 // parse_url detects for news: and mailto: the host part of an url as path
2263 // We have to correct this wrong detection
2264 if ( isset ( $bits['path'] ) ) {
2265 $bits['host'] = $bits['path'];
2272 // Reverse the labels in the hostname, convert to lower case
2273 // For emails reverse domainpart only
2274 if ( $bits['scheme'] == 'mailto' ) {
2275 $mailparts = explode( '@', $bits['host'], 2 );
2276 if ( count($mailparts) === 2 ) {
2277 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2279 // No domain specified, don't mangle it
2282 $reversedHost = $domainpart . '@' . $mailparts[0];
2284 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2286 // Add an extra dot to the end
2287 // Why? Is it in wrong place in mailto links?
2288 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2289 $reversedHost .= '.';
2291 // Reconstruct the pseudo-URL
2292 $prot = $bits['scheme'];
2293 $index = "$prot$delimiter$reversedHost";
2294 // Leave out user and password. Add the port, path, query and fragment
2295 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2296 if ( isset( $bits['path'] ) ) {
2297 $index .= $bits['path'];
2301 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2302 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2307 * Do any deferred updates and clear the list
2308 * TODO: This could be in Wiki.php if that class made any sense at all
2310 function wfDoUpdates()
2312 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2313 foreach ( $wgDeferredUpdateList as $update ) {
2314 $update->doUpdate();
2316 foreach ( $wgPostCommitUpdateList as $update ) {
2317 $update->doUpdate();
2319 $wgDeferredUpdateList = array();
2320 $wgPostCommitUpdateList = array();
2324 * @deprecated use StringUtils::explodeMarkup
2326 function wfExplodeMarkup( $separator, $text ) {
2327 return StringUtils
::explodeMarkup( $separator, $text );
2331 * Convert an arbitrarily-long digit string from one numeric base
2332 * to another, optionally zero-padding to a minimum column width.
2334 * Supports base 2 through 36; digit values 10-36 are represented
2335 * as lowercase letters a-z. Input is case-insensitive.
2337 * @param $input string of digits
2338 * @param $sourceBase int 2-36
2339 * @param $destBase int 2-36
2340 * @param $pad int 1 or greater
2341 * @param $lowercase bool
2342 * @return string or false on invalid input
2344 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2345 $input = strval( $input );
2346 if( $sourceBase < 2 ||
2351 $sourceBase != intval( $sourceBase ) ||
2352 $destBase != intval( $destBase ) ||
2353 $pad != intval( $pad ) ||
2354 !is_string( $input ) ||
2358 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2359 $inDigits = array();
2362 // Decode and validate input string
2363 $input = strtolower( $input );
2364 for( $i = 0; $i < strlen( $input ); $i++
) {
2365 $n = strpos( $digitChars, $input{$i} );
2366 if( $n === false ||
$n > $sourceBase ) {
2372 // Iterate over the input, modulo-ing out an output digit
2373 // at a time until input is gone.
2374 while( count( $inDigits ) ) {
2376 $workDigits = array();
2379 foreach( $inDigits as $digit ) {
2380 $work *= $sourceBase;
2383 if( $work < $destBase ) {
2384 // Gonna need to pull another digit.
2385 if( count( $workDigits ) ) {
2386 // Avoid zero-padding; this lets us find
2387 // the end of the input very easily when
2388 // length drops to zero.
2392 // Finally! Actual division!
2393 $workDigits[] = intval( $work / $destBase );
2395 // Isn't it annoying that most programming languages
2396 // don't have a single divide-and-remainder operator,
2397 // even though the CPU implements it that way?
2398 $work = $work %
$destBase;
2402 // All that division leaves us with a remainder,
2403 // which is conveniently our next output digit.
2404 $outChars .= $digitChars[$work];
2407 $inDigits = $workDigits;
2410 while( strlen( $outChars ) < $pad ) {
2414 return strrev( $outChars );
2418 * Create an object with a given name and an array of construct parameters
2419 * @param string $name
2420 * @param array $p parameters
2422 function wfCreateObject( $name, $p ){
2423 $p = array_values( $p );
2424 switch ( count( $p ) ) {
2428 return new $name( $p[0] );
2430 return new $name( $p[0], $p[1] );
2432 return new $name( $p[0], $p[1], $p[2] );
2434 return new $name( $p[0], $p[1], $p[2], $p[3] );
2436 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2438 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2440 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2445 * Alias for modularized function
2446 * @deprecated Use Http::get() instead
2448 function wfGetHTTP( $url, $timeout = 'default' ) {
2449 wfDeprecated(__FUNCTION__
);
2450 return Http
::get( $url, $timeout );
2454 * Alias for modularized function
2455 * @deprecated Use Http::isLocalURL() instead
2457 function wfIsLocalURL( $url ) {
2458 wfDeprecated(__FUNCTION__
);
2459 return Http
::isLocalURL( $url );
2462 function wfHttpOnlySafe() {
2463 global $wgHttpOnlyBlacklist;
2464 if( !version_compare("5.2", PHP_VERSION
, "<") )
2467 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2468 foreach( $wgHttpOnlyBlacklist as $regex ) {
2469 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2479 * Initialise php session
2481 function wfSetupSession() {
2482 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2483 if( $wgSessionsInMemcached ) {
2484 require_once( 'MemcachedSessions.php' );
2485 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2486 # If it's left on 'user' or another setting from another
2487 # application, it will end up failing. Try to recover.
2488 ini_set ( 'session.save_handler', 'files' );
2490 $httpOnlySafe = wfHttpOnlySafe();
2491 wfDebugLog( 'cookie',
2492 'session_set_cookie_params: "' . implode( '", "',
2498 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2499 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2500 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2502 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2503 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2505 session_cache_limiter( 'private, must-revalidate' );
2506 wfSuppressWarnings();
2508 wfRestoreWarnings();
2512 * Get an object from the precompiled serialized directory
2514 * @return mixed The variable on success, false on failure
2516 function wfGetPrecompiledData( $name ) {
2519 $file = "$IP/serialized/$name";
2520 if ( file_exists( $file ) ) {
2521 $blob = file_get_contents( $file );
2523 return unserialize( $blob );
2529 function wfGetCaller( $level = 2 ) {
2530 $backtrace = wfDebugBacktrace();
2531 if ( isset( $backtrace[$level] ) ) {
2532 return wfFormatStackFrame($backtrace[$level]);
2534 $caller = 'unknown';
2539 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2540 function wfGetAllCallers() {
2541 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2544 /** Return a string representation of frame */
2545 function wfFormatStackFrame($frame) {
2546 return isset( $frame["class"] )?
2547 $frame["class"]."::".$frame["function"]:
2554 function wfMemcKey( /*... */ ) {
2555 $args = func_get_args();
2556 $key = wfWikiID() . ':' . implode( ':', $args );
2561 * Get a cache key for a foreign DB
2563 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2564 $args = array_slice( func_get_args(), 2 );
2566 $key = "$db-$prefix:" . implode( ':', $args );
2568 $key = $db . ':' . implode( ':', $args );
2574 * Get an ASCII string identifying this wiki
2575 * This is used as a prefix in memcached keys
2577 function wfWikiID( $db = null ) {
2578 if( $db instanceof Database
) {
2579 return $db->getWikiID();
2581 global $wgDBprefix, $wgDBname;
2582 if ( $wgDBprefix ) {
2583 return "$wgDBname-$wgDBprefix";
2591 * Split a wiki ID into DB name and table prefix
2593 function wfSplitWikiID( $wiki ) {
2594 $bits = explode( '-', $wiki, 2 );
2595 if ( count( $bits ) < 2 ) {
2602 * Get a Database object.
2603 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2604 * master (for write queries), DB_SLAVE for potentially lagged
2605 * read queries, or an integer >= 0 for a particular server.
2607 * @param mixed $groups Query groups. An array of group names that this query
2608 * belongs to. May contain a single string if the query is only
2611 * @param string $wiki The wiki ID, or false for the current wiki
2613 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2614 * will always return the same object, unless the underlying connection or load
2615 * balancer is manually destroyed.
2617 function &wfGetDB( $db = DB_LAST
, $groups = array(), $wiki = false ) {
2618 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2622 * Get a load balancer object.
2624 * @param array $groups List of query groups
2625 * @param string $wiki Wiki ID, or false for the current wiki
2626 * @return LoadBalancer
2628 function wfGetLB( $wiki = false ) {
2629 return wfGetLBFactory()->getMainLB( $wiki );
2633 * Get the load balancer factory object
2635 function &wfGetLBFactory() {
2636 return LBFactory
::singleton();
2641 * Shortcut for RepoGroup::singleton()->findFile()
2642 * @param mixed $title Title object or string. May be interwiki.
2643 * @param mixed $time Requested time for an archived image, or false for the
2644 * current version. An image object will be returned which
2645 * was created at the specified time.
2646 * @param mixed $flags FileRepo::FIND_ flags
2647 * @return File, or false if the file does not exist
2649 function wfFindFile( $title, $time = false, $flags = 0 ) {
2650 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2654 * Get an object referring to a locally registered file.
2655 * Returns a valid placeholder object if the file does not exist.
2657 function wfLocalFile( $title ) {
2658 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2662 * Should low-performance queries be disabled?
2666 function wfQueriesMustScale() {
2667 global $wgMiserMode;
2669 ||
( SiteStats
::pages() > 100000
2670 && SiteStats
::edits() > 1000000
2671 && SiteStats
::users() > 10000 );
2675 * Get the path to a specified script file, respecting file
2676 * extensions; this is a wrapper around $wgScriptExtension etc.
2678 * @param string $script Script filename, sans extension
2681 function wfScript( $script = 'index' ) {
2682 global $wgScriptPath, $wgScriptExtension;
2683 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2687 * Convenience function converts boolean values into "true"
2688 * or "false" (string) values
2690 * @param bool $value
2693 function wfBoolToStr( $value ) {
2694 return $value ?
'true' : 'false';
2698 * Load an extension messages file
2700 * @param string $extensionName Name of extension to load messages from\for.
2701 * @param string $langcode Language to load messages for, or false for default
2702 * behvaiour (en, content language and user language).
2703 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2704 * on MediaWiki prior to that
2706 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2707 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2709 #For recording whether extension message files have been loaded in a given language.
2710 static $loaded = array();
2712 if( !array_key_exists( $extensionName, $loaded ) ) {
2713 $loaded[$extensionName] = array();
2716 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2717 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2720 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2721 # Just do en, content language and user language.
2722 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2723 # Mark that they have been loaded.
2724 $loaded[$extensionName]['en'] = true;
2725 $loaded[$extensionName][$wgLang->getCode()] = true;
2726 $loaded[$extensionName][$wgContLang->getCode()] = true;
2727 # Mark that this part has been done to avoid weird if statements.
2728 $loaded[$extensionName]['*'] = true;
2729 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2730 # Load messages for specified language.
2731 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2732 # Mark that they have been loaded.
2733 $loaded[$extensionName][$langcode] = true;
2738 * Get a platform-independent path to the null file, e.g.
2743 function wfGetNull() {
2744 return wfIsWindows()
2750 * Displays a maxlag error
2752 * @param string $host Server that lags the most
2753 * @param int $lag Maxlag (actual)
2754 * @param int $maxLag Maxlag (requested)
2756 function wfMaxlagError( $host, $lag, $maxLag ) {
2757 global $wgShowHostnames;
2758 header( 'HTTP/1.1 503 Service Unavailable' );
2759 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2760 header( 'X-Database-Lag: ' . intval( $lag ) );
2761 header( 'Content-Type: text/plain' );
2762 if( $wgShowHostnames ) {
2763 echo "Waiting for $host: $lag seconds lagged\n";
2765 echo "Waiting for a database server: $lag seconds lagged\n";
2770 * Throws an E_USER_NOTICE saying that $function is deprecated
2771 * @param string $function
2774 function wfDeprecated( $function ) {
2775 global $wgDebugLogFile;
2776 if ( !$wgDebugLogFile ) {
2779 $callers = wfDebugBacktrace();
2780 if( isset( $callers[2] ) ){
2781 $callerfunc = $callers[2];
2782 $callerfile = $callers[1];
2783 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2784 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2786 $file = '(internal function)';
2789 if( isset( $callerfunc['class'] ) )
2790 $func .= $callerfunc['class'] . '::';
2791 $func .= @$callerfunc['function'];
2792 $msg = "Use of $function is deprecated. Called from $func in $file";
2794 $msg = "Use of $function is deprecated.";
2796 wfDebug( "$msg\n" );
2800 * Sleep until the worst slave's replication lag is less than or equal to
2801 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2802 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2803 * a no-op if there are no slaves.
2805 * Every time the function has to wait for a slave, it will print a message to
2806 * that effect (and then sleep for a little while), so it's probably not best
2807 * to use this outside maintenance scripts in its present form.
2809 * @param int $maxLag
2812 function wfWaitForSlaves( $maxLag ) {
2815 list( $host, $lag ) = $lb->getMaxLag();
2816 while( $lag > $maxLag ) {
2817 $name = @gethostbyaddr
( $host );
2818 if( $name !== false ) {
2821 print "Waiting for $host (lagged $lag seconds)...\n";
2823 list( $host, $lag ) = $lb->getMaxLag();
2828 /** Generate a random 32-character hexadecimal token.
2829 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2831 function wfGenerateToken( $salt = '' ) {
2832 $salt = serialize($salt);
2834 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2838 * Replace all invalid characters with -
2839 * @param mixed $title Filename to process
2841 function wfStripIllegalFilenameChars( $name ) {
2842 $name = wfBaseName( $name );
2843 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );