c5d5f1f56785a7958dadca2c9b0a6da9a9fc48a3
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';
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 );
34 # UTF-8 substr function based on a PHP manual comment
35 if ( !function_exists( 'mb_substr' ) ) {
36 function mb_substr( $str, $start ) {
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 ) );
44 return join( '', array_slice( $ar[0], $start ) );
49 if ( !function_exists( 'mb_strlen' ) ) {
51 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
53 * @param string $enc optional encoding; ignored
56 function mb_strlen( $str, $enc="" ) {
57 $counts = count_chars( $str );
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];
73 if ( !function_exists( 'array_diff_key' ) ) {
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 ) {
81 foreach ( $left as $key => $unused ) {
82 if ( isset( $right[$key] ) ) {
83 unset( $result[$key] );
91 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
93 function wfArrayDiff2( $a, $b ) {
94 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
96 function wfArrayDiff2_cmp( $a, $b ) {
97 if ( !is_array( $a ) ) {
98 return strcmp( $a, $b );
99 } elseif ( count( $a ) !== count( $b ) ) {
100 return count( $a ) < count( $b ) ?
-1 : 1;
104 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
105 $cmp = strcmp( $valueA, $valueB );
115 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
116 * PHP 5 won't let you declare a 'clone' function, even conditionally,
117 * so it has to be a wrapper with a different name.
119 function wfClone( $object ) {
120 return clone( $object );
124 * Seed Mersenne Twister
125 * No-op for compatibility; only necessary in PHP < 4.2.0
127 function wfSeedRandom() {
132 * Get a random decimal value between 0 and 1, in a way
133 * not likely to give duplicate values for any realistic
134 * number of articles.
138 function wfRandom() {
139 # The maximum random value is "only" 2^31-1, so get two random
140 # values to reduce the chance of dupes
141 $max = mt_getrandmax() +
1;
142 $rand = number_format( (mt_rand() * $max +
mt_rand())
143 / $max / $max, 12, '.', '' );
148 * We want / and : to be included as literal characters in our title URLs.
149 * %2F in the page titles seems to fatally break for some reason.
154 function wfUrlencode ( $s ) {
155 $s = urlencode( $s );
156 $s = preg_replace( '/%3[Aa]/', ':', $s );
157 $s = preg_replace( '/%2[Ff]/', '/', $s );
163 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
164 * In normal operation this is a NOP.
166 * Controlling globals:
167 * $wgDebugLogFile - points to the log file
168 * $wgProfileOnly - if set, normal debug messages will not be recorded.
169 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
170 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
172 * @param $text String
173 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
175 function wfDebug( $text, $logonly = false ) {
176 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
177 static $recursion = 0;
179 static $cache = array(); // Cache of unoutputted messages
181 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
182 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
186 if ( $wgDebugComments && !$logonly ) {
189 if ( !isset( $wgOut ) ) {
192 if ( !StubObject
::isRealObject( $wgOut ) ) {
201 // add the message and possible cached ones to the output
202 array_map( array( $wgOut, 'debug' ), $cache );
205 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
206 # Strip unprintables; they can switch terminal modes when binary data
207 # gets dumped, which is pretty annoying.
208 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
209 wfErrorLog( $text, $wgDebugLogFile );
214 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
215 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
217 * @param $logGroup String
218 * @param $text String
219 * @param $public Bool: whether to log the event in the public log if no private
220 * log file is specified, (default true)
222 function wfDebugLog( $logGroup, $text, $public = true ) {
223 global $wgDebugLogGroups;
224 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
225 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
226 $time = wfTimestamp( TS_DB
);
228 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
229 } else if ( $public === true ) {
230 wfDebug( $text, true );
235 * Log for database errors
236 * @param $text String: database error message.
238 function wfLogDBError( $text ) {
239 global $wgDBerrorLog, $wgDBname;
240 if ( $wgDBerrorLog ) {
241 $host = trim(`hostname`
);
242 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
243 wfErrorLog( $text, $wgDBerrorLog );
248 * Log to a file without getting "file size exceeded" signals
250 function wfErrorLog( $text, $file ) {
251 wfSuppressWarnings();
252 $exists = file_exists( $file );
253 $size = $exists ?
filesize( $file ) : false;
254 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
255 error_log( $text, 3, $file );
263 function wfLogProfilingData() {
264 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
265 global $wgProfiler, $wgUser;
266 if ( !isset( $wgProfiler ) )
270 $elapsed = $now - $wgRequestTime;
271 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
273 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
274 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
275 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
276 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
277 if( !empty( $_SERVER['HTTP_FROM'] ) )
278 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
280 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
281 // Don't unstub $wgUser at this late stage just for statistics purposes
282 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
284 $log = sprintf( "%s\t%04.3f\t%s\n",
285 gmdate( 'YmdHis' ), $elapsed,
286 urldecode( $wgRequest->getRequestURL() . $forward ) );
287 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
288 wfErrorLog( $log . $prof, $wgDebugLogFile );
293 * Check if the wiki read-only lock file is present. This can be used to lock
294 * off editing functions, but doesn't guarantee that the database will not be
298 function wfReadOnly() {
299 global $wgReadOnlyFile, $wgReadOnly;
301 if ( !is_null( $wgReadOnly ) ) {
302 return (bool)$wgReadOnly;
304 if ( '' == $wgReadOnlyFile ) {
307 // Set $wgReadOnly for faster access next time
308 if ( is_file( $wgReadOnlyFile ) ) {
309 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
313 return (bool)$wgReadOnly;
316 function wfReadOnlyReason() {
323 * Return a Language object from $langcode
324 * @param $langcode Mixed: either:
325 * - a Language object
326 * - code of the language to get the message for, if it is
327 * a valid code create a language for that language, if
328 * it is a string but not a valid code then make a basic
330 * - a boolean: if it's false then use the current users
331 * language (as a fallback for the old parameter
332 * functionality), or if it is true then use the wikis
333 * @return Language object
335 function wfGetLangObj( $langcode = false ){
336 # Identify which language to get or create a language object for.
337 if( $langcode instanceof Language
)
338 # Great, we already have the object!
342 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
343 # $langcode is the language code of the wikis content language object.
344 # or it is a boolean and value is true
348 if( $langcode === $wgLang->getCode() ||
$langcode === false )
349 # $langcode is the language code of user language object.
350 # or it was a boolean and value is false
353 $validCodes = array_keys( Language
::getLanguageNames() );
354 if( in_array( $langcode, $validCodes ) )
355 # $langcode corresponds to a valid language.
356 return Language
::factory( $langcode );
358 # $langcode is a string, but not a valid language code; use content language.
359 wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
364 * Get a message from anywhere, for the current user language.
366 * Use wfMsgForContent() instead if the message should NOT
367 * change depending on the user preferences.
369 * @param $key String: lookup key for the message, usually
370 * defined in languages/Language.php
372 * This function also takes extra optional parameters (not
373 * shown in the function definition), which can by used to
374 * insert variable text into the predefined message.
376 function wfMsg( $key ) {
377 $args = func_get_args();
378 array_shift( $args );
379 return wfMsgReal( $key, $args, true );
383 * Same as above except doesn't transform the message
385 function wfMsgNoTrans( $key ) {
386 $args = func_get_args();
387 array_shift( $args );
388 return wfMsgReal( $key, $args, true, false, false );
392 * Get a message from anywhere, for the current global language
393 * set with $wgLanguageCode.
395 * Use this if the message should NOT change dependent on the
396 * language set in the user's preferences. This is the case for
397 * most text written into logs, as well as link targets (such as
398 * the name of the copyright policy page). Link titles, on the
399 * other hand, should be shown in the UI language.
401 * Note that MediaWiki allows users to change the user interface
402 * language in their preferences, but a single installation
403 * typically only contains content in one language.
405 * Be wary of this distinction: If you use wfMsg() where you should
406 * use wfMsgForContent(), a user of the software may have to
407 * customize over 70 messages in order to, e.g., fix a link in every
410 * @param $key String: lookup key for the message, usually
411 * defined in languages/Language.php
413 function wfMsgForContent( $key ) {
414 global $wgForceUIMsgAsContentMsg;
415 $args = func_get_args();
416 array_shift( $args );
418 if( is_array( $wgForceUIMsgAsContentMsg ) &&
419 in_array( $key, $wgForceUIMsgAsContentMsg ) )
421 return wfMsgReal( $key, $args, true, $forcontent );
425 * Same as above except doesn't transform the message
427 function wfMsgForContentNoTrans( $key ) {
428 global $wgForceUIMsgAsContentMsg;
429 $args = func_get_args();
430 array_shift( $args );
432 if( is_array( $wgForceUIMsgAsContentMsg ) &&
433 in_array( $key, $wgForceUIMsgAsContentMsg ) )
435 return wfMsgReal( $key, $args, true, $forcontent, false );
439 * Get a message from the language file, for the UI elements
441 function wfMsgNoDB( $key ) {
442 $args = func_get_args();
443 array_shift( $args );
444 return wfMsgReal( $key, $args, false );
448 * Get a message from the language file, for the content
450 function wfMsgNoDBForContent( $key ) {
451 global $wgForceUIMsgAsContentMsg;
452 $args = func_get_args();
453 array_shift( $args );
455 if( is_array( $wgForceUIMsgAsContentMsg ) &&
456 in_array( $key, $wgForceUIMsgAsContentMsg ) )
458 return wfMsgReal( $key, $args, false, $forcontent );
463 * Really get a message
464 * @param $key String: key to get.
466 * @param $useDB Boolean
467 * @param $transform Boolean: Whether or not to transform the message.
468 * @param $forContent Boolean
469 * @return String: the requested message.
471 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
472 wfProfileIn( __METHOD__
);
473 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
474 $message = wfMsgReplaceArgs( $message, $args );
475 wfProfileOut( __METHOD__
);
480 * This function provides the message source for messages to be edited which are *not* stored in the database.
481 * @param $key String:
483 function wfMsgWeirdKey ( $key ) {
484 $source = wfMsgGetKey( $key, false, true, false );
485 if ( wfEmptyMsg( $key, $source ) )
492 * Fetch a message string value, but don't replace any keys yet.
495 * @param string $langcode Code of the language to get the message for, or
496 * behaves as a content language switch if it is a
501 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
502 global $wgContLang, $wgMessageCache;
504 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
506 # If $wgMessageCache isn't initialised yet, try to return something sensible.
507 if( is_object( $wgMessageCache ) ) {
508 $message = $wgMessageCache->get( $key, $useDB, $langCode );
510 $message = $wgMessageCache->transform( $message );
513 $lang = wfGetLangObj( $langCode );
515 # MessageCache::get() does this already, Language::getMessage() doesn't
516 # ISSUE: Should we try to handle "message/lang" here too?
517 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
519 if( is_object( $lang ) ) {
520 $message = $lang->getMessage( $key );
530 * Replace message parameter keys on the given formatted output.
532 * @param string $message
537 function wfMsgReplaceArgs( $message, $args ) {
538 # Fix windows line-endings
539 # Some messages are split with explode("\n", $msg)
540 $message = str_replace( "\r", '', $message );
543 if ( count( $args ) ) {
544 if ( is_array( $args[0] ) ) {
545 $args = array_values( $args[0] );
547 $replacementKeys = array();
548 foreach( $args as $n => $param ) {
549 $replacementKeys['$' . ($n +
1)] = $param;
551 $message = strtr( $message, $replacementKeys );
558 * Return an HTML-escaped version of a message.
559 * Parameter replacements, if any, are done *after* the HTML-escaping,
560 * so parameters may contain HTML (eg links or form controls). Be sure
561 * to pre-escape them if you really do want plaintext, or just wrap
562 * the whole thing in htmlspecialchars().
565 * @param string ... parameters
568 function wfMsgHtml( $key ) {
569 $args = func_get_args();
570 array_shift( $args );
571 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
575 * Return an HTML version of message
576 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
577 * so parameters may contain HTML (eg links or form controls). Be sure
578 * to pre-escape them if you really do want plaintext, or just wrap
579 * the whole thing in htmlspecialchars().
582 * @param string ... parameters
585 function wfMsgWikiHtml( $key ) {
587 $args = func_get_args();
588 array_shift( $args );
589 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
593 * Returns message in the requested format
594 * @param string $key Key of the message
595 * @param array $options Processing rules:
596 * <i>parse</i>: parses wikitext to html
597 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
598 * <i>escape</i>: filters message through htmlspecialchars
599 * <i>escapenoentities</i>: same, but allows entity references like through
600 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
601 * <i>parsemag</i>: transform the message using magic phrases
602 * <i>content</i>: fetch message for content language instead of interface
603 * <i>language</i>: language code to fetch message for (overriden by <i>content</i>), its behaviour
604 * with parser, parseinline and parsemag is undefined.
605 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
607 function wfMsgExt( $key, $options ) {
608 global $wgOut, $wgParser;
610 $args = func_get_args();
611 array_shift( $args );
612 array_shift( $args );
614 if( !is_array($options) ) {
615 $options = array($options);
618 if( in_array('content', $options) ) {
621 } elseif( array_key_exists('language', $options) ) {
623 $langCode = $options['language'];
624 $validCodes = array_keys( Language
::getLanguageNames() );
625 if( !in_array($options['language'], $validCodes) ) {
626 # Fallback to en, instead of whatever interface language we might have
634 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
636 if( !in_array('replaceafter', $options) ) {
637 $string = wfMsgReplaceArgs( $string, $args );
640 if( in_array('parse', $options) ) {
641 $string = $wgOut->parse( $string, true, !$forContent );
642 } elseif ( in_array('parseinline', $options) ) {
643 $string = $wgOut->parse( $string, true, !$forContent );
645 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
648 } elseif ( in_array('parsemag', $options) ) {
649 global $wgMessageCache;
650 if ( isset( $wgMessageCache ) ) {
651 $string = $wgMessageCache->transform( $string, !$forContent );
655 if ( in_array('escape', $options) ) {
656 $string = htmlspecialchars ( $string );
657 } elseif ( in_array( 'escapenoentities', $options ) ) {
658 $string = htmlspecialchars( $string );
659 $string = str_replace( '&', '&', $string );
660 $string = Sanitizer
::normalizeCharReferences( $string );
663 if( in_array('replaceafter', $options) ) {
664 $string = wfMsgReplaceArgs( $string, $args );
672 * Just like exit() but makes a note of it.
673 * Commits open transactions except if the error parameter is set
675 * @deprecated Please return control to the caller or throw an exception
677 function wfAbruptExit( $error = false ){
678 static $called = false;
684 $bt = wfDebugBacktrace();
686 for($i = 0; $i < count($bt) ; $i++
){
687 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
688 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
689 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
692 wfDebug('WARNING: Abrupt exit\n');
695 wfLogProfilingData();
698 wfGetLB()->closeAll();
704 * @deprecated Please return control the caller or throw an exception
706 function wfErrorExit() {
707 wfAbruptExit( true );
711 * Print a simple message and die, returning nonzero to the shell if any.
712 * Plain die() fails to return nonzero to the shell if you pass a string.
715 function wfDie( $msg='' ) {
721 * Throw a debugging exception. This function previously once exited the process,
722 * but now throws an exception instead, with similar results.
724 * @param string $msg Message shown when dieing.
726 function wfDebugDieBacktrace( $msg = '' ) {
727 throw new MWException( $msg );
731 * Fetch server name for use in error reporting etc.
732 * Use real server name if available, so we know which machine
733 * in a server farm generated the current page.
736 function wfHostname() {
737 if ( function_exists( 'posix_uname' ) ) {
738 // This function not present on Windows
739 $uname = @posix_uname
();
743 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
744 return $uname['nodename'];
746 # This may be a virtual server.
747 return $_SERVER['SERVER_NAME'];
752 * Returns a HTML comment with the elapsed time since request.
753 * This method has no side effects.
756 function wfReportTime() {
757 global $wgRequestTime, $wgShowHostnames;
760 $elapsed = $now - $wgRequestTime;
762 return $wgShowHostnames
763 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
764 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
768 * Safety wrapper for debug_backtrace().
770 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
771 * murky circumstances, which may be triggered in part by stub objects
772 * or other fancy talkin'.
774 * Will return an empty array if Zend Optimizer is detected, otherwise
775 * the output from debug_backtrace() (trimmed).
777 * @return array of backtrace information
779 function wfDebugBacktrace() {
780 if( extension_loaded( 'Zend Optimizer' ) ) {
781 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
784 return array_slice( debug_backtrace(), 1 );
788 function wfBacktrace() {
789 global $wgCommandLineMode;
791 if ( $wgCommandLineMode ) {
796 $backtrace = wfDebugBacktrace();
797 foreach( $backtrace as $call ) {
798 if( isset( $call['file'] ) ) {
799 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
800 $file = $f[count($f)-1];
804 if( isset( $call['line'] ) ) {
805 $line = $call['line'];
809 if ( $wgCommandLineMode ) {
810 $msg .= "$file line $line calls ";
812 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
814 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
815 $msg .= $call['function'] . '()';
817 if ( $wgCommandLineMode ) {
823 if ( $wgCommandLineMode ) {
833 /* Some generic result counters, pulled out of SearchEngine */
839 function wfShowingResults( $offset, $limit ) {
841 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
847 function wfShowingResultsNum( $offset, $limit, $num ) {
849 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
855 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
857 $fmtLimit = $wgLang->formatNum( $limit );
858 $prev = wfMsg( 'prevn', $fmtLimit );
859 $next = wfMsg( 'nextn', $fmtLimit );
861 if( is_object( $link ) ) {
864 $title = Title
::newFromText( $link );
865 if( is_null( $title ) ) {
870 if ( 0 != $offset ) {
871 $po = $offset - $limit;
872 if ( $po < 0 ) { $po = 0; }
873 $q = "limit={$limit}&offset={$po}";
874 if ( '' != $query ) { $q .= '&'.$query; }
875 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
876 } else { $plink = $prev; }
878 $no = $offset +
$limit;
879 $q = 'limit='.$limit.'&offset='.$no;
880 if ( '' != $query ) { $q .= '&'.$query; }
885 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
887 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
888 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
889 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
890 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
891 wfNumLink( $offset, 500, $title, $query );
893 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
899 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
901 if ( '' == $query ) { $q = ''; }
902 else { $q = $query.'&'; }
903 $q .= 'limit='.$limit.'&offset='.$offset;
905 $fmtLimit = $wgLang->formatNum( $limit );
906 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
912 * @todo FIXME: we may want to blacklist some broken browsers
914 * @return bool Whereas client accept gzip compression
916 function wfClientAcceptsGzip() {
919 # FIXME: we may want to blacklist some broken browsers
922 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
923 $_SERVER['HTTP_ACCEPT_ENCODING'],
925 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
926 wfDebug( " accepts gzip\n" );
934 * Obtain the offset and limit values from the request string;
935 * used in special pages
937 * @param $deflimit Default limit if none supplied
938 * @param $optionname Name of a user preference to check against
942 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
944 return $wgRequest->getLimitOffset( $deflimit, $optionname );
948 * Escapes the given text so that it may be output using addWikiText()
949 * without any linking, formatting, etc. making its way through. This
950 * is achieved by substituting certain characters with HTML entities.
951 * As required by the callers, <nowiki> is not used. It currently does
952 * not filter out characters which have special meaning only at the
953 * start of a line, such as "*".
955 * @param string $text Text to be escaped
957 function wfEscapeWikiText( $text ) {
959 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
960 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
961 htmlspecialchars($text) );
968 function wfQuotedPrintable( $string, $charset = '' ) {
969 # Probably incomplete; see RFC 2045
970 if( empty( $charset ) ) {
971 global $wgInputEncoding;
972 $charset = $wgInputEncoding;
974 $charset = strtoupper( $charset );
975 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
977 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
978 $replace = $illegal . '\t ?_';
979 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
980 $out = "=?$charset?Q?";
981 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
992 return microtime(true);
996 * Sets dest to source and returns the original value of dest
997 * If source is NULL, it just returns the value, it doesn't set the variable
999 function wfSetVar( &$dest, $source ) {
1001 if ( !is_null( $source ) ) {
1008 * As for wfSetVar except setting a bit
1010 function wfSetBit( &$dest, $bit, $state = true ) {
1011 $temp = (bool)($dest & $bit );
1012 if ( !is_null( $state ) ) {
1023 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1024 * "days=7&limit=100". Options in the first array override options in the second.
1025 * Options set to "" will not be output.
1027 function wfArrayToCGI( $array1, $array2 = NULL )
1029 if ( !is_null( $array2 ) ) {
1030 $array1 = $array1 +
$array2;
1034 foreach ( $array1 as $key => $value ) {
1035 if ( '' !== $value ) {
1039 if(is_array($value))
1042 foreach($value as $v)
1044 $cgi .= ($firstTime ?
'' : '&') .
1045 urlencode( $key . '[]' ) . '=' .
1051 $cgi .= urlencode( $key ) . '=' .
1052 urlencode( $value );
1059 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1060 * its argument and returns the same string in array form. This allows compa-
1061 * tibility with legacy functions that accept raw query strings instead of nice
1062 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1063 * valid query strings, or it will explode.
1065 * @param $query string Query string
1066 * @return array Array version of input
1068 function wfCgiToArray( $query ) {
1069 if( isset( $query[0] ) and $query[0] == '?' ) {
1070 $query = substr( $query, 1 );
1072 $bits = explode( '&', $query );
1074 foreach( $bits as $bit ) {
1078 list( $key, $value ) = explode( '=', $bit );
1079 $key = urldecode( $key );
1080 $value = urldecode( $value );
1081 $ret[$key] = $value;
1087 * Append a query string to an existing URL, which may or may not already
1088 * have query string parameters already. If so, they will be combined.
1090 * @param string $url
1091 * @param string $query
1094 function wfAppendQuery( $url, $query ) {
1095 if( $query != '' ) {
1096 if( false === strpos( $url, '?' ) ) {
1107 * Expand a potentially local URL to a fully-qualified URL.
1108 * Assumes $wgServer is correct. :)
1109 * @param string $url, either fully-qualified or a local path + query
1110 * @return string Fully-qualified URL
1112 function wfExpandUrl( $url ) {
1113 if( substr( $url, 0, 1 ) == '/' ) {
1115 return $wgServer . $url;
1122 * This is obsolete, use SquidUpdate::purge()
1125 function wfPurgeSquidServers ($urlArr) {
1126 SquidUpdate
::purge( $urlArr );
1130 * Windows-compatible version of escapeshellarg()
1131 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1132 * function puts single quotes in regardless of OS
1134 function wfEscapeShellArg( ) {
1135 $args = func_get_args();
1138 foreach ( $args as $arg ) {
1145 if ( wfIsWindows() ) {
1146 // Escaping for an MSVC-style command line parser
1147 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1148 // Double the backslashes before any double quotes. Escape the double quotes.
1149 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1152 foreach ( $tokens as $token ) {
1154 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1160 // Double the backslashes before the end of the string, because
1161 // we will soon add a quote
1163 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1164 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1167 // Add surrounding quotes
1168 $retVal .= '"' . $arg . '"';
1170 $retVal .= escapeshellarg( $arg );
1177 * wfMerge attempts to merge differences between three texts.
1178 * Returns true for a clean merge and false for failure or a conflict.
1180 function wfMerge( $old, $mine, $yours, &$result ){
1183 # This check may also protect against code injection in
1184 # case of broken installations.
1185 if(! file_exists( $wgDiff3 ) ){
1186 wfDebug( "diff3 not found\n" );
1190 # Make temporary files
1192 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1193 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1194 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1196 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1197 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1198 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1200 # Check for a conflict
1201 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1202 wfEscapeShellArg( $mytextName ) . ' ' .
1203 wfEscapeShellArg( $oldtextName ) . ' ' .
1204 wfEscapeShellArg( $yourtextName );
1205 $handle = popen( $cmd, 'r' );
1207 if( fgets( $handle, 1024 ) ){
1215 $cmd = $wgDiff3 . ' -a -e --merge ' .
1216 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1217 $handle = popen( $cmd, 'r' );
1220 $data = fread( $handle, 8192 );
1221 if ( strlen( $data ) == 0 ) {
1227 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1229 if ( $result === '' && $old !== '' && $conflict == false ) {
1230 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1237 * Returns unified plain-text diff of two texts.
1238 * Useful for machine processing of diffs.
1239 * @param $before string The text before the changes.
1240 * @param $after string The text after the changes.
1241 * @param $params string Command-line options for the diff command.
1242 * @return string Unified diff of $before and $after
1244 function wfDiff( $before, $after, $params = '-u' ) {
1247 # This check may also protect against code injection in
1248 # case of broken installations.
1249 if( !file_exists( $wgDiff ) ){
1250 wfDebug( "diff executable not found\n" );
1251 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1252 $format = new UnifiedDiffFormatter();
1253 return $format->format( $diffs );
1256 # Make temporary files
1258 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1259 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1261 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1262 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1264 // Get the diff of the two files
1265 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1267 $h = popen( $cmd, 'r' );
1272 $data = fread( $h, 8192 );
1273 if ( strlen( $data ) == 0 ) {
1281 unlink( $oldtextName );
1282 unlink( $newtextName );
1284 // Kill the --- and +++ lines. They're not useful.
1285 $diff_lines = explode( "\n", $diff );
1286 if (strpos( $diff_lines[0], '---' ) === 0) {
1287 unset($diff_lines[0]);
1289 if (strpos( $diff_lines[1], '+++' ) === 0) {
1290 unset($diff_lines[1]);
1293 $diff = implode( "\n", $diff_lines );
1301 function wfVarDump( $var ) {
1303 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1304 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1307 $wgOut->addHTML( $s );
1312 * Provide a simple HTTP error.
1314 function wfHttpError( $code, $label, $desc ) {
1317 header( "HTTP/1.0 $code $label" );
1318 header( "Status: $code $label" );
1319 $wgOut->sendCacheControl();
1321 header( 'Content-type: text/html; charset=utf-8' );
1322 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1323 "<html><head><title>" .
1324 htmlspecialchars( $label ) .
1325 "</title></head><body><h1>" .
1326 htmlspecialchars( $label ) .
1328 nl2br( htmlspecialchars( $desc ) ) .
1329 "</p></body></html>\n";
1333 * Clear away any user-level output buffers, discarding contents.
1335 * Suitable for 'starting afresh', for instance when streaming
1336 * relatively large amounts of data without buffering, or wanting to
1337 * output image files without ob_gzhandler's compression.
1339 * The optional $resetGzipEncoding parameter controls suppression of
1340 * the Content-Encoding header sent by ob_gzhandler; by default it
1341 * is left. See comments for wfClearOutputBuffers() for why it would
1344 * Note that some PHP configuration options may add output buffer
1345 * layers which cannot be removed; these are left in place.
1347 * @param bool $resetGzipEncoding
1349 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1350 if( $resetGzipEncoding ) {
1351 // Suppress Content-Encoding and Content-Length
1352 // headers from 1.10+s wfOutputHandler
1353 global $wgDisableOutputCompression;
1354 $wgDisableOutputCompression = true;
1356 while( $status = ob_get_status() ) {
1357 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1358 // Probably from zlib.output_compression or other
1359 // PHP-internal setting which can't be removed.
1361 // Give up, and hope the result doesn't break
1365 if( !ob_end_clean() ) {
1366 // Could not remove output buffer handler; abort now
1367 // to avoid getting in some kind of infinite loop.
1370 if( $resetGzipEncoding ) {
1371 if( $status['name'] == 'ob_gzhandler' ) {
1372 // Reset the 'Content-Encoding' field set by this handler
1373 // so we can start fresh.
1374 header( 'Content-Encoding:' );
1381 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1383 * Clear away output buffers, but keep the Content-Encoding header
1384 * produced by ob_gzhandler, if any.
1386 * This should be used for HTTP 304 responses, where you need to
1387 * preserve the Content-Encoding header of the real result, but
1388 * also need to suppress the output of ob_gzhandler to keep to spec
1389 * and avoid breaking Firefox in rare cases where the headers and
1390 * body are broken over two packets.
1392 function wfClearOutputBuffers() {
1393 wfResetOutputBuffers( false );
1397 * Converts an Accept-* header into an array mapping string values to quality
1400 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1401 # No arg means accept anything (per HTTP spec)
1403 return array( $def => 1.0 );
1408 $parts = explode( ',', $accept );
1410 foreach( $parts as $part ) {
1411 # FIXME: doesn't deal with params like 'text/html; level=1'
1412 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1414 if( !isset( $qpart ) ) {
1415 $prefs[$value] = 1.0;
1416 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1417 $prefs[$value] = floatval($match[1]);
1425 * Checks if a given MIME type matches any of the keys in the given
1426 * array. Basic wildcards are accepted in the array keys.
1428 * Returns the matching MIME type (or wildcard) if a match, otherwise
1431 * @param string $type
1432 * @param array $avail
1436 function mimeTypeMatch( $type, $avail ) {
1437 if( array_key_exists($type, $avail) ) {
1440 $parts = explode( '/', $type );
1441 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1442 return $parts[0] . '/*';
1443 } elseif( array_key_exists( '*/*', $avail ) ) {
1452 * Returns the 'best' match between a client's requested internet media types
1453 * and the server's list of available types. Each list should be an associative
1454 * array of type to preference (preference is a float between 0.0 and 1.0).
1455 * Wildcards in the types are acceptable.
1457 * @param array $cprefs Client's acceptable type list
1458 * @param array $sprefs Server's offered types
1461 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1462 * XXX: generalize to negotiate other stuff
1464 function wfNegotiateType( $cprefs, $sprefs ) {
1467 foreach( array_keys($sprefs) as $type ) {
1468 $parts = explode( '/', $type );
1469 if( $parts[1] != '*' ) {
1470 $ckey = mimeTypeMatch( $type, $cprefs );
1472 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1477 foreach( array_keys( $cprefs ) as $type ) {
1478 $parts = explode( '/', $type );
1479 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1480 $skey = mimeTypeMatch( $type, $sprefs );
1482 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1490 foreach( array_keys( $combine ) as $type ) {
1491 if( $combine[$type] > $bestq ) {
1493 $bestq = $combine[$type];
1502 * Returns an array where the values in the first array are replaced by the
1503 * values in the second array with the corresponding keys
1507 function wfArrayLookup( $a, $b ) {
1508 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1512 * Convenience function; returns MediaWiki timestamp for the present time.
1515 function wfTimestampNow() {
1517 return wfTimestamp( TS_MW
, time() );
1521 * Reference-counted warning suppression
1523 function wfSuppressWarnings( $end = false ) {
1524 static $suppressCount = 0;
1525 static $originalLevel = false;
1528 if ( $suppressCount ) {
1530 if ( !$suppressCount ) {
1531 error_reporting( $originalLevel );
1535 if ( !$suppressCount ) {
1536 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1543 * Restore error level to previous value
1545 function wfRestoreWarnings() {
1546 wfSuppressWarnings( true );
1549 # Autodetect, convert and provide timestamps of various types
1552 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1554 define('TS_UNIX', 0);
1557 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1562 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1567 * RFC 2822 format, for E-mail and HTTP headers
1569 define('TS_RFC2822', 3);
1572 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1574 * This is used by Special:Export
1576 define('TS_ISO_8601', 4);
1579 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1581 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1582 * DateTime tag and page 36 for the DateTimeOriginal and
1583 * DateTimeDigitized tags.
1585 define('TS_EXIF', 5);
1588 * Oracle format time.
1590 define('TS_ORACLE', 6);
1593 * Postgres format time.
1595 define('TS_POSTGRES', 7);
1598 * @param mixed $outputtype A timestamp in one of the supported formats, the
1599 * function will autodetect which format is supplied
1600 * and act accordingly.
1601 * @return string Time in the format specified in $outputtype
1603 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1608 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1610 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1612 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1614 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1617 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1619 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1620 str_replace("+00:00", "UTC", $ts)));
1621 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1623 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1625 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1628 # Bogus value; fall back to the epoch...
1629 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1633 if (count( $da ) ) {
1634 // Warning! gmmktime() acts oddly if the month or day is set to 0
1635 // We may want to handle that explicitly at some point
1636 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1637 (int)$da[2],(int)$da[3],(int)$da[1]);
1640 switch($outputtype) {
1644 return gmdate( 'YmdHis', $uts );
1646 return gmdate( 'Y-m-d H:i:s', $uts );
1648 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1649 // This shouldn't ever be used, but is included for completeness
1651 return gmdate( 'Y:m:d H:i:s', $uts );
1653 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1655 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1657 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1659 throw new MWException( 'wfTimestamp() called with illegal output type.');
1664 * Return a formatted timestamp, or null if input is null.
1665 * For dealing with nullable timestamp columns in the database.
1666 * @param int $outputtype
1670 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1671 if( is_null( $ts ) ) {
1674 return wfTimestamp( $outputtype, $ts );
1679 * Check if the operating system is Windows
1681 * @return bool True if it's Windows, False otherwise.
1683 function wfIsWindows() {
1684 if (substr(php_uname(), 0, 7) == 'Windows') {
1692 * Swap two variables
1694 function swap( &$x, &$y ) {
1700 function wfGetCachedNotice( $name ) {
1701 global $wgOut, $parserMemc;
1702 $fname = 'wfGetCachedNotice';
1703 wfProfileIn( $fname );
1707 if( $name === 'default' ) {
1709 global $wgSiteNotice;
1710 $notice = $wgSiteNotice;
1711 if( empty( $notice ) ) {
1712 wfProfileOut( $fname );
1716 $notice = wfMsgForContentNoTrans( $name );
1717 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1718 wfProfileOut( $fname );
1723 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1724 if( is_array( $cachedNotice ) ) {
1725 if( md5( $notice ) == $cachedNotice['hash'] ) {
1726 $notice = $cachedNotice['html'];
1735 if( is_object( $wgOut ) ) {
1736 $parsed = $wgOut->parse( $notice );
1737 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1740 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1745 wfProfileOut( $fname );
1749 function wfGetNamespaceNotice() {
1753 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1756 $fname = 'wfGetNamespaceNotice';
1757 wfProfileIn( $fname );
1759 $key = "namespacenotice-" . $wgTitle->getNsText();
1760 $namespaceNotice = wfGetCachedNotice( $key );
1761 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1762 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1764 $namespaceNotice = "";
1767 wfProfileOut( $fname );
1768 return $namespaceNotice;
1771 function wfGetSiteNotice() {
1772 global $wgUser, $wgSiteNotice;
1773 $fname = 'wfGetSiteNotice';
1774 wfProfileIn( $fname );
1777 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1778 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1779 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1781 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1782 if( !$anonNotice ) {
1783 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1785 $siteNotice = $anonNotice;
1788 if( !$siteNotice ) {
1789 $siteNotice = wfGetCachedNotice( 'default' );
1793 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1794 wfProfileOut( $fname );
1799 * BC wrapper for MimeMagic::singleton()
1802 function &wfGetMimeMagic() {
1803 return MimeMagic
::singleton();
1807 * Tries to get the system directory for temporary files.
1808 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1809 * and if none are set /tmp is returned as the generic Unix default.
1811 * NOTE: When possible, use the tempfile() function to create temporary
1812 * files to avoid race conditions on file creation, etc.
1816 function wfTempDir() {
1817 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1818 $tmp = getenv( $var );
1819 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1823 # Hope this is Unix of some kind!
1828 * Make directory, and make all parent directories if they don't exist
1830 * @param string $fullDir Full path to directory to create
1831 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1834 function wfMkdirParents( $fullDir, $mode = null ) {
1835 global $wgDirectoryMode;
1836 if( strval( $fullDir ) === '' )
1838 if( file_exists( $fullDir ) )
1840 // If not defined or isn't an int, set to default
1841 if ( is_null( $mode ) ) {
1842 $mode = $wgDirectoryMode;
1846 # Go back through the paths to find the first directory that exists
1847 $currentDir = $fullDir;
1848 $createList = array();
1849 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1850 # Strip trailing slashes
1851 $currentDir = rtrim( $currentDir, '/\\' );
1853 # Add to create list
1854 $createList[] = $currentDir;
1856 # Find next delimiter searching from the end
1857 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1858 if ( $p === false ) {
1859 $currentDir = false;
1861 $currentDir = substr( $currentDir, 0, $p );
1865 if ( count( $createList ) == 0 ) {
1866 # Directory specified already exists
1868 } elseif ( $currentDir === false ) {
1869 # Went all the way back to root and it apparently doesn't exist
1870 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1873 # Now go forward creating directories
1874 $createList = array_reverse( $createList );
1876 # Is the parent directory writable?
1877 if ( $currentDir === '' ) {
1880 if ( !is_writable( $currentDir ) ) {
1881 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1885 foreach ( $createList as $dir ) {
1886 # use chmod to override the umask, as suggested by the PHP manual
1887 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1888 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1896 * Increment a statistics counter
1898 function wfIncrStats( $key ) {
1899 global $wgStatsMethod;
1901 if( $wgStatsMethod == 'udp' ) {
1902 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1905 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1906 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1907 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1909 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1910 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1911 } elseif( $wgStatsMethod == 'cache' ) {
1913 $key = wfMemcKey( 'stats', $key );
1914 if ( is_null( $wgMemc->incr( $key ) ) ) {
1915 $wgMemc->add( $key, 1 );
1923 * @param mixed $nr The number to format
1924 * @param int $acc The number of digits after the decimal point, default 2
1925 * @param bool $round Whether or not to round the value, default true
1928 function wfPercent( $nr, $acc = 2, $round = true ) {
1929 $ret = sprintf( "%.${acc}f", $nr );
1930 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1934 * Encrypt a username/password.
1936 * @param string $userid ID of the user
1937 * @param string $password Password of the user
1938 * @return string Hashed password
1939 * @deprecated Use User::crypt() or User::oldCrypt() instead
1941 function wfEncryptPassword( $userid, $password ) {
1942 wfDeprecated(__FUNCTION__
);
1943 # Just wrap around User::oldCrypt()
1944 return User
::oldCrypt($password, $userid);
1948 * Appends to second array if $value differs from that in $default
1950 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1951 if ( is_null( $changed ) ) {
1952 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1954 if ( $default[$key] !== $value ) {
1955 $changed[$key] = $value;
1960 * Since wfMsg() and co suck, they don't return false if the message key they
1961 * looked up didn't exist but a XHTML string, this function checks for the
1962 * nonexistance of messages by looking at wfMsg() output
1964 * @param $msg The message key looked up
1965 * @param $wfMsgOut The output of wfMsg*()
1968 function wfEmptyMsg( $msg, $wfMsgOut ) {
1969 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1973 * Find out whether or not a mixed variable exists in a string
1975 * @param mixed needle
1976 * @param string haystack
1979 function in_string( $needle, $str ) {
1980 return strpos( $str, $needle ) !== false;
1983 function wfSpecialList( $page, $details ) {
1985 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1986 return $page . $details;
1990 * Returns a regular expression of url protocols
1994 function wfUrlProtocols() {
1995 global $wgUrlProtocols;
1997 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1998 // with LocalSettings files from 1.5
1999 if ( is_array( $wgUrlProtocols ) ) {
2000 $protocols = array();
2001 foreach ($wgUrlProtocols as $protocol)
2002 $protocols[] = preg_quote( $protocol, '/' );
2004 return implode( '|', $protocols );
2006 return $wgUrlProtocols;
2011 * Safety wrapper around ini_get() for boolean settings.
2012 * The values returned from ini_get() are pre-normalized for settings
2013 * set via php.ini or php_flag/php_admin_flag... but *not*
2014 * for those set via php_value/php_admin_value.
2016 * It's fairly common for people to use php_value instead of php_flag,
2017 * which can leave you with an 'off' setting giving a false positive
2018 * for code that just takes the ini_get() return value as a boolean.
2020 * To make things extra interesting, setting via php_value accepts
2021 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2022 * Unrecognized values go false... again opposite PHP's own coercion
2023 * from string to bool.
2025 * Luckily, 'properly' set settings will always come back as '0' or '1',
2026 * so we only have to worry about them and the 'improper' settings.
2028 * I frickin' hate PHP... :P
2030 * @param string $setting
2033 function wfIniGetBool( $setting ) {
2034 $val = ini_get( $setting );
2035 // 'on' and 'true' can't have whitespace around them, but '1' can.
2036 return strtolower( $val ) == 'on'
2037 ||
strtolower( $val ) == 'true'
2038 ||
strtolower( $val ) == 'yes'
2039 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2043 * Execute a shell command, with time and memory limits mirrored from the PHP
2044 * configuration if supported.
2045 * @param $cmd Command line, properly escaped for shell.
2046 * @param &$retval optional, will receive the program's exit code.
2047 * (non-zero is usually failure)
2048 * @return collected stdout as a string (trailing newlines stripped)
2050 function wfShellExec( $cmd, &$retval=null ) {
2051 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
2053 if( wfIniGetBool( 'safe_mode' ) ) {
2054 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2056 return "Unable to run external programs in safe mode.";
2059 if ( php_uname( 's' ) == 'Linux' ) {
2060 $time = intval( ini_get( 'max_execution_time' ) );
2061 $mem = intval( $wgMaxShellMemory );
2062 $filesize = intval( $wgMaxShellFileSize );
2064 if ( $time > 0 && $mem > 0 ) {
2065 $script = "$IP/bin/ulimit4.sh";
2066 if ( is_executable( $script ) ) {
2067 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2070 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2071 # This is a hack to work around PHP's flawed invocation of cmd.exe
2072 # http://news.php.net/php.internals/21796
2073 $cmd = '"' . $cmd . '"';
2075 wfDebug( "wfShellExec: $cmd\n" );
2077 $retval = 1; // error by default?
2079 passthru( $cmd, $retval );
2080 $output = ob_get_contents();
2087 * This function works like "use VERSION" in Perl, the program will die with a
2088 * backtrace if the current version of PHP is less than the version provided
2090 * This is useful for extensions which due to their nature are not kept in sync
2091 * with releases, and might depend on other versions of PHP than the main code
2093 * Note: PHP might die due to parsing errors in some cases before it ever
2094 * manages to call this function, such is life
2096 * @see perldoc -f use
2098 * @param mixed $version The version to check, can be a string, an integer, or
2101 function wfUsePHP( $req_ver ) {
2102 $php_ver = PHP_VERSION
;
2104 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2105 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2109 * This function works like "use VERSION" in Perl except it checks the version
2110 * of MediaWiki, the program will die with a backtrace if the current version
2111 * of MediaWiki is less than the version provided.
2113 * This is useful for extensions which due to their nature are not kept in sync
2116 * @see perldoc -f use
2118 * @param mixed $version The version to check, can be a string, an integer, or
2121 function wfUseMW( $req_ver ) {
2124 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2125 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2129 * @deprecated use StringUtils::escapeRegexReplacement
2131 function wfRegexReplacement( $string ) {
2132 return StringUtils
::escapeRegexReplacement( $string );
2136 * Return the final portion of a pathname.
2137 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2138 * http://bugs.php.net/bug.php?id=33898
2140 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2141 * We'll consider it so always, as we don't want \s in our Unix paths either.
2143 * @param string $path
2144 * @param string $suffix to remove if present
2147 function wfBaseName( $path, $suffix='' ) {
2148 $encSuffix = ($suffix == '')
2150 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2152 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2160 * Generate a relative path name to the given file.
2161 * May explode on non-matching case-insensitive paths,
2162 * funky symlinks, etc.
2164 * @param string $path Absolute destination path including target filename
2165 * @param string $from Absolute source path, directory only
2168 function wfRelativePath( $path, $from ) {
2169 // Normalize mixed input on Windows...
2170 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2171 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2173 // Trim trailing slashes -- fix for drive root
2174 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2175 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2177 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2178 $against = explode( DIRECTORY_SEPARATOR
, $from );
2180 if( $pieces[0] !== $against[0] ) {
2181 // Non-matching Windows drive letters?
2182 // Return a full path.
2186 // Trim off common prefix
2187 while( count( $pieces ) && count( $against )
2188 && $pieces[0] == $against[0] ) {
2189 array_shift( $pieces );
2190 array_shift( $against );
2193 // relative dots to bump us to the parent
2194 while( count( $against ) ) {
2195 array_unshift( $pieces, '..' );
2196 array_shift( $against );
2199 array_push( $pieces, wfBaseName( $path ) );
2201 return implode( DIRECTORY_SEPARATOR
, $pieces );
2205 * array_merge() does awful things with "numeric" indexes, including
2206 * string indexes when happen to look like integers. When we want
2207 * to merge arrays with arbitrary string indexes, we don't want our
2208 * arrays to be randomly corrupted just because some of them consist
2211 * Fuck you, PHP. Fuck you in the ear!
2213 * @param array $array1, [$array2, [...]]
2216 function wfArrayMerge( $array1/* ... */ ) {
2218 for( $i = 1; $i < func_num_args(); $i++
) {
2219 foreach( func_get_arg( $i ) as $key => $value ) {
2220 $out[$key] = $value;
2227 * Make a URL index, appropriate for the el_index field of externallinks.
2229 function wfMakeUrlIndex( $url ) {
2230 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2231 wfSuppressWarnings();
2232 $bits = parse_url( $url );
2233 wfRestoreWarnings();
2237 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2239 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2241 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2243 // parse_url detects for news: and mailto: the host part of an url as path
2244 // We have to correct this wrong detection
2245 if ( isset ( $bits['path'] ) ) {
2246 $bits['host'] = $bits['path'];
2253 // Reverse the labels in the hostname, convert to lower case
2254 // For emails reverse domainpart only
2255 if ( $bits['scheme'] == 'mailto' ) {
2256 $mailparts = explode( '@', $bits['host'], 2 );
2257 if ( count($mailparts) === 2 ) {
2258 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2260 // No domain specified, don't mangle it
2263 $reversedHost = $domainpart . '@' . $mailparts[0];
2265 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2267 // Add an extra dot to the end
2268 // Why? Is it in wrong place in mailto links?
2269 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2270 $reversedHost .= '.';
2272 // Reconstruct the pseudo-URL
2273 $prot = $bits['scheme'];
2274 $index = "$prot$delimiter$reversedHost";
2275 // Leave out user and password. Add the port, path, query and fragment
2276 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2277 if ( isset( $bits['path'] ) ) {
2278 $index .= $bits['path'];
2282 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2283 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2288 * Do any deferred updates and clear the list
2289 * TODO: This could be in Wiki.php if that class made any sense at all
2291 function wfDoUpdates()
2293 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2294 foreach ( $wgDeferredUpdateList as $update ) {
2295 $update->doUpdate();
2297 foreach ( $wgPostCommitUpdateList as $update ) {
2298 $update->doUpdate();
2300 $wgDeferredUpdateList = array();
2301 $wgPostCommitUpdateList = array();
2305 * @deprecated use StringUtils::explodeMarkup
2307 function wfExplodeMarkup( $separator, $text ) {
2308 return StringUtils
::explodeMarkup( $separator, $text );
2312 * Convert an arbitrarily-long digit string from one numeric base
2313 * to another, optionally zero-padding to a minimum column width.
2315 * Supports base 2 through 36; digit values 10-36 are represented
2316 * as lowercase letters a-z. Input is case-insensitive.
2318 * @param $input string of digits
2319 * @param $sourceBase int 2-36
2320 * @param $destBase int 2-36
2321 * @param $pad int 1 or greater
2322 * @param $lowercase bool
2323 * @return string or false on invalid input
2325 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2326 $input = strval( $input );
2327 if( $sourceBase < 2 ||
2332 $sourceBase != intval( $sourceBase ) ||
2333 $destBase != intval( $destBase ) ||
2334 $pad != intval( $pad ) ||
2335 !is_string( $input ) ||
2339 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2340 $inDigits = array();
2343 // Decode and validate input string
2344 $input = strtolower( $input );
2345 for( $i = 0; $i < strlen( $input ); $i++
) {
2346 $n = strpos( $digitChars, $input{$i} );
2347 if( $n === false ||
$n > $sourceBase ) {
2353 // Iterate over the input, modulo-ing out an output digit
2354 // at a time until input is gone.
2355 while( count( $inDigits ) ) {
2357 $workDigits = array();
2360 foreach( $inDigits as $digit ) {
2361 $work *= $sourceBase;
2364 if( $work < $destBase ) {
2365 // Gonna need to pull another digit.
2366 if( count( $workDigits ) ) {
2367 // Avoid zero-padding; this lets us find
2368 // the end of the input very easily when
2369 // length drops to zero.
2373 // Finally! Actual division!
2374 $workDigits[] = intval( $work / $destBase );
2376 // Isn't it annoying that most programming languages
2377 // don't have a single divide-and-remainder operator,
2378 // even though the CPU implements it that way?
2379 $work = $work %
$destBase;
2383 // All that division leaves us with a remainder,
2384 // which is conveniently our next output digit.
2385 $outChars .= $digitChars[$work];
2388 $inDigits = $workDigits;
2391 while( strlen( $outChars ) < $pad ) {
2395 return strrev( $outChars );
2399 * Create an object with a given name and an array of construct parameters
2400 * @param string $name
2401 * @param array $p parameters
2403 function wfCreateObject( $name, $p ){
2404 $p = array_values( $p );
2405 switch ( count( $p ) ) {
2409 return new $name( $p[0] );
2411 return new $name( $p[0], $p[1] );
2413 return new $name( $p[0], $p[1], $p[2] );
2415 return new $name( $p[0], $p[1], $p[2], $p[3] );
2417 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2419 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2421 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2426 * Alias for modularized function
2427 * @deprecated Use Http::get() instead
2429 function wfGetHTTP( $url, $timeout = 'default' ) {
2430 wfDeprecated(__FUNCTION__
);
2431 return Http
::get( $url, $timeout );
2435 * Alias for modularized function
2436 * @deprecated Use Http::isLocalURL() instead
2438 function wfIsLocalURL( $url ) {
2439 wfDeprecated(__FUNCTION__
);
2440 return Http
::isLocalURL( $url );
2443 function wfHttpOnlySafe() {
2444 global $wgHttpOnlyBlacklist;
2445 if( !version_compare("5.2", PHP_VERSION
, "<") )
2448 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2449 foreach( $wgHttpOnlyBlacklist as $regex ) {
2450 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2460 * Initialise php session
2462 function wfSetupSession() {
2463 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2464 if( $wgSessionsInMemcached ) {
2465 require_once( 'MemcachedSessions.php' );
2466 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2467 # If it's left on 'user' or another setting from another
2468 # application, it will end up failing. Try to recover.
2469 ini_set ( 'session.save_handler', 'files' );
2471 $httpOnlySafe = wfHttpOnlySafe();
2472 wfDebugLog( 'cookie',
2473 'session_set_cookie_params: "' . implode( '", "',
2479 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2480 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2481 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2483 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2484 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2486 session_cache_limiter( 'private, must-revalidate' );
2487 wfSuppressWarnings();
2489 wfRestoreWarnings();
2493 * Get an object from the precompiled serialized directory
2495 * @return mixed The variable on success, false on failure
2497 function wfGetPrecompiledData( $name ) {
2500 $file = "$IP/serialized/$name";
2501 if ( file_exists( $file ) ) {
2502 $blob = file_get_contents( $file );
2504 return unserialize( $blob );
2510 function wfGetCaller( $level = 2 ) {
2511 $backtrace = wfDebugBacktrace();
2512 if ( isset( $backtrace[$level] ) ) {
2513 return wfFormatStackFrame($backtrace[$level]);
2515 $caller = 'unknown';
2520 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2521 function wfGetAllCallers() {
2522 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2525 /** Return a string representation of frame */
2526 function wfFormatStackFrame($frame) {
2527 return isset( $frame["class"] )?
2528 $frame["class"]."::".$frame["function"]:
2535 function wfMemcKey( /*... */ ) {
2536 $args = func_get_args();
2537 $key = wfWikiID() . ':' . implode( ':', $args );
2542 * Get a cache key for a foreign DB
2544 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2545 $args = array_slice( func_get_args(), 2 );
2547 $key = "$db-$prefix:" . implode( ':', $args );
2549 $key = $db . ':' . implode( ':', $args );
2555 * Get an ASCII string identifying this wiki
2556 * This is used as a prefix in memcached keys
2558 function wfWikiID( $db = null ) {
2559 if( $db instanceof Database
) {
2560 return $db->getWikiID();
2562 global $wgDBprefix, $wgDBname;
2563 if ( $wgDBprefix ) {
2564 return "$wgDBname-$wgDBprefix";
2572 * Split a wiki ID into DB name and table prefix
2574 function wfSplitWikiID( $wiki ) {
2575 $bits = explode( '-', $wiki, 2 );
2576 if ( count( $bits ) < 2 ) {
2583 * Get a Database object.
2584 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2585 * master (for write queries), DB_SLAVE for potentially lagged
2586 * read queries, or an integer >= 0 for a particular server.
2588 * @param mixed $groups Query groups. An array of group names that this query
2589 * belongs to. May contain a single string if the query is only
2592 * @param string $wiki The wiki ID, or false for the current wiki
2594 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2595 * will always return the same object, unless the underlying connection or load
2596 * balancer is manually destroyed.
2598 function &wfGetDB( $db = DB_LAST
, $groups = array(), $wiki = false ) {
2599 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2603 * Get a load balancer object.
2605 * @param array $groups List of query groups
2606 * @param string $wiki Wiki ID, or false for the current wiki
2607 * @return LoadBalancer
2609 function wfGetLB( $wiki = false ) {
2610 return wfGetLBFactory()->getMainLB( $wiki );
2614 * Get the load balancer factory object
2616 function &wfGetLBFactory() {
2617 return LBFactory
::singleton();
2622 * Shortcut for RepoGroup::singleton()->findFile()
2623 * @param mixed $title Title object or string. May be interwiki.
2624 * @param mixed $time Requested time for an archived image, or false for the
2625 * current version. An image object will be returned which
2626 * was created at the specified time.
2627 * @param mixed $flags FileRepo::FIND_ flags
2628 * @return File, or false if the file does not exist
2630 function wfFindFile( $title, $time = false, $flags = 0 ) {
2631 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2635 * Get an object referring to a locally registered file.
2636 * Returns a valid placeholder object if the file does not exist.
2638 function wfLocalFile( $title ) {
2639 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2643 * Should low-performance queries be disabled?
2647 function wfQueriesMustScale() {
2648 global $wgMiserMode;
2650 ||
( SiteStats
::pages() > 100000
2651 && SiteStats
::edits() > 1000000
2652 && SiteStats
::users() > 10000 );
2656 * Get the path to a specified script file, respecting file
2657 * extensions; this is a wrapper around $wgScriptExtension etc.
2659 * @param string $script Script filename, sans extension
2662 function wfScript( $script = 'index' ) {
2663 global $wgScriptPath, $wgScriptExtension;
2664 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2668 * Convenience function converts boolean values into "true"
2669 * or "false" (string) values
2671 * @param bool $value
2674 function wfBoolToStr( $value ) {
2675 return $value ?
'true' : 'false';
2679 * Load an extension messages file
2681 * @param string $extensionName Name of extension to load messages from\for.
2682 * @param string $langcode Language to load messages for, or false for default
2683 * behvaiour (en, content language and user language).
2684 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2685 * on MediaWiki prior to that
2687 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2688 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2690 #For recording whether extension message files have been loaded in a given language.
2691 static $loaded = array();
2693 if( !array_key_exists( $extensionName, $loaded ) ) {
2694 $loaded[$extensionName] = array();
2697 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2698 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2701 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2702 # Just do en, content language and user language.
2703 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2704 # Mark that they have been loaded.
2705 $loaded[$extensionName]['en'] = true;
2706 $loaded[$extensionName][$wgLang->getCode()] = true;
2707 $loaded[$extensionName][$wgContLang->getCode()] = true;
2708 # Mark that this part has been done to avoid weird if statements.
2709 $loaded[$extensionName]['*'] = true;
2710 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2711 # Load messages for specified language.
2712 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2713 # Mark that they have been loaded.
2714 $loaded[$extensionName][$langcode] = true;
2719 * Get a platform-independent path to the null file, e.g.
2724 function wfGetNull() {
2725 return wfIsWindows()
2731 * Displays a maxlag error
2733 * @param string $host Server that lags the most
2734 * @param int $lag Maxlag (actual)
2735 * @param int $maxLag Maxlag (requested)
2737 function wfMaxlagError( $host, $lag, $maxLag ) {
2738 global $wgShowHostnames;
2739 header( 'HTTP/1.1 503 Service Unavailable' );
2740 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2741 header( 'X-Database-Lag: ' . intval( $lag ) );
2742 header( 'Content-Type: text/plain' );
2743 if( $wgShowHostnames ) {
2744 echo "Waiting for $host: $lag seconds lagged\n";
2746 echo "Waiting for a database server: $lag seconds lagged\n";
2751 * Throws an E_USER_NOTICE saying that $function is deprecated
2752 * @param string $function
2755 function wfDeprecated( $function ) {
2756 global $wgDebugLogFile;
2757 if ( !$wgDebugLogFile ) {
2760 $callers = wfDebugBacktrace();
2761 if( isset( $callers[2] ) ){
2762 $callerfunc = $callers[2];
2763 $callerfile = $callers[1];
2764 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2765 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2767 $file = '(internal function)';
2770 if( isset( $callerfunc['class'] ) )
2771 $func .= $callerfunc['class'] . '::';
2772 $func .= @$callerfunc['function'];
2773 $msg = "Use of $function is deprecated. Called from $func in $file";
2775 $msg = "Use of $function is deprecated.";
2777 wfDebug( "$msg\n" );
2781 * Sleep until the worst slave's replication lag is less than or equal to
2782 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2783 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2784 * a no-op if there are no slaves.
2786 * Every time the function has to wait for a slave, it will print a message to
2787 * that effect (and then sleep for a little while), so it's probably not best
2788 * to use this outside maintenance scripts in its present form.
2790 * @param int $maxLag
2793 function wfWaitForSlaves( $maxLag ) {
2796 list( $host, $lag ) = $lb->getMaxLag();
2797 while( $lag > $maxLag ) {
2798 $name = @gethostbyaddr
( $host );
2799 if( $name !== false ) {
2802 print "Waiting for $host (lagged $lag seconds)...\n";
2804 list( $host, $lag ) = $lb->getMaxLag();
2809 /** Generate a random 32-character hexadecimal token.
2810 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2812 function wfGenerateToken( $salt = '' ) {
2813 $salt = serialize($salt);
2815 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2819 * Replace all invalid characters with -
2820 * @param mixed $title Filename to process
2822 function wfStripIllegalFilenameChars( $name ) {
2823 $name = wfBaseName( $name );
2824 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );