3825f08b60da08633b63a49ed05737a25c0d8d49
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 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
180 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
184 if ( $wgDebugComments && !$logonly ) {
185 if ( !isset( $wgOut ) ) {
188 if ( !StubObject
::isRealObject( $wgOut ) ) {
196 $wgOut->debug( $text );
198 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
199 # Strip unprintables; they can switch terminal modes when binary data
200 # gets dumped, which is pretty annoying.
201 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
202 wfErrorLog( $text, $wgDebugLogFile );
207 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
208 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
210 * @param $logGroup String
211 * @param $text String
212 * @param $public Bool: whether to log the event in the public log if no private
213 * log file is specified, (default true)
215 function wfDebugLog( $logGroup, $text, $public = true ) {
216 global $wgDebugLogGroups;
217 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
218 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
219 $time = wfTimestamp( TS_DB
);
221 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
222 } else if ( $public === true ) {
223 wfDebug( $text, true );
228 * Log for database errors
229 * @param $text String: database error message.
231 function wfLogDBError( $text ) {
232 global $wgDBerrorLog, $wgDBname;
233 if ( $wgDBerrorLog ) {
234 $host = trim(`hostname`
);
235 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
236 wfErrorLog( $text, $wgDBerrorLog );
241 * Log to a file without getting "file size exceeded" signals
243 function wfErrorLog( $text, $file ) {
244 wfSuppressWarnings();
245 $exists = file_exists( $file );
246 $size = $exists ?
filesize( $file ) : false;
247 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
248 error_log( $text, 3, $file );
256 function wfLogProfilingData() {
257 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
258 global $wgProfiler, $wgUser;
259 if ( !isset( $wgProfiler ) )
263 $elapsed = $now - $wgRequestTime;
264 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
266 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
267 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
268 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
269 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
270 if( !empty( $_SERVER['HTTP_FROM'] ) )
271 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
273 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
274 // Don't unstub $wgUser at this late stage just for statistics purposes
275 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
277 $log = sprintf( "%s\t%04.3f\t%s\n",
278 gmdate( 'YmdHis' ), $elapsed,
279 urldecode( $wgRequest->getRequestURL() . $forward ) );
280 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
281 wfErrorLog( $log . $prof, $wgDebugLogFile );
286 * Check if the wiki read-only lock file is present. This can be used to lock
287 * off editing functions, but doesn't guarantee that the database will not be
291 function wfReadOnly() {
292 global $wgReadOnlyFile, $wgReadOnly;
294 if ( !is_null( $wgReadOnly ) ) {
295 return (bool)$wgReadOnly;
297 if ( '' == $wgReadOnlyFile ) {
300 // Set $wgReadOnly for faster access next time
301 if ( is_file( $wgReadOnlyFile ) ) {
302 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
306 return (bool)$wgReadOnly;
309 function wfReadOnlyReason() {
316 * Get a message from anywhere, for the current user language.
318 * Use wfMsgForContent() instead if the message should NOT
319 * change depending on the user preferences.
321 * @param $key String: lookup key for the message, usually
322 * defined in languages/Language.php
324 * This function also takes extra optional parameters (not
325 * shown in the function definition), which can by used to
326 * insert variable text into the predefined message.
328 function wfMsg( $key ) {
329 $args = func_get_args();
330 array_shift( $args );
331 return wfMsgReal( $key, $args, true );
335 * Same as above except doesn't transform the message
337 function wfMsgNoTrans( $key ) {
338 $args = func_get_args();
339 array_shift( $args );
340 return wfMsgReal( $key, $args, true, false, false );
344 * Get a message from anywhere, for the current global language
345 * set with $wgLanguageCode.
347 * Use this if the message should NOT change dependent on the
348 * language set in the user's preferences. This is the case for
349 * most text written into logs, as well as link targets (such as
350 * the name of the copyright policy page). Link titles, on the
351 * other hand, should be shown in the UI language.
353 * Note that MediaWiki allows users to change the user interface
354 * language in their preferences, but a single installation
355 * typically only contains content in one language.
357 * Be wary of this distinction: If you use wfMsg() where you should
358 * use wfMsgForContent(), a user of the software may have to
359 * customize over 70 messages in order to, e.g., fix a link in every
362 * @param $key String: lookup key for the message, usually
363 * defined in languages/Language.php
365 function wfMsgForContent( $key ) {
366 global $wgForceUIMsgAsContentMsg;
367 $args = func_get_args();
368 array_shift( $args );
370 if( is_array( $wgForceUIMsgAsContentMsg ) &&
371 in_array( $key, $wgForceUIMsgAsContentMsg ) )
373 return wfMsgReal( $key, $args, true, $forcontent );
377 * Same as above except doesn't transform the message
379 function wfMsgForContentNoTrans( $key ) {
380 global $wgForceUIMsgAsContentMsg;
381 $args = func_get_args();
382 array_shift( $args );
384 if( is_array( $wgForceUIMsgAsContentMsg ) &&
385 in_array( $key, $wgForceUIMsgAsContentMsg ) )
387 return wfMsgReal( $key, $args, true, $forcontent, false );
391 * Get a message from the language file, for the UI elements
393 function wfMsgNoDB( $key ) {
394 $args = func_get_args();
395 array_shift( $args );
396 return wfMsgReal( $key, $args, false );
400 * Get a message from the language file, for the content
402 function wfMsgNoDBForContent( $key ) {
403 global $wgForceUIMsgAsContentMsg;
404 $args = func_get_args();
405 array_shift( $args );
407 if( is_array( $wgForceUIMsgAsContentMsg ) &&
408 in_array( $key, $wgForceUIMsgAsContentMsg ) )
410 return wfMsgReal( $key, $args, false, $forcontent );
415 * Really get a message
416 * @param $key String: key to get.
418 * @param $useDB Boolean
419 * @param $transform Boolean: Whether or not to transform the message.
420 * @param $forContent Boolean
421 * @return String: the requested message.
423 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
424 wfProfileIn( __METHOD__
);
425 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
426 $message = wfMsgReplaceArgs( $message, $args );
427 wfProfileOut( __METHOD__
);
432 * This function provides the message source for messages to be edited which are *not* stored in the database.
433 * @param $key String:
435 function wfMsgWeirdKey ( $key ) {
436 $source = wfMsgGetKey( $key, false, true, false );
437 if ( wfEmptyMsg( $key, $source ) )
444 * Fetch a message string value, but don't replace any keys yet.
447 * @param string $langcode Code of the language to get the message for, or
448 * behaves as a content language switch if it is a
453 function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
454 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
456 # If $wgMessageCache isn't initialised yet, try to return something sensible.
457 if( is_object( $wgMessageCache ) ) {
458 $message = $wgMessageCache->get( $key, $useDB, $langCode );
460 $message = $wgMessageCache->transform( $message );
463 if( $langCode === true ) {
464 $lang = &$wgContLang;
465 } elseif( $langCode === false ) {
468 $validCodes = array_keys( Language
::getLanguageNames() );
469 if( in_array( $langCode, $validCodes ) ) {
470 # $langcode corresponds to a valid language.
471 $lang = Language
::factory( $langCode );
473 # $langcode is a string, but not a valid language code; use content language.
474 $lang =& $wgContLang;
475 wfDebug( 'Invalid language code passed to wfMsgGetKey, falling back to content language.' );
479 # MessageCache::get() does this already, Language::getMessage() doesn't
480 # ISSUE: Should we try to handle "message/lang" here too?
481 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
483 if( is_object( $lang ) ) {
484 $message = $lang->getMessage( $key );
494 * Replace message parameter keys on the given formatted output.
496 * @param string $message
501 function wfMsgReplaceArgs( $message, $args ) {
502 # Fix windows line-endings
503 # Some messages are split with explode("\n", $msg)
504 $message = str_replace( "\r", '', $message );
507 if ( count( $args ) ) {
508 if ( is_array( $args[0] ) ) {
509 $args = array_values( $args[0] );
511 $replacementKeys = array();
512 foreach( $args as $n => $param ) {
513 $replacementKeys['$' . ($n +
1)] = $param;
515 $message = strtr( $message, $replacementKeys );
522 * Return an HTML-escaped version of a message.
523 * Parameter replacements, if any, are done *after* the HTML-escaping,
524 * so parameters may contain HTML (eg links or form controls). Be sure
525 * to pre-escape them if you really do want plaintext, or just wrap
526 * the whole thing in htmlspecialchars().
529 * @param string ... parameters
532 function wfMsgHtml( $key ) {
533 $args = func_get_args();
534 array_shift( $args );
535 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
539 * Return an HTML version of message
540 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
541 * so parameters may contain HTML (eg links or form controls). Be sure
542 * to pre-escape them if you really do want plaintext, or just wrap
543 * the whole thing in htmlspecialchars().
546 * @param string ... parameters
549 function wfMsgWikiHtml( $key ) {
551 $args = func_get_args();
552 array_shift( $args );
553 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
557 * Returns message in the requested format
558 * @param string $key Key of the message
559 * @param array $options Processing rules:
560 * <i>parse</i>: parses wikitext to html
561 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
562 * <i>escape</i>: filters message through htmlspecialchars
563 * <i>escapenoentities</i>: same, but allows entity references like through
564 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
565 * <i>parsemag</i>: transform the message using magic phrases
566 * <i>content</i>: fetch message for content language instead of interface
567 * <i>language</i>: language code to fetch message for (overriden by <i>content</i>), its behaviour
568 * with parser, parseinline and parsemag is undefined.
569 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
571 function wfMsgExt( $key, $options ) {
572 global $wgOut, $wgParser;
574 $args = func_get_args();
575 array_shift( $args );
576 array_shift( $args );
578 if( !is_array($options) ) {
579 $options = array($options);
582 if( in_array('content', $options) ) {
585 } elseif( array_key_exists('language', $options) ) {
587 $langCode = $options['language'];
588 $validCodes = array_keys( Language
::getLanguageNames() );
589 if( !in_array($options['language'], $validCodes) ) {
597 $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
599 if( !in_array('replaceafter', $options) ) {
600 $string = wfMsgReplaceArgs( $string, $args );
603 if( in_array('parse', $options) ) {
604 $string = $wgOut->parse( $string, true, !$forContent );
605 } elseif ( in_array('parseinline', $options) ) {
606 $string = $wgOut->parse( $string, true, !$forContent );
608 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
611 } elseif ( in_array('parsemag', $options) ) {
612 global $wgMessageCache;
613 if ( isset( $wgMessageCache ) ) {
614 $string = $wgMessageCache->transform( $string, !$forContent );
618 if ( in_array('escape', $options) ) {
619 $string = htmlspecialchars ( $string );
620 } elseif ( in_array( 'escapenoentities', $options ) ) {
621 $string = htmlspecialchars( $string );
622 $string = str_replace( '&', '&', $string );
623 $string = Sanitizer
::normalizeCharReferences( $string );
626 if( in_array('replaceafter', $options) ) {
627 $string = wfMsgReplaceArgs( $string, $args );
635 * Just like exit() but makes a note of it.
636 * Commits open transactions except if the error parameter is set
638 * @deprecated Please return control to the caller or throw an exception
640 function wfAbruptExit( $error = false ){
641 static $called = false;
647 $bt = wfDebugBacktrace();
649 for($i = 0; $i < count($bt) ; $i++
){
650 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
651 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
652 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
655 wfDebug('WARNING: Abrupt exit\n');
658 wfLogProfilingData();
661 wfGetLB()->closeAll();
667 * @deprecated Please return control the caller or throw an exception
669 function wfErrorExit() {
670 wfAbruptExit( true );
674 * Print a simple message and die, returning nonzero to the shell if any.
675 * Plain die() fails to return nonzero to the shell if you pass a string.
678 function wfDie( $msg='' ) {
684 * Throw a debugging exception. This function previously once exited the process,
685 * but now throws an exception instead, with similar results.
687 * @param string $msg Message shown when dieing.
689 function wfDebugDieBacktrace( $msg = '' ) {
690 throw new MWException( $msg );
694 * Fetch server name for use in error reporting etc.
695 * Use real server name if available, so we know which machine
696 * in a server farm generated the current page.
699 function wfHostname() {
700 if ( function_exists( 'posix_uname' ) ) {
701 // This function not present on Windows
702 $uname = @posix_uname
();
706 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
707 return $uname['nodename'];
709 # This may be a virtual server.
710 return $_SERVER['SERVER_NAME'];
715 * Returns a HTML comment with the elapsed time since request.
716 * This method has no side effects.
719 function wfReportTime() {
720 global $wgRequestTime, $wgShowHostnames;
723 $elapsed = $now - $wgRequestTime;
725 return $wgShowHostnames
726 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
727 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
731 * Safety wrapper for debug_backtrace().
733 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
734 * murky circumstances, which may be triggered in part by stub objects
735 * or other fancy talkin'.
737 * Will return an empty array if Zend Optimizer is detected, otherwise
738 * the output from debug_backtrace() (trimmed).
740 * @return array of backtrace information
742 function wfDebugBacktrace() {
743 if( extension_loaded( 'Zend Optimizer' ) ) {
744 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
747 return array_slice( debug_backtrace(), 1 );
751 function wfBacktrace() {
752 global $wgCommandLineMode;
754 if ( $wgCommandLineMode ) {
759 $backtrace = wfDebugBacktrace();
760 foreach( $backtrace as $call ) {
761 if( isset( $call['file'] ) ) {
762 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
763 $file = $f[count($f)-1];
767 if( isset( $call['line'] ) ) {
768 $line = $call['line'];
772 if ( $wgCommandLineMode ) {
773 $msg .= "$file line $line calls ";
775 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
777 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
778 $msg .= $call['function'] . '()';
780 if ( $wgCommandLineMode ) {
786 if ( $wgCommandLineMode ) {
796 /* Some generic result counters, pulled out of SearchEngine */
802 function wfShowingResults( $offset, $limit ) {
804 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
810 function wfShowingResultsNum( $offset, $limit, $num ) {
812 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
818 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
820 $fmtLimit = $wgLang->formatNum( $limit );
821 $prev = wfMsg( 'prevn', $fmtLimit );
822 $next = wfMsg( 'nextn', $fmtLimit );
824 if( is_object( $link ) ) {
827 $title = Title
::newFromText( $link );
828 if( is_null( $title ) ) {
833 if ( 0 != $offset ) {
834 $po = $offset - $limit;
835 if ( $po < 0 ) { $po = 0; }
836 $q = "limit={$limit}&offset={$po}";
837 if ( '' != $query ) { $q .= '&'.$query; }
838 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
839 } else { $plink = $prev; }
841 $no = $offset +
$limit;
842 $q = 'limit='.$limit.'&offset='.$no;
843 if ( '' != $query ) { $q .= '&'.$query; }
848 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
850 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
851 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
852 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
853 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
854 wfNumLink( $offset, 500, $title, $query );
856 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
862 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
864 if ( '' == $query ) { $q = ''; }
865 else { $q = $query.'&'; }
866 $q .= 'limit='.$limit.'&offset='.$offset;
868 $fmtLimit = $wgLang->formatNum( $limit );
869 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
875 * @todo FIXME: we may want to blacklist some broken browsers
877 * @return bool Whereas client accept gzip compression
879 function wfClientAcceptsGzip() {
882 # FIXME: we may want to blacklist some broken browsers
885 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
886 $_SERVER['HTTP_ACCEPT_ENCODING'],
888 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
889 wfDebug( " accepts gzip\n" );
897 * Obtain the offset and limit values from the request string;
898 * used in special pages
900 * @param $deflimit Default limit if none supplied
901 * @param $optionname Name of a user preference to check against
905 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
907 return $wgRequest->getLimitOffset( $deflimit, $optionname );
911 * Escapes the given text so that it may be output using addWikiText()
912 * without any linking, formatting, etc. making its way through. This
913 * is achieved by substituting certain characters with HTML entities.
914 * As required by the callers, <nowiki> is not used. It currently does
915 * not filter out characters which have special meaning only at the
916 * start of a line, such as "*".
918 * @param string $text Text to be escaped
920 function wfEscapeWikiText( $text ) {
922 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
923 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
924 htmlspecialchars($text) );
931 function wfQuotedPrintable( $string, $charset = '' ) {
932 # Probably incomplete; see RFC 2045
933 if( empty( $charset ) ) {
934 global $wgInputEncoding;
935 $charset = $wgInputEncoding;
937 $charset = strtoupper( $charset );
938 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
940 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
941 $replace = $illegal . '\t ?_';
942 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
943 $out = "=?$charset?Q?";
944 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
955 return microtime(true);
959 * Sets dest to source and returns the original value of dest
960 * If source is NULL, it just returns the value, it doesn't set the variable
962 function wfSetVar( &$dest, $source ) {
964 if ( !is_null( $source ) ) {
971 * As for wfSetVar except setting a bit
973 function wfSetBit( &$dest, $bit, $state = true ) {
974 $temp = (bool)($dest & $bit );
975 if ( !is_null( $state ) ) {
986 * This function takes two arrays as input, and returns a CGI-style string, e.g.
987 * "days=7&limit=100". Options in the first array override options in the second.
988 * Options set to "" will not be output.
990 function wfArrayToCGI( $array1, $array2 = NULL )
992 if ( !is_null( $array2 ) ) {
993 $array1 = $array1 +
$array2;
997 foreach ( $array1 as $key => $value ) {
998 if ( '' !== $value ) {
1002 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
1008 * Build a query string from complex data input and return.
1010 * @param mixed $query The query data to build the string from
1011 * @param string $prefix A prefix to add to numeric keys to make them valid
1012 * @param string $dataKey A key name to use on the data
1013 * @return string The query string
1015 function wfBuildQuery( $query, $prefix = null, $dataKey = null ) {
1016 # Passthrough strings and blank data
1017 if( is_null($query) ||
is_string($query) ) return (string) $query;
1019 # Recursively build the query.
1022 foreach( (array) $query as $key => $value ) {
1023 if( is_int($key) && $prefix != null ) {
1024 # Prefix numeric keys when given a prefix.
1025 $key = "{$prefix}{$key}";
1027 if( isset($dataKey) && $dataKey != '' ) {
1028 # Add array type data to keys when needed
1029 # but don't add the key inside the [] when they are sequential
1030 if( $keyNum === $key ) $key = "{$dataKey}[]";
1031 else $key = "{$dataKey}[{$key}]";
1034 # Push the data onto the end of the array recursing if needed.
1036 is_array($value) ||
is_object($value)
1037 ?
wfBuildQuery($value,null,$key)
1038 : urlencode($key)."=".urlencode($value) );
1041 # Implode and return.
1042 return implode('&', $data);
1046 * Parse a query string into an array.
1048 * @param mixed $query The query string to parse
1049 * @return array The array data for the query
1051 function wfParseQuery( $query ) {
1052 # Passthrough non-strings.
1053 if( !is_string($query) ) return $query;
1056 # Separate all name-value pairs
1057 $pairs = explode('&', $query);
1058 foreach($pairs as $pair) {
1059 # Pull out the names and the values
1060 list($name, $value) = explode('=', $pair, 2);
1061 # Decode the variable name and look for arrays
1063 $name = urldecode($name);
1064 if( preg_match('/^(.*?)((\[.*?\])+)$/S', $name, $m) !== 0 ) {
1067 $indexes = explode( '][', substr( $braces, 1, -1 ) );
1069 if(!isset($data[$name])) $data[$name] = array();
1070 $recursive =& $data[$name];
1071 foreach( $indexes as $index ) {
1072 if( $index != "" ) {
1073 if(!isset($recursive[$index])) $recursive[$index] = array();
1074 $recursive =& $recursive[$index];
1076 $i = array_push( $recursive, array() ) - 1;
1077 $recursive =& $recursive[$i];
1080 $recursive = urldecode($value);
1082 $data[$name] = urldecode($value);
1089 * Append a query string to an existing URL, which may or may not already
1090 * have query string parameters already. If so, they will be combined.
1092 * @param string $url
1093 * @param string $query
1096 function wfAppendQuery( $url, $query ) {
1097 if( $query != '' ) {
1098 if( false === strpos( $url, '?' ) ) {
1109 * Expand a potentially local URL to a fully-qualified URL.
1110 * Assumes $wgServer is correct. :)
1111 * @param string $url, either fully-qualified or a local path + query
1112 * @return string Fully-qualified URL
1114 function wfExpandUrl( $url ) {
1115 if( substr( $url, 0, 1 ) == '/' ) {
1117 return $wgServer . $url;
1124 * This is obsolete, use SquidUpdate::purge()
1127 function wfPurgeSquidServers ($urlArr) {
1128 SquidUpdate
::purge( $urlArr );
1132 * Windows-compatible version of escapeshellarg()
1133 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1134 * function puts single quotes in regardless of OS
1136 function wfEscapeShellArg( ) {
1137 $args = func_get_args();
1140 foreach ( $args as $arg ) {
1147 if ( wfIsWindows() ) {
1148 // Escaping for an MSVC-style command line parser
1149 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1150 // Double the backslashes before any double quotes. Escape the double quotes.
1151 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1154 foreach ( $tokens as $token ) {
1156 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1162 // Double the backslashes before the end of the string, because
1163 // we will soon add a quote
1165 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1166 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1169 // Add surrounding quotes
1170 $retVal .= '"' . $arg . '"';
1172 $retVal .= escapeshellarg( $arg );
1179 * wfMerge attempts to merge differences between three texts.
1180 * Returns true for a clean merge and false for failure or a conflict.
1182 function wfMerge( $old, $mine, $yours, &$result ){
1185 # This check may also protect against code injection in
1186 # case of broken installations.
1187 if(! file_exists( $wgDiff3 ) ){
1188 wfDebug( "diff3 not found\n" );
1192 # Make temporary files
1194 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1195 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1196 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1198 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1199 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1200 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1202 # Check for a conflict
1203 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1204 wfEscapeShellArg( $mytextName ) . ' ' .
1205 wfEscapeShellArg( $oldtextName ) . ' ' .
1206 wfEscapeShellArg( $yourtextName );
1207 $handle = popen( $cmd, 'r' );
1209 if( fgets( $handle, 1024 ) ){
1217 $cmd = $wgDiff3 . ' -a -e --merge ' .
1218 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1219 $handle = popen( $cmd, 'r' );
1222 $data = fread( $handle, 8192 );
1223 if ( strlen( $data ) == 0 ) {
1229 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1231 if ( $result === '' && $old !== '' && $conflict == false ) {
1232 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1241 function wfVarDump( $var ) {
1243 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1244 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1247 $wgOut->addHTML( $s );
1252 * Provide a simple HTTP error.
1254 function wfHttpError( $code, $label, $desc ) {
1257 header( "HTTP/1.0 $code $label" );
1258 header( "Status: $code $label" );
1259 $wgOut->sendCacheControl();
1261 header( 'Content-type: text/html; charset=utf-8' );
1262 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1263 "<html><head><title>" .
1264 htmlspecialchars( $label ) .
1265 "</title></head><body><h1>" .
1266 htmlspecialchars( $label ) .
1268 nl2br( htmlspecialchars( $desc ) ) .
1269 "</p></body></html>\n";
1273 * Clear away any user-level output buffers, discarding contents.
1275 * Suitable for 'starting afresh', for instance when streaming
1276 * relatively large amounts of data without buffering, or wanting to
1277 * output image files without ob_gzhandler's compression.
1279 * The optional $resetGzipEncoding parameter controls suppression of
1280 * the Content-Encoding header sent by ob_gzhandler; by default it
1281 * is left. See comments for wfClearOutputBuffers() for why it would
1284 * Note that some PHP configuration options may add output buffer
1285 * layers which cannot be removed; these are left in place.
1287 * @param bool $resetGzipEncoding
1289 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1290 if( $resetGzipEncoding ) {
1291 // Suppress Content-Encoding and Content-Length
1292 // headers from 1.10+s wfOutputHandler
1293 global $wgDisableOutputCompression;
1294 $wgDisableOutputCompression = true;
1296 while( $status = ob_get_status() ) {
1297 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1298 // Probably from zlib.output_compression or other
1299 // PHP-internal setting which can't be removed.
1301 // Give up, and hope the result doesn't break
1305 if( !ob_end_clean() ) {
1306 // Could not remove output buffer handler; abort now
1307 // to avoid getting in some kind of infinite loop.
1310 if( $resetGzipEncoding ) {
1311 if( $status['name'] == 'ob_gzhandler' ) {
1312 // Reset the 'Content-Encoding' field set by this handler
1313 // so we can start fresh.
1314 header( 'Content-Encoding:' );
1321 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1323 * Clear away output buffers, but keep the Content-Encoding header
1324 * produced by ob_gzhandler, if any.
1326 * This should be used for HTTP 304 responses, where you need to
1327 * preserve the Content-Encoding header of the real result, but
1328 * also need to suppress the output of ob_gzhandler to keep to spec
1329 * and avoid breaking Firefox in rare cases where the headers and
1330 * body are broken over two packets.
1332 function wfClearOutputBuffers() {
1333 wfResetOutputBuffers( false );
1337 * Converts an Accept-* header into an array mapping string values to quality
1340 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1341 # No arg means accept anything (per HTTP spec)
1343 return array( $def => 1 );
1348 $parts = explode( ',', $accept );
1350 foreach( $parts as $part ) {
1351 # FIXME: doesn't deal with params like 'text/html; level=1'
1352 @list
( $value, $qpart ) = explode( ';', $part );
1354 if( !isset( $qpart ) ) {
1356 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1357 $prefs[$value] = $match[1];
1365 * Checks if a given MIME type matches any of the keys in the given
1366 * array. Basic wildcards are accepted in the array keys.
1368 * Returns the matching MIME type (or wildcard) if a match, otherwise
1371 * @param string $type
1372 * @param array $avail
1376 function mimeTypeMatch( $type, $avail ) {
1377 if( array_key_exists($type, $avail) ) {
1380 $parts = explode( '/', $type );
1381 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1382 return $parts[0] . '/*';
1383 } elseif( array_key_exists( '*/*', $avail ) ) {
1392 * Returns the 'best' match between a client's requested internet media types
1393 * and the server's list of available types. Each list should be an associative
1394 * array of type to preference (preference is a float between 0.0 and 1.0).
1395 * Wildcards in the types are acceptable.
1397 * @param array $cprefs Client's acceptable type list
1398 * @param array $sprefs Server's offered types
1401 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1402 * XXX: generalize to negotiate other stuff
1404 function wfNegotiateType( $cprefs, $sprefs ) {
1407 foreach( array_keys($sprefs) as $type ) {
1408 $parts = explode( '/', $type );
1409 if( $parts[1] != '*' ) {
1410 $ckey = mimeTypeMatch( $type, $cprefs );
1412 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1417 foreach( array_keys( $cprefs ) as $type ) {
1418 $parts = explode( '/', $type );
1419 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1420 $skey = mimeTypeMatch( $type, $sprefs );
1422 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1430 foreach( array_keys( $combine ) as $type ) {
1431 if( $combine[$type] > $bestq ) {
1433 $bestq = $combine[$type];
1442 * Returns an array where the values in the first array are replaced by the
1443 * values in the second array with the corresponding keys
1447 function wfArrayLookup( $a, $b ) {
1448 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1452 * Convenience function; returns MediaWiki timestamp for the present time.
1455 function wfTimestampNow() {
1457 return wfTimestamp( TS_MW
, time() );
1461 * Reference-counted warning suppression
1463 function wfSuppressWarnings( $end = false ) {
1464 static $suppressCount = 0;
1465 static $originalLevel = false;
1468 if ( $suppressCount ) {
1470 if ( !$suppressCount ) {
1471 error_reporting( $originalLevel );
1475 if ( !$suppressCount ) {
1476 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1483 * Restore error level to previous value
1485 function wfRestoreWarnings() {
1486 wfSuppressWarnings( true );
1489 # Autodetect, convert and provide timestamps of various types
1492 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1494 define('TS_UNIX', 0);
1497 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1502 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1507 * RFC 2822 format, for E-mail and HTTP headers
1509 define('TS_RFC2822', 3);
1512 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1514 * This is used by Special:Export
1516 define('TS_ISO_8601', 4);
1519 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1521 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1522 * DateTime tag and page 36 for the DateTimeOriginal and
1523 * DateTimeDigitized tags.
1525 define('TS_EXIF', 5);
1528 * Oracle format time.
1530 define('TS_ORACLE', 6);
1533 * Postgres format time.
1535 define('TS_POSTGRES', 7);
1538 * @param mixed $outputtype A timestamp in one of the supported formats, the
1539 * function will autodetect which format is supplied
1540 * and act accordingly.
1541 * @return string Time in the format specified in $outputtype
1543 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1548 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1550 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1552 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1554 } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
1557 } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
1559 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1560 str_replace("+00:00", "UTC", $ts)));
1561 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1563 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1565 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1568 # Bogus value; fall back to the epoch...
1569 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1573 if (count( $da ) ) {
1574 // Warning! gmmktime() acts oddly if the month or day is set to 0
1575 // We may want to handle that explicitly at some point
1576 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1577 (int)$da[2],(int)$da[3],(int)$da[1]);
1580 switch($outputtype) {
1584 return gmdate( 'YmdHis', $uts );
1586 return gmdate( 'Y-m-d H:i:s', $uts );
1588 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1589 // This shouldn't ever be used, but is included for completeness
1591 return gmdate( 'Y:m:d H:i:s', $uts );
1593 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1595 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1597 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1599 throw new MWException( 'wfTimestamp() called with illegal output type.');
1604 * Return a formatted timestamp, or null if input is null.
1605 * For dealing with nullable timestamp columns in the database.
1606 * @param int $outputtype
1610 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1611 if( is_null( $ts ) ) {
1614 return wfTimestamp( $outputtype, $ts );
1619 * Check if the operating system is Windows
1621 * @return bool True if it's Windows, False otherwise.
1623 function wfIsWindows() {
1624 if (substr(php_uname(), 0, 7) == 'Windows') {
1632 * Swap two variables
1634 function swap( &$x, &$y ) {
1640 function wfGetCachedNotice( $name ) {
1641 global $wgOut, $parserMemc;
1642 $fname = 'wfGetCachedNotice';
1643 wfProfileIn( $fname );
1647 if( $name === 'default' ) {
1649 global $wgSiteNotice;
1650 $notice = $wgSiteNotice;
1651 if( empty( $notice ) ) {
1652 wfProfileOut( $fname );
1656 $notice = wfMsgForContentNoTrans( $name );
1657 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1658 wfProfileOut( $fname );
1663 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1664 if( is_array( $cachedNotice ) ) {
1665 if( md5( $notice ) == $cachedNotice['hash'] ) {
1666 $notice = $cachedNotice['html'];
1675 if( is_object( $wgOut ) ) {
1676 $parsed = $wgOut->parse( $notice );
1677 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1680 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1685 wfProfileOut( $fname );
1689 function wfGetNamespaceNotice() {
1693 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1696 $fname = 'wfGetNamespaceNotice';
1697 wfProfileIn( $fname );
1699 $key = "namespacenotice-" . $wgTitle->getNsText();
1700 $namespaceNotice = wfGetCachedNotice( $key );
1701 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1702 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1704 $namespaceNotice = "";
1707 wfProfileOut( $fname );
1708 return $namespaceNotice;
1711 function wfGetSiteNotice() {
1712 global $wgUser, $wgSiteNotice;
1713 $fname = 'wfGetSiteNotice';
1714 wfProfileIn( $fname );
1717 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1718 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1719 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1721 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1722 if( !$anonNotice ) {
1723 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1725 $siteNotice = $anonNotice;
1728 if( !$siteNotice ) {
1729 $siteNotice = wfGetCachedNotice( 'default' );
1733 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1734 wfProfileOut( $fname );
1739 * BC wrapper for MimeMagic::singleton()
1742 function &wfGetMimeMagic() {
1743 return MimeMagic
::singleton();
1747 * Tries to get the system directory for temporary files.
1748 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1749 * and if none are set /tmp is returned as the generic Unix default.
1751 * NOTE: When possible, use the tempfile() function to create temporary
1752 * files to avoid race conditions on file creation, etc.
1756 function wfTempDir() {
1757 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1758 $tmp = getenv( $var );
1759 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1763 # Hope this is Unix of some kind!
1768 * Make directory, and make all parent directories if they don't exist
1770 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1771 if( strval( $fullDir ) === '' )
1773 if( file_exists( $fullDir ) )
1775 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR
, $fullDir ), $mode, true );
1779 * Increment a statistics counter
1781 function wfIncrStats( $key ) {
1782 global $wgStatsMethod;
1784 if( $wgStatsMethod == 'udp' ) {
1785 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1788 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1789 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1790 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1792 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1793 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1794 } elseif( $wgStatsMethod == 'cache' ) {
1796 $key = wfMemcKey( 'stats', $key );
1797 if ( is_null( $wgMemc->incr( $key ) ) ) {
1798 $wgMemc->add( $key, 1 );
1806 * @param mixed $nr The number to format
1807 * @param int $acc The number of digits after the decimal point, default 2
1808 * @param bool $round Whether or not to round the value, default true
1811 function wfPercent( $nr, $acc = 2, $round = true ) {
1812 $ret = sprintf( "%.${acc}f", $nr );
1813 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1817 * Encrypt a username/password.
1819 * @param string $userid ID of the user
1820 * @param string $password Password of the user
1821 * @return string Hashed password
1823 function wfEncryptPassword( $userid, $password ) {
1824 global $wgPasswordSalt;
1825 $p = md5( $password);
1828 return md5( "{$userid}-{$p}" );
1834 * Appends to second array if $value differs from that in $default
1836 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1837 if ( is_null( $changed ) ) {
1838 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1840 if ( $default[$key] !== $value ) {
1841 $changed[$key] = $value;
1846 * Since wfMsg() and co suck, they don't return false if the message key they
1847 * looked up didn't exist but a XHTML string, this function checks for the
1848 * nonexistance of messages by looking at wfMsg() output
1850 * @param $msg The message key looked up
1851 * @param $wfMsgOut The output of wfMsg*()
1854 function wfEmptyMsg( $msg, $wfMsgOut ) {
1855 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1859 * Find out whether or not a mixed variable exists in a string
1861 * @param mixed needle
1862 * @param string haystack
1865 function in_string( $needle, $str ) {
1866 return strpos( $str, $needle ) !== false;
1869 function wfSpecialList( $page, $details ) {
1871 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1872 return $page . $details;
1876 * Returns a regular expression of url protocols
1880 function wfUrlProtocols() {
1881 global $wgUrlProtocols;
1883 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1884 // with LocalSettings files from 1.5
1885 if ( is_array( $wgUrlProtocols ) ) {
1886 $protocols = array();
1887 foreach ($wgUrlProtocols as $protocol)
1888 $protocols[] = preg_quote( $protocol, '/' );
1890 return implode( '|', $protocols );
1892 return $wgUrlProtocols;
1897 * Safety wrapper around ini_get() for boolean settings.
1898 * The values returned from ini_get() are pre-normalized for settings
1899 * set via php.ini or php_flag/php_admin_flag... but *not*
1900 * for those set via php_value/php_admin_value.
1902 * It's fairly common for people to use php_value instead of php_flag,
1903 * which can leave you with an 'off' setting giving a false positive
1904 * for code that just takes the ini_get() return value as a boolean.
1906 * To make things extra interesting, setting via php_value accepts
1907 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1908 * Unrecognized values go false... again opposite PHP's own coercion
1909 * from string to bool.
1911 * Luckily, 'properly' set settings will always come back as '0' or '1',
1912 * so we only have to worry about them and the 'improper' settings.
1914 * I frickin' hate PHP... :P
1916 * @param string $setting
1919 function wfIniGetBool( $setting ) {
1920 $val = ini_get( $setting );
1921 // 'on' and 'true' can't have whitespace around them, but '1' can.
1922 return strtolower( $val ) == 'on'
1923 ||
strtolower( $val ) == 'true'
1924 ||
strtolower( $val ) == 'yes'
1925 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1929 * Execute a shell command, with time and memory limits mirrored from the PHP
1930 * configuration if supported.
1931 * @param $cmd Command line, properly escaped for shell.
1932 * @param &$retval optional, will receive the program's exit code.
1933 * (non-zero is usually failure)
1934 * @return collected stdout as a string (trailing newlines stripped)
1936 function wfShellExec( $cmd, &$retval=null ) {
1937 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1939 if( wfIniGetBool( 'safe_mode' ) ) {
1940 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1942 return "Unable to run external programs in safe mode.";
1945 if ( php_uname( 's' ) == 'Linux' ) {
1946 $time = intval( ini_get( 'max_execution_time' ) );
1947 $mem = intval( $wgMaxShellMemory );
1948 $filesize = intval( $wgMaxShellFileSize );
1950 if ( $time > 0 && $mem > 0 ) {
1951 $script = "$IP/bin/ulimit4.sh";
1952 if ( is_executable( $script ) ) {
1953 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1956 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1957 # This is a hack to work around PHP's flawed invocation of cmd.exe
1958 # http://news.php.net/php.internals/21796
1959 $cmd = '"' . $cmd . '"';
1961 wfDebug( "wfShellExec: $cmd\n" );
1963 $retval = 1; // error by default?
1965 passthru( $cmd, $retval );
1966 $output = ob_get_contents();
1973 * This function works like "use VERSION" in Perl, the program will die with a
1974 * backtrace if the current version of PHP is less than the version provided
1976 * This is useful for extensions which due to their nature are not kept in sync
1977 * with releases, and might depend on other versions of PHP than the main code
1979 * Note: PHP might die due to parsing errors in some cases before it ever
1980 * manages to call this function, such is life
1982 * @see perldoc -f use
1984 * @param mixed $version The version to check, can be a string, an integer, or
1987 function wfUsePHP( $req_ver ) {
1988 $php_ver = PHP_VERSION
;
1990 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1991 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1995 * This function works like "use VERSION" in Perl except it checks the version
1996 * of MediaWiki, the program will die with a backtrace if the current version
1997 * of MediaWiki is less than the version provided.
1999 * This is useful for extensions which due to their nature are not kept in sync
2002 * @see perldoc -f use
2004 * @param mixed $version The version to check, can be a string, an integer, or
2007 function wfUseMW( $req_ver ) {
2010 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
2011 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
2015 * @deprecated use StringUtils::escapeRegexReplacement
2017 function wfRegexReplacement( $string ) {
2018 return StringUtils
::escapeRegexReplacement( $string );
2022 * Return the final portion of a pathname.
2023 * Reimplemented because PHP5's basename() is buggy with multibyte text.
2024 * http://bugs.php.net/bug.php?id=33898
2026 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
2027 * We'll consider it so always, as we don't want \s in our Unix paths either.
2029 * @param string $path
2030 * @param string $suffix to remove if present
2033 function wfBaseName( $path, $suffix='' ) {
2034 $encSuffix = ($suffix == '')
2036 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
2038 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
2046 * Generate a relative path name to the given file.
2047 * May explode on non-matching case-insensitive paths,
2048 * funky symlinks, etc.
2050 * @param string $path Absolute destination path including target filename
2051 * @param string $from Absolute source path, directory only
2054 function wfRelativePath( $path, $from ) {
2055 // Normalize mixed input on Windows...
2056 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
2057 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
2059 // Trim trailing slashes -- fix for drive root
2060 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
2061 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
2063 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
2064 $against = explode( DIRECTORY_SEPARATOR
, $from );
2066 if( $pieces[0] !== $against[0] ) {
2067 // Non-matching Windows drive letters?
2068 // Return a full path.
2072 // Trim off common prefix
2073 while( count( $pieces ) && count( $against )
2074 && $pieces[0] == $against[0] ) {
2075 array_shift( $pieces );
2076 array_shift( $against );
2079 // relative dots to bump us to the parent
2080 while( count( $against ) ) {
2081 array_unshift( $pieces, '..' );
2082 array_shift( $against );
2085 array_push( $pieces, wfBaseName( $path ) );
2087 return implode( DIRECTORY_SEPARATOR
, $pieces );
2091 * array_merge() does awful things with "numeric" indexes, including
2092 * string indexes when happen to look like integers. When we want
2093 * to merge arrays with arbitrary string indexes, we don't want our
2094 * arrays to be randomly corrupted just because some of them consist
2097 * Fuck you, PHP. Fuck you in the ear!
2099 * @param array $array1, [$array2, [...]]
2102 function wfArrayMerge( $array1/* ... */ ) {
2104 for( $i = 1; $i < func_num_args(); $i++
) {
2105 foreach( func_get_arg( $i ) as $key => $value ) {
2106 $out[$key] = $value;
2113 * Make a URL index, appropriate for the el_index field of externallinks.
2115 function wfMakeUrlIndex( $url ) {
2116 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2117 wfSuppressWarnings();
2118 $bits = parse_url( $url );
2119 wfRestoreWarnings();
2123 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2125 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2127 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2129 // parse_url detects for news: and mailto: the host part of an url as path
2130 // We have to correct this wrong detection
2131 if ( isset ( $bits['path'] ) ) {
2132 $bits['host'] = $bits['path'];
2139 // Reverse the labels in the hostname, convert to lower case
2140 // For emails reverse domainpart only
2141 if ( $bits['scheme'] == 'mailto' ) {
2142 $mailparts = explode( '@', $bits['host'], 2 );
2143 if ( count($mailparts) === 2 ) {
2144 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2146 // No domain specified, don't mangle it
2149 $reversedHost = $domainpart . '@' . $mailparts[0];
2151 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2153 // Add an extra dot to the end
2154 // Why? Is it in wrong place in mailto links?
2155 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2156 $reversedHost .= '.';
2158 // Reconstruct the pseudo-URL
2159 $prot = $bits['scheme'];
2160 $index = "$prot$delimiter$reversedHost";
2161 // Leave out user and password. Add the port, path, query and fragment
2162 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2163 if ( isset( $bits['path'] ) ) {
2164 $index .= $bits['path'];
2168 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2169 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2174 * Do any deferred updates and clear the list
2175 * TODO: This could be in Wiki.php if that class made any sense at all
2177 function wfDoUpdates()
2179 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2180 foreach ( $wgDeferredUpdateList as $update ) {
2181 $update->doUpdate();
2183 foreach ( $wgPostCommitUpdateList as $update ) {
2184 $update->doUpdate();
2186 $wgDeferredUpdateList = array();
2187 $wgPostCommitUpdateList = array();
2191 * @deprecated use StringUtils::explodeMarkup
2193 function wfExplodeMarkup( $separator, $text ) {
2194 return StringUtils
::explodeMarkup( $separator, $text );
2198 * Convert an arbitrarily-long digit string from one numeric base
2199 * to another, optionally zero-padding to a minimum column width.
2201 * Supports base 2 through 36; digit values 10-36 are represented
2202 * as lowercase letters a-z. Input is case-insensitive.
2204 * @param $input string of digits
2205 * @param $sourceBase int 2-36
2206 * @param $destBase int 2-36
2207 * @param $pad int 1 or greater
2208 * @param $lowercase bool
2209 * @return string or false on invalid input
2211 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2212 $input = strval( $input );
2213 if( $sourceBase < 2 ||
2218 $sourceBase != intval( $sourceBase ) ||
2219 $destBase != intval( $destBase ) ||
2220 $pad != intval( $pad ) ||
2221 !is_string( $input ) ||
2225 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2226 $inDigits = array();
2229 // Decode and validate input string
2230 $input = strtolower( $input );
2231 for( $i = 0; $i < strlen( $input ); $i++
) {
2232 $n = strpos( $digitChars, $input{$i} );
2233 if( $n === false ||
$n > $sourceBase ) {
2239 // Iterate over the input, modulo-ing out an output digit
2240 // at a time until input is gone.
2241 while( count( $inDigits ) ) {
2243 $workDigits = array();
2246 foreach( $inDigits as $digit ) {
2247 $work *= $sourceBase;
2250 if( $work < $destBase ) {
2251 // Gonna need to pull another digit.
2252 if( count( $workDigits ) ) {
2253 // Avoid zero-padding; this lets us find
2254 // the end of the input very easily when
2255 // length drops to zero.
2259 // Finally! Actual division!
2260 $workDigits[] = intval( $work / $destBase );
2262 // Isn't it annoying that most programming languages
2263 // don't have a single divide-and-remainder operator,
2264 // even though the CPU implements it that way?
2265 $work = $work %
$destBase;
2269 // All that division leaves us with a remainder,
2270 // which is conveniently our next output digit.
2271 $outChars .= $digitChars[$work];
2274 $inDigits = $workDigits;
2277 while( strlen( $outChars ) < $pad ) {
2281 return strrev( $outChars );
2285 * Create an object with a given name and an array of construct parameters
2286 * @param string $name
2287 * @param array $p parameters
2289 function wfCreateObject( $name, $p ){
2290 $p = array_values( $p );
2291 switch ( count( $p ) ) {
2295 return new $name( $p[0] );
2297 return new $name( $p[0], $p[1] );
2299 return new $name( $p[0], $p[1], $p[2] );
2301 return new $name( $p[0], $p[1], $p[2], $p[3] );
2303 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2305 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2307 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2312 * Aliases for modularized functions
2314 function wfGetHTTP( $url, $timeout = 'default' ) {
2315 return Http
::get( $url, $timeout );
2317 function wfIsLocalURL( $url ) {
2318 return Http
::isLocalURL( $url );
2321 function wfHttpOnlySafe() {
2322 global $wgHttpOnlyBlacklist;
2323 if( !version_compare("5.2", PHP_VERSION
, "<") )
2326 if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
2327 foreach( $wgHttpOnlyBlacklist as $regex ) {
2328 if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
2338 * Initialise php session
2340 function wfSetupSession() {
2341 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
2342 if( $wgSessionsInMemcached ) {
2343 require_once( 'MemcachedSessions.php' );
2344 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2345 # If it's left on 'user' or another setting from another
2346 # application, it will end up failing. Try to recover.
2347 ini_set ( 'session.save_handler', 'files' );
2349 $httpOnlySafe = wfHttpOnlySafe();
2350 wfDebugLog( 'cookie',
2351 'session_set_cookie_params: "' . implode( '", "',
2357 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2358 if( $httpOnlySafe && $wgCookieHttpOnly ) {
2359 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
2361 // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
2362 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2364 session_cache_limiter( 'private, must-revalidate' );
2365 wfSuppressWarnings();
2367 wfRestoreWarnings();
2371 * Get an object from the precompiled serialized directory
2373 * @return mixed The variable on success, false on failure
2375 function wfGetPrecompiledData( $name ) {
2378 $file = "$IP/serialized/$name";
2379 if ( file_exists( $file ) ) {
2380 $blob = file_get_contents( $file );
2382 return unserialize( $blob );
2388 function wfGetCaller( $level = 2 ) {
2389 $backtrace = wfDebugBacktrace();
2390 if ( isset( $backtrace[$level] ) ) {
2391 return wfFormatStackFrame($backtrace[$level]);
2393 $caller = 'unknown';
2398 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2399 function wfGetAllCallers() {
2400 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2403 /** Return a string representation of frame */
2404 function wfFormatStackFrame($frame) {
2405 return isset( $frame["class"] )?
2406 $frame["class"]."::".$frame["function"]:
2413 function wfMemcKey( /*... */ ) {
2414 $args = func_get_args();
2415 $key = wfWikiID() . ':' . implode( ':', $args );
2420 * Get a cache key for a foreign DB
2422 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2423 $args = array_slice( func_get_args(), 2 );
2425 $key = "$db-$prefix:" . implode( ':', $args );
2427 $key = $db . ':' . implode( ':', $args );
2433 * Get an ASCII string identifying this wiki
2434 * This is used as a prefix in memcached keys
2436 function wfWikiID( $db = null ) {
2437 if( $db instanceof Database
) {
2438 return $db->getWikiID();
2440 global $wgDBprefix, $wgDBname;
2441 if ( $wgDBprefix ) {
2442 return "$wgDBname-$wgDBprefix";
2450 * Split a wiki ID into DB name and table prefix
2452 function wfSplitWikiID( $wiki ) {
2453 $bits = explode( '-', $wiki, 2 );
2454 if ( count( $bits ) < 2 ) {
2461 * Get a Database object
2462 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2463 * master (for write queries), DB_SLAVE for potentially lagged
2464 * read queries, or an integer >= 0 for a particular server.
2466 * @param mixed $groups Query groups. An array of group names that this query
2467 * belongs to. May contain a single string if the query is only
2470 * @param string $wiki The wiki ID, or false for the current wiki
2472 function &wfGetDB( $db = DB_LAST
, $groups = array(), $wiki = false ) {
2473 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2477 * Get a load balancer object.
2479 * @param array $groups List of query groups
2480 * @param string $wiki Wiki ID, or false for the current wiki
2481 * @return LoadBalancer
2483 function wfGetLB( $wiki = false ) {
2484 return wfGetLBFactory()->getMainLB( $wiki );
2488 * Get the load balancer factory object
2490 function &wfGetLBFactory() {
2491 return LBFactory
::singleton();
2496 * Shortcut for RepoGroup::singleton()->findFile()
2497 * @param mixed $title Title object or string. May be interwiki.
2498 * @param mixed $time Requested time for an archived image, or false for the
2499 * current version. An image object will be returned which
2500 * was created at the specified time.
2501 * @param mixed $flags FileRepo::FIND_ flags
2502 * @return File, or false if the file does not exist
2504 function wfFindFile( $title, $time = false, $flags = 0 ) {
2505 return RepoGroup
::singleton()->findFile( $title, $time, $flags );
2509 * Get an object referring to a locally registered file.
2510 * Returns a valid placeholder object if the file does not exist.
2512 function wfLocalFile( $title ) {
2513 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2517 * Should low-performance queries be disabled?
2521 function wfQueriesMustScale() {
2522 global $wgMiserMode;
2524 ||
( SiteStats
::pages() > 100000
2525 && SiteStats
::edits() > 1000000
2526 && SiteStats
::users() > 10000 );
2530 * Get the path to a specified script file, respecting file
2531 * extensions; this is a wrapper around $wgScriptExtension etc.
2533 * @param string $script Script filename, sans extension
2536 function wfScript( $script = 'index' ) {
2537 global $wgScriptPath, $wgScriptExtension;
2538 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2542 * Convenience function converts boolean values into "true"
2543 * or "false" (string) values
2545 * @param bool $value
2548 function wfBoolToStr( $value ) {
2549 return $value ?
'true' : 'false';
2553 * Load an extension messages file
2555 * @param string $extensionName Name of extension to load messages from\for.
2556 * @param string $langcode Language to load messages for, or false for default
2557 * behvaiour (en, content language and user language).
2559 function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
2560 global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
2562 #For recording whether extension message files have been loaded in a given language.
2563 static $loaded = array();
2565 if( !array_key_exists( $extensionName, $loaded ) ) {
2566 $loaded[$extensionName] = array();
2569 if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
2570 # Just do en, content language and user language.
2571 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
2572 # Mark that they have been loaded.
2573 $loaded[$extensionName]['en'] = true;
2574 $loaded[$extensionName][$wgLang->getCode()] = true;
2575 $loaded[$extensionName][$wgContLang->getCode()] = true;
2576 # Mark that this part has been done to avoid weird if statements.
2577 $loaded[$extensionName]['*'] = true;
2578 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
2579 # Load messages for specified language.
2580 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
2581 # Mark that they have been loaded.
2582 $loaded[$extensionName][$langcode] = true;
2587 * Get a platform-independent path to the null file, e.g.
2592 function wfGetNull() {
2593 return wfIsWindows()
2599 * Displays a maxlag error
2601 * @param string $host Server that lags the most
2602 * @param int $lag Maxlag (actual)
2603 * @param int $maxLag Maxlag (requested)
2605 function wfMaxlagError( $host, $lag, $maxLag ) {
2606 global $wgShowHostnames;
2607 header( 'HTTP/1.1 503 Service Unavailable' );
2608 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2609 header( 'X-Database-Lag: ' . intval( $lag ) );
2610 header( 'Content-Type: text/plain' );
2611 if( $wgShowHostnames ) {
2612 echo "Waiting for $host: $lag seconds lagged\n";
2614 echo "Waiting for a database server: $lag seconds lagged\n";
2619 * Throws an E_USER_NOTICE saying that $function is deprecated
2620 * @param string $function
2623 function wfDeprecated( $function ) {
2624 global $wgDebugLogFile;
2625 if ( !$wgDebugLogFile ) {
2628 $callers = wfDebugBacktrace();
2629 if( isset( $callers[2] ) ){
2630 $callerfunc = $callers[2];
2631 $callerfile = $callers[1];
2632 if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
2633 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
2635 $file = '(internal function)';
2638 if( isset( $callerfunc['class'] ) )
2639 $func .= $callerfunc['class'] . '::';
2640 $func .= @$callerfunc['function'];
2641 $msg = "Use of $function is deprecated. Called from $func in $file";
2643 $msg = "Use of $function is deprecated.";
2645 wfDebug( "$msg\n" );
2649 * Sleep until the worst slave's replication lag is less than or equal to
2650 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2651 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2652 * a no-op if there are no slaves.
2654 * Every time the function has to wait for a slave, it will print a message to
2655 * that effect (and then sleep for a little while), so it's probably not best
2656 * to use this outside maintenance scripts in its present form.
2658 * @param int $maxLag
2661 function wfWaitForSlaves( $maxLag ) {
2664 list( $host, $lag ) = $lb->getMaxLag();
2665 while( $lag > $maxLag ) {
2666 $name = @gethostbyaddr
( $host );
2667 if( $name !== false ) {
2670 print "Waiting for $host (lagged $lag seconds)...\n";
2672 list( $host, $lag ) = $lb->getMaxLag();
2677 /** Generate a random 32-character hexadecimal token.
2678 * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
2680 function wfGenerateToken( $salt = '' ) {
2681 $salt = serialize($salt);
2683 return md5( mt_rand( 0, 0x7fffffff ) . $salt );