3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( "This file is part of MediaWiki, it is not a valid entry point" );
8 * Global functions used everywhere
12 * Some globals and requires needed
15 /** Total number of articles */
16 $wgNumberOfArticles = -1; # Unset
18 /** Total number of views */
21 /** Total number of edits */
25 require_once dirname(__FILE__
) . '/LogPage.php';
26 require_once dirname(__FILE__
) . '/normal/UtfNormalUtil.php';
27 require_once dirname(__FILE__
) . '/XmlFunctions.php';
30 * Compatibility functions
32 * We more or less support PHP 5.0.x and up.
33 * Re-implementations of newer functions or functions in non-standard
34 * PHP extensions may be included here.
36 if( !function_exists('iconv') ) {
37 # iconv support is not in the default configuration and so may not be present.
38 # Assume will only ever use utf-8 and iso-8859-1.
39 # This will *not* work in all circumstances.
40 function iconv( $from, $to, $string ) {
41 if(strcasecmp( $from, $to ) == 0) return $string;
42 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
43 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
48 # UTF-8 substr function based on a PHP manual comment
49 if ( !function_exists( 'mb_substr' ) ) {
50 function mb_substr( $str, $start ) {
52 preg_match_all( '/./us', $str, $ar );
54 if( func_num_args() >= 3 ) {
55 $end = func_get_arg( 2 );
56 return join( '', array_slice( $ar[0], $start, $end ) );
58 return join( '', array_slice( $ar[0], $start ) );
63 if ( !function_exists( 'mb_strlen' ) ) {
65 * Fallback implementation of mb_strlen, hardcoded to UTF-8.
67 * @param string $enc optional encoding; ignored
70 function mb_strlen( $str, $enc="" ) {
71 $counts = count_chars( $str );
75 for( $i = 0; $i < 0x80; $i++
) {
76 $total +
= $counts[$i];
79 // Count multibyte sequence heads
80 for( $i = 0xc0; $i < 0xff; $i++
) {
81 $total +
= $counts[$i];
87 if ( !function_exists( 'array_diff_key' ) ) {
89 * Exists in PHP 5.1.0+
90 * Not quite compatible, two-argument version only
91 * Null values will cause problems due to this use of isset()
93 function array_diff_key( $left, $right ) {
95 foreach ( $left as $key => $unused ) {
96 if ( isset( $right[$key] ) ) {
97 unset( $result[$key] );
106 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
107 * PHP 5 won't let you declare a 'clone' function, even conditionally,
108 * so it has to be a wrapper with a different name.
110 function wfClone( $object ) {
111 return clone( $object );
115 * Where as we got a random seed
117 $wgRandomSeeded = false;
120 * Seed Mersenne Twister
121 * No-op for compatibility; only necessary in PHP < 4.2.0
123 function wfSeedRandom() {
128 * Get a random decimal value between 0 and 1, in a way
129 * not likely to give duplicate values for any realistic
130 * number of articles.
134 function wfRandom() {
135 # The maximum random value is "only" 2^31-1, so get two random
136 # values to reduce the chance of dupes
137 $max = mt_getrandmax() +
1;
138 $rand = number_format( (mt_rand() * $max +
mt_rand())
139 / $max / $max, 12, '.', '' );
144 * We want / and : to be included as literal characters in our title URLs.
145 * %2F in the page titles seems to fatally break for some reason.
150 function wfUrlencode ( $s ) {
151 $s = urlencode( $s );
152 $s = preg_replace( '/%3[Aa]/', ':', $s );
153 $s = preg_replace( '/%2[Ff]/', '/', $s );
159 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
160 * In normal operation this is a NOP.
162 * Controlling globals:
163 * $wgDebugLogFile - points to the log file
164 * $wgProfileOnly - if set, normal debug messages will not be recorded.
165 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
166 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
168 * @param $text String
169 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
171 function wfDebug( $text, $logonly = false ) {
172 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
173 static $recursion = 0;
175 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
176 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
180 if ( $wgDebugComments && !$logonly ) {
181 if ( !isset( $wgOut ) ) {
184 if ( !StubObject
::isRealObject( $wgOut ) ) {
192 $wgOut->debug( $text );
194 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
195 # Strip unprintables; they can switch terminal modes when binary data
196 # gets dumped, which is pretty annoying.
197 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
198 wfErrorLog( $text, $wgDebugLogFile );
203 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
204 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
206 * @param $logGroup String
207 * @param $text String
208 * @param $public Bool: whether to log the event in the public log if no private
209 * log file is specified, (default true)
211 function wfDebugLog( $logGroup, $text, $public = true ) {
212 global $wgDebugLogGroups;
213 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
214 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
215 $time = wfTimestamp( TS_DB
);
217 wfErrorLog( "$time $wiki: $text", $wgDebugLogGroups[$logGroup] );
218 } else if ( $public === true ) {
219 wfDebug( $text, true );
224 * Log for database errors
225 * @param $text String: database error message.
227 function wfLogDBError( $text ) {
228 global $wgDBerrorLog, $wgDBname;
229 if ( $wgDBerrorLog ) {
230 $host = trim(`hostname`
);
231 $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
232 wfErrorLog( $text, $wgDBerrorLog );
237 * Log to a file without getting "file size exceeded" signals
239 function wfErrorLog( $text, $file ) {
240 # Temp: add unique request prefix
242 if ( !isset( $prefix ) ) {
243 $prefix = chr( mt_rand( 33, 126 ) ) . chr( mt_rand( 33, 126 ) ) . chr( mt_rand( 33, 126 ) ) . '| ';
245 $text = $prefix . $text;
247 wfSuppressWarnings();
248 $exists = file_exists( $file );
249 $size = $exists ?
filesize( $file ) : false;
250 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
251 error_log( $text, 3, $file );
259 function wfLogProfilingData() {
260 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
261 global $wgProfiling, $wgUser;
262 if ( $wgProfiling ) {
264 $elapsed = $now - $wgRequestTime;
265 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
267 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
268 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
269 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
270 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
271 if( !empty( $_SERVER['HTTP_FROM'] ) )
272 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
274 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
275 // Don't unstub $wgUser at this late stage just for statistics purposes
276 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
278 $log = sprintf( "%s\t%04.3f\t%s\n",
279 gmdate( 'YmdHis' ), $elapsed,
280 urldecode( $wgRequest->getRequestURL() . $forward ) );
281 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
282 wfErrorLog( $log . $prof, $wgDebugLogFile );
288 * Check if the wiki read-only lock file is present. This can be used to lock
289 * off editing functions, but doesn't guarantee that the database will not be
293 function wfReadOnly() {
294 global $wgReadOnlyFile, $wgReadOnly;
296 if ( !is_null( $wgReadOnly ) ) {
297 return (bool)$wgReadOnly;
299 if ( '' == $wgReadOnlyFile ) {
302 // Set $wgReadOnly for faster access next time
303 if ( is_file( $wgReadOnlyFile ) ) {
304 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
308 return (bool)$wgReadOnly;
313 * Get a message from anywhere, for the current user language.
315 * Use wfMsgForContent() instead if the message should NOT
316 * change depending on the user preferences.
318 * Note that the message may contain HTML, and is therefore
319 * not safe for insertion anywhere. Some functions such as
320 * addWikiText will do the escaping for you. Use wfMsgHtml()
321 * if you need an escaped message.
323 * @param $key String: lookup key for the message, usually
324 * defined in languages/Language.php
326 * This function also takes extra optional parameters (not
327 * shown in the function definition), which can by used to
328 * insert variable text into the predefined message.
330 function wfMsg( $key ) {
331 $args = func_get_args();
332 array_shift( $args );
333 return wfMsgReal( $key, $args, true );
337 * Same as above except doesn't transform the message
339 function wfMsgNoTrans( $key ) {
340 $args = func_get_args();
341 array_shift( $args );
342 return wfMsgReal( $key, $args, true, false, false );
346 * Get a message from anywhere, for the current global language
347 * set with $wgLanguageCode.
349 * Use this if the message should NOT change dependent on the
350 * language set in the user's preferences. This is the case for
351 * most text written into logs, as well as link targets (such as
352 * the name of the copyright policy page). Link titles, on the
353 * other hand, should be shown in the UI language.
355 * Note that MediaWiki allows users to change the user interface
356 * language in their preferences, but a single installation
357 * typically only contains content in one language.
359 * Be wary of this distinction: If you use wfMsg() where you should
360 * use wfMsgForContent(), a user of the software may have to
361 * customize over 70 messages in order to, e.g., fix a link in every
364 * @param $key String: lookup key for the message, usually
365 * defined in languages/Language.php
367 function wfMsgForContent( $key ) {
368 global $wgForceUIMsgAsContentMsg;
369 $args = func_get_args();
370 array_shift( $args );
372 if( is_array( $wgForceUIMsgAsContentMsg ) &&
373 in_array( $key, $wgForceUIMsgAsContentMsg ) )
375 return wfMsgReal( $key, $args, true, $forcontent );
379 * Same as above except doesn't transform the message
381 function wfMsgForContentNoTrans( $key ) {
382 global $wgForceUIMsgAsContentMsg;
383 $args = func_get_args();
384 array_shift( $args );
386 if( is_array( $wgForceUIMsgAsContentMsg ) &&
387 in_array( $key, $wgForceUIMsgAsContentMsg ) )
389 return wfMsgReal( $key, $args, true, $forcontent, false );
393 * Get a message from the language file, for the UI elements
395 function wfMsgNoDB( $key ) {
396 $args = func_get_args();
397 array_shift( $args );
398 return wfMsgReal( $key, $args, false );
402 * Get a message from the language file, for the content
404 function wfMsgNoDBForContent( $key ) {
405 global $wgForceUIMsgAsContentMsg;
406 $args = func_get_args();
407 array_shift( $args );
409 if( is_array( $wgForceUIMsgAsContentMsg ) &&
410 in_array( $key, $wgForceUIMsgAsContentMsg ) )
412 return wfMsgReal( $key, $args, false, $forcontent );
417 * Really get a message
418 * @param $key String: key to get.
420 * @param $useDB Boolean
421 * @param $transform Boolean: Whether or not to transform the message.
422 * @param $forContent Boolean
423 * @return String: the requested message.
425 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
426 $fname = 'wfMsgReal';
427 wfProfileIn( $fname );
428 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
429 $message = wfMsgReplaceArgs( $message, $args );
430 wfProfileOut( $fname );
435 * This function provides the message source for messages to be edited which are *not* stored in the database.
436 * @param $key String:
438 function wfMsgWeirdKey ( $key ) {
439 $source = wfMsgGetKey( $key, false, true, false );
440 if ( wfEmptyMsg( $key, $source ) )
447 * Fetch a message string value, but don't replace any keys yet.
450 * @param bool $forContent
454 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
455 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
457 /* <Vyznev> btw, is all that code in wfMsgGetKey() that check
458 * if the message cache exists of not really necessary, or is
460 * <TimStarling> Vyznev: it's probably not necessary
461 * <TimStarling> I think I wrote it in an attempt to report DB
462 * connection errors properly
463 * <TimStarling> but eventually we gave up on using the
464 * message cache for that and just hard-coded the strings
465 * <TimStarling> it may have other uses, it's not mere paranoia
468 if ( is_object( $wgMessageCache ) )
469 $transstat = $wgMessageCache->getTransform();
471 if( is_object( $wgMessageCache ) ) {
473 $wgMessageCache->disableTransform();
474 $message = $wgMessageCache->get( $key, $useDB, $forContent );
477 $lang = &$wgContLang;
482 # MessageCache::get() does this already, Language::getMessage() doesn't
483 # ISSUE: Should we try to handle "message/lang" here too?
484 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
486 wfSuppressWarnings();
487 if( is_object( $lang ) ) {
488 $message = $lang->getMessage( $key );
494 if ( $transform && strstr( $message, '{{' ) !== false ) {
495 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
499 if ( is_object( $wgMessageCache ) && ! $transform )
500 $wgMessageCache->setTransform( $transstat );
506 * Replace message parameter keys on the given formatted output.
508 * @param string $message
513 function wfMsgReplaceArgs( $message, $args ) {
514 # Fix windows line-endings
515 # Some messages are split with explode("\n", $msg)
516 $message = str_replace( "\r", '', $message );
519 if ( count( $args ) ) {
520 if ( is_array( $args[0] ) ) {
521 foreach ( $args[0] as $key => $val ) {
522 $message = str_replace( '$' . $key, $val, $message );
525 foreach( $args as $n => $param ) {
526 $replacementKeys['$' . ($n +
1)] = $param;
528 $message = strtr( $message, $replacementKeys );
536 * Return an HTML-escaped version of a message.
537 * Parameter replacements, if any, are done *after* the HTML-escaping,
538 * so parameters may contain HTML (eg links or form controls). Be sure
539 * to pre-escape them if you really do want plaintext, or just wrap
540 * the whole thing in htmlspecialchars().
543 * @param string ... parameters
546 function wfMsgHtml( $key ) {
547 $args = func_get_args();
548 array_shift( $args );
549 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
553 * Return an HTML version of message
554 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
555 * so parameters may contain HTML (eg links or form controls). Be sure
556 * to pre-escape them if you really do want plaintext, or just wrap
557 * the whole thing in htmlspecialchars().
560 * @param string ... parameters
563 function wfMsgWikiHtml( $key ) {
565 $args = func_get_args();
566 array_shift( $args );
567 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
571 * Returns message in the requested format
572 * @param string $key Key of the message
573 * @param array $options Processing rules:
574 * <i>parse</i>: parses wikitext to html
575 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
576 * <i>escape</i>: filters message trough htmlspecialchars
577 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
578 * <i>parsemag</i>: transform the message using magic phrases
580 function wfMsgExt( $key, $options ) {
581 global $wgOut, $wgParser;
583 $args = func_get_args();
584 array_shift( $args );
585 array_shift( $args );
587 if( !is_array($options) ) {
588 $options = array($options);
591 $string = wfMsgGetKey( $key, true, false, false );
593 if( !in_array('replaceafter', $options) ) {
594 $string = wfMsgReplaceArgs( $string, $args );
597 if( in_array('parse', $options) ) {
598 $string = $wgOut->parse( $string, true, true );
599 } elseif ( in_array('parseinline', $options) ) {
600 $string = $wgOut->parse( $string, true, true );
602 if( preg_match( '/^<p>(.*)\n?<\/p>$/sU', $string, $m ) ) {
605 } elseif ( in_array('parsemag', $options) ) {
606 global $wgMessageCache;
607 if ( isset( $wgMessageCache ) ) {
608 $string = $wgMessageCache->transform( $string );
612 if ( in_array('escape', $options) ) {
613 $string = htmlspecialchars ( $string );
616 if( in_array('replaceafter', $options) ) {
617 $string = wfMsgReplaceArgs( $string, $args );
625 * Just like exit() but makes a note of it.
626 * Commits open transactions except if the error parameter is set
628 * @deprecated Please return control to the caller or throw an exception
630 function wfAbruptExit( $error = false ){
631 global $wgLoadBalancer;
632 static $called = false;
638 $bt = wfDebugBacktrace();
640 for($i = 0; $i < count($bt) ; $i++
){
641 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
642 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
643 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
646 wfDebug('WARNING: Abrupt exit\n');
649 wfLogProfilingData();
652 $wgLoadBalancer->closeAll();
658 * @deprecated Please return control the caller or throw an exception
660 function wfErrorExit() {
661 wfAbruptExit( true );
665 * Print a simple message and die, returning nonzero to the shell if any.
666 * Plain die() fails to return nonzero to the shell if you pass a string.
669 function wfDie( $msg='' ) {
675 * Throw a debugging exception. This function previously once exited the process,
676 * but now throws an exception instead, with similar results.
678 * @param string $msg Message shown when dieing.
680 function wfDebugDieBacktrace( $msg = '' ) {
681 throw new MWException( $msg );
685 * Fetch server name for use in error reporting etc.
686 * Use real server name if available, so we know which machine
687 * in a server farm generated the current page.
690 function wfHostname() {
691 if ( function_exists( 'posix_uname' ) ) {
692 // This function not present on Windows
693 $uname = @posix_uname
();
697 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
698 return $uname['nodename'];
700 # This may be a virtual server.
701 return $_SERVER['SERVER_NAME'];
706 * Returns a HTML comment with the elapsed time since request.
707 * This method has no side effects.
710 function wfReportTime() {
711 global $wgRequestTime, $wgShowHostnames;
714 $elapsed = $now - $wgRequestTime;
716 return $wgShowHostnames
717 ?
sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
718 : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
722 * Safety wrapper for debug_backtrace().
724 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
725 * murky circumstances, which may be triggered in part by stub objects
726 * or other fancy talkin'.
728 * Will return an empty array if Zend Optimizer is detected, otherwise
729 * the output from debug_backtrace() (trimmed).
731 * @return array of backtrace information
733 function wfDebugBacktrace() {
734 if( extension_loaded( 'Zend Optimizer' ) ) {
735 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
738 return array_slice( debug_backtrace(), 1 );
742 function wfBacktrace() {
743 global $wgCommandLineMode;
745 if ( $wgCommandLineMode ) {
750 $backtrace = wfDebugBacktrace();
751 foreach( $backtrace as $call ) {
752 if( isset( $call['file'] ) ) {
753 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
754 $file = $f[count($f)-1];
758 if( isset( $call['line'] ) ) {
759 $line = $call['line'];
763 if ( $wgCommandLineMode ) {
764 $msg .= "$file line $line calls ";
766 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
768 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
769 $msg .= $call['function'] . '()';
771 if ( $wgCommandLineMode ) {
777 if ( $wgCommandLineMode ) {
787 /* Some generic result counters, pulled out of SearchEngine */
793 function wfShowingResults( $offset, $limit ) {
795 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
801 function wfShowingResultsNum( $offset, $limit, $num ) {
803 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
809 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
811 $fmtLimit = $wgLang->formatNum( $limit );
812 $prev = wfMsg( 'prevn', $fmtLimit );
813 $next = wfMsg( 'nextn', $fmtLimit );
815 if( is_object( $link ) ) {
818 $title = Title
::newFromText( $link );
819 if( is_null( $title ) ) {
824 if ( 0 != $offset ) {
825 $po = $offset - $limit;
826 if ( $po < 0 ) { $po = 0; }
827 $q = "limit={$limit}&offset={$po}";
828 if ( '' != $query ) { $q .= '&'.$query; }
829 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-prevlink\">{$prev}</a>";
830 } else { $plink = $prev; }
832 $no = $offset +
$limit;
833 $q = 'limit='.$limit.'&offset='.$no;
834 if ( '' != $query ) { $q .= '&'.$query; }
839 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-nextlink\">{$next}</a>";
841 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
842 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
843 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
844 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
845 wfNumLink( $offset, 500, $title, $query );
847 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
853 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
855 if ( '' == $query ) { $q = ''; }
856 else { $q = $query.'&'; }
857 $q .= 'limit='.$limit.'&offset='.$offset;
859 $fmtLimit = $wgLang->formatNum( $limit );
860 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" class=\"mw-numlink\">{$fmtLimit}</a>";
866 * @todo FIXME: we may want to blacklist some broken browsers
868 * @return bool Whereas client accept gzip compression
870 function wfClientAcceptsGzip() {
873 # FIXME: we may want to blacklist some broken browsers
876 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
877 $_SERVER['HTTP_ACCEPT_ENCODING'],
879 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
880 wfDebug( " accepts gzip\n" );
888 * Obtain the offset and limit values from the request string;
889 * used in special pages
891 * @param $deflimit Default limit if none supplied
892 * @param $optionname Name of a user preference to check against
896 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
898 return $wgRequest->getLimitOffset( $deflimit, $optionname );
902 * Escapes the given text so that it may be output using addWikiText()
903 * without any linking, formatting, etc. making its way through. This
904 * is achieved by substituting certain characters with HTML entities.
905 * As required by the callers, <nowiki> is not used. It currently does
906 * not filter out characters which have special meaning only at the
907 * start of a line, such as "*".
909 * @param string $text Text to be escaped
911 function wfEscapeWikiText( $text ) {
913 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
914 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
915 htmlspecialchars($text) );
922 function wfQuotedPrintable( $string, $charset = '' ) {
923 # Probably incomplete; see RFC 2045
924 if( empty( $charset ) ) {
925 global $wgInputEncoding;
926 $charset = $wgInputEncoding;
928 $charset = strtoupper( $charset );
929 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
931 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
932 $replace = $illegal . '\t ?_';
933 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
934 $out = "=?$charset?Q?";
935 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
946 return microtime(true);
950 * Sets dest to source and returns the original value of dest
951 * If source is NULL, it just returns the value, it doesn't set the variable
953 function wfSetVar( &$dest, $source ) {
955 if ( !is_null( $source ) ) {
962 * As for wfSetVar except setting a bit
964 function wfSetBit( &$dest, $bit, $state = true ) {
965 $temp = (bool)($dest & $bit );
966 if ( !is_null( $state ) ) {
977 * This function takes two arrays as input, and returns a CGI-style string, e.g.
978 * "days=7&limit=100". Options in the first array override options in the second.
979 * Options set to "" will not be output.
981 function wfArrayToCGI( $array1, $array2 = NULL )
983 if ( !is_null( $array2 ) ) {
984 $array1 = $array1 +
$array2;
988 foreach ( $array1 as $key => $value ) {
989 if ( '' !== $value ) {
993 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
1000 * Append a query string to an existing URL, which may or may not already
1001 * have query string parameters already. If so, they will be combined.
1003 * @param string $url
1004 * @param string $query
1007 function wfAppendQuery( $url, $query ) {
1008 if( $query != '' ) {
1009 if( false === strpos( $url, '?' ) ) {
1020 * This is obsolete, use SquidUpdate::purge()
1023 function wfPurgeSquidServers ($urlArr) {
1024 SquidUpdate
::purge( $urlArr );
1028 * Windows-compatible version of escapeshellarg()
1029 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1030 * function puts single quotes in regardless of OS
1032 function wfEscapeShellArg( ) {
1033 $args = func_get_args();
1036 foreach ( $args as $arg ) {
1043 if ( wfIsWindows() ) {
1044 // Escaping for an MSVC-style command line parser
1045 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1046 // Double the backslashes before any double quotes. Escape the double quotes.
1047 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1050 foreach ( $tokens as $token ) {
1052 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1058 // Double the backslashes before the end of the string, because
1059 // we will soon add a quote
1061 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1062 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1065 // Add surrounding quotes
1066 $retVal .= '"' . $arg . '"';
1068 $retVal .= escapeshellarg( $arg );
1075 * wfMerge attempts to merge differences between three texts.
1076 * Returns true for a clean merge and false for failure or a conflict.
1078 function wfMerge( $old, $mine, $yours, &$result ){
1081 # This check may also protect against code injection in
1082 # case of broken installations.
1083 if(! file_exists( $wgDiff3 ) ){
1084 wfDebug( "diff3 not found\n" );
1088 # Make temporary files
1090 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1091 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1092 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1094 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1095 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1096 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1098 # Check for a conflict
1099 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1100 wfEscapeShellArg( $mytextName ) . ' ' .
1101 wfEscapeShellArg( $oldtextName ) . ' ' .
1102 wfEscapeShellArg( $yourtextName );
1103 $handle = popen( $cmd, 'r' );
1105 if( fgets( $handle, 1024 ) ){
1113 $cmd = $wgDiff3 . ' -a -e --merge ' .
1114 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1115 $handle = popen( $cmd, 'r' );
1118 $data = fread( $handle, 8192 );
1119 if ( strlen( $data ) == 0 ) {
1125 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1127 if ( $result === '' && $old !== '' && $conflict == false ) {
1128 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1137 function wfVarDump( $var ) {
1139 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1140 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1143 $wgOut->addHTML( $s );
1148 * Provide a simple HTTP error.
1150 function wfHttpError( $code, $label, $desc ) {
1153 header( "HTTP/1.0 $code $label" );
1154 header( "Status: $code $label" );
1155 $wgOut->sendCacheControl();
1157 header( 'Content-type: text/html; charset=utf-8' );
1158 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1159 "<html><head><title>" .
1160 htmlspecialchars( $label ) .
1161 "</title></head><body><h1>" .
1162 htmlspecialchars( $label ) .
1164 nl2br( htmlspecialchars( $desc ) ) .
1165 "</p></body></html>\n";
1169 * Clear away any user-level output buffers, discarding contents.
1171 * Suitable for 'starting afresh', for instance when streaming
1172 * relatively large amounts of data without buffering, or wanting to
1173 * output image files without ob_gzhandler's compression.
1175 * The optional $resetGzipEncoding parameter controls suppression of
1176 * the Content-Encoding header sent by ob_gzhandler; by default it
1177 * is left. See comments for wfClearOutputBuffers() for why it would
1180 * Note that some PHP configuration options may add output buffer
1181 * layers which cannot be removed; these are left in place.
1183 * @param bool $resetGzipEncoding
1185 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1186 if( $resetGzipEncoding ) {
1187 // Suppress Content-Encoding and Content-Length
1188 // headers from 1.10+s wfOutputHandler
1189 global $wgDisableOutputCompression;
1190 $wgDisableOutputCompression = true;
1192 while( $status = ob_get_status() ) {
1193 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1194 // Probably from zlib.output_compression or other
1195 // PHP-internal setting which can't be removed.
1197 // Give up, and hope the result doesn't break
1201 if( !ob_end_clean() ) {
1202 // Could not remove output buffer handler; abort now
1203 // to avoid getting in some kind of infinite loop.
1206 if( $resetGzipEncoding ) {
1207 if( $status['name'] == 'ob_gzhandler' ) {
1208 // Reset the 'Content-Encoding' field set by this handler
1209 // so we can start fresh.
1210 header( 'Content-Encoding:' );
1217 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1219 * Clear away output buffers, but keep the Content-Encoding header
1220 * produced by ob_gzhandler, if any.
1222 * This should be used for HTTP 304 responses, where you need to
1223 * preserve the Content-Encoding header of the real result, but
1224 * also need to suppress the output of ob_gzhandler to keep to spec
1225 * and avoid breaking Firefox in rare cases where the headers and
1226 * body are broken over two packets.
1228 function wfClearOutputBuffers() {
1229 wfResetOutputBuffers( false );
1233 * Converts an Accept-* header into an array mapping string values to quality
1236 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1237 # No arg means accept anything (per HTTP spec)
1239 return array( $def => 1 );
1244 $parts = explode( ',', $accept );
1246 foreach( $parts as $part ) {
1247 # FIXME: doesn't deal with params like 'text/html; level=1'
1248 @list
( $value, $qpart ) = explode( ';', $part );
1250 if( !isset( $qpart ) ) {
1252 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1253 $prefs[$value] = $match[1];
1261 * Checks if a given MIME type matches any of the keys in the given
1262 * array. Basic wildcards are accepted in the array keys.
1264 * Returns the matching MIME type (or wildcard) if a match, otherwise
1267 * @param string $type
1268 * @param array $avail
1272 function mimeTypeMatch( $type, $avail ) {
1273 if( array_key_exists($type, $avail) ) {
1276 $parts = explode( '/', $type );
1277 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1278 return $parts[0] . '/*';
1279 } elseif( array_key_exists( '*/*', $avail ) ) {
1288 * Returns the 'best' match between a client's requested internet media types
1289 * and the server's list of available types. Each list should be an associative
1290 * array of type to preference (preference is a float between 0.0 and 1.0).
1291 * Wildcards in the types are acceptable.
1293 * @param array $cprefs Client's acceptable type list
1294 * @param array $sprefs Server's offered types
1297 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1298 * XXX: generalize to negotiate other stuff
1300 function wfNegotiateType( $cprefs, $sprefs ) {
1303 foreach( array_keys($sprefs) as $type ) {
1304 $parts = explode( '/', $type );
1305 if( $parts[1] != '*' ) {
1306 $ckey = mimeTypeMatch( $type, $cprefs );
1308 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1313 foreach( array_keys( $cprefs ) as $type ) {
1314 $parts = explode( '/', $type );
1315 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1316 $skey = mimeTypeMatch( $type, $sprefs );
1318 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1326 foreach( array_keys( $combine ) as $type ) {
1327 if( $combine[$type] > $bestq ) {
1329 $bestq = $combine[$type];
1338 * Returns an array where the values in the first array are replaced by the
1339 * values in the second array with the corresponding keys
1343 function wfArrayLookup( $a, $b ) {
1344 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1348 * Convenience function; returns MediaWiki timestamp for the present time.
1351 function wfTimestampNow() {
1353 return wfTimestamp( TS_MW
, time() );
1357 * Reference-counted warning suppression
1359 function wfSuppressWarnings( $end = false ) {
1360 static $suppressCount = 0;
1361 static $originalLevel = false;
1364 if ( $suppressCount ) {
1366 if ( !$suppressCount ) {
1367 error_reporting( $originalLevel );
1371 if ( !$suppressCount ) {
1372 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1379 * Restore error level to previous value
1381 function wfRestoreWarnings() {
1382 wfSuppressWarnings( true );
1385 # Autodetect, convert and provide timestamps of various types
1388 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1390 define('TS_UNIX', 0);
1393 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1398 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1403 * RFC 2822 format, for E-mail and HTTP headers
1405 define('TS_RFC2822', 3);
1408 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1410 * This is used by Special:Export
1412 define('TS_ISO_8601', 4);
1415 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1417 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1418 * DateTime tag and page 36 for the DateTimeOriginal and
1419 * DateTimeDigitized tags.
1421 define('TS_EXIF', 5);
1424 * Oracle format time.
1426 define('TS_ORACLE', 6);
1429 * Postgres format time.
1431 define('TS_POSTGRES', 7);
1434 * @param mixed $outputtype A timestamp in one of the supported formats, the
1435 * function will autodetect which format is supplied
1436 * and act accordingly.
1437 * @return string Time in the format specified in $outputtype
1439 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1444 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1446 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1447 (int)$da[2],(int)$da[3],(int)$da[1]);
1448 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1450 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1451 (int)$da[2],(int)$da[3],(int)$da[1]);
1452 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1454 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1455 (int)$da[2],(int)$da[3],(int)$da[1]);
1456 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1459 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1461 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1462 str_replace("+00:00", "UTC", $ts)));
1463 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1465 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1466 (int)$da[2],(int)$da[3],(int)$da[1]);
1467 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1469 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1470 (int)$da[2],(int)$da[3],(int)$da[1]);
1471 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1473 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1474 (int)$da[2],(int)$da[3],(int)$da[1]);
1476 # Bogus value; fall back to the epoch...
1477 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1482 switch($outputtype) {
1486 return gmdate( 'YmdHis', $uts );
1488 return gmdate( 'Y-m-d H:i:s', $uts );
1490 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1491 // This shouldn't ever be used, but is included for completeness
1493 return gmdate( 'Y:m:d H:i:s', $uts );
1495 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1497 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1499 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1501 throw new MWException( 'wfTimestamp() called with illegal output type.');
1506 * Return a formatted timestamp, or null if input is null.
1507 * For dealing with nullable timestamp columns in the database.
1508 * @param int $outputtype
1512 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1513 if( is_null( $ts ) ) {
1516 return wfTimestamp( $outputtype, $ts );
1521 * Check if the operating system is Windows
1523 * @return bool True if it's Windows, False otherwise.
1525 function wfIsWindows() {
1526 if (substr(php_uname(), 0, 7) == 'Windows') {
1534 * Swap two variables
1536 function swap( &$x, &$y ) {
1542 function wfGetCachedNotice( $name ) {
1543 global $wgOut, $parserMemc;
1544 $fname = 'wfGetCachedNotice';
1545 wfProfileIn( $fname );
1549 if( $name === 'default' ) {
1551 global $wgSiteNotice;
1552 $notice = $wgSiteNotice;
1553 if( empty( $notice ) ) {
1554 wfProfileOut( $fname );
1558 $notice = wfMsgForContentNoTrans( $name );
1559 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1560 wfProfileOut( $fname );
1565 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1566 if( is_array( $cachedNotice ) ) {
1567 if( md5( $notice ) == $cachedNotice['hash'] ) {
1568 $notice = $cachedNotice['html'];
1577 if( is_object( $wgOut ) ) {
1578 $parsed = $wgOut->parse( $notice );
1579 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1582 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1587 wfProfileOut( $fname );
1591 function wfGetNamespaceNotice() {
1595 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1598 $fname = 'wfGetNamespaceNotice';
1599 wfProfileIn( $fname );
1601 $key = "namespacenotice-" . $wgTitle->getNsText();
1602 $namespaceNotice = wfGetCachedNotice( $key );
1603 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1604 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1606 $namespaceNotice = "";
1609 wfProfileOut( $fname );
1610 return $namespaceNotice;
1613 function wfGetSiteNotice() {
1614 global $wgUser, $wgSiteNotice;
1615 $fname = 'wfGetSiteNotice';
1616 wfProfileIn( $fname );
1619 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1620 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1621 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1623 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1624 if( !$anonNotice ) {
1625 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1627 $siteNotice = $anonNotice;
1630 if( !$siteNotice ) {
1631 $siteNotice = wfGetCachedNotice( 'default' );
1635 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1636 wfProfileOut( $fname );
1641 * BC wrapper for MimeMagic::singleton()
1644 function &wfGetMimeMagic() {
1645 return MimeMagic
::singleton();
1649 * Tries to get the system directory for temporary files.
1650 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1651 * and if none are set /tmp is returned as the generic Unix default.
1653 * NOTE: When possible, use the tempfile() function to create temporary
1654 * files to avoid race conditions on file creation, etc.
1658 function wfTempDir() {
1659 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1660 $tmp = getenv( $var );
1661 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1665 # Hope this is Unix of some kind!
1670 * Make directory, and make all parent directories if they don't exist
1672 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1673 if( strval( $fullDir ) === '' )
1675 if( file_exists( $fullDir ) )
1677 return mkdir( str_replace( '/', DIRECTORY_SEPARATOR
, $fullDir ), $mode, true );
1681 * Increment a statistics counter
1683 function wfIncrStats( $key ) {
1685 $key = wfMemcKey( 'stats', $key );
1686 if ( is_null( $wgMemc->incr( $key ) ) ) {
1687 $wgMemc->add( $key, 1 );
1692 * @param mixed $nr The number to format
1693 * @param int $acc The number of digits after the decimal point, default 2
1694 * @param bool $round Whether or not to round the value, default true
1697 function wfPercent( $nr, $acc = 2, $round = true ) {
1698 $ret = sprintf( "%.${acc}f", $nr );
1699 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1703 * Encrypt a username/password.
1705 * @param string $userid ID of the user
1706 * @param string $password Password of the user
1707 * @return string Hashed password
1709 function wfEncryptPassword( $userid, $password ) {
1710 global $wgPasswordSalt;
1711 $p = md5( $password);
1714 return md5( "{$userid}-{$p}" );
1720 * Appends to second array if $value differs from that in $default
1722 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1723 if ( is_null( $changed ) ) {
1724 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1726 if ( $default[$key] !== $value ) {
1727 $changed[$key] = $value;
1732 * Since wfMsg() and co suck, they don't return false if the message key they
1733 * looked up didn't exist but a XHTML string, this function checks for the
1734 * nonexistance of messages by looking at wfMsg() output
1736 * @param $msg The message key looked up
1737 * @param $wfMsgOut The output of wfMsg*()
1740 function wfEmptyMsg( $msg, $wfMsgOut ) {
1741 return $wfMsgOut === htmlspecialchars( "<$msg>" );
1745 * Find out whether or not a mixed variable exists in a string
1747 * @param mixed needle
1748 * @param string haystack
1751 function in_string( $needle, $str ) {
1752 return strpos( $str, $needle ) !== false;
1755 function wfSpecialList( $page, $details ) {
1757 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1758 return $page . $details;
1762 * Returns a regular expression of url protocols
1766 function wfUrlProtocols() {
1767 global $wgUrlProtocols;
1769 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1770 // with LocalSettings files from 1.5
1771 if ( is_array( $wgUrlProtocols ) ) {
1772 $protocols = array();
1773 foreach ($wgUrlProtocols as $protocol)
1774 $protocols[] = preg_quote( $protocol, '/' );
1776 return implode( '|', $protocols );
1778 return $wgUrlProtocols;
1783 * Execute a shell command, with time and memory limits mirrored from the PHP
1784 * configuration if supported.
1785 * @param $cmd Command line, properly escaped for shell.
1786 * @param &$retval optional, will receive the program's exit code.
1787 * (non-zero is usually failure)
1788 * @return collected stdout as a string (trailing newlines stripped)
1790 function wfShellExec( $cmd, &$retval=null ) {
1791 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1793 if( ini_get( 'safe_mode' ) ) {
1794 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1796 return "Unable to run external programs in safe mode.";
1799 if ( php_uname( 's' ) == 'Linux' ) {
1800 $time = intval( ini_get( 'max_execution_time' ) );
1801 $mem = intval( $wgMaxShellMemory );
1802 $filesize = intval( $wgMaxShellFileSize );
1804 if ( $time > 0 && $mem > 0 ) {
1805 $script = "$IP/bin/ulimit4.sh";
1806 if ( is_executable( $script ) ) {
1807 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1810 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1811 # This is a hack to work around PHP's flawed invocation of cmd.exe
1812 # http://news.php.net/php.internals/21796
1813 $cmd = '"' . $cmd . '"';
1815 wfDebug( "wfShellExec: $cmd\n" );
1818 $retval = 1; // error by default?
1819 exec( $cmd, $output, $retval ); // returns the last line of output.
1820 return implode( "\n", $output );
1825 * This function works like "use VERSION" in Perl, the program will die with a
1826 * backtrace if the current version of PHP is less than the version provided
1828 * This is useful for extensions which due to their nature are not kept in sync
1829 * with releases, and might depend on other versions of PHP than the main code
1831 * Note: PHP might die due to parsing errors in some cases before it ever
1832 * manages to call this function, such is life
1834 * @see perldoc -f use
1836 * @param mixed $version The version to check, can be a string, an integer, or
1839 function wfUsePHP( $req_ver ) {
1840 $php_ver = PHP_VERSION
;
1842 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1843 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1847 * This function works like "use VERSION" in Perl except it checks the version
1848 * of MediaWiki, the program will die with a backtrace if the current version
1849 * of MediaWiki is less than the version provided.
1851 * This is useful for extensions which due to their nature are not kept in sync
1854 * @see perldoc -f use
1856 * @param mixed $version The version to check, can be a string, an integer, or
1859 function wfUseMW( $req_ver ) {
1862 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1863 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1867 * @deprecated use StringUtils::escapeRegexReplacement
1869 function wfRegexReplacement( $string ) {
1870 return StringUtils
::escapeRegexReplacement( $string );
1874 * Return the final portion of a pathname.
1875 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1876 * http://bugs.php.net/bug.php?id=33898
1878 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1879 * We'll consider it so always, as we don't want \s in our Unix paths either.
1881 * @param string $path
1882 * @param string $suffix to remove if present
1885 function wfBaseName( $path, $suffix='' ) {
1886 $encSuffix = ($suffix == '')
1888 : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
1890 if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
1898 * Generate a relative path name to the given file.
1899 * May explode on non-matching case-insensitive paths,
1900 * funky symlinks, etc.
1902 * @param string $path Absolute destination path including target filename
1903 * @param string $from Absolute source path, directory only
1906 function wfRelativePath( $path, $from ) {
1907 // Normalize mixed input on Windows...
1908 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1909 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1911 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1912 $against = explode( DIRECTORY_SEPARATOR
, $from );
1914 // Trim off common prefix
1915 while( count( $pieces ) && count( $against )
1916 && $pieces[0] == $against[0] ) {
1917 array_shift( $pieces );
1918 array_shift( $against );
1921 // relative dots to bump us to the parent
1922 while( count( $against ) ) {
1923 array_unshift( $pieces, '..' );
1924 array_shift( $against );
1927 array_push( $pieces, wfBaseName( $path ) );
1929 return implode( DIRECTORY_SEPARATOR
, $pieces );
1933 * Make a URL index, appropriate for the el_index field of externallinks.
1935 function wfMakeUrlIndex( $url ) {
1936 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1937 $bits = parse_url( $url );
1938 wfSuppressWarnings();
1939 wfRestoreWarnings();
1943 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1945 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1947 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1949 // parse_url detects for news: and mailto: the host part of an url as path
1950 // We have to correct this wrong detection
1951 if ( isset ( $bits['path'] ) ) {
1952 $bits['host'] = $bits['path'];
1959 // Reverse the labels in the hostname, convert to lower case
1960 // For emails reverse domainpart only
1961 if ( $bits['scheme'] == 'mailto' ) {
1962 $mailparts = explode( '@', $bits['host'] );
1963 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1964 $reversedHost = $domainpart . '@' . $mailparts[0];
1966 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1968 // Add an extra dot to the end
1969 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1970 $reversedHost .= '.';
1972 // Reconstruct the pseudo-URL
1973 $prot = $bits['scheme'];
1974 $index = "$prot$delimiter$reversedHost";
1975 // Leave out user and password. Add the port, path, query and fragment
1976 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1977 if ( isset( $bits['path'] ) ) {
1978 $index .= $bits['path'];
1982 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1983 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1988 * Do any deferred updates and clear the list
1989 * TODO: This could be in Wiki.php if that class made any sense at all
1991 function wfDoUpdates()
1993 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1994 foreach ( $wgDeferredUpdateList as $update ) {
1995 $update->doUpdate();
1997 foreach ( $wgPostCommitUpdateList as $update ) {
1998 $update->doUpdate();
2000 $wgDeferredUpdateList = array();
2001 $wgPostCommitUpdateList = array();
2005 * @deprecated use StringUtils::explodeMarkup
2007 function wfExplodeMarkup( $separator, $text ) {
2008 return StringUtils
::explodeMarkup( $separator, $text );
2012 * Convert an arbitrarily-long digit string from one numeric base
2013 * to another, optionally zero-padding to a minimum column width.
2015 * Supports base 2 through 36; digit values 10-36 are represented
2016 * as lowercase letters a-z. Input is case-insensitive.
2018 * @param $input string of digits
2019 * @param $sourceBase int 2-36
2020 * @param $destBase int 2-36
2021 * @param $pad int 1 or greater
2022 * @param $lowercase bool
2023 * @return string or false on invalid input
2025 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2026 $input = strval( $input );
2027 if( $sourceBase < 2 ||
2032 $sourceBase != intval( $sourceBase ) ||
2033 $destBase != intval( $destBase ) ||
2034 $pad != intval( $pad ) ||
2035 !is_string( $input ) ||
2039 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2040 $inDigits = array();
2043 // Decode and validate input string
2044 $input = strtolower( $input );
2045 for( $i = 0; $i < strlen( $input ); $i++
) {
2046 $n = strpos( $digitChars, $input{$i} );
2047 if( $n === false ||
$n > $sourceBase ) {
2053 // Iterate over the input, modulo-ing out an output digit
2054 // at a time until input is gone.
2055 while( count( $inDigits ) ) {
2057 $workDigits = array();
2060 foreach( $inDigits as $digit ) {
2061 $work *= $sourceBase;
2064 if( $work < $destBase ) {
2065 // Gonna need to pull another digit.
2066 if( count( $workDigits ) ) {
2067 // Avoid zero-padding; this lets us find
2068 // the end of the input very easily when
2069 // length drops to zero.
2073 // Finally! Actual division!
2074 $workDigits[] = intval( $work / $destBase );
2076 // Isn't it annoying that most programming languages
2077 // don't have a single divide-and-remainder operator,
2078 // even though the CPU implements it that way?
2079 $work = $work %
$destBase;
2083 // All that division leaves us with a remainder,
2084 // which is conveniently our next output digit.
2085 $outChars .= $digitChars[$work];
2088 $inDigits = $workDigits;
2091 while( strlen( $outChars ) < $pad ) {
2095 return strrev( $outChars );
2099 * Create an object with a given name and an array of construct parameters
2100 * @param string $name
2101 * @param array $p parameters
2103 function wfCreateObject( $name, $p ){
2104 $p = array_values( $p );
2105 switch ( count( $p ) ) {
2109 return new $name( $p[0] );
2111 return new $name( $p[0], $p[1] );
2113 return new $name( $p[0], $p[1], $p[2] );
2115 return new $name( $p[0], $p[1], $p[2], $p[3] );
2117 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2119 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2121 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2126 * Aliases for modularized functions
2128 function wfGetHTTP( $url, $timeout = 'default' ) {
2129 return Http
::get( $url, $timeout );
2131 function wfIsLocalURL( $url ) {
2132 return Http
::isLocalURL( $url );
2136 * Initialise php session
2138 function wfSetupSession() {
2139 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2140 if( $wgSessionsInMemcached ) {
2141 require_once( 'MemcachedSessions.php' );
2142 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2143 # If it's left on 'user' or another setting from another
2144 # application, it will end up failing. Try to recover.
2145 ini_set ( 'session.save_handler', 'files' );
2147 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2148 session_cache_limiter( 'private, must-revalidate' );
2149 wfDebug( "Starting session..." );
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 if ( isset( $backtrace[$level]['class'] ) ) {
2176 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2178 $caller = $backtrace[$level]['function'];
2181 $caller = 'unknown';
2186 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2187 function wfGetAllCallers() {
2188 return implode('/', array_map(
2189 create_function('$frame','
2190 return isset( $frame["class"] )?
2191 $frame["class"]."::".$frame["function"]:
2194 array_reverse(wfDebugBacktrace())));
2200 function wfMemcKey( /*... */ ) {
2201 global $wgDBprefix, $wgDBname;
2202 $args = func_get_args();
2203 if ( $wgDBprefix ) {
2204 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2206 $key = $wgDBname . ':' . implode( ':', $args );
2212 * Get a cache key for a foreign DB
2214 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2215 $args = array_slice( func_get_args(), 2 );
2217 $key = "$db-$prefix:" . implode( ':', $args );
2219 $key = $db . ':' . implode( ':', $args );
2225 * Get an ASCII string identifying this wiki
2226 * This is used as a prefix in memcached keys
2228 function wfWikiID() {
2229 global $wgDBprefix, $wgDBname;
2230 if ( $wgDBprefix ) {
2231 return "$wgDBname-$wgDBprefix";
2238 * Get a Database object
2239 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2240 * master (for write queries), DB_SLAVE for potentially lagged
2241 * read queries, or an integer >= 0 for a particular server.
2243 * @param mixed $groups Query groups. An array of group names that this query
2244 * belongs to. May contain a single string if the query is only
2247 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2248 global $wgLoadBalancer;
2249 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
2255 * Shortcut for RepoGroup::singleton()->findFile()
2256 * @param mixed $title Title object or string. May be interwiki.
2257 * @param mixed $time Requested time for an archived image, or false for the
2258 * current version. An image object will be returned which
2259 * existed at or before the specified time.
2260 * @return File, or false if the file does not exist
2262 function wfFindFile( $title, $time = false ) {
2263 return RepoGroup
::singleton()->findFile( $title, $time );
2267 * Get an object referring to a locally registered file.
2268 * Returns a valid placeholder object if the file does not exist.
2270 function wfLocalFile( $title ) {
2271 return RepoGroup
::singleton()->getLocalRepo()->newFile( $title );
2275 * Should low-performance queries be disabled?
2279 function wfQueriesMustScale() {
2280 global $wgMiserMode;
2282 ||
( SiteStats
::pages() > 100000
2283 && SiteStats
::edits() > 1000000
2284 && SiteStats
::users() > 10000 );
2288 * Get the path to a specified script file, respecting file
2289 * extensions; this is a wrapper around $wgScriptExtension etc.
2291 * @param string $script Script filename, sans extension
2294 function wfScript( $script = 'index' ) {
2295 global $wgScriptPath, $wgScriptExtension;
2296 return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
2300 * Convenience function converts boolean values into "true"
2301 * or "false" (string) values
2303 * @param bool $value
2306 function wfBoolToStr( $value ) {
2307 return $value ?
'true' : 'false';