80e5843776cbffd1d76057eff428695e6c53fe8d
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 giving PHP memory usage.
236 * @param $exact Bool : print exact values instead of kilobytes (default: false)
238 function wfDebugMem( $exact = false ) {
239 $mem = memory_get_usage();
241 $mem = floor( $mem / 1024 ) . ' kilobytes';
245 wfDebug( "Memory usage: $mem\n" );
249 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
250 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
252 * @param $logGroup String
253 * @param $text String
254 * @param $public Bool: whether to log the event in the public log if no private
255 * log file is specified, (default true)
257 function wfDebugLog( $logGroup, $text, $public = true ) {
258 global $wgDebugLogGroups, $wgShowHostnames;
259 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
260 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
261 $time = wfTimestamp( TS_DB
);
263 if ( $wgShowHostnames ) {
264 $host = wfHostname();
268 wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
269 } else if ( $public === true ) {
270 wfDebug( $text, true );
275 * Log for database errors
276 * @param $text String: database error message.
278 function wfLogDBError( $text ) {
279 global $wgDBerrorLog, $wgDBname;
280 if ( $wgDBerrorLog ) {
281 $host = trim(`hostname`
);
282 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
283 wfErrorLog( $text, $wgDBerrorLog );
288 * Log to a file without getting "file size exceeded" signals.
290 * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
291 * send lines to the specified port, prefixed by the specified prefix and a space.
293 function wfErrorLog( $text, $file ) {
294 if ( substr( $file, 0, 4 ) == 'udp:' ) {
295 if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
296 // IPv6 bracketed host
300 $prefix = isset( $m[4] ) ?
$m[4] : '';
301 } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
305 $prefix = isset( $m[4] ) ?
$m[4] : '';
307 throw new MWException( __METHOD__
.": Invalid UDP specification" );
309 $prefix = strval( $prefix );
310 if ( $prefix != '' ) {
313 $sock = fsockopen( "$protocol://$host", $port );
317 fwrite( $sock, $prefix . $text );
320 wfSuppressWarnings();
321 $exists = file_exists( $file );
322 $size = $exists ?
filesize( $file ) : false;
323 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
324 error_log( $text, 3, $file );
333 function wfLogProfilingData() {
334 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
335 global $wgProfiler, $wgUser;
336 if ( !isset( $wgProfiler ) )
340 $elapsed = $now - $wgRequestTime;
341 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
343 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
344 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
345 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
346 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
347 if( !empty( $_SERVER['HTTP_FROM'] ) )
348 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
350 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
351 // Don't unstub $wgUser at this late stage just for statistics purposes
352 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
354 $log = sprintf( "%s\t%04.3f\t%s\n",
355 gmdate( 'YmdHis' ), $elapsed,
356 urldecode( $wgRequest->getRequestURL() . $forward ) );
357 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
358 wfErrorLog( $log . $prof, $wgDebugLogFile );
363 * Check if the wiki read-only lock file is present. This can be used to lock
364 * off editing functions, but doesn't guarantee that the database will not be
368 function wfReadOnly() {
369 global $wgReadOnlyFile, $wgReadOnly;
371 if ( !is_null( $wgReadOnly ) ) {
372 return (bool)$wgReadOnly;
374 if ( '' == $wgReadOnlyFile ) {
377 // Set $wgReadOnly for faster access next time
378 if ( is_file( $wgReadOnlyFile ) ) {
379 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
383 return (bool)$wgReadOnly;
386 function wfReadOnlyReason() {
393 * Return a Language object from $langcode
394 * @param $langcode Mixed: either:
395 * - a Language object
396 * - code of the language to get the message for, if it is
397 * a valid code create a language for that language, if
398 * it is a string but not a valid code then make a basic
400 * - a boolean: if it's false then use the current users
401 * language (as a fallback for the old parameter
402 * functionality), or if it is true then use the wikis
403 * @return Language object
405 function wfGetLangObj( $langcode = false ){
406 # Identify which language to get or create a language object for.
407 if( $langcode instanceof Language
)
408 # Great, we already have the object!
412 if( $langcode === $wgContLang->getCode() ||
$langcode === true )
413 # $langcode is the language code of the wikis content language object.
414 # or it is a boolean and value is true
418 if( $langcode === $wgLang->getCode() ||
$langcode === false )
419 # $langcode is the language code of user language object.
420 # or it was a boolean and value is false
423 $validCodes = array_keys( Language
::getLanguageNames() );
424 if( in_array( $langcode, $validCodes ) )
425 # $langcode corresponds to a valid language.
426 return Language
::factory( $langcode );
428 # $langcode is a string, but not a valid language code; use content language.
429 wfDebug( 'Invalid language code passed to wfGetLangObj, falling back to content language.' );
434 * Get a message from anywhere, for the current user language.
436 * Use wfMsgForContent() instead if the message should NOT
437 * change depending on the user preferences.
439 * @param $key String: lookup key for the message, usually
440 * defined in languages/Language.php
442 * This function also takes extra optional parameters (not
443 * shown in the function definition), which can by used to
444 * insert variable text into the predefined message.
446 function wfMsg( $key ) {
447 $args = func_get_args();
448 array_shift( $args );
449 return wfMsgReal( $key, $args, true );
453 * Same as above except doesn't transform the message
455 function wfMsgNoTrans( $key ) {
456 $args = func_get_args();
457 array_shift( $args );
458 return wfMsgReal( $key, $args, true, false, false );
462 * Get a message from anywhere, for the current global language
463 * set with $wgLanguageCode.
465 * Use this if the message should NOT change dependent on the
466 * language set in the user's preferences. This is the case for
467 * most text written into logs, as well as link targets (such as
468 * the name of the copyright policy page). Link titles, on the
469 * other hand, should be shown in the UI language.
471 * Note that MediaWiki allows users to change the user interface
472 * language in their preferences, but a single installation
473 * typically only contains content in one language.
475 * Be wary of this distinction: If you use wfMsg() where you should
476 * use wfMsgForContent(), a user of the software may have to
477 * customize over 70 messages in order to, e.g., fix a link in every
480 * @param $key String: lookup key for the message, usually
481 * defined in languages/Language.php
483 function wfMsgForContent( $key ) {
484 global $wgForceUIMsgAsContentMsg;
485 $args = func_get_args();
486 array_shift( $args );
488 if( is_array( $wgForceUIMsgAsContentMsg ) &&
489 in_array( $key, $wgForceUIMsgAsContentMsg ) )
491 return wfMsgReal( $key, $args, true, $forcontent );
495 * Same as above except doesn't transform the message
497 function wfMsgForContentNoTrans( $key ) {
498 global $wgForceUIMsgAsContentMsg;
499 $args = func_get_args();
500 array_shift( $args );
502 if( is_array( $wgForceUIMsgAsContentMsg ) &&
503 in_array( $key, $wgForceUIMsgAsContentMsg ) )
505 return wfMsgReal( $key, $args, true, $forcontent, false );
509 * Get a message from the language file, for the UI elements
511 function wfMsgNoDB( $key ) {
512 $args = func_get_args();
513 array_shift( $args );
514 return wfMsgReal( $key, $args, false );
518 * Get a message from the language file, for the content
520 function wfMsgNoDBForContent( $key ) {
521 global $wgForceUIMsgAsContentMsg;
522 $args = func_get_args();
523 array_shift( $args );
525 if( is_array( $wgForceUIMsgAsContentMsg ) &&
526 in_array( $key, $wgForceUIMsgAsContentMsg ) )
528 return wfMsgReal( $key, $args, false, $forcontent );
533 * Really get a message
534 * @param $key String: key to get.
536 * @param $useDB Boolean
537 * @param $transform Boolean: Whether or not to transform the message.
538 * @param $forContent Boolean
539 * @return String: the requested message.
541 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
542 wfProfileIn( __METHOD__
);
543 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
544 $message = wfMsgReplaceArgs( $message, $args );
545 wfProfileOut( __METHOD__
);
550 * This function provides the message source for messages to be edited which are *not* stored in the database.
551 * @param $key String:
553 function wfMsgWeirdKey ( $key ) {
554 $source = wfMsgGetKey( $key, false, true, false );
555 if ( wfEmptyMsg( $key, $source ) )
562 * Fetch a message string value, but don't replace any keys yet.
565 * @param string $langcode Code of the language to get the message for, or
566 * behaves as a content language switch if it is a
571 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
572 global $wgContLang, $wgMessageCache;
574 wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
576 # If $wgMessageCache isn't initialised yet, try to return something sensible.
577 if( is_object( $wgMessageCache ) ) {
578 $message = $wgMessageCache->get( $key, $useDB, $langCode );
580 $message = $wgMessageCache->transform( $message );
583 $lang = wfGetLangObj( $langCode );
585 # MessageCache::get() does this already, Language::getMessage() doesn't
586 # ISSUE: Should we try to handle "message/lang" here too?
587 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
589 if( is_object( $lang ) ) {
590 $message = $lang->getMessage( $key );
600 * Replace message parameter keys on the given formatted output.
602 * @param string $message
607 function wfMsgReplaceArgs( $message, $args ) {
608 # Fix windows line-endings
609 # Some messages are split with explode("\n", $msg)
610 $message = str_replace( "\r", '', $message );
613 if ( count( $args ) ) {
614 if ( is_array( $args[0] ) ) {
615 $args = array_values( $args[0] );
617 $replacementKeys = array();
618 foreach( $args as $n => $param ) {
619 $replacementKeys['$' . ($n +
1)] = $param;
621 $message = strtr( $message, $replacementKeys );
628 * Return an HTML-escaped version of a message.
629 * Parameter replacements, if any, are done *after* the HTML-escaping,
630 * so parameters may contain HTML (eg links or form controls). Be sure
631 * to pre-escape them if you really do want plaintext, or just wrap
632 * the whole thing in htmlspecialchars().
635 * @param string ... parameters
638 function wfMsgHtml( $key ) {
639 $args = func_get_args();
640 array_shift( $args );
641 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
645 * Return an HTML version of message
646 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
647 * so parameters may contain HTML (eg links or form controls). Be sure
648 * to pre-escape them if you really do want plaintext, or just wrap
649 * the whole thing in htmlspecialchars().
652 * @param string ... parameters
655 function wfMsgWikiHtml( $key ) {
657 $args = func_get_args();
658 array_shift( $args );
659 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
663 * Returns message in the requested format
664 * @param string $key Key of the message
665 * @param array $options Processing rules:
666 * <i>parse</i>: parses wikitext to html
667 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
668 * <i>escape</i>: filters message through htmlspecialchars
669 * <i>escapenoentities</i>: same, but allows entity references like through
670 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
671 * <i>parsemag</i>: transform the message using magic phrases
672 * <i>content</i>: fetch message for content language instead of interface
673 * <i>language</i>: language code to fetch message for (overriden by <i>content</i>), its behaviour
674 * with parser, parseinline and parsemag is undefined.
675 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
677 function wfMsgExt( $key, $options ) {
678 global $wgOut, $wgParser;
680 $args = func_get_args();
681 array_shift( $args );
682 array_shift( $args );
684 if( !is_array($options) ) {
685 $options = array($options);
688 if( in_array('content', $options) ) {
691 } elseif( array_key_exists('language', $options) ) {
693 $langCode = $options['language'];
694 $validCodes = array_keys( Language
::getLanguageNames() );
695 if( !in_array($options['language'], $validCodes) ) {
696 # Fallback to en, instead of whatever interface language we might have
704 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
706 if( !in_array('replaceafter', $options) ) {
707 $string = wfMsgReplaceArgs( $string, $args );
710 if( in_array('parse', $options) ) {
711 $string = $wgOut->parse( $string, true, !$forContent );
712 } elseif ( in_array('parseinline', $options) ) {
713 $string = $wgOut->parse( $string, true, !$forContent );
715 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
718 } elseif ( in_array('parsemag', $options) ) {
719 global $wgMessageCache;
720 if ( isset( $wgMessageCache ) ) {
721 $string = $wgMessageCache->transform( $string, !$forContent );
725 if ( in_array('escape', $options) ) {
726 $string = htmlspecialchars ( $string );
727 } elseif ( in_array( 'escapenoentities', $options ) ) {
728 $string = Sanitizer
::escapeHtmlAllowEntities( $string );
731 if( in_array('replaceafter', $options) ) {
732 $string = wfMsgReplaceArgs( $string, $args );
740 * Just like exit() but makes a note of it.
741 * Commits open transactions except if the error parameter is set
743 * @deprecated Please return control to the caller or throw an exception
745 function wfAbruptExit( $error = false ){
746 static $called = false;
752 $bt = wfDebugBacktrace();
754 for($i = 0; $i < count($bt) ; $i++
){
755 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
756 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
757 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
760 wfDebug('WARNING: Abrupt exit\n');
763 wfLogProfilingData();
766 wfGetLB()->closeAll();
772 * @deprecated Please return control the caller or throw an exception
774 function wfErrorExit() {
775 wfAbruptExit( true );
779 * Print a simple message and die, returning nonzero to the shell if any.
780 * Plain die() fails to return nonzero to the shell if you pass a string.
783 function wfDie( $msg='' ) {
789 * Throw a debugging exception. This function previously once exited the process,
790 * but now throws an exception instead, with similar results.
792 * @param string $msg Message shown when dieing.
794 function wfDebugDieBacktrace( $msg = '' ) {
795 throw new MWException( $msg );
799 * Fetch server name for use in error reporting etc.
800 * Use real server name if available, so we know which machine
801 * in a server farm generated the current page.
804 function wfHostname() {
806 if ( is_null( $host ) ) {
807 if ( function_exists( 'posix_uname' ) ) {
808 // This function not present on Windows
809 $uname = @posix_uname
();
813 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
814 $host = $uname['nodename'];
816 # This may be a virtual server.
817 $host = $_SERVER['SERVER_NAME'];
824 * Returns a HTML comment with the elapsed time since request.
825 * This method has no side effects.
828 function wfReportTime() {
829 global $wgRequestTime, $wgShowHostnames;
832 $elapsed = $now - $wgRequestTime;
834 return $wgShowHostnames
835 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
836 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
840 * Safety wrapper for debug_backtrace().
842 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
843 * murky circumstances, which may be triggered in part by stub objects
844 * or other fancy talkin'.
846 * Will return an empty array if Zend Optimizer is detected, otherwise
847 * the output from debug_backtrace() (trimmed).
849 * @return array of backtrace information
851 function wfDebugBacktrace() {
852 if( extension_loaded( 'Zend Optimizer' ) ) {
853 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
856 return array_slice( debug_backtrace(), 1 );
860 function wfBacktrace() {
861 global $wgCommandLineMode;
863 if ( $wgCommandLineMode ) {
868 $backtrace = wfDebugBacktrace();
869 foreach( $backtrace as $call ) {
870 if( isset( $call['file'] ) ) {
871 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
872 $file = $f[count($f)-1];
876 if( isset( $call['line'] ) ) {
877 $line = $call['line'];
881 if ( $wgCommandLineMode ) {
882 $msg .= "$file line $line calls ";
884 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
886 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
887 $msg .= $call['function'] . '()';
889 if ( $wgCommandLineMode ) {
895 if ( $wgCommandLineMode ) {
905 /* Some generic result counters, pulled out of SearchEngine */
911 function wfShowingResults( $offset, $limit ) {
913 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
919 function wfShowingResultsNum( $offset, $limit, $num ) {
921 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
927 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
929 $fmtLimit = $wgLang->formatNum( $limit );
930 $prev = wfMsg( 'prevn', $fmtLimit );
931 $next = wfMsg( 'nextn', $fmtLimit );
933 if( is_object( $link ) ) {
936 $title = Title
::newFromText( $link );
937 if( is_null( $title ) ) {
942 if ( 0 != $offset ) {
943 $po = $offset - $limit;
944 if ( $po < 0 ) { $po = 0; }
945 $q = "limit={$limit}&offset={$po}";
946 if ( '' != $query ) { $q .= '&'.$query; }
947 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
948 } else { $plink = $prev; }
950 $no = $offset +
$limit;
951 $q = 'limit='.$limit.'&offset='.$no;
952 if ( '' != $query ) { $q .= '&'.$query; }
957 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
959 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
960 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
961 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
962 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
963 wfNumLink( $offset, 500, $title, $query );
965 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
971 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
973 if ( '' == $query ) { $q = ''; }
974 else { $q = $query.'&'; }
975 $q .= 'limit='.$limit.'&offset='.$offset;
977 $fmtLimit = $wgLang->formatNum( $limit );
978 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
984 * @todo FIXME: we may want to blacklist some broken browsers
986 * @return bool Whereas client accept gzip compression
988 function wfClientAcceptsGzip() {
991 # FIXME: we may want to blacklist some broken browsers
994 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
995 $_SERVER['HTTP_ACCEPT_ENCODING'],
997 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
998 wfDebug( " accepts gzip\n" );
1006 * Obtain the offset and limit values from the request string;
1007 * used in special pages
1009 * @param $deflimit Default limit if none supplied
1010 * @param $optionname Name of a user preference to check against
1014 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
1016 return $wgRequest->getLimitOffset( $deflimit, $optionname );
1020 * Escapes the given text so that it may be output using addWikiText()
1021 * without any linking, formatting, etc. making its way through. This
1022 * is achieved by substituting certain characters with HTML entities.
1023 * As required by the callers, <nowiki> is not used. It currently does
1024 * not filter out characters which have special meaning only at the
1025 * start of a line, such as "*".
1027 * @param string $text Text to be escaped
1029 function wfEscapeWikiText( $text ) {
1030 $text = str_replace(
1031 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1032 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
1033 htmlspecialchars($text) );
1040 function wfQuotedPrintable( $string, $charset = '' ) {
1041 # Probably incomplete; see RFC 2045
1042 if( empty( $charset ) ) {
1043 global $wgInputEncoding;
1044 $charset = $wgInputEncoding;
1046 $charset = strtoupper( $charset );
1047 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
1049 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
1050 $replace = $illegal . '\t ?_';
1051 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
1052 $out = "=?$charset?Q?";
1053 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
1064 return microtime(true);
1068 * Sets dest to source and returns the original value of dest
1069 * If source is NULL, it just returns the value, it doesn't set the variable
1071 function wfSetVar( &$dest, $source ) {
1073 if ( !is_null( $source ) ) {
1080 * As for wfSetVar except setting a bit
1082 function wfSetBit( &$dest, $bit, $state = true ) {
1083 $temp = (bool)($dest & $bit );
1084 if ( !is_null( $state ) ) {
1095 * This function takes two arrays as input, and returns a CGI-style string, e.g.
1096 * "days=7&limit=100". Options in the first array override options in the second.
1097 * Options set to "" will not be output.
1099 function wfArrayToCGI( $array1, $array2 = NULL )
1101 if ( !is_null( $array2 ) ) {
1102 $array1 = $array1 +
$array2;
1106 foreach ( $array1 as $key => $value ) {
1107 if ( '' !== $value ) {
1111 if(is_array($value))
1114 foreach($value as $v)
1116 $cgi .= ($firstTime ?
'' : '&') .
1117 urlencode( $key . '[]' ) . '=' .
1123 $cgi .= urlencode( $key ) . '=' .
1124 urlencode( $value );
1131 * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
1132 * its argument and returns the same string in array form. This allows compa-
1133 * tibility with legacy functions that accept raw query strings instead of nice
1134 * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
1135 * valid query strings, or it will explode.
1137 * @param $query string Query string
1138 * @return array Array version of input
1140 function wfCgiToArray( $query ) {
1141 if( isset( $query[0] ) and $query[0] == '?' ) {
1142 $query = substr( $query, 1 );
1144 $bits = explode( '&', $query );
1146 foreach( $bits as $bit ) {
1150 list( $key, $value ) = explode( '=', $bit );
1151 $key = urldecode( $key );
1152 $value = urldecode( $value );
1153 $ret[$key] = $value;
1159 * Append a query string to an existing URL, which may or may not already
1160 * have query string parameters already. If so, they will be combined.
1162 * @param string $url
1163 * @param string $query
1166 function wfAppendQuery( $url, $query ) {
1167 if( $query != '' ) {
1168 if( false === strpos( $url, '?' ) ) {
1179 * Expand a potentially local URL to a fully-qualified URL.
1180 * Assumes $wgServer is correct. :)
1181 * @param string $url, either fully-qualified or a local path + query
1182 * @return string Fully-qualified URL
1184 function wfExpandUrl( $url ) {
1185 if( substr( $url, 0, 1 ) == '/' ) {
1187 return $wgServer . $url;
1194 * This is obsolete, use SquidUpdate::purge()
1197 function wfPurgeSquidServers ($urlArr) {
1198 SquidUpdate
::purge( $urlArr );
1202 * Windows-compatible version of escapeshellarg()
1203 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1204 * function puts single quotes in regardless of OS
1206 function wfEscapeShellArg( ) {
1207 $args = func_get_args();
1210 foreach ( $args as $arg ) {
1217 if ( wfIsWindows() ) {
1218 // Escaping for an MSVC-style command line parser
1219 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1220 // Double the backslashes before any double quotes. Escape the double quotes.
1221 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1224 foreach ( $tokens as $token ) {
1226 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1232 // Double the backslashes before the end of the string, because
1233 // we will soon add a quote
1235 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1236 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1239 // Add surrounding quotes
1240 $retVal .= '"' . $arg . '"';
1242 $retVal .= escapeshellarg( $arg );
1249 * wfMerge attempts to merge differences between three texts.
1250 * Returns true for a clean merge and false for failure or a conflict.
1252 function wfMerge( $old, $mine, $yours, &$result ){
1255 # This check may also protect against code injection in
1256 # case of broken installations.
1257 if(! file_exists( $wgDiff3 ) ){
1258 wfDebug( "diff3 not found\n" );
1262 # Make temporary files
1264 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1265 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1266 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1268 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1269 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1270 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1272 # Check for a conflict
1273 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1274 wfEscapeShellArg( $mytextName ) . ' ' .
1275 wfEscapeShellArg( $oldtextName ) . ' ' .
1276 wfEscapeShellArg( $yourtextName );
1277 $handle = popen( $cmd, 'r' );
1279 if( fgets( $handle, 1024 ) ){
1287 $cmd = $wgDiff3 . ' -a -e --merge ' .
1288 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1289 $handle = popen( $cmd, 'r' );
1292 $data = fread( $handle, 8192 );
1293 if ( strlen( $data ) == 0 ) {
1299 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1301 if ( $result === '' && $old !== '' && $conflict == false ) {
1302 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1309 * Returns unified plain-text diff of two texts.
1310 * Useful for machine processing of diffs.
1311 * @param $before string The text before the changes.
1312 * @param $after string The text after the changes.
1313 * @param $params string Command-line options for the diff command.
1314 * @return string Unified diff of $before and $after
1316 function wfDiff( $before, $after, $params = '-u' ) {
1319 # This check may also protect against code injection in
1320 # case of broken installations.
1321 if( !file_exists( $wgDiff ) ){
1322 wfDebug( "diff executable not found\n" );
1323 $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
1324 $format = new UnifiedDiffFormatter();
1325 return $format->format( $diffs );
1328 # Make temporary files
1330 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1331 $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
1333 fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
1334 fwrite( $newtextFile, $after ); fclose( $newtextFile );
1336 // Get the diff of the two files
1337 $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
1339 $h = popen( $cmd, 'r' );
1344 $data = fread( $h, 8192 );
1345 if ( strlen( $data ) == 0 ) {
1353 unlink( $oldtextName );
1354 unlink( $newtextName );
1356 // Kill the --- and +++ lines. They're not useful.
1357 $diff_lines = explode( "\n", $diff );
1358 if (strpos( $diff_lines[0], '---' ) === 0) {
1359 unset($diff_lines[0]);
1361 if (strpos( $diff_lines[1], '+++' ) === 0) {
1362 unset($diff_lines[1]);
1365 $diff = implode( "\n", $diff_lines );
1373 function wfVarDump( $var ) {
1375 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1376 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1379 $wgOut->addHTML( $s );
1384 * Provide a simple HTTP error.
1386 function wfHttpError( $code, $label, $desc ) {
1389 header( "HTTP/1.0 $code $label" );
1390 header( "Status: $code $label" );
1391 $wgOut->sendCacheControl();
1393 header( 'Content-type: text/html; charset=utf-8' );
1394 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1395 "<html><head><title>" .
1396 htmlspecialchars( $label ) .
1397 "</title></head><body><h1>" .
1398 htmlspecialchars( $label ) .
1400 nl2br( htmlspecialchars( $desc ) ) .
1401 "</p></body></html>\n";
1405 * Clear away any user-level output buffers, discarding contents.
1407 * Suitable for 'starting afresh', for instance when streaming
1408 * relatively large amounts of data without buffering, or wanting to
1409 * output image files without ob_gzhandler's compression.
1411 * The optional $resetGzipEncoding parameter controls suppression of
1412 * the Content-Encoding header sent by ob_gzhandler; by default it
1413 * is left. See comments for wfClearOutputBuffers() for why it would
1416 * Note that some PHP configuration options may add output buffer
1417 * layers which cannot be removed; these are left in place.
1419 * @param bool $resetGzipEncoding
1421 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1422 if( $resetGzipEncoding ) {
1423 // Suppress Content-Encoding and Content-Length
1424 // headers from 1.10+s wfOutputHandler
1425 global $wgDisableOutputCompression;
1426 $wgDisableOutputCompression = true;
1428 while( $status = ob_get_status() ) {
1429 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1430 // Probably from zlib.output_compression or other
1431 // PHP-internal setting which can't be removed.
1433 // Give up, and hope the result doesn't break
1437 if( !ob_end_clean() ) {
1438 // Could not remove output buffer handler; abort now
1439 // to avoid getting in some kind of infinite loop.
1442 if( $resetGzipEncoding ) {
1443 if( $status['name'] == 'ob_gzhandler' ) {
1444 // Reset the 'Content-Encoding' field set by this handler
1445 // so we can start fresh.
1446 header( 'Content-Encoding:' );
1454 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1456 * Clear away output buffers, but keep the Content-Encoding header
1457 * produced by ob_gzhandler, if any.
1459 * This should be used for HTTP 304 responses, where you need to
1460 * preserve the Content-Encoding header of the real result, but
1461 * also need to suppress the output of ob_gzhandler to keep to spec
1462 * and avoid breaking Firefox in rare cases where the headers and
1463 * body are broken over two packets.
1465 function wfClearOutputBuffers() {
1466 wfResetOutputBuffers( false );
1470 * Converts an Accept-* header into an array mapping string values to quality
1473 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1474 # No arg means accept anything (per HTTP spec)
1476 return array( $def => 1.0 );
1481 $parts = explode( ',', $accept );
1483 foreach( $parts as $part ) {
1484 # FIXME: doesn't deal with params like 'text/html; level=1'
1485 @list
( $value, $qpart ) = explode( ';', trim( $part ) );
1487 if( !isset( $qpart ) ) {
1488 $prefs[$value] = 1.0;
1489 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1490 $prefs[$value] = floatval($match[1]);
1498 * Checks if a given MIME type matches any of the keys in the given
1499 * array. Basic wildcards are accepted in the array keys.
1501 * Returns the matching MIME type (or wildcard) if a match, otherwise
1504 * @param string $type
1505 * @param array $avail
1509 function mimeTypeMatch( $type, $avail ) {
1510 if( array_key_exists($type, $avail) ) {
1513 $parts = explode( '/', $type );
1514 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1515 return $parts[0] . '/*';
1516 } elseif( array_key_exists( '*/*', $avail ) ) {
1525 * Returns the 'best' match between a client's requested internet media types
1526 * and the server's list of available types. Each list should be an associative
1527 * array of type to preference (preference is a float between 0.0 and 1.0).
1528 * Wildcards in the types are acceptable.
1530 * @param array $cprefs Client's acceptable type list
1531 * @param array $sprefs Server's offered types
1534 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1535 * XXX: generalize to negotiate other stuff
1537 function wfNegotiateType( $cprefs, $sprefs ) {
1540 foreach( array_keys($sprefs) as $type ) {
1541 $parts = explode( '/', $type );
1542 if( $parts[1] != '*' ) {
1543 $ckey = mimeTypeMatch( $type, $cprefs );
1545 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1550 foreach( array_keys( $cprefs ) as $type ) {
1551 $parts = explode( '/', $type );
1552 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1553 $skey = mimeTypeMatch( $type, $sprefs );
1555 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1563 foreach( array_keys( $combine ) as $type ) {
1564 if( $combine[$type] > $bestq ) {
1566 $bestq = $combine[$type];
1575 * Returns an array where the values in the first array are replaced by the
1576 * values in the second array with the corresponding keys
1580 function wfArrayLookup( $a, $b ) {
1581 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1585 * Convenience function; returns MediaWiki timestamp for the present time.
1588 function wfTimestampNow() {
1590 return wfTimestamp( TS_MW
, time() );
1594 * Reference-counted warning suppression
1596 function wfSuppressWarnings( $end = false ) {
1597 static $suppressCount = 0;
1598 static $originalLevel = false;
1601 if ( $suppressCount ) {
1603 if ( !$suppressCount ) {
1604 error_reporting( $originalLevel );
1608 if ( !$suppressCount ) {
1609 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1616 * Restore error level to previous value
1618 function wfRestoreWarnings() {
1619 wfSuppressWarnings( true );
1622 # Autodetect, convert and provide timestamps of various types
1625 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1627 define('TS_UNIX', 0);
1630 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1635 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1640 * RFC 2822 format, for E-mail and HTTP headers
1642 define('TS_RFC2822', 3);
1645 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1647 * This is used by Special:Export
1649 define('TS_ISO_8601', 4);
1652 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1654 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1655 * DateTime tag and page 36 for the DateTimeOriginal and
1656 * DateTimeDigitized tags.
1658 define('TS_EXIF', 5);
1661 * Oracle format time.
1663 define('TS_ORACLE', 6);
1666 * Postgres format time.
1668 define('TS_POSTGRES', 7);
1671 * @param mixed $outputtype A timestamp in one of the supported formats, the
1672 * function will autodetect which format is supplied
1673 * and act accordingly.
1674 * @return string Time in the format specified in $outputtype
1676 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1681 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1683 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1685 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1687 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1690 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1692 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1693 str_replace("+00:00", "UTC", $ts)));
1694 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1696 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1698 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1701 # Bogus value; fall back to the epoch...
1702 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1706 if (count( $da ) ) {
1707 // Warning! gmmktime() acts oddly if the month or day is set to 0
1708 // We may want to handle that explicitly at some point
1709 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1710 (int)$da[2],(int)$da[3],(int)$da[1]);
1713 switch($outputtype) {
1717 return gmdate( 'YmdHis', $uts );
1719 return gmdate( 'Y-m-d H:i:s', $uts );
1721 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1722 // This shouldn't ever be used, but is included for completeness
1724 return gmdate( 'Y:m:d H:i:s', $uts );
1726 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1728 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1730 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1732 throw new MWException( 'wfTimestamp() called with illegal output type.');
1737 * Return a formatted timestamp, or null if input is null.
1738 * For dealing with nullable timestamp columns in the database.
1739 * @param int $outputtype
1743 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1744 if( is_null( $ts ) ) {
1747 return wfTimestamp( $outputtype, $ts );
1752 * Check if the operating system is Windows
1754 * @return bool True if it's Windows, False otherwise.
1756 function wfIsWindows() {
1757 if (substr(php_uname(), 0, 7) == 'Windows') {
1765 * Swap two variables
1767 function swap( &$x, &$y ) {
1773 function wfGetCachedNotice( $name ) {
1774 global $wgOut, $wgRenderHashAppend, $parserMemc;
1775 $fname = 'wfGetCachedNotice';
1776 wfProfileIn( $fname );
1780 if( $name === 'default' ) {
1782 global $wgSiteNotice;
1783 $notice = $wgSiteNotice;
1784 if( empty( $notice ) ) {
1785 wfProfileOut( $fname );
1789 $notice = wfMsgForContentNoTrans( $name );
1790 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1791 wfProfileOut( $fname );
1796 // Use the extra hash appender to let eg SSL variants separately cache.
1797 $key = wfMemcKey( $name . $wgRenderHashAppend );
1798 $cachedNotice = $parserMemc->get( $key );
1799 if( is_array( $cachedNotice ) ) {
1800 if( md5( $notice ) == $cachedNotice['hash'] ) {
1801 $notice = $cachedNotice['html'];
1810 if( is_object( $wgOut ) ) {
1811 $parsed = $wgOut->parse( $notice );
1812 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1815 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1820 wfProfileOut( $fname );
1824 function wfGetNamespaceNotice() {
1828 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1831 $fname = 'wfGetNamespaceNotice';
1832 wfProfileIn( $fname );
1834 $key = "namespacenotice-" . $wgTitle->getNsText();
1835 $namespaceNotice = wfGetCachedNotice( $key );
1836 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1837 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1839 $namespaceNotice = "";
1842 wfProfileOut( $fname );
1843 return $namespaceNotice;
1846 function wfGetSiteNotice() {
1847 global $wgUser, $wgSiteNotice;
1848 $fname = 'wfGetSiteNotice';
1849 wfProfileIn( $fname );
1852 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1853 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1854 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1856 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1857 if( !$anonNotice ) {
1858 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1860 $siteNotice = $anonNotice;
1863 if( !$siteNotice ) {
1864 $siteNotice = wfGetCachedNotice( 'default' );
1868 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1869 wfProfileOut( $fname );
1874 * BC wrapper for MimeMagic::singleton()
1877 function &wfGetMimeMagic() {
1878 return MimeMagic
::singleton();
1882 * Tries to get the system directory for temporary files.
1883 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1884 * and if none are set /tmp is returned as the generic Unix default.
1886 * NOTE: When possible, use the tempfile() function to create temporary
1887 * files to avoid race conditions on file creation, etc.
1891 function wfTempDir() {
1892 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1893 $tmp = getenv( $var );
1894 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1898 # Hope this is Unix of some kind!
1903 * Make directory, and make all parent directories if they don't exist
1905 * @param string $fullDir Full path to directory to create
1906 * @param int $mode Chmod value to use, default is $wgDirectoryMode
1909 function wfMkdirParents( $fullDir, $mode = null ) {
1910 global $wgDirectoryMode;
1911 if( strval( $fullDir ) === '' )
1913 if( file_exists( $fullDir ) )
1915 // If not defined or isn't an int, set to default
1916 if ( is_null( $mode ) ) {
1917 $mode = $wgDirectoryMode;
1921 # Go back through the paths to find the first directory that exists
1922 $currentDir = $fullDir;
1923 $createList = array();
1924 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1925 # Strip trailing slashes
1926 $currentDir = rtrim( $currentDir, '/\\' );
1928 # Add to create list
1929 $createList[] = $currentDir;
1931 # Find next delimiter searching from the end
1932 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1933 if ( $p === false ) {
1934 $currentDir = false;
1936 $currentDir = substr( $currentDir, 0, $p );
1940 if ( count( $createList ) == 0 ) {
1941 # Directory specified already exists
1943 } elseif ( $currentDir === false ) {
1944 # Went all the way back to root and it apparently doesn't exist
1945 wfDebugLog( 'mkdir', "Root doesn't exist?\n" );
1948 # Now go forward creating directories
1949 $createList = array_reverse( $createList );
1951 # Is the parent directory writable?
1952 if ( $currentDir === '' ) {
1955 if ( !is_writable( $currentDir ) ) {
1956 wfDebugLog( 'mkdir', "Not writable: $currentDir\n" );
1960 foreach ( $createList as $dir ) {
1961 # use chmod to override the umask, as suggested by the PHP manual
1962 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1963 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1971 * Increment a statistics counter
1973 function wfIncrStats( $key ) {
1974 global $wgStatsMethod;
1976 if( $wgStatsMethod == 'udp' ) {
1977 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1980 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1981 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1982 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1984 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1985 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1986 } elseif( $wgStatsMethod == 'cache' ) {
1988 $key = wfMemcKey( 'stats', $key );
1989 if ( is_null( $wgMemc->incr( $key ) ) ) {
1990 $wgMemc->add( $key, 1 );
1998 * @param mixed $nr The number to format
1999 * @param int $acc The number of digits after the decimal point, default 2
2000 * @param bool $round Whether or not to round the value, default true
2003 function wfPercent( $nr, $acc = 2, $round = true ) {
2004 $ret = sprintf( "%.${acc}f", $nr );
2005 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
2009 * Encrypt a username/password.
2011 * @param string $userid ID of the user
2012 * @param string $password Password of the user
2013 * @return string Hashed password
2014 * @deprecated Use User::crypt() or User::oldCrypt() instead
2016 function wfEncryptPassword( $userid, $password ) {
2017 wfDeprecated(__FUNCTION__
);
2018 # Just wrap around User::oldCrypt()
2019 return User
::oldCrypt($password, $userid);
2023 * Appends to second array if $value differs from that in $default
2025 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
2026 if ( is_null( $changed ) ) {
2027 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
2029 if ( $default[$key] !== $value ) {
2030 $changed[$key] = $value;
2035 * Since wfMsg() and co suck, they don't return false if the message key they
2036 * looked up didn't exist but a XHTML string, this function checks for the
2037 * nonexistance of messages by looking at wfMsg() output
2039 * @param $msg The message key looked up
2040 * @param $wfMsgOut The output of wfMsg*()
2043 function wfEmptyMsg( $msg, $wfMsgOut ) {
2044 return $wfMsgOut === htmlspecialchars( "<$msg>" );
2048 * Find out whether or not a mixed variable exists in a string
2050 * @param mixed needle
2051 * @param string haystack
2054 function in_string( $needle, $str ) {
2055 return strpos( $str, $needle ) !== false;
2058 function wfSpecialList( $page, $details ) {
2060 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
2061 return $page . $details;
2065 * Returns a regular expression of url protocols
2069 function wfUrlProtocols() {
2070 global $wgUrlProtocols;
2072 // Support old-style $wgUrlProtocols strings, for backwards compatibility
2073 // with LocalSettings files from 1.5
2074 if ( is_array( $wgUrlProtocols ) ) {
2075 $protocols = array();
2076 foreach ($wgUrlProtocols as $protocol)
2077 $protocols[] = preg_quote( $protocol, '/' );
2079 return implode( '|', $protocols );
2081 return $wgUrlProtocols;
2086 * Safety wrapper around ini_get() for boolean settings.
2087 * The values returned from ini_get() are pre-normalized for settings
2088 * set via php.ini or php_flag/php_admin_flag... but *not*
2089 * for those set via php_value/php_admin_value.
2091 * It's fairly common for people to use php_value instead of php_flag,
2092 * which can leave you with an 'off' setting giving a false positive
2093 * for code that just takes the ini_get() return value as a boolean.
2095 * To make things extra interesting, setting via php_value accepts
2096 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
2097 * Unrecognized values go false... again opposite PHP's own coercion
2098 * from string to bool.
2100 * Luckily, 'properly' set settings will always come back as '0' or '1',
2101 * so we only have to worry about them and the 'improper' settings.
2103 * I frickin' hate PHP... :P
2105 * @param string $setting
2108 function wfIniGetBool( $setting ) {
2109 $val = ini_get( $setting );
2110 // 'on' and 'true' can't have whitespace around them, but '1' can.
2111 return strtolower( $val ) == 'on'
2112 ||
strtolower( $val ) == 'true'
2113 ||
strtolower( $val ) == 'yes'
2114 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
2118 * Execute a shell command, with time and memory limits mirrored from the PHP
2119 * configuration if supported.
2120 * @param $cmd Command line, properly escaped for shell.
2121 * @param &$retval optional, will receive the program's exit code.
2122 * (non-zero is usually failure)
2123 * @return collected stdout as a string (trailing newlines stripped)
2125 function wfShellExec( $cmd, &$retval=null ) {
2126 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
2128 if( wfIniGetBool( 'safe_mode' ) ) {
2129 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
2131 return "Unable to run external programs in safe mode.";
2134 if ( php_uname( 's' ) == 'Linux' ) {
2135 $time = intval( ini_get( 'max_execution_time' ) );
2136 $mem = intval( $wgMaxShellMemory );
2137 $filesize = intval( $wgMaxShellFileSize );
2139 if ( $time > 0 && $mem > 0 ) {
2140 $script = "$IP/bin/ulimit4.sh";
2141 if ( is_executable( $script ) ) {
2142 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
2145 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
2146 # This is a hack to work around PHP's flawed invocation of cmd.exe
2147 # http://news.php.net/php.internals/21796
2148 $cmd = '"' . $cmd . '"';
2150 wfDebug( "wfShellExec: $cmd\n" );
2152 $retval = 1; // error by default?
2154 passthru( $cmd, $retval );
2155 $output = ob_get_contents();
2158 if ( $retval == 127 ) {
2159 wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
2166 * This function works like "use VERSION" in Perl, the program will die with a
2167 * backtrace if the current version of PHP is less than the version provided
2169 * This is useful for extensions which due to their nature are not kept in sync
2170 * with releases, and might depend on other versions of PHP than the main code
2172 * Note: PHP might die due to parsing errors in some cases before it ever
2173 * manages to call this function, such is life
2175 * @see perldoc -f use
2177 * @param mixed $version The version to check, can be a string, an integer, or
2180 function wfUsePHP( $req_ver ) {
2181 $php_ver = PHP_VERSION
;
2183 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
2184 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
2188 * This function works like "use VERSION" in Perl except it checks the version
2189 * of MediaWiki, the program will die with a backtrace if the current version
2190 * of MediaWiki is less than the version provided.
2192 * This is useful for extensions which due to their nature are not kept in sync
2195 * @see perldoc -f use
2197 * @param mixed $version The version to check, can be a string, an integer, or
2200 function wfUseMW( $req_ver ) {
2203 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2204 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2208 * @deprecated use StringUtils::escapeRegexReplacement
2210 function wfRegexReplacement( $string ) {
2211 return StringUtils
::escapeRegexReplacement( $string );
2215 * Return the final portion of a pathname.
2216 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2217 * http://bugs.php.net/bug.php?id=33898
2219 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2220 * We'll consider it so always, as we don't want \s in our Unix paths either.
2222 * @param string $path
2223 * @param string $suffix to remove if present
2226 function wfBaseName( $path, $suffix='' ) {
2227 $encSuffix = ($suffix == '')
2229 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2231 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2239 * Generate a relative path name to the given file.
2240 * May explode on non-matching case-insensitive paths,
2241 * funky symlinks, etc.
2243 * @param string $path Absolute destination path including target filename
2244 * @param string $from Absolute source path, directory only
2247 function wfRelativePath( $path, $from ) {
2248 // Normalize mixed input on Windows...
2249 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2250 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2252 // Trim trailing slashes -- fix for drive root
2253 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2254 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2256 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2257 $against = explode( DIRECTORY_SEPARATOR
, $from );
2259 if( $pieces[0] !== $against[0] ) {
2260 // Non-matching Windows drive letters?
2261 // Return a full path.
2265 // Trim off common prefix
2266 while( count( $pieces ) && count( $against )
2267 && $pieces[0] == $against[0] ) {
2268 array_shift( $pieces );
2269 array_shift( $against );
2272 // relative dots to bump us to the parent
2273 while( count( $against ) ) {
2274 array_unshift( $pieces, '..' );
2275 array_shift( $against );
2278 array_push( $pieces, wfBaseName( $path ) );
2280 return implode( DIRECTORY_SEPARATOR
, $pieces );
2284 * array_merge() does awful things with "numeric" indexes, including
2285 * string indexes when happen to look like integers. When we want
2286 * to merge arrays with arbitrary string indexes, we don't want our
2287 * arrays to be randomly corrupted just because some of them consist
2290 * Fuck you, PHP. Fuck you in the ear!
2292 * @param array $array1, [$array2, [...]]
2295 function wfArrayMerge( $array1/* ... */ ) {
2297 for( $i = 1; $i < func_num_args(); $i++
) {
2298 foreach( func_get_arg( $i ) as $key => $value ) {
2299 $out[$key] = $value;
2306 * Make a URL index, appropriate for the el_index field of externallinks.
2308 function wfMakeUrlIndex( $url ) {
2309 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2310 wfSuppressWarnings();
2311 $bits = parse_url( $url );
2312 wfRestoreWarnings();
2316 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2318 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2320 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2322 // parse_url detects for news: and mailto: the host part of an url as path
2323 // We have to correct this wrong detection
2324 if ( isset ( $bits['path'] ) ) {
2325 $bits['host'] = $bits['path'];
2332 // Reverse the labels in the hostname, convert to lower case
2333 // For emails reverse domainpart only
2334 if ( $bits['scheme'] == 'mailto' ) {
2335 $mailparts = explode( '@', $bits['host'], 2 );
2336 if ( count($mailparts) === 2 ) {
2337 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2339 // No domain specified, don't mangle it
2342 $reversedHost = $domainpart . '@' . $mailparts[0];
2344 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2346 // Add an extra dot to the end
2347 // Why? Is it in wrong place in mailto links?
2348 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2349 $reversedHost .= '.';
2351 // Reconstruct the pseudo-URL
2352 $prot = $bits['scheme'];
2353 $index = "$prot$delimiter$reversedHost";
2354 // Leave out user and password. Add the port, path, query and fragment
2355 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2356 if ( isset( $bits['path'] ) ) {
2357 $index .= $bits['path'];
2361 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2362 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2367 * Do any deferred updates and clear the list
2368 * TODO: This could be in Wiki.php if that class made any sense at all
2370 function wfDoUpdates()
2372 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2373 foreach ( $wgDeferredUpdateList as $update ) {
2374 $update->doUpdate();
2376 foreach ( $wgPostCommitUpdateList as $update ) {
2377 $update->doUpdate();
2379 $wgDeferredUpdateList = array();
2380 $wgPostCommitUpdateList = array();
2384 * @deprecated use StringUtils::explodeMarkup
2386 function wfExplodeMarkup( $separator, $text ) {
2387 return StringUtils
::explodeMarkup( $separator, $text );
2391 * Convert an arbitrarily-long digit string from one numeric base
2392 * to another, optionally zero-padding to a minimum column width.
2394 * Supports base 2 through 36; digit values 10-36 are represented
2395 * as lowercase letters a-z. Input is case-insensitive.
2397 * @param $input string of digits
2398 * @param $sourceBase int 2-36
2399 * @param $destBase int 2-36
2400 * @param $pad int 1 or greater
2401 * @param $lowercase bool
2402 * @return string or false on invalid input
2404 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2405 $input = strval( $input );
2406 if( $sourceBase < 2 ||
2411 $sourceBase != intval( $sourceBase ) ||
2412 $destBase != intval( $destBase ) ||
2413 $pad != intval( $pad ) ||
2414 !is_string( $input ) ||
2418 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2419 $inDigits = array();
2422 // Decode and validate input string
2423 $input = strtolower( $input );
2424 for( $i = 0; $i < strlen( $input ); $i++
) {
2425 $n = strpos( $digitChars, $input{$i} );
2426 if( $n === false ||
$n > $sourceBase ) {
2432 // Iterate over the input, modulo-ing out an output digit
2433 // at a time until input is gone.
2434 while( count( $inDigits ) ) {
2436 $workDigits = array();
2439 foreach( $inDigits as $digit ) {
2440 $work *= $sourceBase;
2443 if( $work < $destBase ) {
2444 // Gonna need to pull another digit.
2445 if( count( $workDigits ) ) {
2446 // Avoid zero-padding; this lets us find
2447 // the end of the input very easily when
2448 // length drops to zero.
2452 // Finally! Actual division!
2453 $workDigits[] = intval( $work / $destBase );
2455 // Isn't it annoying that most programming languages
2456 // don't have a single divide-and-remainder operator,
2457 // even though the CPU implements it that way?
2458 $work = $work %
$destBase;
2462 // All that division leaves us with a remainder,
2463 // which is conveniently our next output digit.
2464 $outChars .= $digitChars[$work];
2467 $inDigits = $workDigits;
2470 while( strlen( $outChars ) < $pad ) {
2474 return strrev( $outChars );
2478 * Create an object with a given name and an array of construct parameters
2479 * @param string $name
2480 * @param array $p parameters
2482 function wfCreateObject( $name, $p ){
2483 $p = array_values( $p );
2484 switch ( count( $p ) ) {
2488 return new $name( $p[0] );
2490 return new $name( $p[0], $p[1] );
2492 return new $name( $p[0], $p[1], $p[2] );
2494 return new $name( $p[0], $p[1], $p[2], $p[3] );
2496 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2498 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2500 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2505 * Alias for modularized function
2506 * @deprecated Use Http::get() instead
2508 function wfGetHTTP( $url, $timeout = 'default' ) {
2509 wfDeprecated(__FUNCTION__
);
2510 return Http
::get( $url, $timeout );
2514 * Alias for modularized function
2515 * @deprecated Use Http::isLocalURL() instead
2517 function wfIsLocalURL( $url ) {
2518 wfDeprecated(__FUNCTION__
);
2519 return Http
::isLocalURL( $url );
2522 function wfHttpOnlySafe() {
2523 global $wgHttpOnlyBlacklist;
2524 if( !version_compare("5.2", PHP_VERSION
, "<") )
2527 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2528 foreach( $wgHttpOnlyBlacklist as $regex ) {
2529 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2539 * Initialise php session
2541 function wfSetupSession() {
2542 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2543 if( $wgSessionsInMemcached ) {
2544 require_once( 'MemcachedSessions.php' );
2545 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2546 # If it's left on 'user' or another setting from another
2547 # application, it will end up failing. Try to recover.
2548 ini_set ( 'session.save_handler', 'files' );
2550 $httpOnlySafe = wfHttpOnlySafe();
2551 wfDebugLog( 'cookie',
2552 'session_set_cookie_params: "' . implode( '", "',
2558 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2559 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2560 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2562 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2563 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2565 session_cache_limiter( 'private, must-revalidate' );
2566 wfSuppressWarnings();
2568 wfRestoreWarnings();
2572 * Get an object from the precompiled serialized directory
2574 * @return mixed The variable on success, false on failure
2576 function wfGetPrecompiledData( $name ) {
2579 $file = "$IP/serialized/$name";
2580 if ( file_exists( $file ) ) {
2581 $blob = file_get_contents( $file );
2583 return unserialize( $blob );
2589 function wfGetCaller( $level = 2 ) {
2590 $backtrace = wfDebugBacktrace();
2591 if ( isset( $backtrace[$level] ) ) {
2592 return wfFormatStackFrame($backtrace[$level]);
2594 $caller = 'unknown';
2599 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2600 function wfGetAllCallers() {
2601 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2604 /** Return a string representation of frame */
2605 function wfFormatStackFrame($frame) {
2606 return isset( $frame["class"] )?
2607 $frame["class"]."::".$frame["function"]:
2614 function wfMemcKey( /*... */ ) {
2615 $args = func_get_args();
2616 $key = wfWikiID() . ':' . implode( ':', $args );
2621 * Get a cache key for a foreign DB
2623 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2624 $args = array_slice( func_get_args(), 2 );
2626 $key = "$db-$prefix:" . implode( ':', $args );
2628 $key = $db . ':' . implode( ':', $args );
2634 * Get an ASCII string identifying this wiki
2635 * This is used as a prefix in memcached keys
2637 function wfWikiID( $db = null ) {
2638 if( $db instanceof Database
) {
2639 return $db->getWikiID();
2641 global $wgDBprefix, $wgDBname;
2642 if ( $wgDBprefix ) {
2643 return "$wgDBname-$wgDBprefix";
2651 * Split a wiki ID into DB name and table prefix
2653 function wfSplitWikiID( $wiki ) {
2654 $bits = explode( '-', $wiki, 2 );
2655 if ( count( $bits ) < 2 ) {
2662 * Get a Database object.
2663 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2664 * master (for write queries), DB_SLAVE for potentially lagged
2665 * read queries, or an integer >= 0 for a particular server.
2667 * @param mixed $groups Query groups. An array of group names that this query
2668 * belongs to. May contain a single string if the query is only
2671 * @param string $wiki The wiki ID, or false for the current wiki
2673 * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
2674 * will always return the same object, unless the underlying connection or load
2675 * balancer is manually destroyed.
2677 function &wfGetDB( $db, $groups = array(), $wiki = false ) {
2678 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2682 * Get a load balancer object.
2684 * @param array $groups List of query groups
2685 * @param string $wiki Wiki ID, or false for the current wiki
2686 * @return LoadBalancer
2688 function wfGetLB( $wiki = false ) {
2689 return wfGetLBFactory()->getMainLB( $wiki );
2693 * Get the load balancer factory object
2695 function &wfGetLBFactory() {
2696 return LBFactory
::singleton();
2701 * Shortcut for RepoGroup::singleton()->findFile()
2702 * @param mixed $title Title object or string. May be interwiki.
2703 * @param mixed $time Requested time for an archived image, or false for the
2704 * current version. An image object will be returned which
2705 * was created at the specified time.
2706 * @param mixed $flags FileRepo::FIND_ flags
2707 * @return File, or false if the file does not exist
2709 function wfFindFile( $title, $time = false, $flags = 0 ) {
2710 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2714 * Get an object referring to a locally registered file.
2715 * Returns a valid placeholder object if the file does not exist.
2717 function wfLocalFile( $title ) {
2718 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2722 * Should low-performance queries be disabled?
2726 function wfQueriesMustScale() {
2727 global $wgMiserMode;
2729 ||
( SiteStats
::pages() > 100000
2730 && SiteStats
::edits() > 1000000
2731 && SiteStats
::users() > 10000 );
2735 * Get the path to a specified script file, respecting file
2736 * extensions; this is a wrapper around $wgScriptExtension etc.
2738 * @param string $script Script filename, sans extension
2741 function wfScript( $script = 'index' ) {
2742 global $wgScriptPath, $wgScriptExtension;
2743 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2747 * Convenience function converts boolean values into "true"
2748 * or "false" (string) values
2750 * @param bool $value
2753 function wfBoolToStr( $value ) {
2754 return $value ?
'true' : 'false';
2758 * Load an extension messages file
2760 * @param string $extensionName Name of extension to load messages from\for.
2761 * @param string $langcode Language to load messages for, or false for default
2762 * behvaiour (en, content language and user language).
2763 * @since r24808 (v1.11) Using this method of loading extension messages will not work
2764 * on MediaWiki prior to that
2766 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2767 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2769 #For recording whether extension message files have been loaded in a given language.
2770 static $loaded = array();
2772 if( !array_key_exists( $extensionName, $loaded ) ) {
2773 $loaded[$extensionName] = array();
2776 if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
2777 throw new MWException( "Messages file for extensions $extensionName is not defined" );
2780 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2781 # Just do en, content language and user language.
2782 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2783 # Mark that they have been loaded.
2784 $loaded[$extensionName]['en'] = true;
2785 $loaded[$extensionName][$wgLang->getCode()] = true;
2786 $loaded[$extensionName][$wgContLang->getCode()] = true;
2787 # Mark that this part has been done to avoid weird if statements.
2788 $loaded[$extensionName]['*'] = true;
2789 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2790 # Load messages for specified language.
2791 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2792 # Mark that they have been loaded.
2793 $loaded[$extensionName][$langcode] = true;
2798 * Get a platform-independent path to the null file, e.g.
2803 function wfGetNull() {
2804 return wfIsWindows()
2810 * Displays a maxlag error
2812 * @param string $host Server that lags the most
2813 * @param int $lag Maxlag (actual)
2814 * @param int $maxLag Maxlag (requested)
2816 function wfMaxlagError( $host, $lag, $maxLag ) {
2817 global $wgShowHostnames;
2818 header( 'HTTP/1.1 503 Service Unavailable' );
2819 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2820 header( 'X-Database-Lag: ' . intval( $lag ) );
2821 header( 'Content-Type: text/plain' );
2822 if( $wgShowHostnames ) {
2823 echo "Waiting for $host: $lag seconds lagged\n";
2825 echo "Waiting for a database server: $lag seconds lagged\n";
2830 * Throws an E_USER_NOTICE saying that $function is deprecated
2831 * @param string $function
2834 function wfDeprecated( $function ) {
2835 global $wgDebugLogFile;
2836 if ( !$wgDebugLogFile ) {
2839 $callers = wfDebugBacktrace();
2840 if( isset( $callers[2] ) ){
2841 $callerfunc = $callers[2];
2842 $callerfile = $callers[1];
2843 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2844 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2846 $file = '(internal function)';
2849 if( isset( $callerfunc['class'] ) )
2850 $func .= $callerfunc['class'] . '::';
2851 $func .= @$callerfunc['function'];
2852 $msg = "Use of $function is deprecated. Called from $func in $file";
2854 $msg = "Use of $function is deprecated.";
2856 wfDebug( "$msg\n" );
2860 * Sleep until the worst slave's replication lag is less than or equal to
2861 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2862 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2863 * a no-op if there are no slaves.
2865 * Every time the function has to wait for a slave, it will print a message to
2866 * that effect (and then sleep for a little while), so it's probably not best
2867 * to use this outside maintenance scripts in its present form.
2869 * @param int $maxLag
2872 function wfWaitForSlaves( $maxLag ) {
2875 list( $host, $lag ) = $lb->getMaxLag();
2876 while( $lag > $maxLag ) {
2877 $name = @gethostbyaddr
( $host );
2878 if( $name !== false ) {
2881 print "Waiting for $host (lagged $lag seconds)...\n";
2883 list( $host, $lag ) = $lb->getMaxLag();
2888 /** Generate a random 32-character hexadecimal token.
2889 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2891 function wfGenerateToken( $salt = '' ) {
2892 $salt = serialize($salt);
2894 return md5( mt_rand( 0, 0x7fffffff ) . $salt );
2898 * Replace all invalid characters with -
2899 * @param mixed $title Filename to process
2901 function wfStripIllegalFilenameChars( $name ) {
2902 $name = wfBaseName( $name );
2903 $name = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $name );
2909 * @param string $line
2911 function wfRecentChange2UDP( $line ) {
2912 global $wgRC2UDPAddress, $wgRC2UDPPort, $wgRC2UDPPrefix;
2913 # Notify external application via UDP
2914 if( $wgRC2UDPAddress ) {
2915 $conn = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
2917 $line = $wgRC2UDPPrefix . $line;
2918 socket_sendto( $conn, $line, strlen($line), 0, $wgRC2UDPAddress, $wgRC2UDPPort );
2919 socket_close( $conn );