7acd3e85c12657d51c494bb65d4c6f1ec48ba64f
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 $wgProfiling, $wgUser;
259 if ( $wgProfiling ) {
261 $elapsed = $now - $wgRequestTime;
262 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
264 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
265 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
266 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
267 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
268 if( !empty( $_SERVER['HTTP_FROM'] ) )
269 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
271 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
272 // Don't unstub $wgUser at this late stage just for statistics purposes
273 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
275 $log = sprintf( "%s\t%04.3f\t%s\n",
276 gmdate( 'YmdHis' ), $elapsed,
277 urldecode( $wgRequest->getRequestURL() . $forward ) );
278 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
279 wfErrorLog( $log . $prof, $wgDebugLogFile );
285 * Check if the wiki read-only lock file is present. This can be used to lock
286 * off editing functions, but doesn't guarantee that the database will not be
290 function wfReadOnly() {
291 global $wgReadOnlyFile, $wgReadOnly;
293 if ( !is_null( $wgReadOnly ) ) {
294 return (bool)$wgReadOnly;
296 if ( '' == $wgReadOnlyFile ) {
299 // Set $wgReadOnly for faster access next time
300 if ( is_file( $wgReadOnlyFile ) ) {
301 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
305 return (bool)$wgReadOnly;
308 function wfReadOnlyReason() {
315 * Get a message from anywhere, for the current user language.
317 * Use wfMsgForContent() instead if the message should NOT
318 * change depending on the user preferences.
320 * @param $key String: lookup key for the message, usually
321 * defined in languages/Language.php
323 * This function also takes extra optional parameters (not
324 * shown in the function definition), which can by used to
325 * insert variable text into the predefined message.
327 function wfMsg( $key ) {
328 $args = func_get_args();
329 array_shift( $args );
330 return wfMsgReal( $key, $args, true );
334 * Same as above except doesn't transform the message
336 function wfMsgNoTrans( $key ) {
337 $args = func_get_args();
338 array_shift( $args );
339 return wfMsgReal( $key, $args, true, false, false );
343 * Get a message from anywhere, for the current global language
344 * set with $wgLanguageCode.
346 * Use this if the message should NOT change dependent on the
347 * language set in the user's preferences. This is the case for
348 * most text written into logs, as well as link targets (such as
349 * the name of the copyright policy page). Link titles, on the
350 * other hand, should be shown in the UI language.
352 * Note that MediaWiki allows users to change the user interface
353 * language in their preferences, but a single installation
354 * typically only contains content in one language.
356 * Be wary of this distinction: If you use wfMsg() where you should
357 * use wfMsgForContent(), a user of the software may have to
358 * customize over 70 messages in order to, e.g., fix a link in every
361 * @param $key String: lookup key for the message, usually
362 * defined in languages/Language.php
364 function wfMsgForContent( $key ) {
365 global $wgForceUIMsgAsContentMsg;
366 $args = func_get_args();
367 array_shift( $args );
369 if( is_array( $wgForceUIMsgAsContentMsg ) &&
370 in_array( $key, $wgForceUIMsgAsContentMsg ) )
372 return wfMsgReal( $key, $args, true, $forcontent );
376 * Same as above except doesn't transform the message
378 function wfMsgForContentNoTrans( $key ) {
379 global $wgForceUIMsgAsContentMsg;
380 $args = func_get_args();
381 array_shift( $args );
383 if( is_array( $wgForceUIMsgAsContentMsg ) &&
384 in_array( $key, $wgForceUIMsgAsContentMsg ) )
386 return wfMsgReal( $key, $args, true, $forcontent, false );
390 * Get a message from the language file, for the UI elements
392 function wfMsgNoDB( $key ) {
393 $args = func_get_args();
394 array_shift( $args );
395 return wfMsgReal( $key, $args, false );
399 * Get a message from the language file, for the content
401 function wfMsgNoDBForContent( $key ) {
402 global $wgForceUIMsgAsContentMsg;
403 $args = func_get_args();
404 array_shift( $args );
406 if( is_array( $wgForceUIMsgAsContentMsg ) &&
407 in_array( $key, $wgForceUIMsgAsContentMsg ) )
409 return wfMsgReal( $key, $args, false, $forcontent );
414 * Really get a message
415 * @param $key String: key to get.
417 * @param $useDB Boolean
418 * @param $transform Boolean: Whether or not to transform the message.
419 * @param $forContent Boolean
420 * @return String: the requested message.
422 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
423 wfProfileIn( __METHOD__
);
424 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
425 $message = wfMsgReplaceArgs( $message, $args );
426 wfProfileOut( __METHOD__
);
431 * This function provides the message source for messages to be edited which are *not* stored in the database.
432 * @param $key String:
434 function wfMsgWeirdKey ( $key ) {
435 $source = wfMsgGetKey( $key, false, true, false );
436 if ( wfEmptyMsg( $key, $source ) )
443 * Fetch a message string value, but don't replace any keys yet.
446 * @param bool $forContent
450 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
451 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
453 # If $wgMessageCache isn't initialised yet, try to return something sensible.
454 if( is_object( $wgMessageCache ) ) {
455 $message = $wgMessageCache->get( $key, $useDB, $forContent );
457 $message = $wgMessageCache->transform( $message );
461 $lang = &$wgContLang;
466 # MessageCache::get() does this already, Language::getMessage() doesn't
467 # ISSUE: Should we try to handle "message/lang" here too?
468 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
470 if( is_object( $lang ) ) {
471 $message = $lang->getMessage( $key );
481 * Replace message parameter keys on the given formatted output.
483 * @param string $message
488 function wfMsgReplaceArgs( $message, $args ) {
489 # Fix windows line-endings
490 # Some messages are split with explode("\n", $msg)
491 $message = str_replace( "\r", '', $message );
494 if ( count( $args ) ) {
495 if ( is_array( $args[0] ) ) {
496 $args = array_values( $args[0] );
498 $replacementKeys = array();
499 foreach( $args as $n => $param ) {
500 $replacementKeys['$' . ($n +
1)] = $param;
502 $message = strtr( $message, $replacementKeys );
509 * Return an HTML-escaped version of a message.
510 * Parameter replacements, if any, are done *after* the HTML-escaping,
511 * so parameters may contain HTML (eg links or form controls). Be sure
512 * to pre-escape them if you really do want plaintext, or just wrap
513 * the whole thing in htmlspecialchars().
516 * @param string ... parameters
519 function wfMsgHtml( $key ) {
520 $args = func_get_args();
521 array_shift( $args );
522 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
526 * Return an HTML version of message
527 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
528 * so parameters may contain HTML (eg links or form controls). Be sure
529 * to pre-escape them if you really do want plaintext, or just wrap
530 * the whole thing in htmlspecialchars().
533 * @param string ... parameters
536 function wfMsgWikiHtml( $key ) {
538 $args = func_get_args();
539 array_shift( $args );
540 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
544 * Returns message in the requested format
545 * @param string $key Key of the message
546 * @param array $options Processing rules:
547 * <i>parse</i>: parses wikitext to html
548 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
549 * <i>escape</i>: filters message through htmlspecialchars
550 * <i>escapenoentities</i>: same, but allows entity references like through
551 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
552 * <i>parsemag</i>: transform the message using magic phrases
553 * <i>content</i>: fetch message for content language instead of interface
554 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
556 function wfMsgExt( $key, $options ) {
557 global $wgOut, $wgParser;
559 $args = func_get_args();
560 array_shift( $args );
561 array_shift( $args );
563 if( !is_array($options) ) {
564 $options = array($options);
568 if( in_array('content', $options) ) {
572 $string = wfMsgGetKey( $key, /*DB*/true, $forContent, /*Transform*/false );
574 if( !in_array('replaceafter', $options) ) {
575 $string = wfMsgReplaceArgs( $string, $args );
578 if( in_array('parse', $options) ) {
579 $string = $wgOut->parse( $string, true, !$forContent );
580 } elseif ( in_array('parseinline', $options) ) {
581 $string = $wgOut->parse( $string, true, !$forContent );
583 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
586 } elseif ( in_array('parsemag', $options) ) {
587 global $wgMessageCache;
588 if ( isset( $wgMessageCache ) ) {
589 $string = $wgMessageCache->transform( $string, !$forContent );
593 if ( in_array('escape', $options) ) {
594 $string = htmlspecialchars ( $string );
595 } elseif ( in_array( 'escapenoentities', $options ) ) {
596 $string = htmlspecialchars( $string );
597 $string = str_replace( '&', '&', $string );
598 $string = Sanitizer
::normalizeCharReferences( $string );
601 if( in_array('replaceafter', $options) ) {
602 $string = wfMsgReplaceArgs( $string, $args );
610 * Just like exit() but makes a note of it.
611 * Commits open transactions except if the error parameter is set
613 * @deprecated Please return control to the caller or throw an exception
615 function wfAbruptExit( $error = false ){
616 global $wgLoadBalancer;
617 static $called = false;
623 $bt = wfDebugBacktrace();
625 for($i = 0; $i < count($bt) ; $i++
){
626 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
627 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
628 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
631 wfDebug('WARNING: Abrupt exit\n');
634 wfLogProfilingData();
637 $wgLoadBalancer->closeAll();
643 * @deprecated Please return control the caller or throw an exception
645 function wfErrorExit() {
646 wfAbruptExit( true );
650 * Print a simple message and die, returning nonzero to the shell if any.
651 * Plain die() fails to return nonzero to the shell if you pass a string.
654 function wfDie( $msg='' ) {
660 * Throw a debugging exception. This function previously once exited the process,
661 * but now throws an exception instead, with similar results.
663 * @param string $msg Message shown when dieing.
665 function wfDebugDieBacktrace( $msg = '' ) {
666 throw new MWException( $msg );
670 * Fetch server name for use in error reporting etc.
671 * Use real server name if available, so we know which machine
672 * in a server farm generated the current page.
675 function wfHostname() {
676 if ( function_exists( 'posix_uname' ) ) {
677 // This function not present on Windows
678 $uname = @posix_uname
();
682 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
683 return $uname['nodename'];
685 # This may be a virtual server.
686 return $_SERVER['SERVER_NAME'];
691 * Returns a HTML comment with the elapsed time since request.
692 * This method has no side effects.
695 function wfReportTime() {
696 global $wgRequestTime, $wgShowHostnames;
699 $elapsed = $now - $wgRequestTime;
701 return $wgShowHostnames
702 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
703 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
707 * Safety wrapper for debug_backtrace().
709 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
710 * murky circumstances, which may be triggered in part by stub objects
711 * or other fancy talkin'.
713 * Will return an empty array if Zend Optimizer is detected, otherwise
714 * the output from debug_backtrace() (trimmed).
716 * @return array of backtrace information
718 function wfDebugBacktrace() {
719 if( extension_loaded( 'Zend Optimizer' ) ) {
720 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
723 return array_slice( debug_backtrace(), 1 );
727 function wfBacktrace() {
728 global $wgCommandLineMode;
730 if ( $wgCommandLineMode ) {
735 $backtrace = wfDebugBacktrace();
736 foreach( $backtrace as $call ) {
737 if( isset( $call['file'] ) ) {
738 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
739 $file = $f[count($f)-1];
743 if( isset( $call['line'] ) ) {
744 $line = $call['line'];
748 if ( $wgCommandLineMode ) {
749 $msg .= "$file line $line calls ";
751 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
753 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
754 $msg .= $call['function'] . '()';
756 if ( $wgCommandLineMode ) {
762 if ( $wgCommandLineMode ) {
772 /* Some generic result counters, pulled out of SearchEngine */
778 function wfShowingResults( $offset, $limit ) {
780 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
786 function wfShowingResultsNum( $offset, $limit, $num ) {
788 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
794 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
796 $fmtLimit = $wgLang->formatNum( $limit );
797 $prev = wfMsg( 'prevn', $fmtLimit );
798 $next = wfMsg( 'nextn', $fmtLimit );
800 if( is_object( $link ) ) {
803 $title = Title
::newFromText( $link );
804 if( is_null( $title ) ) {
809 if ( 0 != $offset ) {
810 $po = $offset - $limit;
811 if ( $po < 0 ) { $po = 0; }
812 $q = "limit={$limit}&offset={$po}";
813 if ( '' != $query ) { $q .= '&'.$query; }
814 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
815 } else { $plink = $prev; }
817 $no = $offset +
$limit;
818 $q = 'limit='.$limit.'&offset='.$no;
819 if ( '' != $query ) { $q .= '&'.$query; }
824 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
826 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
827 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
828 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
829 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
830 wfNumLink( $offset, 500, $title, $query );
832 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
838 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
840 if ( '' == $query ) { $q = ''; }
841 else { $q = $query.'&'; }
842 $q .= 'limit='.$limit.'&offset='.$offset;
844 $fmtLimit = $wgLang->formatNum( $limit );
845 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
851 * @todo FIXME: we may want to blacklist some broken browsers
853 * @return bool Whereas client accept gzip compression
855 function wfClientAcceptsGzip() {
858 # FIXME: we may want to blacklist some broken browsers
861 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
862 $_SERVER['HTTP_ACCEPT_ENCODING'],
864 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
865 wfDebug( " accepts gzip\n" );
873 * Obtain the offset and limit values from the request string;
874 * used in special pages
876 * @param $deflimit Default limit if none supplied
877 * @param $optionname Name of a user preference to check against
881 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
883 return $wgRequest->getLimitOffset( $deflimit, $optionname );
887 * Escapes the given text so that it may be output using addWikiText()
888 * without any linking, formatting, etc. making its way through. This
889 * is achieved by substituting certain characters with HTML entities.
890 * As required by the callers, <nowiki> is not used. It currently does
891 * not filter out characters which have special meaning only at the
892 * start of a line, such as "*".
894 * @param string $text Text to be escaped
896 function wfEscapeWikiText( $text ) {
898 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
899 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
900 htmlspecialchars($text) );
907 function wfQuotedPrintable( $string, $charset = '' ) {
908 # Probably incomplete; see RFC 2045
909 if( empty( $charset ) ) {
910 global $wgInputEncoding;
911 $charset = $wgInputEncoding;
913 $charset = strtoupper( $charset );
914 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
916 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
917 $replace = $illegal . '\t ?_';
918 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
919 $out = "=?$charset?Q?";
920 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
931 return microtime(true);
935 * Sets dest to source and returns the original value of dest
936 * If source is NULL, it just returns the value, it doesn't set the variable
938 function wfSetVar( &$dest, $source ) {
940 if ( !is_null( $source ) ) {
947 * As for wfSetVar except setting a bit
949 function wfSetBit( &$dest, $bit, $state = true ) {
950 $temp = (bool)($dest & $bit );
951 if ( !is_null( $state ) ) {
962 * This function takes two arrays as input, and returns a CGI-style string, e.g.
963 * "days=7&limit=100". Options in the first array override options in the second.
964 * Options set to "" will not be output.
966 function wfArrayToCGI( $array1, $array2 = NULL )
968 if ( !is_null( $array2 ) ) {
969 $array1 = $array1 +
$array2;
973 foreach ( $array1 as $key => $value ) {
974 if ( '' !== $value ) {
978 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
985 * Append a query string to an existing URL, which may or may not already
986 * have query string parameters already. If so, they will be combined.
989 * @param string $query
992 function wfAppendQuery( $url, $query ) {
994 if( false === strpos( $url, '?' ) ) {
1005 * Expand a potentially local URL to a fully-qualified URL.
1006 * Assumes $wgServer is correct. :)
1007 * @param string $url, either fully-qualified or a local path + query
1008 * @return string Fully-qualified URL
1010 function wfExpandUrl( $url ) {
1011 if( substr( $url, 0, 1 ) == '/' ) {
1013 return $wgServer . $url;
1020 * This is obsolete, use SquidUpdate::purge()
1023 function wfPurgeSquidServers ($urlArr) {
1024 SquidUpdate
::purge( $urlArr );
1028 * Windows-compatible version of escapeshellarg()
1029 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1030 * function puts single quotes in regardless of OS
1032 function wfEscapeShellArg( ) {
1033 $args = func_get_args();
1036 foreach ( $args as $arg ) {
1043 if ( wfIsWindows() ) {
1044 // Escaping for an MSVC-style command line parser
1045 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1046 // Double the backslashes before any double quotes. Escape the double quotes.
1047 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1050 foreach ( $tokens as $token ) {
1052 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1058 // Double the backslashes before the end of the string, because
1059 // we will soon add a quote
1061 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1062 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1065 // Add surrounding quotes
1066 $retVal .= '"' . $arg . '"';
1068 $retVal .= escapeshellarg( $arg );
1075 * wfMerge attempts to merge differences between three texts.
1076 * Returns true for a clean merge and false for failure or a conflict.
1078 function wfMerge( $old, $mine, $yours, &$result ){
1081 # This check may also protect against code injection in
1082 # case of broken installations.
1083 if(! file_exists( $wgDiff3 ) ){
1084 wfDebug( "diff3 not found\n" );
1088 # Make temporary files
1090 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1091 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1092 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1094 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1095 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1096 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1098 # Check for a conflict
1099 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1100 wfEscapeShellArg( $mytextName ) . ' ' .
1101 wfEscapeShellArg( $oldtextName ) . ' ' .
1102 wfEscapeShellArg( $yourtextName );
1103 $handle = popen( $cmd, 'r' );
1105 if( fgets( $handle, 1024 ) ){
1113 $cmd = $wgDiff3 . ' -a -e --merge ' .
1114 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1115 $handle = popen( $cmd, 'r' );
1118 $data = fread( $handle, 8192 );
1119 if ( strlen( $data ) == 0 ) {
1125 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1127 if ( $result === '' && $old !== '' && $conflict == false ) {
1128 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1137 function wfVarDump( $var ) {
1139 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1140 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1143 $wgOut->addHTML( $s );
1148 * Provide a simple HTTP error.
1150 function wfHttpError( $code, $label, $desc ) {
1153 header( "HTTP/1.0 $code $label" );
1154 header( "Status: $code $label" );
1155 $wgOut->sendCacheControl();
1157 header( 'Content-type: text/html; charset=utf-8' );
1158 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1159 "<html><head><title>" .
1160 htmlspecialchars( $label ) .
1161 "</title></head><body><h1>" .
1162 htmlspecialchars( $label ) .
1164 nl2br( htmlspecialchars( $desc ) ) .
1165 "</p></body></html>\n";
1169 * Clear away any user-level output buffers, discarding contents.
1171 * Suitable for 'starting afresh', for instance when streaming
1172 * relatively large amounts of data without buffering, or wanting to
1173 * output image files without ob_gzhandler's compression.
1175 * The optional $resetGzipEncoding parameter controls suppression of
1176 * the Content-Encoding header sent by ob_gzhandler; by default it
1177 * is left. See comments for wfClearOutputBuffers() for why it would
1180 * Note that some PHP configuration options may add output buffer
1181 * layers which cannot be removed; these are left in place.
1183 * @param bool $resetGzipEncoding
1185 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1186 if( $resetGzipEncoding ) {
1187 // Suppress Content-Encoding and Content-Length
1188 // headers from 1.10+s wfOutputHandler
1189 global $wgDisableOutputCompression;
1190 $wgDisableOutputCompression = true;
1192 while( $status = ob_get_status() ) {
1193 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1194 // Probably from zlib.output_compression or other
1195 // PHP-internal setting which can't be removed.
1197 // Give up, and hope the result doesn't break
1201 if( !ob_end_clean() ) {
1202 // Could not remove output buffer handler; abort now
1203 // to avoid getting in some kind of infinite loop.
1206 if( $resetGzipEncoding ) {
1207 if( $status['name'] == 'ob_gzhandler' ) {
1208 // Reset the 'Content-Encoding' field set by this handler
1209 // so we can start fresh.
1210 header( 'Content-Encoding:' );
1217 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1219 * Clear away output buffers, but keep the Content-Encoding header
1220 * produced by ob_gzhandler, if any.
1222 * This should be used for HTTP 304 responses, where you need to
1223 * preserve the Content-Encoding header of the real result, but
1224 * also need to suppress the output of ob_gzhandler to keep to spec
1225 * and avoid breaking Firefox in rare cases where the headers and
1226 * body are broken over two packets.
1228 function wfClearOutputBuffers() {
1229 wfResetOutputBuffers( false );
1233 * Converts an Accept-* header into an array mapping string values to quality
1236 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1237 # No arg means accept anything (per HTTP spec)
1239 return array( $def => 1 );
1244 $parts = explode( ',', $accept );
1246 foreach( $parts as $part ) {
1247 # FIXME: doesn't deal with params like 'text/html; level=1'
1248 @list
( $value, $qpart ) = explode( ';', $part );
1250 if( !isset( $qpart ) ) {
1252 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1253 $prefs[$value] = $match[1];
1261 * Checks if a given MIME type matches any of the keys in the given
1262 * array. Basic wildcards are accepted in the array keys.
1264 * Returns the matching MIME type (or wildcard) if a match, otherwise
1267 * @param string $type
1268 * @param array $avail
1272 function mimeTypeMatch( $type, $avail ) {
1273 if( array_key_exists($type, $avail) ) {
1276 $parts = explode( '/', $type );
1277 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1278 return $parts[0] . '/*';
1279 } elseif( array_key_exists( '*/*', $avail ) ) {
1288 * Returns the 'best' match between a client's requested internet media types
1289 * and the server's list of available types. Each list should be an associative
1290 * array of type to preference (preference is a float between 0.0 and 1.0).
1291 * Wildcards in the types are acceptable.
1293 * @param array $cprefs Client's acceptable type list
1294 * @param array $sprefs Server's offered types
1297 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1298 * XXX: generalize to negotiate other stuff
1300 function wfNegotiateType( $cprefs, $sprefs ) {
1303 foreach( array_keys($sprefs) as $type ) {
1304 $parts = explode( '/', $type );
1305 if( $parts[1] != '*' ) {
1306 $ckey = mimeTypeMatch( $type, $cprefs );
1308 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1313 foreach( array_keys( $cprefs ) as $type ) {
1314 $parts = explode( '/', $type );
1315 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1316 $skey = mimeTypeMatch( $type, $sprefs );
1318 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1326 foreach( array_keys( $combine ) as $type ) {
1327 if( $combine[$type] > $bestq ) {
1329 $bestq = $combine[$type];
1338 * Returns an array where the values in the first array are replaced by the
1339 * values in the second array with the corresponding keys
1343 function wfArrayLookup( $a, $b ) {
1344 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1348 * Convenience function; returns MediaWiki timestamp for the present time.
1351 function wfTimestampNow() {
1353 return wfTimestamp( TS_MW
, time() );
1357 * Reference-counted warning suppression
1359 function wfSuppressWarnings( $end = false ) {
1360 static $suppressCount = 0;
1361 static $originalLevel = false;
1364 if ( $suppressCount ) {
1366 if ( !$suppressCount ) {
1367 error_reporting( $originalLevel );
1371 if ( !$suppressCount ) {
1372 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1379 * Restore error level to previous value
1381 function wfRestoreWarnings() {
1382 wfSuppressWarnings( true );
1385 # Autodetect, convert and provide timestamps of various types
1388 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1390 define('TS_UNIX', 0);
1393 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1398 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1403 * RFC 2822 format, for E-mail and HTTP headers
1405 define('TS_RFC2822', 3);
1408 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1410 * This is used by Special:Export
1412 define('TS_ISO_8601', 4);
1415 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1417 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1418 * DateTime tag and page 36 for the DateTimeOriginal and
1419 * DateTimeDigitized tags.
1421 define('TS_EXIF', 5);
1424 * Oracle format time.
1426 define('TS_ORACLE', 6);
1429 * Postgres format time.
1431 define('TS_POSTGRES', 7);
1434 * @param mixed $outputtype A timestamp in one of the supported formats, the
1435 * function will autodetect which format is supplied
1436 * and act accordingly.
1437 * @return string Time in the format specified in $outputtype
1439 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1444 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1446 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1447 (int)$da[2],(int)$da[3],(int)$da[1]);
1448 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1450 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1451 (int)$da[2],(int)$da[3],(int)$da[1]);
1452 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1454 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1455 (int)$da[2],(int)$da[3],(int)$da[1]);
1456 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1459 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1461 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1462 str_replace("+00:00", "UTC", $ts)));
1463 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1465 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1466 (int)$da[2],(int)$da[3],(int)$da[1]);
1467 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1469 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1470 (int)$da[2],(int)$da[3],(int)$da[1]);
1471 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1473 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1474 (int)$da[2],(int)$da[3],(int)$da[1]);
1476 # Bogus value; fall back to the epoch...
1477 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1482 switch($outputtype) {
1486 return gmdate( 'YmdHis', $uts );
1488 return gmdate( 'Y-m-d H:i:s', $uts );
1490 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1491 // This shouldn't ever be used, but is included for completeness
1493 return gmdate( 'Y:m:d H:i:s', $uts );
1495 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1497 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1499 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1501 throw new MWException( 'wfTimestamp() called with illegal output type.');
1506 * Return a formatted timestamp, or null if input is null.
1507 * For dealing with nullable timestamp columns in the database.
1508 * @param int $outputtype
1512 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1513 if( is_null( $ts ) ) {
1516 return wfTimestamp( $outputtype, $ts );
1521 * Check if the operating system is Windows
1523 * @return bool True if it's Windows, False otherwise.
1525 function wfIsWindows() {
1526 if (substr(php_uname(), 0, 7) == 'Windows') {
1534 * Swap two variables
1536 function swap( &$x, &$y ) {
1542 function wfGetCachedNotice( $name ) {
1543 global $wgOut, $parserMemc;
1544 $fname = 'wfGetCachedNotice';
1545 wfProfileIn( $fname );
1549 if( $name === 'default' ) {
1551 global $wgSiteNotice;
1552 $notice = $wgSiteNotice;
1553 if( empty( $notice ) ) {
1554 wfProfileOut( $fname );
1558 $notice = wfMsgForContentNoTrans( $name );
1559 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1560 wfProfileOut( $fname );
1565 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1566 if( is_array( $cachedNotice ) ) {
1567 if( md5( $notice ) == $cachedNotice['hash'] ) {
1568 $notice = $cachedNotice['html'];
1577 if( is_object( $wgOut ) ) {
1578 $parsed = $wgOut->parse( $notice );
1579 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1582 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1587 wfProfileOut( $fname );
1591 function wfGetNamespaceNotice() {
1595 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1598 $fname = 'wfGetNamespaceNotice';
1599 wfProfileIn( $fname );
1601 $key = "namespacenotice-" . $wgTitle->getNsText();
1602 $namespaceNotice = wfGetCachedNotice( $key );
1603 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1604 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1606 $namespaceNotice = "";
1609 wfProfileOut( $fname );
1610 return $namespaceNotice;
1613 function wfGetSiteNotice() {
1614 global $wgUser, $wgSiteNotice;
1615 $fname = 'wfGetSiteNotice';
1616 wfProfileIn( $fname );
1619 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1620 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1621 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1623 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1624 if( !$anonNotice ) {
1625 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1627 $siteNotice = $anonNotice;
1630 if( !$siteNotice ) {
1631 $siteNotice = wfGetCachedNotice( 'default' );
1635 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1636 wfProfileOut( $fname );
1641 * BC wrapper for MimeMagic::singleton()
1644 function &wfGetMimeMagic() {
1645 return MimeMagic
::singleton();
1649 * Tries to get the system directory for temporary files.
1650 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1651 * and if none are set /tmp is returned as the generic Unix default.
1653 * NOTE: When possible, use the tempfile() function to create temporary
1654 * files to avoid race conditions on file creation, etc.
1658 function wfTempDir() {
1659 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1660 $tmp = getenv( $var );
1661 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1665 # Hope this is Unix of some kind!
1670 * Make directory, and make all parent directories if they don't exist
1672 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1673 if( strval( $fullDir ) === '' )
1675 if( file_exists( $fullDir ) )
1677 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR
, $fullDir ), $mode, true );
1681 * Increment a statistics counter
1683 function wfIncrStats( $key ) {
1684 global $wgStatsMethod;
1686 if( $wgStatsMethod == 'udp' ) {
1687 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1690 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1691 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1692 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1694 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1695 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1696 } elseif( $wgStatsMethod == 'cache' ) {
1698 $key = wfMemcKey( 'stats', $key );
1699 if ( is_null( $wgMemc->incr( $key ) ) ) {
1700 $wgMemc->add( $key, 1 );
1708 * @param mixed $nr The number to format
1709 * @param int $acc The number of digits after the decimal point, default 2
1710 * @param bool $round Whether or not to round the value, default true
1713 function wfPercent( $nr, $acc = 2, $round = true ) {
1714 $ret = sprintf( "%.${acc}f", $nr );
1715 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1719 * Encrypt a username/password.
1721 * @param string $userid ID of the user
1722 * @param string $password Password of the user
1723 * @return string Hashed password
1725 function wfEncryptPassword( $userid, $password ) {
1726 global $wgPasswordSalt;
1727 $p = md5( $password);
1730 return md5( "{$userid}-{$p}" );
1736 * Appends to second array if $value differs from that in $default
1738 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1739 if ( is_null( $changed ) ) {
1740 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1742 if ( $default[$key] !== $value ) {
1743 $changed[$key] = $value;
1748 * Since wfMsg() and co suck, they don't return false if the message key they
1749 * looked up didn't exist but a XHTML string, this function checks for the
1750 * nonexistance of messages by looking at wfMsg() output
1752 * @param $msg The message key looked up
1753 * @param $wfMsgOut The output of wfMsg*()
1756 function wfEmptyMsg( $msg, $wfMsgOut ) {
1757 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1761 * Find out whether or not a mixed variable exists in a string
1763 * @param mixed needle
1764 * @param string haystack
1767 function in_string( $needle, $str ) {
1768 return strpos( $str, $needle ) !== false;
1771 function wfSpecialList( $page, $details ) {
1773 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1774 return $page . $details;
1778 * Returns a regular expression of url protocols
1782 function wfUrlProtocols() {
1783 global $wgUrlProtocols;
1785 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1786 // with LocalSettings files from 1.5
1787 if ( is_array( $wgUrlProtocols ) ) {
1788 $protocols = array();
1789 foreach ($wgUrlProtocols as $protocol)
1790 $protocols[] = preg_quote( $protocol, '/' );
1792 return implode( '|', $protocols );
1794 return $wgUrlProtocols;
1799 * Safety wrapper around ini_get() for boolean settings.
1800 * The values returned from ini_get() are pre-normalized for settings
1801 * set via php.ini or php_flag/php_admin_flag... but *not*
1802 * for those set via php_value/php_admin_value.
1804 * It's fairly common for people to use php_value instead of php_flag,
1805 * which can leave you with an 'off' setting giving a false positive
1806 * for code that just takes the ini_get() return value as a boolean.
1808 * To make things extra interesting, setting via php_value accepts
1809 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1810 * Unrecognized values go false... again opposite PHP's own coercion
1811 * from string to bool.
1813 * Luckily, 'properly' set settings will always come back as '0' or '1',
1814 * so we only have to worry about them and the 'improper' settings.
1816 * I frickin' hate PHP... :P
1818 * @param string $setting
1821 function wfIniGetBool( $setting ) {
1822 $val = ini_get( $setting );
1823 // 'on' and 'true' can't have whitespace around them, but '1' can.
1824 return strtolower( $val ) == 'on'
1825 ||
strtolower( $val ) == 'true'
1826 ||
strtolower( $val ) == 'yes'
1827 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1831 * Execute a shell command, with time and memory limits mirrored from the PHP
1832 * configuration if supported.
1833 * @param $cmd Command line, properly escaped for shell.
1834 * @param &$retval optional, will receive the program's exit code.
1835 * (non-zero is usually failure)
1836 * @return collected stdout as a string (trailing newlines stripped)
1838 function wfShellExec( $cmd, &$retval=null ) {
1839 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1841 if( wfIniGetBool( 'safe_mode' ) ) {
1842 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1844 return "Unable to run external programs in safe mode.";
1847 if ( php_uname( 's' ) == 'Linux' ) {
1848 $time = intval( ini_get( 'max_execution_time' ) );
1849 $mem = intval( $wgMaxShellMemory );
1850 $filesize = intval( $wgMaxShellFileSize );
1852 if ( $time > 0 && $mem > 0 ) {
1853 $script = "$IP/bin/ulimit4.sh";
1854 if ( is_executable( $script ) ) {
1855 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1858 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1859 # This is a hack to work around PHP's flawed invocation of cmd.exe
1860 # http://news.php.net/php.internals/21796
1861 $cmd = '"' . $cmd . '"';
1863 wfDebug( "wfShellExec: $cmd\n" );
1865 $retval = 1; // error by default?
1867 passthru( $cmd, $retval );
1868 $output = ob_get_contents();
1875 * This function works like "use VERSION" in Perl, the program will die with a
1876 * backtrace if the current version of PHP is less than the version provided
1878 * This is useful for extensions which due to their nature are not kept in sync
1879 * with releases, and might depend on other versions of PHP than the main code
1881 * Note: PHP might die due to parsing errors in some cases before it ever
1882 * manages to call this function, such is life
1884 * @see perldoc -f use
1886 * @param mixed $version The version to check, can be a string, an integer, or
1889 function wfUsePHP( $req_ver ) {
1890 $php_ver = PHP_VERSION
;
1892 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1893 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1897 * This function works like "use VERSION" in Perl except it checks the version
1898 * of MediaWiki, the program will die with a backtrace if the current version
1899 * of MediaWiki is less than the version provided.
1901 * This is useful for extensions which due to their nature are not kept in sync
1904 * @see perldoc -f use
1906 * @param mixed $version The version to check, can be a string, an integer, or
1909 function wfUseMW( $req_ver ) {
1912 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1913 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1917 * @deprecated use StringUtils::escapeRegexReplacement
1919 function wfRegexReplacement( $string ) {
1920 return StringUtils
::escapeRegexReplacement( $string );
1924 * Return the final portion of a pathname.
1925 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1926 * http://bugs.php.net/bug.php?id=33898
1928 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1929 * We'll consider it so always, as we don't want \s in our Unix paths either.
1931 * @param string $path
1932 * @param string $suffix to remove if present
1935 function wfBaseName( $path, $suffix='' ) {
1936 $encSuffix = ($suffix == '')
1938 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1940 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1948 * Generate a relative path name to the given file.
1949 * May explode on non-matching case-insensitive paths,
1950 * funky symlinks, etc.
1952 * @param string $path Absolute destination path including target filename
1953 * @param string $from Absolute source path, directory only
1956 function wfRelativePath( $path, $from ) {
1957 // Normalize mixed input on Windows...
1958 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1959 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1961 // Trim trailing slashes -- fix for drive root
1962 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
1963 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
1965 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1966 $against = explode( DIRECTORY_SEPARATOR
, $from );
1968 if( $pieces[0] !== $against[0] ) {
1969 // Non-matching Windows drive letters?
1970 // Return a full path.
1974 // Trim off common prefix
1975 while( count( $pieces ) && count( $against )
1976 && $pieces[0] == $against[0] ) {
1977 array_shift( $pieces );
1978 array_shift( $against );
1981 // relative dots to bump us to the parent
1982 while( count( $against ) ) {
1983 array_unshift( $pieces, '..' );
1984 array_shift( $against );
1987 array_push( $pieces, wfBaseName( $path ) );
1989 return implode( DIRECTORY_SEPARATOR
, $pieces );
1993 * array_merge() does awful things with "numeric" indexes, including
1994 * string indexes when happen to look like integers. When we want
1995 * to merge arrays with arbitrary string indexes, we don't want our
1996 * arrays to be randomly corrupted just because some of them consist
1999 * Fuck you, PHP. Fuck you in the ear!
2001 * @param array $array1, [$array2, [...]]
2004 function wfArrayMerge( $array1/* ... */ ) {
2006 for( $i = 1; $i < func_num_args(); $i++
) {
2007 foreach( func_get_arg( $i ) as $key => $value ) {
2008 $out[$key] = $value;
2015 * Make a URL index, appropriate for the el_index field of externallinks.
2017 function wfMakeUrlIndex( $url ) {
2018 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2019 wfSuppressWarnings();
2020 $bits = parse_url( $url );
2021 wfRestoreWarnings();
2025 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2027 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2029 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2031 // parse_url detects for news: and mailto: the host part of an url as path
2032 // We have to correct this wrong detection
2033 if ( isset ( $bits['path'] ) ) {
2034 $bits['host'] = $bits['path'];
2041 // Reverse the labels in the hostname, convert to lower case
2042 // For emails reverse domainpart only
2043 if ( $bits['scheme'] == 'mailto' ) {
2044 $mailparts = explode( '@', $bits['host'], 2 );
2045 if ( count($mailparts) === 2 ) {
2046 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2048 // No domain specified, don't mangle it
2051 $reversedHost = $domainpart . '@' . $mailparts[0];
2053 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2055 // Add an extra dot to the end
2056 // Why? Is it in wrong place in mailto links?
2057 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2058 $reversedHost .= '.';
2060 // Reconstruct the pseudo-URL
2061 $prot = $bits['scheme'];
2062 $index = "$prot$delimiter$reversedHost";
2063 // Leave out user and password. Add the port, path, query and fragment
2064 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2065 if ( isset( $bits['path'] ) ) {
2066 $index .= $bits['path'];
2070 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2071 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2076 * Do any deferred updates and clear the list
2077 * TODO: This could be in Wiki.php if that class made any sense at all
2079 function wfDoUpdates()
2081 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2082 foreach ( $wgDeferredUpdateList as $update ) {
2083 $update->doUpdate();
2085 foreach ( $wgPostCommitUpdateList as $update ) {
2086 $update->doUpdate();
2088 $wgDeferredUpdateList = array();
2089 $wgPostCommitUpdateList = array();
2093 * @deprecated use StringUtils::explodeMarkup
2095 function wfExplodeMarkup( $separator, $text ) {
2096 return StringUtils
::explodeMarkup( $separator, $text );
2100 * Convert an arbitrarily-long digit string from one numeric base
2101 * to another, optionally zero-padding to a minimum column width.
2103 * Supports base 2 through 36; digit values 10-36 are represented
2104 * as lowercase letters a-z. Input is case-insensitive.
2106 * @param $input string of digits
2107 * @param $sourceBase int 2-36
2108 * @param $destBase int 2-36
2109 * @param $pad int 1 or greater
2110 * @param $lowercase bool
2111 * @return string or false on invalid input
2113 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2114 $input = strval( $input );
2115 if( $sourceBase < 2 ||
2120 $sourceBase != intval( $sourceBase ) ||
2121 $destBase != intval( $destBase ) ||
2122 $pad != intval( $pad ) ||
2123 !is_string( $input ) ||
2127 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2128 $inDigits = array();
2131 // Decode and validate input string
2132 $input = strtolower( $input );
2133 for( $i = 0; $i < strlen( $input ); $i++
) {
2134 $n = strpos( $digitChars, $input{$i} );
2135 if( $n === false ||
$n > $sourceBase ) {
2141 // Iterate over the input, modulo-ing out an output digit
2142 // at a time until input is gone.
2143 while( count( $inDigits ) ) {
2145 $workDigits = array();
2148 foreach( $inDigits as $digit ) {
2149 $work *= $sourceBase;
2152 if( $work < $destBase ) {
2153 // Gonna need to pull another digit.
2154 if( count( $workDigits ) ) {
2155 // Avoid zero-padding; this lets us find
2156 // the end of the input very easily when
2157 // length drops to zero.
2161 // Finally! Actual division!
2162 $workDigits[] = intval( $work / $destBase );
2164 // Isn't it annoying that most programming languages
2165 // don't have a single divide-and-remainder operator,
2166 // even though the CPU implements it that way?
2167 $work = $work %
$destBase;
2171 // All that division leaves us with a remainder,
2172 // which is conveniently our next output digit.
2173 $outChars .= $digitChars[$work];
2176 $inDigits = $workDigits;
2179 while( strlen( $outChars ) < $pad ) {
2183 return strrev( $outChars );
2187 * Create an object with a given name and an array of construct parameters
2188 * @param string $name
2189 * @param array $p parameters
2191 function wfCreateObject( $name, $p ){
2192 $p = array_values( $p );
2193 switch ( count( $p ) ) {
2197 return new $name( $p[0] );
2199 return new $name( $p[0], $p[1] );
2201 return new $name( $p[0], $p[1], $p[2] );
2203 return new $name( $p[0], $p[1], $p[2], $p[3] );
2205 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2207 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2209 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2214 * Aliases for modularized functions
2216 function wfGetHTTP( $url, $timeout = 'default' ) {
2217 return Http
::get( $url, $timeout );
2219 function wfIsLocalURL( $url ) {
2220 return Http
::isLocalURL( $url );
2224 * Initialise php session
2226 function wfSetupSession() {
2227 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2228 if( $wgSessionsInMemcached ) {
2229 require_once( 'MemcachedSessions.php' );
2230 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2231 # If it's left on 'user' or another setting from another
2232 # application, it will end up failing. Try to recover.
2233 ini_set ( 'session.save_handler', 'files' );
2235 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2236 session_cache_limiter( 'private, must-revalidate' );
2241 * Get an object from the precompiled serialized directory
2243 * @return mixed The variable on success, false on failure
2245 function wfGetPrecompiledData( $name ) {
2248 $file = "$IP/serialized/$name";
2249 if ( file_exists( $file ) ) {
2250 $blob = file_get_contents( $file );
2252 return unserialize( $blob );
2258 function wfGetCaller( $level = 2 ) {
2259 $backtrace = wfDebugBacktrace();
2260 if ( isset( $backtrace[$level] ) ) {
2261 return wfFormatStackFrame($backtrace[$level]);
2263 $caller = 'unknown';
2268 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2269 function wfGetAllCallers() {
2270 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2273 /** Return a string representation of frame */
2274 function wfFormatStackFrame($frame) {
2275 return isset( $frame["class"] )?
2276 $frame["class"]."::".$frame["function"]:
2283 function wfMemcKey( /*... */ ) {
2284 global $wgDBprefix, $wgDBname;
2285 $args = func_get_args();
2286 if ( $wgDBprefix ) {
2287 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2289 $key = $wgDBname . ':' . implode( ':', $args );
2295 * Get a cache key for a foreign DB
2297 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2298 $args = array_slice( func_get_args(), 2 );
2300 $key = "$db-$prefix:" . implode( ':', $args );
2302 $key = $db . ':' . implode( ':', $args );
2308 * Get an ASCII string identifying this wiki
2309 * This is used as a prefix in memcached keys
2311 function wfWikiID() {
2312 global $wgDBprefix, $wgDBname;
2313 if ( $wgDBprefix ) {
2314 return "$wgDBname-$wgDBprefix";
2321 * Get a Database object
2322 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2323 * master (for write queries), DB_SLAVE for potentially lagged
2324 * read queries, or an integer >= 0 for a particular server.
2326 * @param mixed $groups Query groups. An array of group names that this query
2327 * belongs to. May contain a single string if the query is only
2330 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2331 global $wgLoadBalancer;
2332 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2338 * Shortcut for RepoGroup::singleton()->findFile()
2339 * @param mixed $title Title object or string. May be interwiki.
2340 * @param mixed $time Requested time for an archived image, or false for the
2341 * current version. An image object will be returned which
2342 * existed at the specified time.
2343 * @return File, or false if the file does not exist
2345 function wfFindFile( $title, $time = false ) {
2346 return RepoGroup
::singleton()->findFile( $title, $time );
2350 * Get an object referring to a locally registered file.
2351 * Returns a valid placeholder object if the file does not exist.
2353 function wfLocalFile( $title ) {
2354 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2358 * Should low-performance queries be disabled?
2362 function wfQueriesMustScale() {
2363 global $wgMiserMode;
2365 ||
( SiteStats
::pages() > 100000
2366 && SiteStats
::edits() > 1000000
2367 && SiteStats
::users() > 10000 );
2371 * Get the path to a specified script file, respecting file
2372 * extensions; this is a wrapper around $wgScriptExtension etc.
2374 * @param string $script Script filename, sans extension
2377 function wfScript( $script = 'index' ) {
2378 global $wgScriptPath, $wgScriptExtension;
2379 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2383 * Convenience function converts boolean values into "true"
2384 * or "false" (string) values
2386 * @param bool $value
2389 function wfBoolToStr( $value ) {
2390 return $value ?
'true' : 'false';
2394 * Load an extension messages file
2396 function wfLoadExtensionMessages( $extensionName ) {
2397 global $wgExtensionMessagesFiles, $wgMessageCache;
2398 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2399 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2400 // Prevent double-loading
2401 $wgExtensionMessagesFiles[$extensionName] = false;
2406 * Get a platform-independent path to the null file, e.g.
2411 function wfGetNull() {
2412 return wfIsWindows()
2418 * Displays a maxlag error
2420 * @param string $host Server that lags the most
2421 * @param int $lag Maxlag (actual)
2422 * @param int $maxLag Maxlag (requested)
2424 function wfMaxlagError( $host, $lag, $maxLag ) {
2425 global $wgShowHostnames;
2426 header( 'HTTP/1.1 503 Service Unavailable' );
2427 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2428 header( 'X-Database-Lag: ' . intval( $lag ) );
2429 header( 'Content-Type: text/plain' );
2430 if( $wgShowHostnames ) {
2431 echo "Waiting for $host: $lag seconds lagged\n";
2433 echo "Waiting for a database server: $lag seconds lagged\n";
2438 * Throws an E_USER_NOTICE saying that $function is deprecated
2439 * @param string $function
2442 function wfDeprecated( $function ) {
2443 trigger_error( "Use of $function is deprecated", E_USER_NOTICE
);
2447 * Sleep until the worst slave's replication lag is less than or equal to
2448 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2449 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2450 * a no-op if there are no slaves.
2452 * Every time the function has to wait for a slave, it will print a message to
2453 * that effect (and then sleep for a little while), so it's probably not best
2454 * to use this outside maintenance scripts in its present form.
2456 * @param int $maxLag
2459 function wfWaitForSlaves( $maxLag ) {
2460 global $wgLoadBalancer;
2462 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
2463 while( $lag > $maxLag ) {
2464 $name = @gethostbyaddr
( $host );
2465 if( $name !== false ) {
2468 print "Waiting for $host (lagged $lag seconds)...\n";
2470 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();