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] );
92 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
93 * PHP 5 won't let you declare a 'clone' function, even conditionally,
94 * so it has to be a wrapper with a different name.
96 function wfClone( $object ) {
97 return clone( $object );
101 * Seed Mersenne Twister
102 * No-op for compatibility; only necessary in PHP < 4.2.0
104 function wfSeedRandom() {
109 * Get a random decimal value between 0 and 1, in a way
110 * not likely to give duplicate values for any realistic
111 * number of articles.
115 function wfRandom() {
116 # The maximum random value is "only" 2^31-1, so get two random
117 # values to reduce the chance of dupes
118 $max = mt_getrandmax() +
1;
119 $rand = number_format( (mt_rand() * $max +
mt_rand())
120 / $max / $max, 12, '.', '' );
125 * We want / and : to be included as literal characters in our title URLs.
126 * %2F in the page titles seems to fatally break for some reason.
131 function wfUrlencode ( $s ) {
132 $s = urlencode( $s );
133 $s = preg_replace( '/%3[Aa]/', ':', $s );
134 $s = preg_replace( '/%2[Ff]/', '/', $s );
140 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
141 * In normal operation this is a NOP.
143 * Controlling globals:
144 * $wgDebugLogFile - points to the log file
145 * $wgProfileOnly - if set, normal debug messages will not be recorded.
146 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
147 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
149 * @param $text String
150 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
152 function wfDebug( $text, $logonly = false ) {
153 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
154 static $recursion = 0;
156 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
157 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
161 if ( $wgDebugComments && !$logonly ) {
162 if ( !isset( $wgOut ) ) {
165 if ( !StubObject
::isRealObject( $wgOut ) ) {
173 $wgOut->debug( $text );
175 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
176 # Strip unprintables; they can switch terminal modes when binary data
177 # gets dumped, which is pretty annoying.
178 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
179 wfErrorLog( $text, $wgDebugLogFile );
184 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
185 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
187 * @param $logGroup String
188 * @param $text String
189 * @param $public Bool: whether to log the event in the public log if no private
190 * log file is specified, (default true)
192 function wfDebugLog( $logGroup, $text, $public = true ) {
193 global $wgDebugLogGroups;
194 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
195 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
196 $time = wfTimestamp( TS_DB
);
198 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
199 } else if ( $public === true ) {
200 wfDebug( $text, true );
205 * Log for database errors
206 * @param $text String: database error message.
208 function wfLogDBError( $text ) {
209 global $wgDBerrorLog, $wgDBname;
210 if ( $wgDBerrorLog ) {
211 $host = trim(`hostname`
);
212 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
213 wfErrorLog( $text, $wgDBerrorLog );
218 * Log to a file without getting "file size exceeded" signals
220 function wfErrorLog( $text, $file ) {
221 wfSuppressWarnings();
222 $exists = file_exists( $file );
223 $size = $exists ?
filesize( $file ) : false;
224 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
225 error_log( $text, 3, $file );
233 function wfLogProfilingData() {
234 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
235 global $wgProfiling, $wgUser;
236 if ( $wgProfiling ) {
238 $elapsed = $now - $wgRequestTime;
239 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
241 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
242 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
243 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
244 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
245 if( !empty( $_SERVER['HTTP_FROM'] ) )
246 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
248 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
249 // Don't unstub $wgUser at this late stage just for statistics purposes
250 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
252 $log = sprintf( "%s\t%04.3f\t%s\n",
253 gmdate( 'YmdHis' ), $elapsed,
254 urldecode( $wgRequest->getRequestURL() . $forward ) );
255 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
256 wfErrorLog( $log . $prof, $wgDebugLogFile );
262 * Check if the wiki read-only lock file is present. This can be used to lock
263 * off editing functions, but doesn't guarantee that the database will not be
267 function wfReadOnly() {
268 global $wgReadOnlyFile, $wgReadOnly;
270 if ( !is_null( $wgReadOnly ) ) {
271 return (bool)$wgReadOnly;
273 if ( '' == $wgReadOnlyFile ) {
276 // Set $wgReadOnly for faster access next time
277 if ( is_file( $wgReadOnlyFile ) ) {
278 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
282 return (bool)$wgReadOnly;
287 * Get a message from anywhere, for the current user language.
289 * Use wfMsgForContent() instead if the message should NOT
290 * change depending on the user preferences.
292 * Note that the message may contain HTML, and is therefore
293 * not safe for insertion anywhere. Some functions such as
294 * addWikiText will do the escaping for you. Use wfMsgHtml()
295 * if you need an escaped message.
297 * @param $key String: lookup key for the message, usually
298 * defined in languages/Language.php
300 * This function also takes extra optional parameters (not
301 * shown in the function definition), which can by used to
302 * insert variable text into the predefined message.
304 function wfMsg( $key ) {
305 $args = func_get_args();
306 array_shift( $args );
307 return wfMsgReal( $key, $args, true );
311 * Same as above except doesn't transform the message
313 function wfMsgNoTrans( $key ) {
314 $args = func_get_args();
315 array_shift( $args );
316 return wfMsgReal( $key, $args, true, false, false );
320 * Get a message from anywhere, for the current global language
321 * set with $wgLanguageCode.
323 * Use this if the message should NOT change dependent on the
324 * language set in the user's preferences. This is the case for
325 * most text written into logs, as well as link targets (such as
326 * the name of the copyright policy page). Link titles, on the
327 * other hand, should be shown in the UI language.
329 * Note that MediaWiki allows users to change the user interface
330 * language in their preferences, but a single installation
331 * typically only contains content in one language.
333 * Be wary of this distinction: If you use wfMsg() where you should
334 * use wfMsgForContent(), a user of the software may have to
335 * customize over 70 messages in order to, e.g., fix a link in every
338 * @param $key String: lookup key for the message, usually
339 * defined in languages/Language.php
341 function wfMsgForContent( $key ) {
342 global $wgForceUIMsgAsContentMsg;
343 $args = func_get_args();
344 array_shift( $args );
346 if( is_array( $wgForceUIMsgAsContentMsg ) &&
347 in_array( $key, $wgForceUIMsgAsContentMsg ) )
349 return wfMsgReal( $key, $args, true, $forcontent );
353 * Same as above except doesn't transform the message
355 function wfMsgForContentNoTrans( $key ) {
356 global $wgForceUIMsgAsContentMsg;
357 $args = func_get_args();
358 array_shift( $args );
360 if( is_array( $wgForceUIMsgAsContentMsg ) &&
361 in_array( $key, $wgForceUIMsgAsContentMsg ) )
363 return wfMsgReal( $key, $args, true, $forcontent, false );
367 * Get a message from the language file, for the UI elements
369 function wfMsgNoDB( $key ) {
370 $args = func_get_args();
371 array_shift( $args );
372 return wfMsgReal( $key, $args, false );
376 * Get a message from the language file, for the content
378 function wfMsgNoDBForContent( $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, false, $forcontent );
391 * Really get a message
392 * @param $key String: key to get.
394 * @param $useDB Boolean
395 * @param $transform Boolean: Whether or not to transform the message.
396 * @param $forContent Boolean
397 * @return String: the requested message.
399 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
400 wfProfileIn( __METHOD__
);
401 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
402 $message = wfMsgReplaceArgs( $message, $args );
403 wfProfileOut( __METHOD__
);
408 * This function provides the message source for messages to be edited which are *not* stored in the database.
409 * @param $key String:
411 function wfMsgWeirdKey ( $key ) {
412 $source = wfMsgGetKey( $key, false, true, false );
413 if ( wfEmptyMsg( $key, $source ) )
420 * Fetch a message string value, but don't replace any keys yet.
423 * @param bool $forContent
427 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
428 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
430 /* <Vyznev> btw, is all that code in wfMsgGetKey() that check
431 * if the message cache exists of not really necessary, or is
433 * <TimStarling> Vyznev: it's probably not necessary
434 * <TimStarling> I think I wrote it in an attempt to report DB
435 * connection errors properly
436 * <TimStarling> but eventually we gave up on using the
437 * message cache for that and just hard-coded the strings
438 * <TimStarling> it may have other uses, it's not mere paranoia
441 if ( is_object( $wgMessageCache ) )
442 $transstat = $wgMessageCache->getTransform();
444 if( is_object( $wgMessageCache ) ) {
446 $wgMessageCache->disableTransform();
447 $message = $wgMessageCache->get( $key, $useDB, $forContent );
450 $lang = &$wgContLang;
455 # MessageCache::get() does this already, Language::getMessage() doesn't
456 # ISSUE: Should we try to handle "message/lang" here too?
457 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
459 wfSuppressWarnings();
460 if( is_object( $lang ) ) {
461 $message = $lang->getMessage( $key );
467 if ( $transform && strstr( $message, '{{' ) !== false ) {
468 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
472 if ( is_object( $wgMessageCache ) && ! $transform )
473 $wgMessageCache->setTransform( $transstat );
479 * Replace message parameter keys on the given formatted output.
481 * @param string $message
486 function wfMsgReplaceArgs( $message, $args ) {
487 # Fix windows line-endings
488 # Some messages are split with explode("\n", $msg)
489 $message = str_replace( "\r", '', $message );
492 if ( count( $args ) ) {
493 if ( is_array( $args[0] ) ) {
494 foreach ( $args[0] as $key => $val ) {
495 $message = str_replace( '$' . $key, $val, $message );
498 foreach( $args as $n => $param ) {
499 $replacementKeys['$' . ($n +
1)] = $param;
501 $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 trough htmlspecialchars
550 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
551 * <i>parsemag</i>: transform the message using magic phrases
552 * <i>content</i>: fetch message for content language instead of interface
554 function wfMsgExt( $key, $options ) {
555 global $wgOut, $wgParser;
557 $args = func_get_args();
558 array_shift( $args );
559 array_shift( $args );
561 if( !is_array($options) ) {
562 $options = array($options);
566 if( in_array('content', $options) ) {
570 $string = wfMsgGetKey( $key, /*DB*/true, $forContent, /*Transform*/false );
572 if( !in_array('replaceafter', $options) ) {
573 $string = wfMsgReplaceArgs( $string, $args );
576 if( in_array('parse', $options) ) {
577 $string = $wgOut->parse( $string, true, !$forContent );
578 } elseif ( in_array('parseinline', $options) ) {
579 $string = $wgOut->parse( $string, true, !$forContent );
581 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
584 } elseif ( in_array('parsemag', $options) ) {
585 global $wgMessageCache;
586 if ( isset( $wgMessageCache ) ) {
587 $string = $wgMessageCache->transform( $string, !$forContent );
591 if ( in_array('escape', $options) ) {
592 $string = htmlspecialchars ( $string );
595 if( in_array('replaceafter', $options) ) {
596 $string = wfMsgReplaceArgs( $string, $args );
604 * Just like exit() but makes a note of it.
605 * Commits open transactions except if the error parameter is set
607 * @deprecated Please return control to the caller or throw an exception
609 function wfAbruptExit( $error = false ){
610 global $wgLoadBalancer;
611 static $called = false;
617 $bt = wfDebugBacktrace();
619 for($i = 0; $i < count($bt) ; $i++
){
620 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
621 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
622 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
625 wfDebug('WARNING: Abrupt exit\n');
628 wfLogProfilingData();
631 $wgLoadBalancer->closeAll();
637 * @deprecated Please return control the caller or throw an exception
639 function wfErrorExit() {
640 wfAbruptExit( true );
644 * Print a simple message and die, returning nonzero to the shell if any.
645 * Plain die() fails to return nonzero to the shell if you pass a string.
648 function wfDie( $msg='' ) {
654 * Throw a debugging exception. This function previously once exited the process,
655 * but now throws an exception instead, with similar results.
657 * @param string $msg Message shown when dieing.
659 function wfDebugDieBacktrace( $msg = '' ) {
660 throw new MWException( $msg );
664 * Fetch server name for use in error reporting etc.
665 * Use real server name if available, so we know which machine
666 * in a server farm generated the current page.
669 function wfHostname() {
670 if ( function_exists( 'posix_uname' ) ) {
671 // This function not present on Windows
672 $uname = @posix_uname
();
676 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
677 return $uname['nodename'];
679 # This may be a virtual server.
680 return $_SERVER['SERVER_NAME'];
685 * Returns a HTML comment with the elapsed time since request.
686 * This method has no side effects.
689 function wfReportTime() {
690 global $wgRequestTime, $wgShowHostnames;
693 $elapsed = $now - $wgRequestTime;
695 return $wgShowHostnames
696 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
697 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
701 * Safety wrapper for debug_backtrace().
703 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
704 * murky circumstances, which may be triggered in part by stub objects
705 * or other fancy talkin'.
707 * Will return an empty array if Zend Optimizer is detected, otherwise
708 * the output from debug_backtrace() (trimmed).
710 * @return array of backtrace information
712 function wfDebugBacktrace() {
713 if( extension_loaded( 'Zend Optimizer' ) ) {
714 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
717 return array_slice( debug_backtrace(), 1 );
721 function wfBacktrace() {
722 global $wgCommandLineMode;
724 if ( $wgCommandLineMode ) {
729 $backtrace = wfDebugBacktrace();
730 foreach( $backtrace as $call ) {
731 if( isset( $call['file'] ) ) {
732 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
733 $file = $f[count($f)-1];
737 if( isset( $call['line'] ) ) {
738 $line = $call['line'];
742 if ( $wgCommandLineMode ) {
743 $msg .= "$file line $line calls ";
745 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
747 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
748 $msg .= $call['function'] . '()';
750 if ( $wgCommandLineMode ) {
756 if ( $wgCommandLineMode ) {
766 /* Some generic result counters, pulled out of SearchEngine */
772 function wfShowingResults( $offset, $limit ) {
774 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
780 function wfShowingResultsNum( $offset, $limit, $num ) {
782 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
788 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
790 $fmtLimit = $wgLang->formatNum( $limit );
791 $prev = wfMsg( 'prevn', $fmtLimit );
792 $next = wfMsg( 'nextn', $fmtLimit );
794 if( is_object( $link ) ) {
797 $title = Title
::newFromText( $link );
798 if( is_null( $title ) ) {
803 if ( 0 != $offset ) {
804 $po = $offset - $limit;
805 if ( $po < 0 ) { $po = 0; }
806 $q = "limit={$limit}&offset={$po}";
807 if ( '' != $query ) { $q .= '&'.$query; }
808 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
809 } else { $plink = $prev; }
811 $no = $offset +
$limit;
812 $q = 'limit='.$limit.'&offset='.$no;
813 if ( '' != $query ) { $q .= '&'.$query; }
818 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
820 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
821 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
822 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
823 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
824 wfNumLink( $offset, 500, $title, $query );
826 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
832 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
834 if ( '' == $query ) { $q = ''; }
835 else { $q = $query.'&'; }
836 $q .= 'limit='.$limit.'&offset='.$offset;
838 $fmtLimit = $wgLang->formatNum( $limit );
839 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
845 * @todo FIXME: we may want to blacklist some broken browsers
847 * @return bool Whereas client accept gzip compression
849 function wfClientAcceptsGzip() {
852 # FIXME: we may want to blacklist some broken browsers
855 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
856 $_SERVER['HTTP_ACCEPT_ENCODING'],
858 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
859 wfDebug( " accepts gzip\n" );
867 * Obtain the offset and limit values from the request string;
868 * used in special pages
870 * @param $deflimit Default limit if none supplied
871 * @param $optionname Name of a user preference to check against
875 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
877 return $wgRequest->getLimitOffset( $deflimit, $optionname );
881 * Escapes the given text so that it may be output using addWikiText()
882 * without any linking, formatting, etc. making its way through. This
883 * is achieved by substituting certain characters with HTML entities.
884 * As required by the callers, <nowiki> is not used. It currently does
885 * not filter out characters which have special meaning only at the
886 * start of a line, such as "*".
888 * @param string $text Text to be escaped
890 function wfEscapeWikiText( $text ) {
892 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
893 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
894 htmlspecialchars($text) );
901 function wfQuotedPrintable( $string, $charset = '' ) {
902 # Probably incomplete; see RFC 2045
903 if( empty( $charset ) ) {
904 global $wgInputEncoding;
905 $charset = $wgInputEncoding;
907 $charset = strtoupper( $charset );
908 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
910 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
911 $replace = $illegal . '\t ?_';
912 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
913 $out = "=?$charset?Q?";
914 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
925 return microtime(true);
929 * Sets dest to source and returns the original value of dest
930 * If source is NULL, it just returns the value, it doesn't set the variable
932 function wfSetVar( &$dest, $source ) {
934 if ( !is_null( $source ) ) {
941 * As for wfSetVar except setting a bit
943 function wfSetBit( &$dest, $bit, $state = true ) {
944 $temp = (bool)($dest & $bit );
945 if ( !is_null( $state ) ) {
956 * This function takes two arrays as input, and returns a CGI-style string, e.g.
957 * "days=7&limit=100". Options in the first array override options in the second.
958 * Options set to "" will not be output.
960 function wfArrayToCGI( $array1, $array2 = NULL )
962 if ( !is_null( $array2 ) ) {
963 $array1 = $array1 +
$array2;
967 foreach ( $array1 as $key => $value ) {
968 if ( '' !== $value ) {
972 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
979 * Append a query string to an existing URL, which may or may not already
980 * have query string parameters already. If so, they will be combined.
983 * @param string $query
986 function wfAppendQuery( $url, $query ) {
988 if( false === strpos( $url, '?' ) ) {
999 * This is obsolete, use SquidUpdate::purge()
1002 function wfPurgeSquidServers ($urlArr) {
1003 SquidUpdate
::purge( $urlArr );
1007 * Windows-compatible version of escapeshellarg()
1008 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1009 * function puts single quotes in regardless of OS
1011 function wfEscapeShellArg( ) {
1012 $args = func_get_args();
1015 foreach ( $args as $arg ) {
1022 if ( wfIsWindows() ) {
1023 // Escaping for an MSVC-style command line parser
1024 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1025 // Double the backslashes before any double quotes. Escape the double quotes.
1026 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1029 foreach ( $tokens as $token ) {
1031 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1037 // Double the backslashes before the end of the string, because
1038 // we will soon add a quote
1040 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1041 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1044 // Add surrounding quotes
1045 $retVal .= '"' . $arg . '"';
1047 $retVal .= escapeshellarg( $arg );
1054 * wfMerge attempts to merge differences between three texts.
1055 * Returns true for a clean merge and false for failure or a conflict.
1057 function wfMerge( $old, $mine, $yours, &$result ){
1060 # This check may also protect against code injection in
1061 # case of broken installations.
1062 if(! file_exists( $wgDiff3 ) ){
1063 wfDebug( "diff3 not found\n" );
1067 # Make temporary files
1069 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1070 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1071 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1073 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1074 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1075 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1077 # Check for a conflict
1078 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1079 wfEscapeShellArg( $mytextName ) . ' ' .
1080 wfEscapeShellArg( $oldtextName ) . ' ' .
1081 wfEscapeShellArg( $yourtextName );
1082 $handle = popen( $cmd, 'r' );
1084 if( fgets( $handle, 1024 ) ){
1092 $cmd = $wgDiff3 . ' -a -e --merge ' .
1093 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1094 $handle = popen( $cmd, 'r' );
1097 $data = fread( $handle, 8192 );
1098 if ( strlen( $data ) == 0 ) {
1104 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1106 if ( $result === '' && $old !== '' && $conflict == false ) {
1107 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1116 function wfVarDump( $var ) {
1118 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1119 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1122 $wgOut->addHTML( $s );
1127 * Provide a simple HTTP error.
1129 function wfHttpError( $code, $label, $desc ) {
1132 header( "HTTP/1.0 $code $label" );
1133 header( "Status: $code $label" );
1134 $wgOut->sendCacheControl();
1136 header( 'Content-type: text/html; charset=utf-8' );
1137 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1138 "<html><head><title>" .
1139 htmlspecialchars( $label ) .
1140 "</title></head><body><h1>" .
1141 htmlspecialchars( $label ) .
1143 nl2br( htmlspecialchars( $desc ) ) .
1144 "</p></body></html>\n";
1148 * Clear away any user-level output buffers, discarding contents.
1150 * Suitable for 'starting afresh', for instance when streaming
1151 * relatively large amounts of data without buffering, or wanting to
1152 * output image files without ob_gzhandler's compression.
1154 * The optional $resetGzipEncoding parameter controls suppression of
1155 * the Content-Encoding header sent by ob_gzhandler; by default it
1156 * is left. See comments for wfClearOutputBuffers() for why it would
1159 * Note that some PHP configuration options may add output buffer
1160 * layers which cannot be removed; these are left in place.
1162 * @param bool $resetGzipEncoding
1164 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1165 if( $resetGzipEncoding ) {
1166 // Suppress Content-Encoding and Content-Length
1167 // headers from 1.10+s wfOutputHandler
1168 global $wgDisableOutputCompression;
1169 $wgDisableOutputCompression = true;
1171 while( $status = ob_get_status() ) {
1172 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1173 // Probably from zlib.output_compression or other
1174 // PHP-internal setting which can't be removed.
1176 // Give up, and hope the result doesn't break
1180 if( !ob_end_clean() ) {
1181 // Could not remove output buffer handler; abort now
1182 // to avoid getting in some kind of infinite loop.
1185 if( $resetGzipEncoding ) {
1186 if( $status['name'] == 'ob_gzhandler' ) {
1187 // Reset the 'Content-Encoding' field set by this handler
1188 // so we can start fresh.
1189 header( 'Content-Encoding:' );
1196 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1198 * Clear away output buffers, but keep the Content-Encoding header
1199 * produced by ob_gzhandler, if any.
1201 * This should be used for HTTP 304 responses, where you need to
1202 * preserve the Content-Encoding header of the real result, but
1203 * also need to suppress the output of ob_gzhandler to keep to spec
1204 * and avoid breaking Firefox in rare cases where the headers and
1205 * body are broken over two packets.
1207 function wfClearOutputBuffers() {
1208 wfResetOutputBuffers( false );
1212 * Converts an Accept-* header into an array mapping string values to quality
1215 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1216 # No arg means accept anything (per HTTP spec)
1218 return array( $def => 1 );
1223 $parts = explode( ',', $accept );
1225 foreach( $parts as $part ) {
1226 # FIXME: doesn't deal with params like 'text/html; level=1'
1227 @list
( $value, $qpart ) = explode( ';', $part );
1229 if( !isset( $qpart ) ) {
1231 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1232 $prefs[$value] = $match[1];
1240 * Checks if a given MIME type matches any of the keys in the given
1241 * array. Basic wildcards are accepted in the array keys.
1243 * Returns the matching MIME type (or wildcard) if a match, otherwise
1246 * @param string $type
1247 * @param array $avail
1251 function mimeTypeMatch( $type, $avail ) {
1252 if( array_key_exists($type, $avail) ) {
1255 $parts = explode( '/', $type );
1256 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1257 return $parts[0] . '/*';
1258 } elseif( array_key_exists( '*/*', $avail ) ) {
1267 * Returns the 'best' match between a client's requested internet media types
1268 * and the server's list of available types. Each list should be an associative
1269 * array of type to preference (preference is a float between 0.0 and 1.0).
1270 * Wildcards in the types are acceptable.
1272 * @param array $cprefs Client's acceptable type list
1273 * @param array $sprefs Server's offered types
1276 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1277 * XXX: generalize to negotiate other stuff
1279 function wfNegotiateType( $cprefs, $sprefs ) {
1282 foreach( array_keys($sprefs) as $type ) {
1283 $parts = explode( '/', $type );
1284 if( $parts[1] != '*' ) {
1285 $ckey = mimeTypeMatch( $type, $cprefs );
1287 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1292 foreach( array_keys( $cprefs ) as $type ) {
1293 $parts = explode( '/', $type );
1294 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1295 $skey = mimeTypeMatch( $type, $sprefs );
1297 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1305 foreach( array_keys( $combine ) as $type ) {
1306 if( $combine[$type] > $bestq ) {
1308 $bestq = $combine[$type];
1317 * Returns an array where the values in the first array are replaced by the
1318 * values in the second array with the corresponding keys
1322 function wfArrayLookup( $a, $b ) {
1323 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1327 * Convenience function; returns MediaWiki timestamp for the present time.
1330 function wfTimestampNow() {
1332 return wfTimestamp( TS_MW
, time() );
1336 * Reference-counted warning suppression
1338 function wfSuppressWarnings( $end = false ) {
1339 static $suppressCount = 0;
1340 static $originalLevel = false;
1343 if ( $suppressCount ) {
1345 if ( !$suppressCount ) {
1346 error_reporting( $originalLevel );
1350 if ( !$suppressCount ) {
1351 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1358 * Restore error level to previous value
1360 function wfRestoreWarnings() {
1361 wfSuppressWarnings( true );
1364 # Autodetect, convert and provide timestamps of various types
1367 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1369 define('TS_UNIX', 0);
1372 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1377 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1382 * RFC 2822 format, for E-mail and HTTP headers
1384 define('TS_RFC2822', 3);
1387 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1389 * This is used by Special:Export
1391 define('TS_ISO_8601', 4);
1394 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1396 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1397 * DateTime tag and page 36 for the DateTimeOriginal and
1398 * DateTimeDigitized tags.
1400 define('TS_EXIF', 5);
1403 * Oracle format time.
1405 define('TS_ORACLE', 6);
1408 * Postgres format time.
1410 define('TS_POSTGRES', 7);
1413 * @param mixed $outputtype A timestamp in one of the supported formats, the
1414 * function will autodetect which format is supplied
1415 * and act accordingly.
1416 * @return string Time in the format specified in $outputtype
1418 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1423 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1425 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1426 (int)$da[2],(int)$da[3],(int)$da[1]);
1427 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1429 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1430 (int)$da[2],(int)$da[3],(int)$da[1]);
1431 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1433 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1434 (int)$da[2],(int)$da[3],(int)$da[1]);
1435 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1438 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1440 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1441 str_replace("+00:00", "UTC", $ts)));
1442 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1444 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1445 (int)$da[2],(int)$da[3],(int)$da[1]);
1446 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1448 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1449 (int)$da[2],(int)$da[3],(int)$da[1]);
1450 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1452 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1453 (int)$da[2],(int)$da[3],(int)$da[1]);
1455 # Bogus value; fall back to the epoch...
1456 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1461 switch($outputtype) {
1465 return gmdate( 'YmdHis', $uts );
1467 return gmdate( 'Y-m-d H:i:s', $uts );
1469 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1470 // This shouldn't ever be used, but is included for completeness
1472 return gmdate( 'Y:m:d H:i:s', $uts );
1474 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1476 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1478 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1480 throw new MWException( 'wfTimestamp() called with illegal output type.');
1485 * Return a formatted timestamp, or null if input is null.
1486 * For dealing with nullable timestamp columns in the database.
1487 * @param int $outputtype
1491 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1492 if( is_null( $ts ) ) {
1495 return wfTimestamp( $outputtype, $ts );
1500 * Check if the operating system is Windows
1502 * @return bool True if it's Windows, False otherwise.
1504 function wfIsWindows() {
1505 if (substr(php_uname(), 0, 7) == 'Windows') {
1513 * Swap two variables
1515 function swap( &$x, &$y ) {
1521 function wfGetCachedNotice( $name ) {
1522 global $wgOut, $parserMemc;
1523 $fname = 'wfGetCachedNotice';
1524 wfProfileIn( $fname );
1528 if( $name === 'default' ) {
1530 global $wgSiteNotice;
1531 $notice = $wgSiteNotice;
1532 if( empty( $notice ) ) {
1533 wfProfileOut( $fname );
1537 $notice = wfMsgForContentNoTrans( $name );
1538 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1539 wfProfileOut( $fname );
1544 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1545 if( is_array( $cachedNotice ) ) {
1546 if( md5( $notice ) == $cachedNotice['hash'] ) {
1547 $notice = $cachedNotice['html'];
1556 if( is_object( $wgOut ) ) {
1557 $parsed = $wgOut->parse( $notice );
1558 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1561 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1566 wfProfileOut( $fname );
1570 function wfGetNamespaceNotice() {
1574 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1577 $fname = 'wfGetNamespaceNotice';
1578 wfProfileIn( $fname );
1580 $key = "namespacenotice-" . $wgTitle->getNsText();
1581 $namespaceNotice = wfGetCachedNotice( $key );
1582 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1583 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1585 $namespaceNotice = "";
1588 wfProfileOut( $fname );
1589 return $namespaceNotice;
1592 function wfGetSiteNotice() {
1593 global $wgUser, $wgSiteNotice;
1594 $fname = 'wfGetSiteNotice';
1595 wfProfileIn( $fname );
1598 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1599 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1600 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1602 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1603 if( !$anonNotice ) {
1604 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1606 $siteNotice = $anonNotice;
1609 if( !$siteNotice ) {
1610 $siteNotice = wfGetCachedNotice( 'default' );
1614 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1615 wfProfileOut( $fname );
1620 * BC wrapper for MimeMagic::singleton()
1623 function &wfGetMimeMagic() {
1624 return MimeMagic
::singleton();
1628 * Tries to get the system directory for temporary files.
1629 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1630 * and if none are set /tmp is returned as the generic Unix default.
1632 * NOTE: When possible, use the tempfile() function to create temporary
1633 * files to avoid race conditions on file creation, etc.
1637 function wfTempDir() {
1638 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1639 $tmp = getenv( $var );
1640 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1644 # Hope this is Unix of some kind!
1649 * Make directory, and make all parent directories if they don't exist
1651 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1652 if( strval( $fullDir ) === '' )
1654 if( file_exists( $fullDir ) )
1656 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR
, $fullDir ), $mode, true );
1660 * Increment a statistics counter
1662 function wfIncrStats( $key ) {
1664 $key = wfMemcKey( 'stats', $key );
1665 if ( is_null( $wgMemc->incr( $key ) ) ) {
1666 $wgMemc->add( $key, 1 );
1671 * @param mixed $nr The number to format
1672 * @param int $acc The number of digits after the decimal point, default 2
1673 * @param bool $round Whether or not to round the value, default true
1676 function wfPercent( $nr, $acc = 2, $round = true ) {
1677 $ret = sprintf( "%.${acc}f", $nr );
1678 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1682 * Encrypt a username/password.
1684 * @param string $userid ID of the user
1685 * @param string $password Password of the user
1686 * @return string Hashed password
1688 function wfEncryptPassword( $userid, $password ) {
1689 global $wgPasswordSalt;
1690 $p = md5( $password);
1693 return md5( "{$userid}-{$p}" );
1699 * Appends to second array if $value differs from that in $default
1701 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1702 if ( is_null( $changed ) ) {
1703 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1705 if ( $default[$key] !== $value ) {
1706 $changed[$key] = $value;
1711 * Since wfMsg() and co suck, they don't return false if the message key they
1712 * looked up didn't exist but a XHTML string, this function checks for the
1713 * nonexistance of messages by looking at wfMsg() output
1715 * @param $msg The message key looked up
1716 * @param $wfMsgOut The output of wfMsg*()
1719 function wfEmptyMsg( $msg, $wfMsgOut ) {
1720 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1724 * Find out whether or not a mixed variable exists in a string
1726 * @param mixed needle
1727 * @param string haystack
1730 function in_string( $needle, $str ) {
1731 return strpos( $str, $needle ) !== false;
1734 function wfSpecialList( $page, $details ) {
1736 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1737 return $page . $details;
1741 * Returns a regular expression of url protocols
1745 function wfUrlProtocols() {
1746 global $wgUrlProtocols;
1748 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1749 // with LocalSettings files from 1.5
1750 if ( is_array( $wgUrlProtocols ) ) {
1751 $protocols = array();
1752 foreach ($wgUrlProtocols as $protocol)
1753 $protocols[] = preg_quote( $protocol, '/' );
1755 return implode( '|', $protocols );
1757 return $wgUrlProtocols;
1762 * Safety wrapper around ini_get() for boolean settings.
1763 * The values returned from ini_get() are pre-normalized for settings
1764 * set via php.ini or php_flag/php_admin_flag... but *not*
1765 * for those set via php_value/php_admin_value.
1767 * It's fairly common for people to use php_value instead of php_flag,
1768 * which can leave you with an 'off' setting giving a false positive
1769 * for code that just takes the ini_get() return value as a boolean.
1771 * To make things extra interesting, setting via php_value accepts
1772 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1773 * Unrecognized values go false... again opposite PHP's own coercion
1774 * from string to bool.
1776 * Luckily, 'properly' set settings will always come back as '0' or '1',
1777 * so we only have to worry about them and the 'improper' settings.
1779 * I frickin' hate PHP... :P
1781 * @param string $setting
1784 function wfIniGetBool( $setting ) {
1785 $val = ini_get( $setting );
1786 // 'on' and 'true' can't have whitespace around them, but '1' can.
1787 return strtolower( $val ) == 'on'
1788 ||
strtolower( $val ) == 'true'
1789 ||
strtolower( $val ) == 'yes'
1790 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1794 * Execute a shell command, with time and memory limits mirrored from the PHP
1795 * configuration if supported.
1796 * @param $cmd Command line, properly escaped for shell.
1797 * @param &$retval optional, will receive the program's exit code.
1798 * (non-zero is usually failure)
1799 * @return collected stdout as a string (trailing newlines stripped)
1801 function wfShellExec( $cmd, &$retval=null ) {
1802 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1804 if( wfIniGetBool( 'safe_mode' ) ) {
1805 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1807 return "Unable to run external programs in safe mode.";
1810 if ( php_uname( 's' ) == 'Linux' ) {
1811 $time = intval( ini_get( 'max_execution_time' ) );
1812 $mem = intval( $wgMaxShellMemory );
1813 $filesize = intval( $wgMaxShellFileSize );
1815 if ( $time > 0 && $mem > 0 ) {
1816 $script = "$IP/bin/ulimit4.sh";
1817 if ( is_executable( $script ) ) {
1818 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1821 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1822 # This is a hack to work around PHP's flawed invocation of cmd.exe
1823 # http://news.php.net/php.internals/21796
1824 $cmd = '"' . $cmd . '"';
1826 wfDebug( "wfShellExec: $cmd\n" );
1829 $retval = 1; // error by default?
1830 exec( $cmd, $output, $retval ); // returns the last line of output.
1831 return implode( "\n", $output );
1836 * This function works like "use VERSION" in Perl, the program will die with a
1837 * backtrace if the current version of PHP is less than the version provided
1839 * This is useful for extensions which due to their nature are not kept in sync
1840 * with releases, and might depend on other versions of PHP than the main code
1842 * Note: PHP might die due to parsing errors in some cases before it ever
1843 * manages to call this function, such is life
1845 * @see perldoc -f use
1847 * @param mixed $version The version to check, can be a string, an integer, or
1850 function wfUsePHP( $req_ver ) {
1851 $php_ver = PHP_VERSION
;
1853 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1854 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1858 * This function works like "use VERSION" in Perl except it checks the version
1859 * of MediaWiki, the program will die with a backtrace if the current version
1860 * of MediaWiki is less than the version provided.
1862 * This is useful for extensions which due to their nature are not kept in sync
1865 * @see perldoc -f use
1867 * @param mixed $version The version to check, can be a string, an integer, or
1870 function wfUseMW( $req_ver ) {
1873 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1874 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1878 * @deprecated use StringUtils::escapeRegexReplacement
1880 function wfRegexReplacement( $string ) {
1881 return StringUtils
::escapeRegexReplacement( $string );
1885 * Return the final portion of a pathname.
1886 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1887 * http://bugs.php.net/bug.php?id=33898
1889 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1890 * We'll consider it so always, as we don't want \s in our Unix paths either.
1892 * @param string $path
1893 * @param string $suffix to remove if present
1896 function wfBaseName( $path, $suffix='' ) {
1897 $encSuffix = ($suffix == '')
1899 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1901 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1909 * Generate a relative path name to the given file.
1910 * May explode on non-matching case-insensitive paths,
1911 * funky symlinks, etc.
1913 * @param string $path Absolute destination path including target filename
1914 * @param string $from Absolute source path, directory only
1917 function wfRelativePath( $path, $from ) {
1918 // Normalize mixed input on Windows...
1919 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1920 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1922 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1923 $against = explode( DIRECTORY_SEPARATOR
, $from );
1925 // Trim off common prefix
1926 while( count( $pieces ) && count( $against )
1927 && $pieces[0] == $against[0] ) {
1928 array_shift( $pieces );
1929 array_shift( $against );
1932 // relative dots to bump us to the parent
1933 while( count( $against ) ) {
1934 array_unshift( $pieces, '..' );
1935 array_shift( $against );
1938 array_push( $pieces, wfBaseName( $path ) );
1940 return implode( DIRECTORY_SEPARATOR
, $pieces );
1944 * Make a URL index, appropriate for the el_index field of externallinks.
1946 function wfMakeUrlIndex( $url ) {
1947 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1948 $bits = parse_url( $url );
1949 wfSuppressWarnings();
1950 wfRestoreWarnings();
1954 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1956 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1958 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1960 // parse_url detects for news: and mailto: the host part of an url as path
1961 // We have to correct this wrong detection
1962 if ( isset ( $bits['path'] ) ) {
1963 $bits['host'] = $bits['path'];
1970 // Reverse the labels in the hostname, convert to lower case
1971 // For emails reverse domainpart only
1972 if ( $bits['scheme'] == 'mailto' ) {
1973 $mailparts = explode( '@', $bits['host'] );
1974 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1975 $reversedHost = $domainpart . '@' . $mailparts[0];
1977 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1979 // Add an extra dot to the end
1980 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1981 $reversedHost .= '.';
1983 // Reconstruct the pseudo-URL
1984 $prot = $bits['scheme'];
1985 $index = "$prot$delimiter$reversedHost";
1986 // Leave out user and password. Add the port, path, query and fragment
1987 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1988 if ( isset( $bits['path'] ) ) {
1989 $index .= $bits['path'];
1993 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1994 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1999 * Do any deferred updates and clear the list
2000 * TODO: This could be in Wiki.php if that class made any sense at all
2002 function wfDoUpdates()
2004 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2005 foreach ( $wgDeferredUpdateList as $update ) {
2006 $update->doUpdate();
2008 foreach ( $wgPostCommitUpdateList as $update ) {
2009 $update->doUpdate();
2011 $wgDeferredUpdateList = array();
2012 $wgPostCommitUpdateList = array();
2016 * @deprecated use StringUtils::explodeMarkup
2018 function wfExplodeMarkup( $separator, $text ) {
2019 return StringUtils
::explodeMarkup( $separator, $text );
2023 * Convert an arbitrarily-long digit string from one numeric base
2024 * to another, optionally zero-padding to a minimum column width.
2026 * Supports base 2 through 36; digit values 10-36 are represented
2027 * as lowercase letters a-z. Input is case-insensitive.
2029 * @param $input string of digits
2030 * @param $sourceBase int 2-36
2031 * @param $destBase int 2-36
2032 * @param $pad int 1 or greater
2033 * @param $lowercase bool
2034 * @return string or false on invalid input
2036 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2037 $input = strval( $input );
2038 if( $sourceBase < 2 ||
2043 $sourceBase != intval( $sourceBase ) ||
2044 $destBase != intval( $destBase ) ||
2045 $pad != intval( $pad ) ||
2046 !is_string( $input ) ||
2050 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2051 $inDigits = array();
2054 // Decode and validate input string
2055 $input = strtolower( $input );
2056 for( $i = 0; $i < strlen( $input ); $i++
) {
2057 $n = strpos( $digitChars, $input{$i} );
2058 if( $n === false ||
$n > $sourceBase ) {
2064 // Iterate over the input, modulo-ing out an output digit
2065 // at a time until input is gone.
2066 while( count( $inDigits ) ) {
2068 $workDigits = array();
2071 foreach( $inDigits as $digit ) {
2072 $work *= $sourceBase;
2075 if( $work < $destBase ) {
2076 // Gonna need to pull another digit.
2077 if( count( $workDigits ) ) {
2078 // Avoid zero-padding; this lets us find
2079 // the end of the input very easily when
2080 // length drops to zero.
2084 // Finally! Actual division!
2085 $workDigits[] = intval( $work / $destBase );
2087 // Isn't it annoying that most programming languages
2088 // don't have a single divide-and-remainder operator,
2089 // even though the CPU implements it that way?
2090 $work = $work %
$destBase;
2094 // All that division leaves us with a remainder,
2095 // which is conveniently our next output digit.
2096 $outChars .= $digitChars[$work];
2099 $inDigits = $workDigits;
2102 while( strlen( $outChars ) < $pad ) {
2106 return strrev( $outChars );
2110 * Create an object with a given name and an array of construct parameters
2111 * @param string $name
2112 * @param array $p parameters
2114 function wfCreateObject( $name, $p ){
2115 $p = array_values( $p );
2116 switch ( count( $p ) ) {
2120 return new $name( $p[0] );
2122 return new $name( $p[0], $p[1] );
2124 return new $name( $p[0], $p[1], $p[2] );
2126 return new $name( $p[0], $p[1], $p[2], $p[3] );
2128 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2130 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2132 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2137 * Aliases for modularized functions
2139 function wfGetHTTP( $url, $timeout = 'default' ) {
2140 return Http
::get( $url, $timeout );
2142 function wfIsLocalURL( $url ) {
2143 return Http
::isLocalURL( $url );
2147 * Initialise php session
2149 function wfSetupSession() {
2150 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2151 if( $wgSessionsInMemcached ) {
2152 require_once( 'MemcachedSessions.php' );
2153 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2154 # If it's left on 'user' or another setting from another
2155 # application, it will end up failing. Try to recover.
2156 ini_set ( 'session.save_handler', 'files' );
2158 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2159 session_cache_limiter( 'private, must-revalidate' );
2164 * Get an object from the precompiled serialized directory
2166 * @return mixed The variable on success, false on failure
2168 function wfGetPrecompiledData( $name ) {
2171 $file = "$IP/serialized/$name";
2172 if ( file_exists( $file ) ) {
2173 $blob = file_get_contents( $file );
2175 return unserialize( $blob );
2181 function wfGetCaller( $level = 2 ) {
2182 $backtrace = wfDebugBacktrace();
2183 if ( isset( $backtrace[$level] ) ) {
2184 if ( isset( $backtrace[$level]['class'] ) ) {
2185 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2187 $caller = $backtrace[$level]['function'];
2190 $caller = 'unknown';
2195 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2196 function wfGetAllCallers() {
2197 return implode('/', array_map(
2198 create_function('$frame','
2199 return isset( $frame["class"] )?
2200 $frame["class"]."::".$frame["function"]:
2203 array_reverse(wfDebugBacktrace())));
2209 function wfMemcKey( /*... */ ) {
2210 global $wgDBprefix, $wgDBname;
2211 $args = func_get_args();
2212 if ( $wgDBprefix ) {
2213 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2215 $key = $wgDBname . ':' . implode( ':', $args );
2221 * Get a cache key for a foreign DB
2223 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2224 $args = array_slice( func_get_args(), 2 );
2226 $key = "$db-$prefix:" . implode( ':', $args );
2228 $key = $db . ':' . implode( ':', $args );
2234 * Get an ASCII string identifying this wiki
2235 * This is used as a prefix in memcached keys
2237 function wfWikiID() {
2238 global $wgDBprefix, $wgDBname;
2239 if ( $wgDBprefix ) {
2240 return "$wgDBname-$wgDBprefix";
2247 * Get a Database object
2248 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2249 * master (for write queries), DB_SLAVE for potentially lagged
2250 * read queries, or an integer >= 0 for a particular server.
2252 * @param mixed $groups Query groups. An array of group names that this query
2253 * belongs to. May contain a single string if the query is only
2256 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2257 global $wgLoadBalancer;
2258 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2264 * Shortcut for RepoGroup::singleton()->findFile()
2265 * @param mixed $title Title object or string. May be interwiki.
2266 * @param mixed $time Requested time for an archived image, or false for the
2267 * current version. An image object will be returned which
2268 * existed at or before the specified time.
2269 * @return File, or false if the file does not exist
2271 function wfFindFile( $title, $time = false ) {
2272 return RepoGroup
::singleton()->findFile( $title, $time );
2276 * Get an object referring to a locally registered file.
2277 * Returns a valid placeholder object if the file does not exist.
2279 function wfLocalFile( $title ) {
2280 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2284 * Should low-performance queries be disabled?
2288 function wfQueriesMustScale() {
2289 global $wgMiserMode;
2291 ||
( SiteStats
::pages() > 100000
2292 && SiteStats
::edits() > 1000000
2293 && SiteStats
::users() > 10000 );
2297 * Get the path to a specified script file, respecting file
2298 * extensions; this is a wrapper around $wgScriptExtension etc.
2300 * @param string $script Script filename, sans extension
2303 function wfScript( $script = 'index' ) {
2304 global $wgScriptPath, $wgScriptExtension;
2305 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2309 * Convenience function converts boolean values into "true"
2310 * or "false" (string) values
2312 * @param bool $value
2315 function wfBoolToStr( $value ) {
2316 return $value ?
'true' : 'false';
2320 * Load an extension messages file
2322 function wfLoadExtensionMessages( $extensionName ) {
2323 global $wgExtensionMessagesFiles, $wgMessageCache;
2324 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2325 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2326 // Prevent double-loading
2327 $wgExtensionMessagesFiles[$extensionName] = false;
2332 * Get a platform-independent path to the null file, e.g.
2337 function wfGetNull() {
2338 return wfIsWindows()