3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
11 require_once dirname(__FILE__
) . '/LogPage.php';
12 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
13 require_once dirname(__FILE__
) . '/XmlFunctions.php';
16 * Compatibility functions
18 * We more or less support PHP 5.0.x and up.
19 * Re-implementations of newer functions or functions in non-standard
20 * PHP extensions may be included here.
22 if( !function_exists('iconv') ) {
23 # iconv support is not in the default configuration and so may not be present.
24 # Assume will only ever use utf-8 and iso-8859-1.
25 # This will *not* work in all circumstances.
26 function iconv( $from, $to, $string ) {
27 if(strcasecmp( $from, $to ) == 0) return $string;
28 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
29 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
34 # UTF-8 substr function based on a PHP manual comment
35 if ( !function_exists( 'mb_substr' ) ) {
36 function mb_substr( $str, $start ) {
38 preg_match_all( '/./us', $str, $ar );
40 if( func_num_args() >= 3 ) {
41 $end = func_get_arg( 2 );
42 return join( '', array_slice( $ar[0], $start, $end ) );
44 return join( '', array_slice( $ar[0], $start ) );
49 if ( !function_exists( 'mb_strlen' ) ) {
51 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
53 * @param string $enc optional encoding; ignored
56 function mb_strlen( $str, $enc="" ) {
57 $counts = count_chars( $str );
61 for( $i = 0; $i < 0x80; $i++
) {
62 $total +
= $counts[$i];
65 // Count multibyte sequence heads
66 for( $i = 0xc0; $i < 0xff; $i++
) {
67 $total +
= $counts[$i];
73 if ( !function_exists( 'array_diff_key' ) ) {
75 * Exists in PHP 5.1.0+
76 * Not quite compatible, two-argument version only
77 * Null values will cause problems due to this use of isset()
79 function array_diff_key( $left, $right ) {
81 foreach ( $left as $key => $unused ) {
82 if ( isset( $right[$key] ) ) {
83 unset( $result[$key] );
91 * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
93 function wfArrayDiff2( $a, $b ) {
94 return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
96 function wfArrayDiff2_cmp( $a, $b ) {
97 if ( !is_array( $a ) ) {
98 return strcmp( $a, $b );
99 } elseif ( count( $a ) !== count( $b ) ) {
100 return count( $a ) < count( $b ) ?
-1 : 1;
104 while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
105 $cmp = strcmp( $valueA, $valueB );
115 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
116 * PHP 5 won't let you declare a 'clone' function, even conditionally,
117 * so it has to be a wrapper with a different name.
119 function wfClone( $object ) {
120 return clone( $object );
124 * Seed Mersenne Twister
125 * No-op for compatibility; only necessary in PHP < 4.2.0
127 function wfSeedRandom() {
132 * Get a random decimal value between 0 and 1, in a way
133 * not likely to give duplicate values for any realistic
134 * number of articles.
138 function wfRandom() {
139 # The maximum random value is "only" 2^31-1, so get two random
140 # values to reduce the chance of dupes
141 $max = mt_getrandmax() +
1;
142 $rand = number_format( (mt_rand() * $max +
mt_rand())
143 / $max / $max, 12, '.', '' );
148 * We want / and : to be included as literal characters in our title URLs.
149 * %2F in the page titles seems to fatally break for some reason.
154 function wfUrlencode ( $s ) {
155 $s = urlencode( $s );
156 $s = preg_replace( '/%3[Aa]/', ':', $s );
157 $s = preg_replace( '/%2[Ff]/', '/', $s );
163 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
164 * In normal operation this is a NOP.
166 * Controlling globals:
167 * $wgDebugLogFile - points to the log file
168 * $wgProfileOnly - if set, normal debug messages will not be recorded.
169 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
170 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
172 * @param $text String
173 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
175 function wfDebug( $text, $logonly = false ) {
176 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
177 static $recursion = 0;
179 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
180 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
184 if ( $wgDebugComments && !$logonly ) {
185 if ( !isset( $wgOut ) ) {
188 if ( !StubObject
::isRealObject( $wgOut ) ) {
196 $wgOut->debug( $text );
198 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
199 # Strip unprintables; they can switch terminal modes when binary data
200 # gets dumped, which is pretty annoying.
201 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
202 wfErrorLog( $text, $wgDebugLogFile );
207 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
208 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
210 * @param $logGroup String
211 * @param $text String
212 * @param $public Bool: whether to log the event in the public log if no private
213 * log file is specified, (default true)
215 function wfDebugLog( $logGroup, $text, $public = true ) {
216 global $wgDebugLogGroups;
217 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
218 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
219 $time = wfTimestamp( TS_DB
);
221 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
222 } else if ( $public === true ) {
223 wfDebug( $text, true );
228 * Log for database errors
229 * @param $text String: database error message.
231 function wfLogDBError( $text ) {
232 global $wgDBerrorLog, $wgDBname;
233 if ( $wgDBerrorLog ) {
234 $host = trim(`hostname`
);
235 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
236 wfErrorLog( $text, $wgDBerrorLog );
241 * Log to a file without getting "file size exceeded" signals
243 function wfErrorLog( $text, $file ) {
244 wfSuppressWarnings();
245 $exists = file_exists( $file );
246 $size = $exists ?
filesize( $file ) : false;
247 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
248 error_log( $text, 3, $file );
256 function wfLogProfilingData() {
257 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
258 global $wgProfiling, $wgUser;
259 if ( $wgProfiling ) {
261 $elapsed = $now - $wgRequestTime;
262 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
264 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
265 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
266 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
267 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
268 if( !empty( $_SERVER['HTTP_FROM'] ) )
269 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
271 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
272 // Don't unstub $wgUser at this late stage just for statistics purposes
273 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
275 $log = sprintf( "%s\t%04.3f\t%s\n",
276 gmdate( 'YmdHis' ), $elapsed,
277 urldecode( $wgRequest->getRequestURL() . $forward ) );
278 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
279 wfErrorLog( $log . $prof, $wgDebugLogFile );
285 * Check if the wiki read-only lock file is present. This can be used to lock
286 * off editing functions, but doesn't guarantee that the database will not be
290 function wfReadOnly() {
291 global $wgReadOnlyFile, $wgReadOnly;
293 if ( !is_null( $wgReadOnly ) ) {
294 return (bool)$wgReadOnly;
296 if ( '' == $wgReadOnlyFile ) {
299 // Set $wgReadOnly for faster access next time
300 if ( is_file( $wgReadOnlyFile ) ) {
301 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
305 return (bool)$wgReadOnly;
308 function wfReadOnlyReason() {
315 * Get a message from anywhere, for the current user language.
317 * Use wfMsgForContent() instead if the message should NOT
318 * change depending on the user preferences.
320 * @param $key String: lookup key for the message, usually
321 * defined in languages/Language.php
323 * This function also takes extra optional parameters (not
324 * shown in the function definition), which can by used to
325 * insert variable text into the predefined message.
327 function wfMsg( $key ) {
328 $args = func_get_args();
329 array_shift( $args );
330 return wfMsgReal( $key, $args, true );
334 * Same as above except doesn't transform the message
336 function wfMsgNoTrans( $key ) {
337 $args = func_get_args();
338 array_shift( $args );
339 return wfMsgReal( $key, $args, true, false, false );
343 * Get a message from anywhere, for the current global language
344 * set with $wgLanguageCode.
346 * Use this if the message should NOT change dependent on the
347 * language set in the user's preferences. This is the case for
348 * most text written into logs, as well as link targets (such as
349 * the name of the copyright policy page). Link titles, on the
350 * other hand, should be shown in the UI language.
352 * Note that MediaWiki allows users to change the user interface
353 * language in their preferences, but a single installation
354 * typically only contains content in one language.
356 * Be wary of this distinction: If you use wfMsg() where you should
357 * use wfMsgForContent(), a user of the software may have to
358 * customize over 70 messages in order to, e.g., fix a link in every
361 * @param $key String: lookup key for the message, usually
362 * defined in languages/Language.php
364 function wfMsgForContent( $key ) {
365 global $wgForceUIMsgAsContentMsg;
366 $args = func_get_args();
367 array_shift( $args );
369 if( is_array( $wgForceUIMsgAsContentMsg ) &&
370 in_array( $key, $wgForceUIMsgAsContentMsg ) )
372 return wfMsgReal( $key, $args, true, $forcontent );
376 * Same as above except doesn't transform the message
378 function wfMsgForContentNoTrans( $key ) {
379 global $wgForceUIMsgAsContentMsg;
380 $args = func_get_args();
381 array_shift( $args );
383 if( is_array( $wgForceUIMsgAsContentMsg ) &&
384 in_array( $key, $wgForceUIMsgAsContentMsg ) )
386 return wfMsgReal( $key, $args, true, $forcontent, false );
390 * Get a message from the language file, for the UI elements
392 function wfMsgNoDB( $key ) {
393 $args = func_get_args();
394 array_shift( $args );
395 return wfMsgReal( $key, $args, false );
399 * Get a message from the language file, for the content
401 function wfMsgNoDBForContent( $key ) {
402 global $wgForceUIMsgAsContentMsg;
403 $args = func_get_args();
404 array_shift( $args );
406 if( is_array( $wgForceUIMsgAsContentMsg ) &&
407 in_array( $key, $wgForceUIMsgAsContentMsg ) )
409 return wfMsgReal( $key, $args, false, $forcontent );
414 * Really get a message
415 * @param $key String: key to get.
417 * @param $useDB Boolean
418 * @param $transform Boolean: Whether or not to transform the message.
419 * @param $forContent Boolean
420 * @return String: the requested message.
422 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
423 wfProfileIn( __METHOD__
);
424 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
425 $message = wfMsgReplaceArgs( $message, $args );
426 wfProfileOut( __METHOD__
);
431 * This function provides the message source for messages to be edited which are *not* stored in the database.
432 * @param $key String:
434 function wfMsgWeirdKey ( $key ) {
435 $source = wfMsgGetKey( $key, false, true, false );
436 if ( wfEmptyMsg( $key, $source ) )
443 * Fetch a message string value, but don't replace any keys yet.
446 * @param bool $forContent
450 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
451 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
453 # If $wgMessageCache isn't initialised yet, try to return something sensible.
454 if( is_object( $wgMessageCache ) ) {
455 $message = $wgMessageCache->get( $key, $useDB, $forContent );
457 $message = $wgMessageCache->transform( $message );
461 $lang = &$wgContLang;
466 # MessageCache::get() does this already, Language::getMessage() doesn't
467 # ISSUE: Should we try to handle "message/lang" here too?
468 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
470 if( is_object( $lang ) ) {
471 $message = $lang->getMessage( $key );
481 * Replace message parameter keys on the given formatted output.
483 * @param string $message
488 function wfMsgReplaceArgs( $message, $args ) {
489 # Fix windows line-endings
490 # Some messages are split with explode("\n", $msg)
491 $message = str_replace( "\r", '', $message );
494 if ( count( $args ) ) {
495 if ( is_array( $args[0] ) ) {
496 $args = array_values( $args[0] );
498 $replacementKeys = array();
499 foreach( $args as $n => $param ) {
500 $replacementKeys['$' . ($n +
1)] = $param;
502 $message = strtr( $message, $replacementKeys );
509 * Return an HTML-escaped version of a message.
510 * Parameter replacements, if any, are done *after* the HTML-escaping,
511 * so parameters may contain HTML (eg links or form controls). Be sure
512 * to pre-escape them if you really do want plaintext, or just wrap
513 * the whole thing in htmlspecialchars().
516 * @param string ... parameters
519 function wfMsgHtml( $key ) {
520 $args = func_get_args();
521 array_shift( $args );
522 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
526 * Return an HTML version of message
527 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
528 * so parameters may contain HTML (eg links or form controls). Be sure
529 * to pre-escape them if you really do want plaintext, or just wrap
530 * the whole thing in htmlspecialchars().
533 * @param string ... parameters
536 function wfMsgWikiHtml( $key ) {
538 $args = func_get_args();
539 array_shift( $args );
540 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
544 * Returns message in the requested format
545 * @param string $key Key of the message
546 * @param array $options Processing rules:
547 * <i>parse</i>: parses wikitext to html
548 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
549 * <i>escape</i>: filters message through htmlspecialchars
550 * <i>escapenoentities</i>: same, but allows entity references like through
551 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
552 * <i>parsemag</i>: transform the message using magic phrases
553 * <i>content</i>: fetch message for content language instead of interface
554 * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
556 function wfMsgExt( $key, $options ) {
557 global $wgOut, $wgParser;
559 $args = func_get_args();
560 array_shift( $args );
561 array_shift( $args );
563 if( !is_array($options) ) {
564 $options = array($options);
568 if( in_array('content', $options) ) {
572 $string = wfMsgGetKey( $key, /*DB*/true, $forContent, /*Transform*/false );
574 if( !in_array('replaceafter', $options) ) {
575 $string = wfMsgReplaceArgs( $string, $args );
578 if( in_array('parse', $options) ) {
579 $string = $wgOut->parse( $string, true, !$forContent );
580 } elseif ( in_array('parseinline', $options) ) {
581 $string = $wgOut->parse( $string, true, !$forContent );
583 if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
586 } elseif ( in_array('parsemag', $options) ) {
587 global $wgMessageCache;
588 if ( isset( $wgMessageCache ) ) {
589 $string = $wgMessageCache->transform( $string, !$forContent );
593 if ( in_array('escape', $options) ) {
594 $string = htmlspecialchars ( $string );
595 } elseif ( in_array( 'escapenoentities', $options ) ) {
596 $string = htmlspecialchars( $string );
597 $string = str_replace( '&', '&', $string );
598 $string = Sanitizer
::normalizeCharReferences( $string );
601 if( in_array('replaceafter', $options) ) {
602 $string = wfMsgReplaceArgs( $string, $args );
610 * Just like exit() but makes a note of it.
611 * Commits open transactions except if the error parameter is set
613 * @deprecated Please return control to the caller or throw an exception
615 function wfAbruptExit( $error = false ){
616 static $called = false;
622 $bt = wfDebugBacktrace();
624 for($i = 0; $i < count($bt) ; $i++
){
625 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
626 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
627 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
630 wfDebug('WARNING: Abrupt exit\n');
633 wfLogProfilingData();
636 wfGetLB()->closeAll();
642 * @deprecated Please return control the caller or throw an exception
644 function wfErrorExit() {
645 wfAbruptExit( true );
649 * Print a simple message and die, returning nonzero to the shell if any.
650 * Plain die() fails to return nonzero to the shell if you pass a string.
653 function wfDie( $msg='' ) {
659 * Throw a debugging exception. This function previously once exited the process,
660 * but now throws an exception instead, with similar results.
662 * @param string $msg Message shown when dieing.
664 function wfDebugDieBacktrace( $msg = '' ) {
665 throw new MWException( $msg );
669 * Fetch server name for use in error reporting etc.
670 * Use real server name if available, so we know which machine
671 * in a server farm generated the current page.
674 function wfHostname() {
675 if ( function_exists( 'posix_uname' ) ) {
676 // This function not present on Windows
677 $uname = @posix_uname
();
681 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
682 return $uname['nodename'];
684 # This may be a virtual server.
685 return $_SERVER['SERVER_NAME'];
690 * Returns a HTML comment with the elapsed time since request.
691 * This method has no side effects.
694 function wfReportTime() {
695 global $wgRequestTime, $wgShowHostnames;
698 $elapsed = $now - $wgRequestTime;
700 return $wgShowHostnames
701 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
702 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
706 * Safety wrapper for debug_backtrace().
708 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
709 * murky circumstances, which may be triggered in part by stub objects
710 * or other fancy talkin'.
712 * Will return an empty array if Zend Optimizer is detected, otherwise
713 * the output from debug_backtrace() (trimmed).
715 * @return array of backtrace information
717 function wfDebugBacktrace() {
718 if( extension_loaded( 'Zend Optimizer' ) ) {
719 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
722 return array_slice( debug_backtrace(), 1 );
726 function wfBacktrace() {
727 global $wgCommandLineMode;
729 if ( $wgCommandLineMode ) {
734 $backtrace = wfDebugBacktrace();
735 foreach( $backtrace as $call ) {
736 if( isset( $call['file'] ) ) {
737 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
738 $file = $f[count($f)-1];
742 if( isset( $call['line'] ) ) {
743 $line = $call['line'];
747 if ( $wgCommandLineMode ) {
748 $msg .= "$file line $line calls ";
750 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
752 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
753 $msg .= $call['function'] . '()';
755 if ( $wgCommandLineMode ) {
761 if ( $wgCommandLineMode ) {
771 /* Some generic result counters, pulled out of SearchEngine */
777 function wfShowingResults( $offset, $limit ) {
779 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
785 function wfShowingResultsNum( $offset, $limit, $num ) {
787 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
793 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
795 $fmtLimit = $wgLang->formatNum( $limit );
796 $prev = wfMsg( 'prevn', $fmtLimit );
797 $next = wfMsg( 'nextn', $fmtLimit );
799 if( is_object( $link ) ) {
802 $title = Title
::newFromText( $link );
803 if( is_null( $title ) ) {
808 if ( 0 != $offset ) {
809 $po = $offset - $limit;
810 if ( $po < 0 ) { $po = 0; }
811 $q = "limit={$limit}&offset={$po}";
812 if ( '' != $query ) { $q .= '&'.$query; }
813 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
814 } else { $plink = $prev; }
816 $no = $offset +
$limit;
817 $q = 'limit='.$limit.'&offset='.$no;
818 if ( '' != $query ) { $q .= '&'.$query; }
823 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
825 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
826 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
827 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
828 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
829 wfNumLink( $offset, 500, $title, $query );
831 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
837 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
839 if ( '' == $query ) { $q = ''; }
840 else { $q = $query.'&'; }
841 $q .= 'limit='.$limit.'&offset='.$offset;
843 $fmtLimit = $wgLang->formatNum( $limit );
844 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
850 * @todo FIXME: we may want to blacklist some broken browsers
852 * @return bool Whereas client accept gzip compression
854 function wfClientAcceptsGzip() {
857 # FIXME: we may want to blacklist some broken browsers
860 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
861 $_SERVER['HTTP_ACCEPT_ENCODING'],
863 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
864 wfDebug( " accepts gzip\n" );
872 * Obtain the offset and limit values from the request string;
873 * used in special pages
875 * @param $deflimit Default limit if none supplied
876 * @param $optionname Name of a user preference to check against
880 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
882 return $wgRequest->getLimitOffset( $deflimit, $optionname );
886 * Escapes the given text so that it may be output using addWikiText()
887 * without any linking, formatting, etc. making its way through. This
888 * is achieved by substituting certain characters with HTML entities.
889 * As required by the callers, <nowiki> is not used. It currently does
890 * not filter out characters which have special meaning only at the
891 * start of a line, such as "*".
893 * @param string $text Text to be escaped
895 function wfEscapeWikiText( $text ) {
897 array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
898 array( '[', '|', ']', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
899 htmlspecialchars($text) );
906 function wfQuotedPrintable( $string, $charset = '' ) {
907 # Probably incomplete; see RFC 2045
908 if( empty( $charset ) ) {
909 global $wgInputEncoding;
910 $charset = $wgInputEncoding;
912 $charset = strtoupper( $charset );
913 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
915 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
916 $replace = $illegal . '\t ?_';
917 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
918 $out = "=?$charset?Q?";
919 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
930 return microtime(true);
934 * Sets dest to source and returns the original value of dest
935 * If source is NULL, it just returns the value, it doesn't set the variable
937 function wfSetVar( &$dest, $source ) {
939 if ( !is_null( $source ) ) {
946 * As for wfSetVar except setting a bit
948 function wfSetBit( &$dest, $bit, $state = true ) {
949 $temp = (bool)($dest & $bit );
950 if ( !is_null( $state ) ) {
961 * This function takes two arrays as input, and returns a CGI-style string, e.g.
962 * "days=7&limit=100". Options in the first array override options in the second.
963 * Options set to "" will not be output.
965 function wfArrayToCGI( $array1, $array2 = NULL )
967 if ( !is_null( $array2 ) ) {
968 $array1 = $array1 +
$array2;
972 foreach ( $array1 as $key => $value ) {
973 if ( '' !== $value ) {
977 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
984 * Append a query string to an existing URL, which may or may not already
985 * have query string parameters already. If so, they will be combined.
988 * @param string $query
991 function wfAppendQuery( $url, $query ) {
993 if( false === strpos( $url, '?' ) ) {
1004 * Expand a potentially local URL to a fully-qualified URL.
1005 * Assumes $wgServer is correct. :)
1006 * @param string $url, either fully-qualified or a local path + query
1007 * @return string Fully-qualified URL
1009 function wfExpandUrl( $url ) {
1010 if( substr( $url, 0, 1 ) == '/' ) {
1012 return $wgServer . $url;
1019 * This is obsolete, use SquidUpdate::purge()
1022 function wfPurgeSquidServers ($urlArr) {
1023 SquidUpdate
::purge( $urlArr );
1027 * Windows-compatible version of escapeshellarg()
1028 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1029 * function puts single quotes in regardless of OS
1031 function wfEscapeShellArg( ) {
1032 $args = func_get_args();
1035 foreach ( $args as $arg ) {
1042 if ( wfIsWindows() ) {
1043 // Escaping for an MSVC-style command line parser
1044 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1045 // Double the backslashes before any double quotes. Escape the double quotes.
1046 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1049 foreach ( $tokens as $token ) {
1051 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1057 // Double the backslashes before the end of the string, because
1058 // we will soon add a quote
1060 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1061 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1064 // Add surrounding quotes
1065 $retVal .= '"' . $arg . '"';
1067 $retVal .= escapeshellarg( $arg );
1074 * wfMerge attempts to merge differences between three texts.
1075 * Returns true for a clean merge and false for failure or a conflict.
1077 function wfMerge( $old, $mine, $yours, &$result ){
1080 # This check may also protect against code injection in
1081 # case of broken installations.
1082 if(! file_exists( $wgDiff3 ) ){
1083 wfDebug( "diff3 not found\n" );
1087 # Make temporary files
1089 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1090 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1091 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1093 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1094 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1095 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1097 # Check for a conflict
1098 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1099 wfEscapeShellArg( $mytextName ) . ' ' .
1100 wfEscapeShellArg( $oldtextName ) . ' ' .
1101 wfEscapeShellArg( $yourtextName );
1102 $handle = popen( $cmd, 'r' );
1104 if( fgets( $handle, 1024 ) ){
1112 $cmd = $wgDiff3 . ' -a -e --merge ' .
1113 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1114 $handle = popen( $cmd, 'r' );
1117 $data = fread( $handle, 8192 );
1118 if ( strlen( $data ) == 0 ) {
1124 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1126 if ( $result === '' && $old !== '' && $conflict == false ) {
1127 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1136 function wfVarDump( $var ) {
1138 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1139 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1142 $wgOut->addHTML( $s );
1147 * Provide a simple HTTP error.
1149 function wfHttpError( $code, $label, $desc ) {
1152 header( "HTTP/1.0 $code $label" );
1153 header( "Status: $code $label" );
1154 $wgOut->sendCacheControl();
1156 header( 'Content-type: text/html; charset=utf-8' );
1157 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1158 "<html><head><title>" .
1159 htmlspecialchars( $label ) .
1160 "</title></head><body><h1>" .
1161 htmlspecialchars( $label ) .
1163 nl2br( htmlspecialchars( $desc ) ) .
1164 "</p></body></html>\n";
1168 * Clear away any user-level output buffers, discarding contents.
1170 * Suitable for 'starting afresh', for instance when streaming
1171 * relatively large amounts of data without buffering, or wanting to
1172 * output image files without ob_gzhandler's compression.
1174 * The optional $resetGzipEncoding parameter controls suppression of
1175 * the Content-Encoding header sent by ob_gzhandler; by default it
1176 * is left. See comments for wfClearOutputBuffers() for why it would
1179 * Note that some PHP configuration options may add output buffer
1180 * layers which cannot be removed; these are left in place.
1182 * @param bool $resetGzipEncoding
1184 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1185 if( $resetGzipEncoding ) {
1186 // Suppress Content-Encoding and Content-Length
1187 // headers from 1.10+s wfOutputHandler
1188 global $wgDisableOutputCompression;
1189 $wgDisableOutputCompression = true;
1191 while( $status = ob_get_status() ) {
1192 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1193 // Probably from zlib.output_compression or other
1194 // PHP-internal setting which can't be removed.
1196 // Give up, and hope the result doesn't break
1200 if( !ob_end_clean() ) {
1201 // Could not remove output buffer handler; abort now
1202 // to avoid getting in some kind of infinite loop.
1205 if( $resetGzipEncoding ) {
1206 if( $status['name'] == 'ob_gzhandler' ) {
1207 // Reset the 'Content-Encoding' field set by this handler
1208 // so we can start fresh.
1209 header( 'Content-Encoding:' );
1216 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1218 * Clear away output buffers, but keep the Content-Encoding header
1219 * produced by ob_gzhandler, if any.
1221 * This should be used for HTTP 304 responses, where you need to
1222 * preserve the Content-Encoding header of the real result, but
1223 * also need to suppress the output of ob_gzhandler to keep to spec
1224 * and avoid breaking Firefox in rare cases where the headers and
1225 * body are broken over two packets.
1227 function wfClearOutputBuffers() {
1228 wfResetOutputBuffers( false );
1232 * Converts an Accept-* header into an array mapping string values to quality
1235 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1236 # No arg means accept anything (per HTTP spec)
1238 return array( $def => 1 );
1243 $parts = explode( ',', $accept );
1245 foreach( $parts as $part ) {
1246 # FIXME: doesn't deal with params like 'text/html; level=1'
1247 @list
( $value, $qpart ) = explode( ';', $part );
1249 if( !isset( $qpart ) ) {
1251 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1252 $prefs[$value] = $match[1];
1260 * Checks if a given MIME type matches any of the keys in the given
1261 * array. Basic wildcards are accepted in the array keys.
1263 * Returns the matching MIME type (or wildcard) if a match, otherwise
1266 * @param string $type
1267 * @param array $avail
1271 function mimeTypeMatch( $type, $avail ) {
1272 if( array_key_exists($type, $avail) ) {
1275 $parts = explode( '/', $type );
1276 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1277 return $parts[0] . '/*';
1278 } elseif( array_key_exists( '*/*', $avail ) ) {
1287 * Returns the 'best' match between a client's requested internet media types
1288 * and the server's list of available types. Each list should be an associative
1289 * array of type to preference (preference is a float between 0.0 and 1.0).
1290 * Wildcards in the types are acceptable.
1292 * @param array $cprefs Client's acceptable type list
1293 * @param array $sprefs Server's offered types
1296 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1297 * XXX: generalize to negotiate other stuff
1299 function wfNegotiateType( $cprefs, $sprefs ) {
1302 foreach( array_keys($sprefs) as $type ) {
1303 $parts = explode( '/', $type );
1304 if( $parts[1] != '*' ) {
1305 $ckey = mimeTypeMatch( $type, $cprefs );
1307 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1312 foreach( array_keys( $cprefs ) as $type ) {
1313 $parts = explode( '/', $type );
1314 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1315 $skey = mimeTypeMatch( $type, $sprefs );
1317 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1325 foreach( array_keys( $combine ) as $type ) {
1326 if( $combine[$type] > $bestq ) {
1328 $bestq = $combine[$type];
1337 * Returns an array where the values in the first array are replaced by the
1338 * values in the second array with the corresponding keys
1342 function wfArrayLookup( $a, $b ) {
1343 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1347 * Convenience function; returns MediaWiki timestamp for the present time.
1350 function wfTimestampNow() {
1352 return wfTimestamp( TS_MW
, time() );
1356 * Reference-counted warning suppression
1358 function wfSuppressWarnings( $end = false ) {
1359 static $suppressCount = 0;
1360 static $originalLevel = false;
1363 if ( $suppressCount ) {
1365 if ( !$suppressCount ) {
1366 error_reporting( $originalLevel );
1370 if ( !$suppressCount ) {
1371 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1378 * Restore error level to previous value
1380 function wfRestoreWarnings() {
1381 wfSuppressWarnings( true );
1384 # Autodetect, convert and provide timestamps of various types
1387 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1389 define('TS_UNIX', 0);
1392 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1397 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1402 * RFC 2822 format, for E-mail and HTTP headers
1404 define('TS_RFC2822', 3);
1407 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1409 * This is used by Special:Export
1411 define('TS_ISO_8601', 4);
1414 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1416 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1417 * DateTime tag and page 36 for the DateTimeOriginal and
1418 * DateTimeDigitized tags.
1420 define('TS_EXIF', 5);
1423 * Oracle format time.
1425 define('TS_ORACLE', 6);
1428 * Postgres format time.
1430 define('TS_POSTGRES', 7);
1433 * @param mixed $outputtype A timestamp in one of the supported formats, the
1434 * function will autodetect which format is supplied
1435 * and act accordingly.
1436 * @return string Time in the format specified in $outputtype
1438 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1443 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1445 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1446 (int)$da[2],(int)$da[3],(int)$da[1]);
1447 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1449 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1450 (int)$da[2],(int)$da[3],(int)$da[1]);
1451 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1453 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1454 (int)$da[2],(int)$da[3],(int)$da[1]);
1455 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1458 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1460 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1461 str_replace("+00:00", "UTC", $ts)));
1462 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1464 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1465 (int)$da[2],(int)$da[3],(int)$da[1]);
1466 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1468 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1469 (int)$da[2],(int)$da[3],(int)$da[1]);
1470 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1472 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1473 (int)$da[2],(int)$da[3],(int)$da[1]);
1475 # Bogus value; fall back to the epoch...
1476 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1481 switch($outputtype) {
1485 return gmdate( 'YmdHis', $uts );
1487 return gmdate( 'Y-m-d H:i:s', $uts );
1489 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1490 // This shouldn't ever be used, but is included for completeness
1492 return gmdate( 'Y:m:d H:i:s', $uts );
1494 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1496 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1498 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1500 throw new MWException( 'wfTimestamp() called with illegal output type.');
1505 * Return a formatted timestamp, or null if input is null.
1506 * For dealing with nullable timestamp columns in the database.
1507 * @param int $outputtype
1511 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1512 if( is_null( $ts ) ) {
1515 return wfTimestamp( $outputtype, $ts );
1520 * Check if the operating system is Windows
1522 * @return bool True if it's Windows, False otherwise.
1524 function wfIsWindows() {
1525 if (substr(php_uname(), 0, 7) == 'Windows') {
1533 * Swap two variables
1535 function swap( &$x, &$y ) {
1541 function wfGetCachedNotice( $name ) {
1542 global $wgOut, $parserMemc;
1543 $fname = 'wfGetCachedNotice';
1544 wfProfileIn( $fname );
1548 if( $name === 'default' ) {
1550 global $wgSiteNotice;
1551 $notice = $wgSiteNotice;
1552 if( empty( $notice ) ) {
1553 wfProfileOut( $fname );
1557 $notice = wfMsgForContentNoTrans( $name );
1558 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1559 wfProfileOut( $fname );
1564 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1565 if( is_array( $cachedNotice ) ) {
1566 if( md5( $notice ) == $cachedNotice['hash'] ) {
1567 $notice = $cachedNotice['html'];
1576 if( is_object( $wgOut ) ) {
1577 $parsed = $wgOut->parse( $notice );
1578 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1581 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1586 wfProfileOut( $fname );
1590 function wfGetNamespaceNotice() {
1594 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1597 $fname = 'wfGetNamespaceNotice';
1598 wfProfileIn( $fname );
1600 $key = "namespacenotice-" . $wgTitle->getNsText();
1601 $namespaceNotice = wfGetCachedNotice( $key );
1602 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1603 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1605 $namespaceNotice = "";
1608 wfProfileOut( $fname );
1609 return $namespaceNotice;
1612 function wfGetSiteNotice() {
1613 global $wgUser, $wgSiteNotice;
1614 $fname = 'wfGetSiteNotice';
1615 wfProfileIn( $fname );
1618 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1619 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1620 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1622 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1623 if( !$anonNotice ) {
1624 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1626 $siteNotice = $anonNotice;
1629 if( !$siteNotice ) {
1630 $siteNotice = wfGetCachedNotice( 'default' );
1634 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1635 wfProfileOut( $fname );
1640 * BC wrapper for MimeMagic::singleton()
1643 function &wfGetMimeMagic() {
1644 return MimeMagic
::singleton();
1648 * Tries to get the system directory for temporary files.
1649 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1650 * and if none are set /tmp is returned as the generic Unix default.
1652 * NOTE: When possible, use the tempfile() function to create temporary
1653 * files to avoid race conditions on file creation, etc.
1657 function wfTempDir() {
1658 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1659 $tmp = getenv( $var );
1660 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1664 # Hope this is Unix of some kind!
1669 * Make directory, and make all parent directories if they don't exist
1671 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1672 if( strval( $fullDir ) === '' )
1674 if( file_exists( $fullDir ) )
1676 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR
, $fullDir ), $mode, true );
1680 * Increment a statistics counter
1682 function wfIncrStats( $key ) {
1683 global $wgStatsMethod;
1685 if( $wgStatsMethod == 'udp' ) {
1686 global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
1689 $socket=socket_create(AF_INET
, SOCK_DGRAM
, SOL_UDP
);
1690 $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
1691 socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1693 $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
1694 @socket_sendto
($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
1695 } elseif( $wgStatsMethod == 'cache' ) {
1697 $key = wfMemcKey( 'stats', $key );
1698 if ( is_null( $wgMemc->incr( $key ) ) ) {
1699 $wgMemc->add( $key, 1 );
1707 * @param mixed $nr The number to format
1708 * @param int $acc The number of digits after the decimal point, default 2
1709 * @param bool $round Whether or not to round the value, default true
1712 function wfPercent( $nr, $acc = 2, $round = true ) {
1713 $ret = sprintf( "%.${acc}f", $nr );
1714 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1718 * Encrypt a username/password.
1720 * @param string $userid ID of the user
1721 * @param string $password Password of the user
1722 * @return string Hashed password
1724 function wfEncryptPassword( $userid, $password ) {
1725 global $wgPasswordSalt;
1726 $p = md5( $password);
1729 return md5( "{$userid}-{$p}" );
1735 * Appends to second array if $value differs from that in $default
1737 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1738 if ( is_null( $changed ) ) {
1739 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1741 if ( $default[$key] !== $value ) {
1742 $changed[$key] = $value;
1747 * Since wfMsg() and co suck, they don't return false if the message key they
1748 * looked up didn't exist but a XHTML string, this function checks for the
1749 * nonexistance of messages by looking at wfMsg() output
1751 * @param $msg The message key looked up
1752 * @param $wfMsgOut The output of wfMsg*()
1755 function wfEmptyMsg( $msg, $wfMsgOut ) {
1756 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1760 * Find out whether or not a mixed variable exists in a string
1762 * @param mixed needle
1763 * @param string haystack
1766 function in_string( $needle, $str ) {
1767 return strpos( $str, $needle ) !== false;
1770 function wfSpecialList( $page, $details ) {
1772 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1773 return $page . $details;
1777 * Returns a regular expression of url protocols
1781 function wfUrlProtocols() {
1782 global $wgUrlProtocols;
1784 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1785 // with LocalSettings files from 1.5
1786 if ( is_array( $wgUrlProtocols ) ) {
1787 $protocols = array();
1788 foreach ($wgUrlProtocols as $protocol)
1789 $protocols[] = preg_quote( $protocol, '/' );
1791 return implode( '|', $protocols );
1793 return $wgUrlProtocols;
1798 * Safety wrapper around ini_get() for boolean settings.
1799 * The values returned from ini_get() are pre-normalized for settings
1800 * set via php.ini or php_flag/php_admin_flag... but *not*
1801 * for those set via php_value/php_admin_value.
1803 * It's fairly common for people to use php_value instead of php_flag,
1804 * which can leave you with an 'off' setting giving a false positive
1805 * for code that just takes the ini_get() return value as a boolean.
1807 * To make things extra interesting, setting via php_value accepts
1808 * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
1809 * Unrecognized values go false... again opposite PHP's own coercion
1810 * from string to bool.
1812 * Luckily, 'properly' set settings will always come back as '0' or '1',
1813 * so we only have to worry about them and the 'improper' settings.
1815 * I frickin' hate PHP... :P
1817 * @param string $setting
1820 function wfIniGetBool( $setting ) {
1821 $val = ini_get( $setting );
1822 // 'on' and 'true' can't have whitespace around them, but '1' can.
1823 return strtolower( $val ) == 'on'
1824 ||
strtolower( $val ) == 'true'
1825 ||
strtolower( $val ) == 'yes'
1826 ||
preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
1830 * Execute a shell command, with time and memory limits mirrored from the PHP
1831 * configuration if supported.
1832 * @param $cmd Command line, properly escaped for shell.
1833 * @param &$retval optional, will receive the program's exit code.
1834 * (non-zero is usually failure)
1835 * @return collected stdout as a string (trailing newlines stripped)
1837 function wfShellExec( $cmd, &$retval=null ) {
1838 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1840 if( wfIniGetBool( 'safe_mode' ) ) {
1841 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1843 return "Unable to run external programs in safe mode.";
1846 if ( php_uname( 's' ) == 'Linux' ) {
1847 $time = intval( ini_get( 'max_execution_time' ) );
1848 $mem = intval( $wgMaxShellMemory );
1849 $filesize = intval( $wgMaxShellFileSize );
1851 if ( $time > 0 && $mem > 0 ) {
1852 $script = "$IP/bin/ulimit4.sh";
1853 if ( is_executable( $script ) ) {
1854 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1857 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1858 # This is a hack to work around PHP's flawed invocation of cmd.exe
1859 # http://news.php.net/php.internals/21796
1860 $cmd = '"' . $cmd . '"';
1862 wfDebug( "wfShellExec: $cmd\n" );
1864 $retval = 1; // error by default?
1866 passthru( $cmd, $retval );
1867 $output = ob_get_contents();
1874 * This function works like "use VERSION" in Perl, the program will die with a
1875 * backtrace if the current version of PHP is less than the version provided
1877 * This is useful for extensions which due to their nature are not kept in sync
1878 * with releases, and might depend on other versions of PHP than the main code
1880 * Note: PHP might die due to parsing errors in some cases before it ever
1881 * manages to call this function, such is life
1883 * @see perldoc -f use
1885 * @param mixed $version The version to check, can be a string, an integer, or
1888 function wfUsePHP( $req_ver ) {
1889 $php_ver = PHP_VERSION
;
1891 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1892 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1896 * This function works like "use VERSION" in Perl except it checks the version
1897 * of MediaWiki, the program will die with a backtrace if the current version
1898 * of MediaWiki is less than the version provided.
1900 * This is useful for extensions which due to their nature are not kept in sync
1903 * @see perldoc -f use
1905 * @param mixed $version The version to check, can be a string, an integer, or
1908 function wfUseMW( $req_ver ) {
1911 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1912 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1916 * @deprecated use StringUtils::escapeRegexReplacement
1918 function wfRegexReplacement( $string ) {
1919 return StringUtils
::escapeRegexReplacement( $string );
1923 * Return the final portion of a pathname.
1924 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1925 * http://bugs.php.net/bug.php?id=33898
1927 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1928 * We'll consider it so always, as we don't want \s in our Unix paths either.
1930 * @param string $path
1931 * @param string $suffix to remove if present
1934 function wfBaseName( $path, $suffix='' ) {
1935 $encSuffix = ($suffix == '')
1937 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1939 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1947 * Generate a relative path name to the given file.
1948 * May explode on non-matching case-insensitive paths,
1949 * funky symlinks, etc.
1951 * @param string $path Absolute destination path including target filename
1952 * @param string $from Absolute source path, directory only
1955 function wfRelativePath( $path, $from ) {
1956 // Normalize mixed input on Windows...
1957 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1958 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1960 // Trim trailing slashes -- fix for drive root
1961 $path = rtrim( $path, DIRECTORY_SEPARATOR
);
1962 $from = rtrim( $from, DIRECTORY_SEPARATOR
);
1964 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1965 $against = explode( DIRECTORY_SEPARATOR
, $from );
1967 if( $pieces[0] !== $against[0] ) {
1968 // Non-matching Windows drive letters?
1969 // Return a full path.
1973 // Trim off common prefix
1974 while( count( $pieces ) && count( $against )
1975 && $pieces[0] == $against[0] ) {
1976 array_shift( $pieces );
1977 array_shift( $against );
1980 // relative dots to bump us to the parent
1981 while( count( $against ) ) {
1982 array_unshift( $pieces, '..' );
1983 array_shift( $against );
1986 array_push( $pieces, wfBaseName( $path ) );
1988 return implode( DIRECTORY_SEPARATOR
, $pieces );
1992 * array_merge() does awful things with "numeric" indexes, including
1993 * string indexes when happen to look like integers. When we want
1994 * to merge arrays with arbitrary string indexes, we don't want our
1995 * arrays to be randomly corrupted just because some of them consist
1998 * Fuck you, PHP. Fuck you in the ear!
2000 * @param array $array1, [$array2, [...]]
2003 function wfArrayMerge( $array1/* ... */ ) {
2005 for( $i = 1; $i < func_num_args(); $i++
) {
2006 foreach( func_get_arg( $i ) as $key => $value ) {
2007 $out[$key] = $value;
2014 * Make a URL index, appropriate for the el_index field of externallinks.
2016 function wfMakeUrlIndex( $url ) {
2017 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
2018 wfSuppressWarnings();
2019 $bits = parse_url( $url );
2020 wfRestoreWarnings();
2024 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
2026 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
2028 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
2030 // parse_url detects for news: and mailto: the host part of an url as path
2031 // We have to correct this wrong detection
2032 if ( isset ( $bits['path'] ) ) {
2033 $bits['host'] = $bits['path'];
2040 // Reverse the labels in the hostname, convert to lower case
2041 // For emails reverse domainpart only
2042 if ( $bits['scheme'] == 'mailto' ) {
2043 $mailparts = explode( '@', $bits['host'], 2 );
2044 if ( count($mailparts) === 2 ) {
2045 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
2047 // No domain specified, don't mangle it
2050 $reversedHost = $domainpart . '@' . $mailparts[0];
2052 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
2054 // Add an extra dot to the end
2055 // Why? Is it in wrong place in mailto links?
2056 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
2057 $reversedHost .= '.';
2059 // Reconstruct the pseudo-URL
2060 $prot = $bits['scheme'];
2061 $index = "$prot$delimiter$reversedHost";
2062 // Leave out user and password. Add the port, path, query and fragment
2063 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
2064 if ( isset( $bits['path'] ) ) {
2065 $index .= $bits['path'];
2069 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
2070 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2075 * Do any deferred updates and clear the list
2076 * TODO: This could be in Wiki.php if that class made any sense at all
2078 function wfDoUpdates()
2080 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2081 foreach ( $wgDeferredUpdateList as $update ) {
2082 $update->doUpdate();
2084 foreach ( $wgPostCommitUpdateList as $update ) {
2085 $update->doUpdate();
2087 $wgDeferredUpdateList = array();
2088 $wgPostCommitUpdateList = array();
2092 * @deprecated use StringUtils::explodeMarkup
2094 function wfExplodeMarkup( $separator, $text ) {
2095 return StringUtils
::explodeMarkup( $separator, $text );
2099 * Convert an arbitrarily-long digit string from one numeric base
2100 * to another, optionally zero-padding to a minimum column width.
2102 * Supports base 2 through 36; digit values 10-36 are represented
2103 * as lowercase letters a-z. Input is case-insensitive.
2105 * @param $input string of digits
2106 * @param $sourceBase int 2-36
2107 * @param $destBase int 2-36
2108 * @param $pad int 1 or greater
2109 * @param $lowercase bool
2110 * @return string or false on invalid input
2112 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2113 $input = strval( $input );
2114 if( $sourceBase < 2 ||
2119 $sourceBase != intval( $sourceBase ) ||
2120 $destBase != intval( $destBase ) ||
2121 $pad != intval( $pad ) ||
2122 !is_string( $input ) ||
2126 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2127 $inDigits = array();
2130 // Decode and validate input string
2131 $input = strtolower( $input );
2132 for( $i = 0; $i < strlen( $input ); $i++
) {
2133 $n = strpos( $digitChars, $input{$i} );
2134 if( $n === false ||
$n > $sourceBase ) {
2140 // Iterate over the input, modulo-ing out an output digit
2141 // at a time until input is gone.
2142 while( count( $inDigits ) ) {
2144 $workDigits = array();
2147 foreach( $inDigits as $digit ) {
2148 $work *= $sourceBase;
2151 if( $work < $destBase ) {
2152 // Gonna need to pull another digit.
2153 if( count( $workDigits ) ) {
2154 // Avoid zero-padding; this lets us find
2155 // the end of the input very easily when
2156 // length drops to zero.
2160 // Finally! Actual division!
2161 $workDigits[] = intval( $work / $destBase );
2163 // Isn't it annoying that most programming languages
2164 // don't have a single divide-and-remainder operator,
2165 // even though the CPU implements it that way?
2166 $work = $work %
$destBase;
2170 // All that division leaves us with a remainder,
2171 // which is conveniently our next output digit.
2172 $outChars .= $digitChars[$work];
2175 $inDigits = $workDigits;
2178 while( strlen( $outChars ) < $pad ) {
2182 return strrev( $outChars );
2186 * Create an object with a given name and an array of construct parameters
2187 * @param string $name
2188 * @param array $p parameters
2190 function wfCreateObject( $name, $p ){
2191 $p = array_values( $p );
2192 switch ( count( $p ) ) {
2196 return new $name( $p[0] );
2198 return new $name( $p[0], $p[1] );
2200 return new $name( $p[0], $p[1], $p[2] );
2202 return new $name( $p[0], $p[1], $p[2], $p[3] );
2204 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2206 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2208 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2213 * Aliases for modularized functions
2215 function wfGetHTTP( $url, $timeout = 'default' ) {
2216 return Http
::get( $url, $timeout );
2218 function wfIsLocalURL( $url ) {
2219 return Http
::isLocalURL( $url );
2223 * Initialise php session
2225 function wfSetupSession() {
2226 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2227 if( $wgSessionsInMemcached ) {
2228 require_once( 'MemcachedSessions.php' );
2229 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2230 # If it's left on 'user' or another setting from another
2231 # application, it will end up failing. Try to recover.
2232 ini_set ( 'session.save_handler', 'files' );
2234 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2235 session_cache_limiter( 'private, must-revalidate' );
2236 wfSuppressWarnings();
2238 wfRestoreWarnings();
2242 * Get an object from the precompiled serialized directory
2244 * @return mixed The variable on success, false on failure
2246 function wfGetPrecompiledData( $name ) {
2249 $file = "$IP/serialized/$name";
2250 if ( file_exists( $file ) ) {
2251 $blob = file_get_contents( $file );
2253 return unserialize( $blob );
2259 function wfGetCaller( $level = 2 ) {
2260 $backtrace = wfDebugBacktrace();
2261 if ( isset( $backtrace[$level] ) ) {
2262 return wfFormatStackFrame($backtrace[$level]);
2264 $caller = 'unknown';
2269 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2270 function wfGetAllCallers() {
2271 return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
2274 /** Return a string representation of frame */
2275 function wfFormatStackFrame($frame) {
2276 return isset( $frame["class"] )?
2277 $frame["class"]."::".$frame["function"]:
2284 function wfMemcKey( /*... */ ) {
2285 global $wgDBprefix, $wgDBname;
2286 $args = func_get_args();
2287 if ( $wgDBprefix ) {
2288 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2290 $key = $wgDBname . ':' . implode( ':', $args );
2296 * Get a cache key for a foreign DB
2298 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2299 $args = array_slice( func_get_args(), 2 );
2301 $key = "$db-$prefix:" . implode( ':', $args );
2303 $key = $db . ':' . implode( ':', $args );
2309 * Get an ASCII string identifying this wiki
2310 * This is used as a prefix in memcached keys
2312 function wfWikiID() {
2313 global $wgDBprefix, $wgDBname;
2314 if ( $wgDBprefix ) {
2315 return "$wgDBname-$wgDBprefix";
2322 * Split a wiki ID into DB name and table prefix
2324 function wfSplitWikiID( $wiki ) {
2325 $bits = explode( '-', $wiki, 2 );
2326 if ( count( $bits ) < 2 ) {
2333 * Get a Database object
2334 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2335 * master (for write queries), DB_SLAVE for potentially lagged
2336 * read queries, or an integer >= 0 for a particular server.
2338 * @param mixed $groups Query groups. An array of group names that this query
2339 * belongs to. May contain a single string if the query is only
2342 * @param string $wiki The wiki ID, or false for the current wiki
2344 function &wfGetDB( $db = DB_LAST
, $groups = array(), $wiki = false ) {
2345 return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
2349 * Get a load balancer object.
2351 * @param array $groups List of query groups
2352 * @param string $wiki Wiki ID, or false for the current wiki
2353 * @return LoadBalancer
2355 function wfGetLB( $wiki = false ) {
2356 return wfGetLBFactory()->getMainLB( $wiki );
2360 * Get the load balancer factory object
2362 function &wfGetLBFactory() {
2363 return LBFactory
::singleton();
2368 * Shortcut for RepoGroup::singleton()->findFile()
2369 * @param mixed $title Title object or string. May be interwiki.
2370 * @param mixed $time Requested time for an archived image, or false for the
2371 * current version. An image object will be returned which
2372 * existed at the specified time.
2373 * @return File, or false if the file does not exist
2375 function wfFindFile( $title, $time = false ) {
2376 return RepoGroup
::singleton()->findFile( $title, $time );
2380 * Get an object referring to a locally registered file.
2381 * Returns a valid placeholder object if the file does not exist.
2383 function wfLocalFile( $title ) {
2384 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2388 * Should low-performance queries be disabled?
2392 function wfQueriesMustScale() {
2393 global $wgMiserMode;
2395 ||
( SiteStats
::pages() > 100000
2396 && SiteStats
::edits() > 1000000
2397 && SiteStats
::users() > 10000 );
2401 * Get the path to a specified script file, respecting file
2402 * extensions; this is a wrapper around $wgScriptExtension etc.
2404 * @param string $script Script filename, sans extension
2407 function wfScript( $script = 'index' ) {
2408 global $wgScriptPath, $wgScriptExtension;
2409 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2413 * Convenience function converts boolean values into "true"
2414 * or "false" (string) values
2416 * @param bool $value
2419 function wfBoolToStr( $value ) {
2420 return $value ?
'true' : 'false';
2424 * Load an extension messages file
2426 function wfLoadExtensionMessages( $extensionName ) {
2427 global $wgExtensionMessagesFiles, $wgMessageCache;
2428 if ( !empty( $wgExtensionMessagesFiles[$extensionName] ) ) {
2429 $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName] );
2430 // Prevent double-loading
2431 $wgExtensionMessagesFiles[$extensionName] = false;
2436 * Get a platform-independent path to the null file, e.g.
2441 function wfGetNull() {
2442 return wfIsWindows()
2448 * Displays a maxlag error
2450 * @param string $host Server that lags the most
2451 * @param int $lag Maxlag (actual)
2452 * @param int $maxLag Maxlag (requested)
2454 function wfMaxlagError( $host, $lag, $maxLag ) {
2455 global $wgShowHostnames;
2456 header( 'HTTP/1.1 503 Service Unavailable' );
2457 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
2458 header( 'X-Database-Lag: ' . intval( $lag ) );
2459 header( 'Content-Type: text/plain' );
2460 if( $wgShowHostnames ) {
2461 echo "Waiting for $host: $lag seconds lagged\n";
2463 echo "Waiting for a database server: $lag seconds lagged\n";
2468 * Throws an E_USER_NOTICE saying that $function is deprecated
2469 * @param string $function
2472 function wfDeprecated( $function ) {
2473 trigger_error( "Use of $function is deprecated", E_USER_NOTICE
);
2477 * Sleep until the worst slave's replication lag is less than or equal to
2478 * $maxLag, in seconds. Use this when updating very large numbers of rows, as
2479 * in maintenance scripts, to avoid causing too much lag. Of course, this is
2480 * a no-op if there are no slaves.
2482 * Every time the function has to wait for a slave, it will print a message to
2483 * that effect (and then sleep for a little while), so it's probably not best
2484 * to use this outside maintenance scripts in its present form.
2486 * @param int $maxLag
2489 function wfWaitForSlaves( $maxLag ) {
2492 list( $host, $lag ) = $lb->getMaxLag();
2493 while( $lag > $maxLag ) {
2494 $name = @gethostbyaddr
( $host );
2495 if( $name !== false ) {
2498 print "Waiting for $host (lagged $lag seconds)...\n";
2500 list( $host, $lag ) = $lb->getMaxLag();