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 # If $wgMessageCache isn't initialised yet, try to return something sensible.
431 if( is_object( $wgMessageCache ) ) {
432 $message = $wgMessageCache->get( $key, $useDB, $forContent );
434 $message = $wgMessageCache->transform( $message );
438 $lang = &$wgContLang;
443 # MessageCache::get() does this already, Language::getMessage() doesn't
444 # ISSUE: Should we try to handle "message/lang" here too?
445 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
447 if( is_object( $lang ) ) {
448 $message = $lang->getMessage( $key );
458 * Replace message parameter keys on the given formatted output.
460 * @param string $message
465 function wfMsgReplaceArgs( $message, $args ) {
466 # Fix windows line-endings
467 # Some messages are split with explode("\n", $msg)
468 $message = str_replace( "\r", '', $message );
471 if ( count( $args ) ) {
472 if ( is_array( $args[0] ) ) {
473 foreach ( $args[0] as $key => $val ) {
474 $message = str_replace( '$' . $key, $val, $message );
477 foreach( $args as $n => $param ) {
478 $replacementKeys['$' . ($n +
1)] = $param;
480 $message = strtr( $message, $replacementKeys );
488 * Return an HTML-escaped version of a message.
489 * Parameter replacements, if any, are done *after* the HTML-escaping,
490 * so parameters may contain HTML (eg links or form controls). Be sure
491 * to pre-escape them if you really do want plaintext, or just wrap
492 * the whole thing in htmlspecialchars().
495 * @param string ... parameters
498 function wfMsgHtml( $key ) {
499 $args = func_get_args();
500 array_shift( $args );
501 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
505 * Return an HTML version of message
506 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
507 * so parameters may contain HTML (eg links or form controls). Be sure
508 * to pre-escape them if you really do want plaintext, or just wrap
509 * the whole thing in htmlspecialchars().
512 * @param string ... parameters
515 function wfMsgWikiHtml( $key ) {
517 $args = func_get_args();
518 array_shift( $args );
519 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
523 * Returns message in the requested format
524 * @param string $key Key of the message
525 * @param array $options Processing rules:
526 * <i>parse</i>: parses wikitext to html
527 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
528 * <i>escape</i>: filters message through htmlspecialchars
529 * <i>escapenoentities</i>: same, but allows entity references like through
530 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
531 * <i>parsemag</i>: transform the message using magic phrases
532 * <i>content</i>: fetch message for content language instead of interface
533 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
535 function wfMsgExt( $key, $options ) {
536 global $wgOut, $wgParser;
538 $args = func_get_args();
539 array_shift( $args );
540 array_shift( $args );
542 if( !is_array($options) ) {
543 $options = array($options);
547 if( in_array('content', $options) ) {
551 $string = wfMsgGetKey( $key, /*DB*/true, $forContent, /*Transform*/false );
553 if( !in_array('replaceafter', $options) ) {
554 $string = wfMsgReplaceArgs( $string, $args );
557 if( in_array('parse', $options) ) {
558 $string = $wgOut->parse( $string, true, !$forContent );
559 } elseif ( in_array('parseinline', $options) ) {
560 $string = $wgOut->parse( $string, true, !$forContent );
562 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
565 } elseif ( in_array('parsemag', $options) ) {
566 global $wgMessageCache;
567 if ( isset( $wgMessageCache ) ) {
568 $string = $wgMessageCache->transform( $string, !$forContent );
572 if ( in_array('escape', $options) ) {
573 $string = htmlspecialchars ( $string );
574 } elseif ( in_array( 'escapenoentities', $options ) ) {
575 $string = htmlspecialchars( $string );
576 $string = str_replace( '&', '&', $string );
577 $string = Sanitizer
::normalizeCharReferences( $string );
580 if( in_array('replaceafter', $options) ) {
581 $string = wfMsgReplaceArgs( $string, $args );
589 * Just like exit() but makes a note of it.
590 * Commits open transactions except if the error parameter is set
592 * @deprecated Please return control to the caller or throw an exception
594 function wfAbruptExit( $error = false ){
595 global $wgLoadBalancer;
596 static $called = false;
602 $bt = wfDebugBacktrace();
604 for($i = 0; $i < count($bt) ; $i++
){
605 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
606 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
607 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
610 wfDebug('WARNING: Abrupt exit\n');
613 wfLogProfilingData();
616 $wgLoadBalancer->closeAll();
622 * @deprecated Please return control the caller or throw an exception
624 function wfErrorExit() {
625 wfAbruptExit( true );
629 * Print a simple message and die, returning nonzero to the shell if any.
630 * Plain die() fails to return nonzero to the shell if you pass a string.
633 function wfDie( $msg='' ) {
639 * Throw a debugging exception. This function previously once exited the process,
640 * but now throws an exception instead, with similar results.
642 * @param string $msg Message shown when dieing.
644 function wfDebugDieBacktrace( $msg = '' ) {
645 throw new MWException( $msg );
649 * Fetch server name for use in error reporting etc.
650 * Use real server name if available, so we know which machine
651 * in a server farm generated the current page.
654 function wfHostname() {
655 if ( function_exists( 'posix_uname' ) ) {
656 // This function not present on Windows
657 $uname = @posix_uname
();
661 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
662 return $uname['nodename'];
664 # This may be a virtual server.
665 return $_SERVER['SERVER_NAME'];
670 * Returns a HTML comment with the elapsed time since request.
671 * This method has no side effects.
674 function wfReportTime() {
675 global $wgRequestTime, $wgShowHostnames;
678 $elapsed = $now - $wgRequestTime;
680 return $wgShowHostnames
681 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
682 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
686 * Safety wrapper for debug_backtrace().
688 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
689 * murky circumstances, which may be triggered in part by stub objects
690 * or other fancy talkin'.
692 * Will return an empty array if Zend Optimizer is detected, otherwise
693 * the output from debug_backtrace() (trimmed).
695 * @return array of backtrace information
697 function wfDebugBacktrace() {
698 if( extension_loaded( 'Zend Optimizer' ) ) {
699 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
702 return array_slice( debug_backtrace(), 1 );
706 function wfBacktrace() {
707 global $wgCommandLineMode;
709 if ( $wgCommandLineMode ) {
714 $backtrace = wfDebugBacktrace();
715 foreach( $backtrace as $call ) {
716 if( isset( $call['file'] ) ) {
717 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
718 $file = $f[count($f)-1];
722 if( isset( $call['line'] ) ) {
723 $line = $call['line'];
727 if ( $wgCommandLineMode ) {
728 $msg .= "$file line $line calls ";
730 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
732 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
733 $msg .= $call['function'] . '()';
735 if ( $wgCommandLineMode ) {
741 if ( $wgCommandLineMode ) {
751 /* Some generic result counters, pulled out of SearchEngine */
757 function wfShowingResults( $offset, $limit ) {
759 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
765 function wfShowingResultsNum( $offset, $limit, $num ) {
767 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
773 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
775 $fmtLimit = $wgLang->formatNum( $limit );
776 $prev = wfMsg( 'prevn', $fmtLimit );
777 $next = wfMsg( 'nextn', $fmtLimit );
779 if( is_object( $link ) ) {
782 $title = Title
::newFromText( $link );
783 if( is_null( $title ) ) {
788 if ( 0 != $offset ) {
789 $po = $offset - $limit;
790 if ( $po < 0 ) { $po = 0; }
791 $q = "limit={$limit}&offset={$po}";
792 if ( '' != $query ) { $q .= '&'.$query; }
793 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
794 } else { $plink = $prev; }
796 $no = $offset +
$limit;
797 $q = 'limit='.$limit.'&offset='.$no;
798 if ( '' != $query ) { $q .= '&'.$query; }
803 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
805 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
806 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
807 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
808 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
809 wfNumLink( $offset, 500, $title, $query );
811 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
817 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
819 if ( '' == $query ) { $q = ''; }
820 else { $q = $query.'&'; }
821 $q .= 'limit='.$limit.'&offset='.$offset;
823 $fmtLimit = $wgLang->formatNum( $limit );
824 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
830 * @todo FIXME: we may want to blacklist some broken browsers
832 * @return bool Whereas client accept gzip compression
834 function wfClientAcceptsGzip() {
837 # FIXME: we may want to blacklist some broken browsers
840 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
841 $_SERVER['HTTP_ACCEPT_ENCODING'],
843 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
844 wfDebug( " accepts gzip\n" );
852 * Obtain the offset and limit values from the request string;
853 * used in special pages
855 * @param $deflimit Default limit if none supplied
856 * @param $optionname Name of a user preference to check against
860 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
862 return $wgRequest->getLimitOffset( $deflimit, $optionname );
866 * Escapes the given text so that it may be output using addWikiText()
867 * without any linking, formatting, etc. making its way through. This
868 * is achieved by substituting certain characters with HTML entities.
869 * As required by the callers, <nowiki> is not used. It currently does
870 * not filter out characters which have special meaning only at the
871 * start of a line, such as "*".
873 * @param string $text Text to be escaped
875 function wfEscapeWikiText( $text ) {
877 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
878 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
879 htmlspecialchars($text) );
886 function wfQuotedPrintable( $string, $charset = '' ) {
887 # Probably incomplete; see RFC 2045
888 if( empty( $charset ) ) {
889 global $wgInputEncoding;
890 $charset = $wgInputEncoding;
892 $charset = strtoupper( $charset );
893 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
895 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
896 $replace = $illegal . '\t ?_';
897 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
898 $out = "=?$charset?Q?";
899 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
910 return microtime(true);
914 * Sets dest to source and returns the original value of dest
915 * If source is NULL, it just returns the value, it doesn't set the variable
917 function wfSetVar( &$dest, $source ) {
919 if ( !is_null( $source ) ) {
926 * As for wfSetVar except setting a bit
928 function wfSetBit( &$dest, $bit, $state = true ) {
929 $temp = (bool)($dest & $bit );
930 if ( !is_null( $state ) ) {
941 * This function takes two arrays as input, and returns a CGI-style string, e.g.
942 * "days=7&limit=100". Options in the first array override options in the second.
943 * Options set to "" will not be output.
945 function wfArrayToCGI( $array1, $array2 = NULL )
947 if ( !is_null( $array2 ) ) {
948 $array1 = $array1 +
$array2;
952 foreach ( $array1 as $key => $value ) {
953 if ( '' !== $value ) {
957 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
964 * Append a query string to an existing URL, which may or may not already
965 * have query string parameters already. If so, they will be combined.
968 * @param string $query
971 function wfAppendQuery( $url, $query ) {
973 if( false === strpos( $url, '?' ) ) {
984 * This is obsolete, use SquidUpdate::purge()
987 function wfPurgeSquidServers ($urlArr) {
988 SquidUpdate
::purge( $urlArr );
992 * Windows-compatible version of escapeshellarg()
993 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
994 * function puts single quotes in regardless of OS
996 function wfEscapeShellArg( ) {
997 $args = func_get_args();
1000 foreach ( $args as $arg ) {
1007 if ( wfIsWindows() ) {
1008 // Escaping for an MSVC-style command line parser
1009 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1010 // Double the backslashes before any double quotes. Escape the double quotes.
1011 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1014 foreach ( $tokens as $token ) {
1016 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1022 // Double the backslashes before the end of the string, because
1023 // we will soon add a quote
1025 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1026 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1029 // Add surrounding quotes
1030 $retVal .= '"' . $arg . '"';
1032 $retVal .= escapeshellarg( $arg );
1039 * wfMerge attempts to merge differences between three texts.
1040 * Returns true for a clean merge and false for failure or a conflict.
1042 function wfMerge( $old, $mine, $yours, &$result ){
1045 # This check may also protect against code injection in
1046 # case of broken installations.
1047 if(! file_exists( $wgDiff3 ) ){
1048 wfDebug( "diff3 not found\n" );
1052 # Make temporary files
1054 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1055 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1056 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1058 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1059 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1060 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1062 # Check for a conflict
1063 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1064 wfEscapeShellArg( $mytextName ) . ' ' .
1065 wfEscapeShellArg( $oldtextName ) . ' ' .
1066 wfEscapeShellArg( $yourtextName );
1067 $handle = popen( $cmd, 'r' );
1069 if( fgets( $handle, 1024 ) ){
1077 $cmd = $wgDiff3 . ' -a -e --merge ' .
1078 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1079 $handle = popen( $cmd, 'r' );
1082 $data = fread( $handle, 8192 );
1083 if ( strlen( $data ) == 0 ) {
1089 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1091 if ( $result === '' && $old !== '' && $conflict == false ) {
1092 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1101 function wfVarDump( $var ) {
1103 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1104 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1107 $wgOut->addHTML( $s );
1112 * Provide a simple HTTP error.
1114 function wfHttpError( $code, $label, $desc ) {
1117 header( "HTTP/1.0 $code $label" );
1118 header( "Status: $code $label" );
1119 $wgOut->sendCacheControl();
1121 header( 'Content-type: text/html; charset=utf-8' );
1122 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1123 "<html><head><title>" .
1124 htmlspecialchars( $label ) .
1125 "</title></head><body><h1>" .
1126 htmlspecialchars( $label ) .
1128 nl2br( htmlspecialchars( $desc ) ) .
1129 "</p></body></html>\n";
1133 * Clear away any user-level output buffers, discarding contents.
1135 * Suitable for 'starting afresh', for instance when streaming
1136 * relatively large amounts of data without buffering, or wanting to
1137 * output image files without ob_gzhandler's compression.
1139 * The optional $resetGzipEncoding parameter controls suppression of
1140 * the Content-Encoding header sent by ob_gzhandler; by default it
1141 * is left. See comments for wfClearOutputBuffers() for why it would
1144 * Note that some PHP configuration options may add output buffer
1145 * layers which cannot be removed; these are left in place.
1147 * @param bool $resetGzipEncoding
1149 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1150 if( $resetGzipEncoding ) {
1151 // Suppress Content-Encoding and Content-Length
1152 // headers from 1.10+s wfOutputHandler
1153 global $wgDisableOutputCompression;
1154 $wgDisableOutputCompression = true;
1156 while( $status = ob_get_status() ) {
1157 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1158 // Probably from zlib.output_compression or other
1159 // PHP-internal setting which can't be removed.
1161 // Give up, and hope the result doesn't break
1165 if( !ob_end_clean() ) {
1166 // Could not remove output buffer handler; abort now
1167 // to avoid getting in some kind of infinite loop.
1170 if( $resetGzipEncoding ) {
1171 if( $status['name'] == 'ob_gzhandler' ) {
1172 // Reset the 'Content-Encoding' field set by this handler
1173 // so we can start fresh.
1174 header( 'Content-Encoding:' );
1181 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1183 * Clear away output buffers, but keep the Content-Encoding header
1184 * produced by ob_gzhandler, if any.
1186 * This should be used for HTTP 304 responses, where you need to
1187 * preserve the Content-Encoding header of the real result, but
1188 * also need to suppress the output of ob_gzhandler to keep to spec
1189 * and avoid breaking Firefox in rare cases where the headers and
1190 * body are broken over two packets.
1192 function wfClearOutputBuffers() {
1193 wfResetOutputBuffers( false );
1197 * Converts an Accept-* header into an array mapping string values to quality
1200 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1201 # No arg means accept anything (per HTTP spec)
1203 return array( $def => 1 );
1208 $parts = explode( ',', $accept );
1210 foreach( $parts as $part ) {
1211 # FIXME: doesn't deal with params like 'text/html; level=1'
1212 @list
( $value, $qpart ) = explode( ';', $part );
1214 if( !isset( $qpart ) ) {
1216 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1217 $prefs[$value] = $match[1];
1225 * Checks if a given MIME type matches any of the keys in the given
1226 * array. Basic wildcards are accepted in the array keys.
1228 * Returns the matching MIME type (or wildcard) if a match, otherwise
1231 * @param string $type
1232 * @param array $avail
1236 function mimeTypeMatch( $type, $avail ) {
1237 if( array_key_exists($type, $avail) ) {
1240 $parts = explode( '/', $type );
1241 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1242 return $parts[0] . '/*';
1243 } elseif( array_key_exists( '*/*', $avail ) ) {
1252 * Returns the 'best' match between a client's requested internet media types
1253 * and the server's list of available types. Each list should be an associative
1254 * array of type to preference (preference is a float between 0.0 and 1.0).
1255 * Wildcards in the types are acceptable.
1257 * @param array $cprefs Client's acceptable type list
1258 * @param array $sprefs Server's offered types
1261 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1262 * XXX: generalize to negotiate other stuff
1264 function wfNegotiateType( $cprefs, $sprefs ) {
1267 foreach( array_keys($sprefs) as $type ) {
1268 $parts = explode( '/', $type );
1269 if( $parts[1] != '*' ) {
1270 $ckey = mimeTypeMatch( $type, $cprefs );
1272 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1277 foreach( array_keys( $cprefs ) as $type ) {
1278 $parts = explode( '/', $type );
1279 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1280 $skey = mimeTypeMatch( $type, $sprefs );
1282 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1290 foreach( array_keys( $combine ) as $type ) {
1291 if( $combine[$type] > $bestq ) {
1293 $bestq = $combine[$type];
1302 * Returns an array where the values in the first array are replaced by the
1303 * values in the second array with the corresponding keys
1307 function wfArrayLookup( $a, $b ) {
1308 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1312 * Convenience function; returns MediaWiki timestamp for the present time.
1315 function wfTimestampNow() {
1317 return wfTimestamp( TS_MW
, time() );
1321 * Reference-counted warning suppression
1323 function wfSuppressWarnings( $end = false ) {
1324 static $suppressCount = 0;
1325 static $originalLevel = false;
1328 if ( $suppressCount ) {
1330 if ( !$suppressCount ) {
1331 error_reporting( $originalLevel );
1335 if ( !$suppressCount ) {
1336 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1343 * Restore error level to previous value
1345 function wfRestoreWarnings() {
1346 wfSuppressWarnings( true );
1349 # Autodetect, convert and provide timestamps of various types
1352 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1354 define('TS_UNIX', 0);
1357 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1362 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1367 * RFC 2822 format, for E-mail and HTTP headers
1369 define('TS_RFC2822', 3);
1372 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1374 * This is used by Special:Export
1376 define('TS_ISO_8601', 4);
1379 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1381 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1382 * DateTime tag and page 36 for the DateTimeOriginal and
1383 * DateTimeDigitized tags.
1385 define('TS_EXIF', 5);
1388 * Oracle format time.
1390 define('TS_ORACLE', 6);
1393 * Postgres format time.
1395 define('TS_POSTGRES', 7);
1398 * @param mixed $outputtype A timestamp in one of the supported formats, the
1399 * function will autodetect which format is supplied
1400 * and act accordingly.
1401 * @return string Time in the format specified in $outputtype
1403 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1408 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1410 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1411 (int)$da[2],(int)$da[3],(int)$da[1]);
1412 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1414 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1415 (int)$da[2],(int)$da[3],(int)$da[1]);
1416 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1418 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1419 (int)$da[2],(int)$da[3],(int)$da[1]);
1420 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1423 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1425 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1426 str_replace("+00:00", "UTC", $ts)));
1427 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $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\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{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1437 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1438 (int)$da[2],(int)$da[3],(int)$da[1]);
1440 # Bogus value; fall back to the epoch...
1441 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1446 switch($outputtype) {
1450 return gmdate( 'YmdHis', $uts );
1452 return gmdate( 'Y-m-d H:i:s', $uts );
1454 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1455 // This shouldn't ever be used, but is included for completeness
1457 return gmdate( 'Y:m:d H:i:s', $uts );
1459 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1461 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1463 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1465 throw new MWException( 'wfTimestamp() called with illegal output type.');
1470 * Return a formatted timestamp, or null if input is null.
1471 * For dealing with nullable timestamp columns in the database.
1472 * @param int $outputtype
1476 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1477 if( is_null( $ts ) ) {
1480 return wfTimestamp( $outputtype, $ts );
1485 * Check if the operating system is Windows
1487 * @return bool True if it's Windows, False otherwise.
1489 function wfIsWindows() {
1490 if (substr(php_uname(), 0, 7) == 'Windows') {
1498 * Swap two variables
1500 function swap( &$x, &$y ) {
1506 function wfGetCachedNotice( $name ) {
1507 global $wgOut, $parserMemc;
1508 $fname = 'wfGetCachedNotice';
1509 wfProfileIn( $fname );
1513 if( $name === 'default' ) {
1515 global $wgSiteNotice;
1516 $notice = $wgSiteNotice;
1517 if( empty( $notice ) ) {
1518 wfProfileOut( $fname );
1522 $notice = wfMsgForContentNoTrans( $name );
1523 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1524 wfProfileOut( $fname );
1529 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1530 if( is_array( $cachedNotice ) ) {
1531 if( md5( $notice ) == $cachedNotice['hash'] ) {
1532 $notice = $cachedNotice['html'];
1541 if( is_object( $wgOut ) ) {
1542 $parsed = $wgOut->parse( $notice );
1543 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1546 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1551 wfProfileOut( $fname );
1555 function wfGetNamespaceNotice() {
1559 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1562 $fname = 'wfGetNamespaceNotice';
1563 wfProfileIn( $fname );
1565 $key = "namespacenotice-" . $wgTitle->getNsText();
1566 $namespaceNotice = wfGetCachedNotice( $key );
1567 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1568 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1570 $namespaceNotice = "";
1573 wfProfileOut( $fname );
1574 return $namespaceNotice;
1577 function wfGetSiteNotice() {
1578 global $wgUser, $wgSiteNotice;
1579 $fname = 'wfGetSiteNotice';
1580 wfProfileIn( $fname );
1583 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1584 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1585 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1587 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1588 if( !$anonNotice ) {
1589 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1591 $siteNotice = $anonNotice;
1594 if( !$siteNotice ) {
1595 $siteNotice = wfGetCachedNotice( 'default' );
1599 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1600 wfProfileOut( $fname );
1605 * BC wrapper for MimeMagic::singleton()
1608 function &wfGetMimeMagic() {
1609 return MimeMagic
::singleton();
1613 * Tries to get the system directory for temporary files.
1614 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1615 * and if none are set /tmp is returned as the generic Unix default.
1617 * NOTE: When possible, use the tempfile() function to create temporary
1618 * files to avoid race conditions on file creation, etc.
1622 function wfTempDir() {
1623 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1624 $tmp = getenv( $var );
1625 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1629 # Hope this is Unix of some kind!
1634 * Make directory, and make all parent directories if they don't exist
1636 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1637 if( strval( $fullDir ) === '' )
1639 if( file_exists( $fullDir ) )
1641 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR
, $fullDir ), $mode, true );
1645 * Increment a statistics counter
1647 function wfIncrStats( $key ) {
1649 $key = wfMemcKey( 'stats', $key );
1650 if ( is_null( $wgMemc->incr( $key ) ) ) {
1651 $wgMemc->add( $key, 1 );
1656 * @param mixed $nr The number to format
1657 * @param int $acc The number of digits after the decimal point, default 2
1658 * @param bool $round Whether or not to round the value, default true
1661 function wfPercent( $nr, $acc = 2, $round = true ) {
1662 $ret = sprintf( "%.${acc}f", $nr );
1663 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1667 * Encrypt a username/password.
1669 * @param string $userid ID of the user
1670 * @param string $password Password of the user
1671 * @return string Hashed password
1673 function wfEncryptPassword( $userid, $password ) {
1674 global $wgPasswordSalt;
1675 $p = md5( $password);
1678 return md5( "{$userid}-{$p}" );
1684 * Appends to second array if $value differs from that in $default
1686 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1687 if ( is_null( $changed ) ) {
1688 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1690 if ( $default[$key] !== $value ) {
1691 $changed[$key] = $value;
1696 * Since wfMsg() and co suck, they don't return false if the message key they
1697 * looked up didn't exist but a XHTML string, this function checks for the
1698 * nonexistance of messages by looking at wfMsg() output
1700 * @param $msg The message key looked up
1701 * @param $wfMsgOut The output of wfMsg*()
1704 function wfEmptyMsg( $msg, $wfMsgOut ) {
1705 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1709 * Find out whether or not a mixed variable exists in a string
1711 * @param mixed needle
1712 * @param string haystack
1715 function in_string( $needle, $str ) {
1716 return strpos( $str, $needle ) !== false;
1719 function wfSpecialList( $page, $details ) {
1721 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1722 return $page . $details;
1726 * Returns a regular expression of url protocols
1730 function wfUrlProtocols() {
1731 global $wgUrlProtocols;
1733 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1734 // with LocalSettings files from 1.5
1735 if ( is_array( $wgUrlProtocols ) ) {
1736 $protocols = array();
1737 foreach ($wgUrlProtocols as $protocol)
1738 $protocols[] = preg_quote( $protocol, '/' );
1740 return implode( '|', $protocols );
1742 return $wgUrlProtocols;
1747 * Safety wrapper around ini_get() for boolean settings.
1748 * The values returned from ini_get() are pre-normalized for settings
1749 * set via php.ini or php_flag/php_admin_flag... but *not*
1750 * for those set via php_value/php_admin_value.
1752 * It's fairly common for people to use php_value instead of php_flag,
1753 * which can leave you with an 'off' setting giving a false positive
1754 * for code that just takes the ini_get() return value as a boolean.
1756 * To make things extra interesting, setting via php_value accepts
1757 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1758 * Unrecognized values go false... again opposite PHP's own coercion
1759 * from string to bool.
1761 * Luckily, 'properly' set settings will always come back as '0' or '1',
1762 * so we only have to worry about them and the 'improper' settings.
1764 * I frickin' hate PHP... :P
1766 * @param string $setting
1769 function wfIniGetBool( $setting ) {
1770 $val = ini_get( $setting );
1771 // 'on' and 'true' can't have whitespace around them, but '1' can.
1772 return strtolower( $val ) == 'on'
1773 ||
strtolower( $val ) == 'true'
1774 ||
strtolower( $val ) == 'yes'
1775 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1779 * Execute a shell command, with time and memory limits mirrored from the PHP
1780 * configuration if supported.
1781 * @param $cmd Command line, properly escaped for shell.
1782 * @param &$retval optional, will receive the program's exit code.
1783 * (non-zero is usually failure)
1784 * @return collected stdout as a string (trailing newlines stripped)
1786 function wfShellExec( $cmd, &$retval=null ) {
1787 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1789 if( wfIniGetBool( 'safe_mode' ) ) {
1790 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1792 return "Unable to run external programs in safe mode.";
1795 if ( php_uname( 's' ) == 'Linux' ) {
1796 $time = intval( ini_get( 'max_execution_time' ) );
1797 $mem = intval( $wgMaxShellMemory );
1798 $filesize = intval( $wgMaxShellFileSize );
1800 if ( $time > 0 && $mem > 0 ) {
1801 $script = "$IP/bin/ulimit4.sh";
1802 if ( is_executable( $script ) ) {
1803 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1806 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1807 # This is a hack to work around PHP's flawed invocation of cmd.exe
1808 # http://news.php.net/php.internals/21796
1809 $cmd = '"' . $cmd . '"';
1811 wfDebug( "wfShellExec: $cmd\n" );
1814 $retval = 1; // error by default?
1815 exec( $cmd, $output, $retval ); // returns the last line of output.
1816 return implode( "\n", $output );
1821 * This function works like "use VERSION" in Perl, the program will die with a
1822 * backtrace if the current version of PHP is less than the version provided
1824 * This is useful for extensions which due to their nature are not kept in sync
1825 * with releases, and might depend on other versions of PHP than the main code
1827 * Note: PHP might die due to parsing errors in some cases before it ever
1828 * manages to call this function, such is life
1830 * @see perldoc -f use
1832 * @param mixed $version The version to check, can be a string, an integer, or
1835 function wfUsePHP( $req_ver ) {
1836 $php_ver = PHP_VERSION
;
1838 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1839 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1843 * This function works like "use VERSION" in Perl except it checks the version
1844 * of MediaWiki, the program will die with a backtrace if the current version
1845 * of MediaWiki is less than the version provided.
1847 * This is useful for extensions which due to their nature are not kept in sync
1850 * @see perldoc -f use
1852 * @param mixed $version The version to check, can be a string, an integer, or
1855 function wfUseMW( $req_ver ) {
1858 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1859 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1863 * @deprecated use StringUtils::escapeRegexReplacement
1865 function wfRegexReplacement( $string ) {
1866 return StringUtils
::escapeRegexReplacement( $string );
1870 * Return the final portion of a pathname.
1871 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1872 * http://bugs.php.net/bug.php?id=33898
1874 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1875 * We'll consider it so always, as we don't want \s in our Unix paths either.
1877 * @param string $path
1878 * @param string $suffix to remove if present
1881 function wfBaseName( $path, $suffix='' ) {
1882 $encSuffix = ($suffix == '')
1884 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1886 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1894 * Generate a relative path name to the given file.
1895 * May explode on non-matching case-insensitive paths,
1896 * funky symlinks, etc.
1898 * @param string $path Absolute destination path including target filename
1899 * @param string $from Absolute source path, directory only
1902 function wfRelativePath( $path, $from ) {
1903 // Normalize mixed input on Windows...
1904 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1905 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1907 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1908 $against = explode( DIRECTORY_SEPARATOR
, $from );
1910 // Trim off common prefix
1911 while( count( $pieces ) && count( $against )
1912 && $pieces[0] == $against[0] ) {
1913 array_shift( $pieces );
1914 array_shift( $against );
1917 // relative dots to bump us to the parent
1918 while( count( $against ) ) {
1919 array_unshift( $pieces, '..' );
1920 array_shift( $against );
1923 array_push( $pieces, wfBaseName( $path ) );
1925 return implode( DIRECTORY_SEPARATOR
, $pieces );
1929 * Make a URL index, appropriate for the el_index field of externallinks.
1931 function wfMakeUrlIndex( $url ) {
1932 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1933 $bits = parse_url( $url );
1934 wfSuppressWarnings();
1935 wfRestoreWarnings();
1939 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1941 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1943 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1945 // parse_url detects for news: and mailto: the host part of an url as path
1946 // We have to correct this wrong detection
1947 if ( isset ( $bits['path'] ) ) {
1948 $bits['host'] = $bits['path'];
1955 // Reverse the labels in the hostname, convert to lower case
1956 // For emails reverse domainpart only
1957 if ( $bits['scheme'] == 'mailto' ) {
1958 $mailparts = explode( '@', $bits['host'], 2 );
1959 if ( count($mailparts) === 2 ) {
1960 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1962 // No domain specified, don't mangle it
1965 $reversedHost = $domainpart . '@' . $mailparts[0];
1967 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1969 // Add an extra dot to the end
1970 // Why? Is it in wrong place in mailto links?
1971 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1972 $reversedHost .= '.';
1974 // Reconstruct the pseudo-URL
1975 $prot = $bits['scheme'];
1976 $index = "$prot$delimiter$reversedHost";
1977 // Leave out user and password. Add the port, path, query and fragment
1978 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1979 if ( isset( $bits['path'] ) ) {
1980 $index .= $bits['path'];
1984 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1985 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1990 * Do any deferred updates and clear the list
1991 * TODO: This could be in Wiki.php if that class made any sense at all
1993 function wfDoUpdates()
1995 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1996 foreach ( $wgDeferredUpdateList as $update ) {
1997 $update->doUpdate();
1999 foreach ( $wgPostCommitUpdateList as $update ) {
2000 $update->doUpdate();
2002 $wgDeferredUpdateList = array();
2003 $wgPostCommitUpdateList = array();
2007 * @deprecated use StringUtils::explodeMarkup
2009 function wfExplodeMarkup( $separator, $text ) {
2010 return StringUtils
::explodeMarkup( $separator, $text );
2014 * Convert an arbitrarily-long digit string from one numeric base
2015 * to another, optionally zero-padding to a minimum column width.
2017 * Supports base 2 through 36; digit values 10-36 are represented
2018 * as lowercase letters a-z. Input is case-insensitive.
2020 * @param $input string of digits
2021 * @param $sourceBase int 2-36
2022 * @param $destBase int 2-36
2023 * @param $pad int 1 or greater
2024 * @param $lowercase bool
2025 * @return string or false on invalid input
2027 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2028 $input = strval( $input );
2029 if( $sourceBase < 2 ||
2034 $sourceBase != intval( $sourceBase ) ||
2035 $destBase != intval( $destBase ) ||
2036 $pad != intval( $pad ) ||
2037 !is_string( $input ) ||
2041 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2042 $inDigits = array();
2045 // Decode and validate input string
2046 $input = strtolower( $input );
2047 for( $i = 0; $i < strlen( $input ); $i++
) {
2048 $n = strpos( $digitChars, $input{$i} );
2049 if( $n === false ||
$n > $sourceBase ) {
2055 // Iterate over the input, modulo-ing out an output digit
2056 // at a time until input is gone.
2057 while( count( $inDigits ) ) {
2059 $workDigits = array();
2062 foreach( $inDigits as $digit ) {
2063 $work *= $sourceBase;
2066 if( $work < $destBase ) {
2067 // Gonna need to pull another digit.
2068 if( count( $workDigits ) ) {
2069 // Avoid zero-padding; this lets us find
2070 // the end of the input very easily when
2071 // length drops to zero.
2075 // Finally! Actual division!
2076 $workDigits[] = intval( $work / $destBase );
2078 // Isn't it annoying that most programming languages
2079 // don't have a single divide-and-remainder operator,
2080 // even though the CPU implements it that way?
2081 $work = $work %
$destBase;
2085 // All that division leaves us with a remainder,
2086 // which is conveniently our next output digit.
2087 $outChars .= $digitChars[$work];
2090 $inDigits = $workDigits;
2093 while( strlen( $outChars ) < $pad ) {
2097 return strrev( $outChars );
2101 * Create an object with a given name and an array of construct parameters
2102 * @param string $name
2103 * @param array $p parameters
2105 function wfCreateObject( $name, $p ){
2106 $p = array_values( $p );
2107 switch ( count( $p ) ) {
2111 return new $name( $p[0] );
2113 return new $name( $p[0], $p[1] );
2115 return new $name( $p[0], $p[1], $p[2] );
2117 return new $name( $p[0], $p[1], $p[2], $p[3] );
2119 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2121 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2123 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2128 * Aliases for modularized functions
2130 function wfGetHTTP( $url, $timeout = 'default' ) {
2131 return Http
::get( $url, $timeout );
2133 function wfIsLocalURL( $url ) {
2134 return Http
::isLocalURL( $url );
2138 * Initialise php session
2140 function wfSetupSession() {
2141 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2142 if( $wgSessionsInMemcached ) {
2143 require_once( 'MemcachedSessions.php' );
2144 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2145 # If it's left on 'user' or another setting from another
2146 # application, it will end up failing. Try to recover.
2147 ini_set ( 'session.save_handler', 'files' );
2149 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2150 session_cache_limiter( 'private, must-revalidate' );
2155 * Get an object from the precompiled serialized directory
2157 * @return mixed The variable on success, false on failure
2159 function wfGetPrecompiledData( $name ) {
2162 $file = "$IP/serialized/$name";
2163 if ( file_exists( $file ) ) {
2164 $blob = file_get_contents( $file );
2166 return unserialize( $blob );
2172 function wfGetCaller( $level = 2 ) {
2173 $backtrace = wfDebugBacktrace();
2174 if ( isset( $backtrace[$level] ) ) {
2175 return wfFormatStackFrame($backtrace[$level]);
2177 $caller = 'unknown';
2182 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2183 function wfGetAllCallers() {
2184 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2187 /** Return a string representation of frame */
2188 function wfFormatStackFrame($frame) {
2189 return isset( $frame["class"] )?
2190 $frame["class"]."::".$frame["function"]:
2197 function wfMemcKey( /*... */ ) {
2198 global $wgDBprefix, $wgDBname;
2199 $args = func_get_args();
2200 if ( $wgDBprefix ) {
2201 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2203 $key = $wgDBname . ':' . implode( ':', $args );
2209 * Get a cache key for a foreign DB
2211 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2212 $args = array_slice( func_get_args(), 2 );
2214 $key = "$db-$prefix:" . implode( ':', $args );
2216 $key = $db . ':' . implode( ':', $args );
2222 * Get an ASCII string identifying this wiki
2223 * This is used as a prefix in memcached keys
2225 function wfWikiID() {
2226 global $wgDBprefix, $wgDBname;
2227 if ( $wgDBprefix ) {
2228 return "$wgDBname-$wgDBprefix";
2235 * Get a Database object
2236 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2237 * master (for write queries), DB_SLAVE for potentially lagged
2238 * read queries, or an integer >= 0 for a particular server.
2240 * @param mixed $groups Query groups. An array of group names that this query
2241 * belongs to. May contain a single string if the query is only
2244 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2245 global $wgLoadBalancer;
2246 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2252 * Shortcut for RepoGroup::singleton()->findFile()
2253 * @param mixed $title Title object or string. May be interwiki.
2254 * @param mixed $time Requested time for an archived image, or false for the
2255 * current version. An image object will be returned which
2256 * existed at or before the specified time.
2257 * @return File, or false if the file does not exist
2259 function wfFindFile( $title, $time = false ) {
2260 return RepoGroup
::singleton()->findFile( $title, $time );
2264 * Get an object referring to a locally registered file.
2265 * Returns a valid placeholder object if the file does not exist.
2267 function wfLocalFile( $title ) {
2268 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2272 * Should low-performance queries be disabled?
2276 function wfQueriesMustScale() {
2277 global $wgMiserMode;
2279 ||
( SiteStats
::pages() > 100000
2280 && SiteStats
::edits() > 1000000
2281 && SiteStats
::users() > 10000 );
2285 * Get the path to a specified script file, respecting file
2286 * extensions; this is a wrapper around $wgScriptExtension etc.
2288 * @param string $script Script filename, sans extension
2291 function wfScript( $script = 'index' ) {
2292 global $wgScriptPath, $wgScriptExtension;
2293 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2297 * Convenience function converts boolean values into "true"
2298 * or "false" (string) values
2300 * @param bool $value
2303 function wfBoolToStr( $value ) {
2304 return $value ?
'true' : 'false';
2308 * Load an extension messages file
2310 function wfLoadExtensionMessages( $extensionName ) {
2311 global $wgExtensionMessagesFiles, $wgMessageCache;
2312 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2313 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2314 // Prevent double-loading
2315 $wgExtensionMessagesFiles[$extensionName] = false;
2320 * Get a platform-independent path to the null file, e.g.
2325 function wfGetNull() {
2326 return wfIsWindows()
2332 * Displays a maxlag error
2334 * @param string $host Server that lags the most
2335 * @param int $lag Maxlag (actual)
2336 * @param int $maxLag Maxlag (requested)
2338 function wfMaxlagError( $host, $lag, $maxLag ) {
2339 global $wgShowHostnames;
2340 header( 'HTTP/1.1 503 Service Unavailable' );
2341 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2342 header( 'X-Database-Lag: ' . intval( $lag ) );
2343 header( 'Content-Type: text/plain' );
2344 if( $wgShowHostnames ) {
2345 echo "Waiting for $host: $lag seconds lagged\n";
2347 echo "Waiting for a database server: $lag seconds lagged\n";