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 wfSuppressWarnings();
241 $exists = file_exists( $file );
242 $size = $exists ?
filesize( $file ) : false;
243 if ( !$exists ||
( $size !== false && $size +
strlen( $text ) < 0x7fffffff ) ) {
244 error_log( $text, 3, $file );
252 function wfLogProfilingData() {
253 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
254 global $wgProfiling, $wgUser;
255 if ( $wgProfiling ) {
257 $elapsed = $now - $wgRequestTime;
258 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
260 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
261 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
262 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
263 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
264 if( !empty( $_SERVER['HTTP_FROM'] ) )
265 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
267 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
268 // Don't unstub $wgUser at this late stage just for statistics purposes
269 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
271 $log = sprintf( "%s\t%04.3f\t%s\n",
272 gmdate( 'YmdHis' ), $elapsed,
273 urldecode( $wgRequest->getRequestURL() . $forward ) );
274 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
275 wfErrorLog( $log . $prof, $wgDebugLogFile );
281 * Check if the wiki read-only lock file is present. This can be used to lock
282 * off editing functions, but doesn't guarantee that the database will not be
286 function wfReadOnly() {
287 global $wgReadOnlyFile, $wgReadOnly;
289 if ( !is_null( $wgReadOnly ) ) {
290 return (bool)$wgReadOnly;
292 if ( '' == $wgReadOnlyFile ) {
295 // Set $wgReadOnly for faster access next time
296 if ( is_file( $wgReadOnlyFile ) ) {
297 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
301 return (bool)$wgReadOnly;
306 * Get a message from anywhere, for the current user language.
308 * Use wfMsgForContent() instead if the message should NOT
309 * change depending on the user preferences.
311 * Note that the message may contain HTML, and is therefore
312 * not safe for insertion anywhere. Some functions such as
313 * addWikiText will do the escaping for you. Use wfMsgHtml()
314 * if you need an escaped message.
316 * @param $key String: lookup key for the message, usually
317 * defined in languages/Language.php
319 * This function also takes extra optional parameters (not
320 * shown in the function definition), which can by used to
321 * insert variable text into the predefined message.
323 function wfMsg( $key ) {
324 $args = func_get_args();
325 array_shift( $args );
326 return wfMsgReal( $key, $args, true );
330 * Same as above except doesn't transform the message
332 function wfMsgNoTrans( $key ) {
333 $args = func_get_args();
334 array_shift( $args );
335 return wfMsgReal( $key, $args, true, false, false );
339 * Get a message from anywhere, for the current global language
340 * set with $wgLanguageCode.
342 * Use this if the message should NOT change dependent on the
343 * language set in the user's preferences. This is the case for
344 * most text written into logs, as well as link targets (such as
345 * the name of the copyright policy page). Link titles, on the
346 * other hand, should be shown in the UI language.
348 * Note that MediaWiki allows users to change the user interface
349 * language in their preferences, but a single installation
350 * typically only contains content in one language.
352 * Be wary of this distinction: If you use wfMsg() where you should
353 * use wfMsgForContent(), a user of the software may have to
354 * customize over 70 messages in order to, e.g., fix a link in every
357 * @param $key String: lookup key for the message, usually
358 * defined in languages/Language.php
360 function wfMsgForContent( $key ) {
361 global $wgForceUIMsgAsContentMsg;
362 $args = func_get_args();
363 array_shift( $args );
365 if( is_array( $wgForceUIMsgAsContentMsg ) &&
366 in_array( $key, $wgForceUIMsgAsContentMsg ) )
368 return wfMsgReal( $key, $args, true, $forcontent );
372 * Same as above except doesn't transform the message
374 function wfMsgForContentNoTrans( $key ) {
375 global $wgForceUIMsgAsContentMsg;
376 $args = func_get_args();
377 array_shift( $args );
379 if( is_array( $wgForceUIMsgAsContentMsg ) &&
380 in_array( $key, $wgForceUIMsgAsContentMsg ) )
382 return wfMsgReal( $key, $args, true, $forcontent, false );
386 * Get a message from the language file, for the UI elements
388 function wfMsgNoDB( $key ) {
389 $args = func_get_args();
390 array_shift( $args );
391 return wfMsgReal( $key, $args, false );
395 * Get a message from the language file, for the content
397 function wfMsgNoDBForContent( $key ) {
398 global $wgForceUIMsgAsContentMsg;
399 $args = func_get_args();
400 array_shift( $args );
402 if( is_array( $wgForceUIMsgAsContentMsg ) &&
403 in_array( $key, $wgForceUIMsgAsContentMsg ) )
405 return wfMsgReal( $key, $args, false, $forcontent );
410 * Really get a message
411 * @param $key String: key to get.
413 * @param $useDB Boolean
414 * @param $transform Boolean: Whether or not to transform the message.
415 * @param $forContent Boolean
416 * @return String: the requested message.
418 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
419 $fname = 'wfMsgReal';
420 wfProfileIn( $fname );
421 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
422 $message = wfMsgReplaceArgs( $message, $args );
423 wfProfileOut( $fname );
428 * This function provides the message source for messages to be edited which are *not* stored in the database.
429 * @param $key String:
431 function wfMsgWeirdKey ( $key ) {
433 $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
434 $source = wfMsgGetKey( $key, false, true, false );
435 if ( wfEmptyMsg( $key, $source ) )
442 * Fetch a message string value, but don't replace any keys yet.
445 * @param bool $forContent
449 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
450 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
452 if ( is_object( $wgMessageCache ) )
453 $transstat = $wgMessageCache->getTransform();
455 if( is_object( $wgMessageCache ) ) {
457 $wgMessageCache->disableTransform();
458 $message = $wgMessageCache->get( $key, $useDB, $forContent );
461 $lang = &$wgContLang;
466 wfSuppressWarnings();
468 if( is_object( $lang ) ) {
469 $message = $lang->getMessage( $key );
474 if($message === false)
475 $message = Language
::getMessage($key);
476 if ( $transform && strstr( $message, '{{' ) !== false ) {
477 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
481 if ( is_object( $wgMessageCache ) && ! $transform )
482 $wgMessageCache->setTransform( $transstat );
488 * Replace message parameter keys on the given formatted output.
490 * @param string $message
495 function wfMsgReplaceArgs( $message, $args ) {
496 # Fix windows line-endings
497 # Some messages are split with explode("\n", $msg)
498 $message = str_replace( "\r", '', $message );
501 if ( count( $args ) ) {
502 if ( is_array( $args[0] ) ) {
503 foreach ( $args[0] as $key => $val ) {
504 $message = str_replace( '$' . $key, $val, $message );
507 foreach( $args as $n => $param ) {
508 $replacementKeys['$' . ($n +
1)] = $param;
510 $message = strtr( $message, $replacementKeys );
518 * Return an HTML-escaped version of a message.
519 * Parameter replacements, if any, are done *after* the HTML-escaping,
520 * so parameters may contain HTML (eg links or form controls). Be sure
521 * to pre-escape them if you really do want plaintext, or just wrap
522 * the whole thing in htmlspecialchars().
525 * @param string ... parameters
528 function wfMsgHtml( $key ) {
529 $args = func_get_args();
530 array_shift( $args );
531 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
535 * Return an HTML version of message
536 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
537 * so parameters may contain HTML (eg links or form controls). Be sure
538 * to pre-escape them if you really do want plaintext, or just wrap
539 * the whole thing in htmlspecialchars().
542 * @param string ... parameters
545 function wfMsgWikiHtml( $key ) {
547 $args = func_get_args();
548 array_shift( $args );
549 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
553 * Returns message in the requested format
554 * @param string $key Key of the message
555 * @param array $options Processing rules:
556 * <i>parse</i>: parses wikitext to html
557 * <i>parseinline</i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
558 * <i>escape</i>: filters message trough htmlspecialchars
559 * <i>replaceafter</i>: parameters are substituted after parsing or escaping
560 * <i>parsemag</i>: transform the message using magic phrases
562 function wfMsgExt( $key, $options ) {
563 global $wgOut, $wgParser;
565 $args = func_get_args();
566 array_shift( $args );
567 array_shift( $args );
569 if( !is_array($options) ) {
570 $options = array($options);
573 $string = wfMsgGetKey( $key, true, false, false );
575 if( !in_array('replaceafter', $options) ) {
576 $string = wfMsgReplaceArgs( $string, $args );
579 if( in_array('parse', $options) ) {
580 $string = $wgOut->parse( $string, true, true );
581 } elseif ( in_array('parseinline', $options) ) {
582 $string = $wgOut->parse( $string, true, true );
584 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
587 } elseif ( in_array('parsemag', $options) ) {
588 global $wgMessageCache;
589 if ( isset( $wgMessageCache ) ) {
590 $string = $wgMessageCache->transform( $string );
594 if ( in_array('escape', $options) ) {
595 $string = htmlspecialchars ( $string );
598 if( in_array('replaceafter', $options) ) {
599 $string = wfMsgReplaceArgs( $string, $args );
607 * Just like exit() but makes a note of it.
608 * Commits open transactions except if the error parameter is set
610 * @deprecated Please return control to the caller or throw an exception
612 function wfAbruptExit( $error = false ){
613 global $wgLoadBalancer;
614 static $called = false;
620 $bt = wfDebugBacktrace();
622 for($i = 0; $i < count($bt) ; $i++
){
623 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
624 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
625 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
628 wfDebug('WARNING: Abrupt exit\n');
631 wfLogProfilingData();
634 $wgLoadBalancer->closeAll();
640 * @deprecated Please return control the caller or throw an exception
642 function wfErrorExit() {
643 wfAbruptExit( true );
647 * Print a simple message and die, returning nonzero to the shell if any.
648 * Plain die() fails to return nonzero to the shell if you pass a string.
651 function wfDie( $msg='' ) {
657 * Throw a debugging exception. This function previously once exited the process,
658 * but now throws an exception instead, with similar results.
660 * @param string $msg Message shown when dieing.
662 function wfDebugDieBacktrace( $msg = '' ) {
663 throw new MWException( $msg );
667 * Fetch server name for use in error reporting etc.
668 * Use real server name if available, so we know which machine
669 * in a server farm generated the current page.
672 function wfHostname() {
673 if ( function_exists( 'posix_uname' ) ) {
674 // This function not present on Windows
675 $uname = @posix_uname
();
679 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
680 return $uname['nodename'];
682 # This may be a virtual server.
683 return $_SERVER['SERVER_NAME'];
688 * Returns a HTML comment with the elapsed time since request.
689 * This method has no side effects.
692 function wfReportTime() {
693 global $wgRequestTime;
696 $elapsed = $now - $wgRequestTime;
698 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
699 wfHostname(), $elapsed );
704 * Safety wrapper for debug_backtrace().
706 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
707 * murky circumstances, which may be triggered in part by stub objects
708 * or other fancy talkin'.
710 * Will return an empty array if Zend Optimizer is detected, otherwise
711 * the output from debug_backtrace() (trimmed).
713 * @return array of backtrace information
715 function wfDebugBacktrace() {
716 if( extension_loaded( 'Zend Optimizer' ) ) {
717 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
720 return array_slice( debug_backtrace(), 1 );
724 function wfBacktrace() {
725 global $wgCommandLineMode;
727 if ( $wgCommandLineMode ) {
732 $backtrace = wfDebugBacktrace();
733 foreach( $backtrace as $call ) {
734 if( isset( $call['file'] ) ) {
735 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
736 $file = $f[count($f)-1];
740 if( isset( $call['line'] ) ) {
741 $line = $call['line'];
745 if ( $wgCommandLineMode ) {
746 $msg .= "$file line $line calls ";
748 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
750 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
751 $msg .= $call['function'] . '()';
753 if ( $wgCommandLineMode ) {
759 if ( $wgCommandLineMode ) {
769 /* Some generic result counters, pulled out of SearchEngine */
775 function wfShowingResults( $offset, $limit ) {
777 return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
783 function wfShowingResultsNum( $offset, $limit, $num ) {
785 return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
791 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
793 $fmtLimit = $wgLang->formatNum( $limit );
794 $prev = wfMsg( 'prevn', $fmtLimit );
795 $next = wfMsg( 'nextn', $fmtLimit );
797 if( is_object( $link ) ) {
800 $title = Title
::newFromText( $link );
801 if( is_null( $title ) ) {
806 if ( 0 != $offset ) {
807 $po = $offset - $limit;
808 if ( $po < 0 ) { $po = 0; }
809 $q = "limit={$limit}&offset={$po}";
810 if ( '' != $query ) { $q .= '&'.$query; }
811 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
812 } else { $plink = $prev; }
814 $no = $offset +
$limit;
815 $q = 'limit='.$limit.'&offset='.$no;
816 if ( '' != $query ) { $q .= '&'.$query; }
821 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
823 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
824 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
825 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
826 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
827 wfNumLink( $offset, 500, $title, $query );
829 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
835 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
837 if ( '' == $query ) { $q = ''; }
838 else { $q = $query.'&'; }
839 $q .= 'limit='.$limit.'&offset='.$offset;
841 $fmtLimit = $wgLang->formatNum( $limit );
842 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
848 * @todo FIXME: we may want to blacklist some broken browsers
850 * @return bool Whereas client accept gzip compression
852 function wfClientAcceptsGzip() {
855 # FIXME: we may want to blacklist some broken browsers
858 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
859 $_SERVER['HTTP_ACCEPT_ENCODING'],
861 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
862 wfDebug( " accepts gzip\n" );
870 * Obtain the offset and limit values from the request string;
871 * used in special pages
873 * @param $deflimit Default limit if none supplied
874 * @param $optionname Name of a user preference to check against
878 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
880 return $wgRequest->getLimitOffset( $deflimit, $optionname );
884 * Escapes the given text so that it may be output using addWikiText()
885 * without any linking, formatting, etc. making its way through. This
886 * is achieved by substituting certain characters with HTML entities.
887 * As required by the callers, <nowiki> is not used. It currently does
888 * not filter out characters which have special meaning only at the
889 * start of a line, such as "*".
891 * @param string $text Text to be escaped
893 function wfEscapeWikiText( $text ) {
895 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
896 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
897 htmlspecialchars($text) );
904 function wfQuotedPrintable( $string, $charset = '' ) {
905 # Probably incomplete; see RFC 2045
906 if( empty( $charset ) ) {
907 global $wgInputEncoding;
908 $charset = $wgInputEncoding;
910 $charset = strtoupper( $charset );
911 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
913 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
914 $replace = $illegal . '\t ?_';
915 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
916 $out = "=?$charset?Q?";
917 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
928 return microtime(true);
932 * Sets dest to source and returns the original value of dest
933 * If source is NULL, it just returns the value, it doesn't set the variable
935 function wfSetVar( &$dest, $source ) {
937 if ( !is_null( $source ) ) {
944 * As for wfSetVar except setting a bit
946 function wfSetBit( &$dest, $bit, $state = true ) {
947 $temp = (bool)($dest & $bit );
948 if ( !is_null( $state ) ) {
959 * This function takes two arrays as input, and returns a CGI-style string, e.g.
960 * "days=7&limit=100". Options in the first array override options in the second.
961 * Options set to "" will not be output.
963 function wfArrayToCGI( $array1, $array2 = NULL )
965 if ( !is_null( $array2 ) ) {
966 $array1 = $array1 +
$array2;
970 foreach ( $array1 as $key => $value ) {
971 if ( '' !== $value ) {
975 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
982 * Append a query string to an existing URL, which may or may not already
983 * have query string parameters already. If so, they will be combined.
986 * @param string $query
989 function wfAppendQuery( $url, $query ) {
991 if( false === strpos( $url, '?' ) ) {
1002 * This is obsolete, use SquidUpdate::purge()
1005 function wfPurgeSquidServers ($urlArr) {
1006 SquidUpdate
::purge( $urlArr );
1010 * Windows-compatible version of escapeshellarg()
1011 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
1012 * function puts single quotes in regardless of OS
1014 function wfEscapeShellArg( ) {
1015 $args = func_get_args();
1018 foreach ( $args as $arg ) {
1025 if ( wfIsWindows() ) {
1026 // Escaping for an MSVC-style command line parser
1027 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
1028 // Double the backslashes before any double quotes. Escape the double quotes.
1029 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
1032 foreach ( $tokens as $token ) {
1034 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
1040 // Double the backslashes before the end of the string, because
1041 // we will soon add a quote
1043 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
1044 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
1047 // Add surrounding quotes
1048 $retVal .= '"' . $arg . '"';
1050 $retVal .= escapeshellarg( $arg );
1057 * wfMerge attempts to merge differences between three texts.
1058 * Returns true for a clean merge and false for failure or a conflict.
1060 function wfMerge( $old, $mine, $yours, &$result ){
1063 # This check may also protect against code injection in
1064 # case of broken installations.
1065 if(! file_exists( $wgDiff3 ) ){
1066 wfDebug( "diff3 not found\n" );
1070 # Make temporary files
1072 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1073 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1074 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1076 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1077 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1078 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1080 # Check for a conflict
1081 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1082 wfEscapeShellArg( $mytextName ) . ' ' .
1083 wfEscapeShellArg( $oldtextName ) . ' ' .
1084 wfEscapeShellArg( $yourtextName );
1085 $handle = popen( $cmd, 'r' );
1087 if( fgets( $handle, 1024 ) ){
1095 $cmd = $wgDiff3 . ' -a -e --merge ' .
1096 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1097 $handle = popen( $cmd, 'r' );
1100 $data = fread( $handle, 8192 );
1101 if ( strlen( $data ) == 0 ) {
1107 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1109 if ( $result === '' && $old !== '' && $conflict == false ) {
1110 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1119 function wfVarDump( $var ) {
1121 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1122 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1125 $wgOut->addHTML( $s );
1130 * Provide a simple HTTP error.
1132 function wfHttpError( $code, $label, $desc ) {
1135 header( "HTTP/1.0 $code $label" );
1136 header( "Status: $code $label" );
1137 $wgOut->sendCacheControl();
1139 header( 'Content-type: text/html; charset=utf-8' );
1140 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1141 "<html><head><title>" .
1142 htmlspecialchars( $label ) .
1143 "</title></head><body><h1>" .
1144 htmlspecialchars( $label ) .
1146 nl2br( htmlspecialchars( $desc ) ) .
1147 "</p></body></html>\n";
1151 * Clear away any user-level output buffers, discarding contents.
1153 * Suitable for 'starting afresh', for instance when streaming
1154 * relatively large amounts of data without buffering, or wanting to
1155 * output image files without ob_gzhandler's compression.
1157 * The optional $resetGzipEncoding parameter controls suppression of
1158 * the Content-Encoding header sent by ob_gzhandler; by default it
1159 * is left. See comments for wfClearOutputBuffers() for why it would
1162 * Note that some PHP configuration options may add output buffer
1163 * layers which cannot be removed; these are left in place.
1165 * @param bool $resetGzipEncoding
1167 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1168 if( $resetGzipEncoding ) {
1169 // Suppress Content-Encoding and Content-Length
1170 // headers from 1.10+s wfOutputHandler
1171 global $wgDisableOutputCompression;
1172 $wgDisableOutputCompression = true;
1174 while( $status = ob_get_status() ) {
1175 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1176 // Probably from zlib.output_compression or other
1177 // PHP-internal setting which can't be removed.
1179 // Give up, and hope the result doesn't break
1183 if( !ob_end_clean() ) {
1184 // Could not remove output buffer handler; abort now
1185 // to avoid getting in some kind of infinite loop.
1188 if( $resetGzipEncoding ) {
1189 if( $status['name'] == 'ob_gzhandler' ) {
1190 // Reset the 'Content-Encoding' field set by this handler
1191 // so we can start fresh.
1192 header( 'Content-Encoding:' );
1199 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1201 * Clear away output buffers, but keep the Content-Encoding header
1202 * produced by ob_gzhandler, if any.
1204 * This should be used for HTTP 304 responses, where you need to
1205 * preserve the Content-Encoding header of the real result, but
1206 * also need to suppress the output of ob_gzhandler to keep to spec
1207 * and avoid breaking Firefox in rare cases where the headers and
1208 * body are broken over two packets.
1210 function wfClearOutputBuffers() {
1211 wfResetOutputBuffers( false );
1215 * Converts an Accept-* header into an array mapping string values to quality
1218 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1219 # No arg means accept anything (per HTTP spec)
1221 return array( $def => 1 );
1226 $parts = explode( ',', $accept );
1228 foreach( $parts as $part ) {
1229 # FIXME: doesn't deal with params like 'text/html; level=1'
1230 @list
( $value, $qpart ) = explode( ';', $part );
1232 if( !isset( $qpart ) ) {
1234 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1235 $prefs[$value] = $match[1];
1243 * Checks if a given MIME type matches any of the keys in the given
1244 * array. Basic wildcards are accepted in the array keys.
1246 * Returns the matching MIME type (or wildcard) if a match, otherwise
1249 * @param string $type
1250 * @param array $avail
1254 function mimeTypeMatch( $type, $avail ) {
1255 if( array_key_exists($type, $avail) ) {
1258 $parts = explode( '/', $type );
1259 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1260 return $parts[0] . '/*';
1261 } elseif( array_key_exists( '*/*', $avail ) ) {
1270 * Returns the 'best' match between a client's requested internet media types
1271 * and the server's list of available types. Each list should be an associative
1272 * array of type to preference (preference is a float between 0.0 and 1.0).
1273 * Wildcards in the types are acceptable.
1275 * @param array $cprefs Client's acceptable type list
1276 * @param array $sprefs Server's offered types
1279 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1280 * XXX: generalize to negotiate other stuff
1282 function wfNegotiateType( $cprefs, $sprefs ) {
1285 foreach( array_keys($sprefs) as $type ) {
1286 $parts = explode( '/', $type );
1287 if( $parts[1] != '*' ) {
1288 $ckey = mimeTypeMatch( $type, $cprefs );
1290 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1295 foreach( array_keys( $cprefs ) as $type ) {
1296 $parts = explode( '/', $type );
1297 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1298 $skey = mimeTypeMatch( $type, $sprefs );
1300 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1308 foreach( array_keys( $combine ) as $type ) {
1309 if( $combine[$type] > $bestq ) {
1311 $bestq = $combine[$type];
1320 * Returns an array where the values in the first array are replaced by the
1321 * values in the second array with the corresponding keys
1325 function wfArrayLookup( $a, $b ) {
1326 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1330 * Convenience function; returns MediaWiki timestamp for the present time.
1333 function wfTimestampNow() {
1335 return wfTimestamp( TS_MW
, time() );
1339 * Reference-counted warning suppression
1341 function wfSuppressWarnings( $end = false ) {
1342 static $suppressCount = 0;
1343 static $originalLevel = false;
1346 if ( $suppressCount ) {
1348 if ( !$suppressCount ) {
1349 error_reporting( $originalLevel );
1353 if ( !$suppressCount ) {
1354 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1361 * Restore error level to previous value
1363 function wfRestoreWarnings() {
1364 wfSuppressWarnings( true );
1367 # Autodetect, convert and provide timestamps of various types
1370 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1372 define('TS_UNIX', 0);
1375 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1380 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1385 * RFC 2822 format, for E-mail and HTTP headers
1387 define('TS_RFC2822', 3);
1390 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1392 * This is used by Special:Export
1394 define('TS_ISO_8601', 4);
1397 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1399 * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1400 * DateTime tag and page 36 for the DateTimeOriginal and
1401 * DateTimeDigitized tags.
1403 define('TS_EXIF', 5);
1406 * Oracle format time.
1408 define('TS_ORACLE', 6);
1411 * Postgres format time.
1413 define('TS_POSTGRES', 7);
1416 * @param mixed $outputtype A timestamp in one of the supported formats, the
1417 * function will autodetect which format is supplied
1418 * and act accordingly.
1419 * @return string Time in the format specified in $outputtype
1421 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1426 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1428 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1429 (int)$da[2],(int)$da[3],(int)$da[1]);
1430 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1432 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1433 (int)$da[2],(int)$da[3],(int)$da[1]);
1434 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1436 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1437 (int)$da[2],(int)$da[3],(int)$da[1]);
1438 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1441 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1443 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1444 str_replace("+00:00", "UTC", $ts)));
1445 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1447 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1448 (int)$da[2],(int)$da[3],(int)$da[1]);
1449 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1451 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1452 (int)$da[2],(int)$da[3],(int)$da[1]);
1453 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1455 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1456 (int)$da[2],(int)$da[3],(int)$da[1]);
1458 # Bogus value; fall back to the epoch...
1459 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1464 switch($outputtype) {
1468 return gmdate( 'YmdHis', $uts );
1470 return gmdate( 'Y-m-d H:i:s', $uts );
1472 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1473 // This shouldn't ever be used, but is included for completeness
1475 return gmdate( 'Y:m:d H:i:s', $uts );
1477 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1479 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1481 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1483 throw new MWException( 'wfTimestamp() called with illegal output type.');
1488 * Return a formatted timestamp, or null if input is null.
1489 * For dealing with nullable timestamp columns in the database.
1490 * @param int $outputtype
1494 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1495 if( is_null( $ts ) ) {
1498 return wfTimestamp( $outputtype, $ts );
1503 * Check if the operating system is Windows
1505 * @return bool True if it's Windows, False otherwise.
1507 function wfIsWindows() {
1508 if (substr(php_uname(), 0, 7) == 'Windows') {
1516 * Swap two variables
1518 function swap( &$x, &$y ) {
1524 function wfGetCachedNotice( $name ) {
1525 global $wgOut, $parserMemc;
1526 $fname = 'wfGetCachedNotice';
1527 wfProfileIn( $fname );
1531 if( $name === 'default' ) {
1533 global $wgSiteNotice;
1534 $notice = $wgSiteNotice;
1535 if( empty( $notice ) ) {
1536 wfProfileOut( $fname );
1540 $notice = wfMsgForContentNoTrans( $name );
1541 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1542 wfProfileOut( $fname );
1547 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1548 if( is_array( $cachedNotice ) ) {
1549 if( md5( $notice ) == $cachedNotice['hash'] ) {
1550 $notice = $cachedNotice['html'];
1559 if( is_object( $wgOut ) ) {
1560 $parsed = $wgOut->parse( $notice );
1561 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1564 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1569 wfProfileOut( $fname );
1573 function wfGetNamespaceNotice() {
1577 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1580 $fname = 'wfGetNamespaceNotice';
1581 wfProfileIn( $fname );
1583 $key = "namespacenotice-" . $wgTitle->getNsText();
1584 $namespaceNotice = wfGetCachedNotice( $key );
1585 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1586 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1588 $namespaceNotice = "";
1591 wfProfileOut( $fname );
1592 return $namespaceNotice;
1595 function wfGetSiteNotice() {
1596 global $wgUser, $wgSiteNotice;
1597 $fname = 'wfGetSiteNotice';
1598 wfProfileIn( $fname );
1601 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1602 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1603 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1605 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1606 if( !$anonNotice ) {
1607 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1609 $siteNotice = $anonNotice;
1612 if( !$siteNotice ) {
1613 $siteNotice = wfGetCachedNotice( 'default' );
1617 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1618 wfProfileOut( $fname );
1623 * BC wrapper for MimeMagic::singleton()
1626 function &wfGetMimeMagic() {
1627 return MimeMagic
::singleton();
1631 * Tries to get the system directory for temporary files.
1632 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1633 * and if none are set /tmp is returned as the generic Unix default.
1635 * NOTE: When possible, use the tempfile() function to create temporary
1636 * files to avoid race conditions on file creation, etc.
1640 function wfTempDir() {
1641 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1642 $tmp = getenv( $var );
1643 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1647 # Hope this is Unix of some kind!
1652 * Make directory, and make all parent directories if they don't exist
1654 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1655 if ( strval( $fullDir ) === '' ) {
1659 # Go back through the paths to find the first directory that exists
1660 $currentDir = $fullDir;
1661 $createList = array();
1662 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1663 # Strip trailing slashes
1664 $currentDir = rtrim( $currentDir, '/\\' );
1666 # Add to create list
1667 $createList[] = $currentDir;
1669 # Find next delimiter searching from the end
1670 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1671 if ( $p === false ) {
1672 $currentDir = false;
1674 $currentDir = substr( $currentDir, 0, $p );
1678 if ( count( $createList ) == 0 ) {
1679 # Directory specified already exists
1681 } elseif ( $currentDir === false ) {
1682 # Went all the way back to root and it apparently doesn't exist
1686 # Now go forward creating directories
1687 $createList = array_reverse( $createList );
1688 foreach ( $createList as $dir ) {
1689 # use chmod to override the umask, as suggested by the PHP manual
1690 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1691 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1699 * Increment a statistics counter
1701 function wfIncrStats( $key ) {
1703 $key = wfMemcKey( 'stats', $key );
1704 if ( is_null( $wgMemc->incr( $key ) ) ) {
1705 $wgMemc->add( $key, 1 );
1710 * @param mixed $nr The number to format
1711 * @param int $acc The number of digits after the decimal point, default 2
1712 * @param bool $round Whether or not to round the value, default true
1715 function wfPercent( $nr, $acc = 2, $round = true ) {
1716 $ret = sprintf( "%.${acc}f", $nr );
1717 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1721 * Encrypt a username/password.
1723 * @param string $userid ID of the user
1724 * @param string $password Password of the user
1725 * @return string Hashed password
1727 function wfEncryptPassword( $userid, $password ) {
1728 global $wgPasswordSalt;
1729 $p = md5( $password);
1732 return md5( "{$userid}-{$p}" );
1738 * Appends to second array if $value differs from that in $default
1740 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1741 if ( is_null( $changed ) ) {
1742 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1744 if ( $default[$key] !== $value ) {
1745 $changed[$key] = $value;
1750 * Since wfMsg() and co suck, they don't return false if the message key they
1751 * looked up didn't exist but a XHTML string, this function checks for the
1752 * nonexistance of messages by looking at wfMsg() output
1754 * @param $msg The message key looked up
1755 * @param $wfMsgOut The output of wfMsg*()
1758 function wfEmptyMsg( $msg, $wfMsgOut ) {
1759 return $wfMsgOut === "<$msg>";
1763 * Find out whether or not a mixed variable exists in a string
1765 * @param mixed needle
1766 * @param string haystack
1769 function in_string( $needle, $str ) {
1770 return strpos( $str, $needle ) !== false;
1773 function wfSpecialList( $page, $details ) {
1775 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1776 return $page . $details;
1780 * Returns a regular expression of url protocols
1784 function wfUrlProtocols() {
1785 global $wgUrlProtocols;
1787 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1788 // with LocalSettings files from 1.5
1789 if ( is_array( $wgUrlProtocols ) ) {
1790 $protocols = array();
1791 foreach ($wgUrlProtocols as $protocol)
1792 $protocols[] = preg_quote( $protocol, '/' );
1794 return implode( '|', $protocols );
1796 return $wgUrlProtocols;
1801 * Execute a shell command, with time and memory limits mirrored from the PHP
1802 * configuration if supported.
1803 * @param $cmd Command line, properly escaped for shell.
1804 * @param &$retval optional, will receive the program's exit code.
1805 * (non-zero is usually failure)
1806 * @return collected stdout as a string (trailing newlines stripped)
1808 function wfShellExec( $cmd, &$retval=null ) {
1809 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1811 if( ini_get( 'safe_mode' ) ) {
1812 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1814 return "Unable to run external programs in safe mode.";
1817 if ( php_uname( 's' ) == 'Linux' ) {
1818 $time = intval( ini_get( 'max_execution_time' ) );
1819 $mem = intval( $wgMaxShellMemory );
1820 $filesize = intval( $wgMaxShellFileSize );
1822 if ( $time > 0 && $mem > 0 ) {
1823 $script = "$IP/bin/ulimit4.sh";
1824 if ( is_executable( $script ) ) {
1825 $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
1828 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1829 # This is a hack to work around PHP's flawed invocation of cmd.exe
1830 # http://news.php.net/php.internals/21796
1831 $cmd = '"' . $cmd . '"';
1833 wfDebug( "wfShellExec: $cmd\n" );
1836 $retval = 1; // error by default?
1837 exec( $cmd, $output, $retval ); // returns the last line of output.
1838 return implode( "\n", $output );
1843 * This function works like "use VERSION" in Perl, the program will die with a
1844 * backtrace if the current version of PHP is less than the version provided
1846 * This is useful for extensions which due to their nature are not kept in sync
1847 * with releases, and might depend on other versions of PHP than the main code
1849 * Note: PHP might die due to parsing errors in some cases before it ever
1850 * manages to call this function, such is life
1852 * @see perldoc -f use
1854 * @param mixed $version The version to check, can be a string, an integer, or
1857 function wfUsePHP( $req_ver ) {
1858 $php_ver = PHP_VERSION
;
1860 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1861 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1865 * This function works like "use VERSION" in Perl except it checks the version
1866 * of MediaWiki, the program will die with a backtrace if the current version
1867 * of MediaWiki is less than the version provided.
1869 * This is useful for extensions which due to their nature are not kept in sync
1872 * @see perldoc -f use
1874 * @param mixed $version The version to check, can be a string, an integer, or
1877 function wfUseMW( $req_ver ) {
1880 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1881 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1885 * @deprecated use StringUtils::escapeRegexReplacement
1887 function wfRegexReplacement( $string ) {
1888 return StringUtils
::escapeRegexReplacement( $string );
1892 * Return the final portion of a pathname.
1893 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1894 * http://bugs.php.net/bug.php?id=33898
1896 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1897 * We'll consider it so always, as we don't want \s in our Unix paths either.
1899 * @param string $path
1902 function wfBaseName( $path ) {
1904 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1912 * Generate a relative path name to the given file.
1913 * May explode on non-matching case-insensitive paths,
1914 * funky symlinks, etc.
1916 * @param string $path Absolute destination path including target filename
1917 * @param string $from Absolute source path, directory only
1920 function wfRelativePath( $path, $from ) {
1921 // Normalize mixed input on Windows...
1922 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1923 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1925 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1926 $against = explode( DIRECTORY_SEPARATOR
, $from );
1928 // Trim off common prefix
1929 while( count( $pieces ) && count( $against )
1930 && $pieces[0] == $against[0] ) {
1931 array_shift( $pieces );
1932 array_shift( $against );
1935 // relative dots to bump us to the parent
1936 while( count( $against ) ) {
1937 array_unshift( $pieces, '..' );
1938 array_shift( $against );
1941 array_push( $pieces, wfBaseName( $path ) );
1943 return implode( DIRECTORY_SEPARATOR
, $pieces );
1947 * Make a URL index, appropriate for the el_index field of externallinks.
1949 function wfMakeUrlIndex( $url ) {
1950 global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
1951 $bits = parse_url( $url );
1952 wfSuppressWarnings();
1953 wfRestoreWarnings();
1957 // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
1959 if ( in_array( $bits['scheme'] . '://' , $wgUrlProtocols ) ) {
1961 } elseif ( in_array( $bits['scheme'] .':' , $wgUrlProtocols ) ) {
1963 // parse_url detects for news: and mailto: the host part of an url as path
1964 // We have to correct this wrong detection
1965 if ( isset ( $bits['path'] ) ) {
1966 $bits['host'] = $bits['path'];
1973 // Reverse the labels in the hostname, convert to lower case
1974 // For emails reverse domainpart only
1975 if ( $bits['scheme'] == 'mailto' ) {
1976 $mailparts = explode( '@', $bits['host'] );
1977 $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
1978 $reversedHost = $domainpart . '@' . $mailparts[0];
1980 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1982 // Add an extra dot to the end
1983 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1984 $reversedHost .= '.';
1986 // Reconstruct the pseudo-URL
1987 $prot = $bits['scheme'];
1988 $index = "$prot$delimiter$reversedHost";
1989 // Leave out user and password. Add the port, path, query and fragment
1990 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1991 if ( isset( $bits['path'] ) ) {
1992 $index .= $bits['path'];
1996 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1997 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
2002 * Do any deferred updates and clear the list
2003 * TODO: This could be in Wiki.php if that class made any sense at all
2005 function wfDoUpdates()
2007 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
2008 foreach ( $wgDeferredUpdateList as $update ) {
2009 $update->doUpdate();
2011 foreach ( $wgPostCommitUpdateList as $update ) {
2012 $update->doUpdate();
2014 $wgDeferredUpdateList = array();
2015 $wgPostCommitUpdateList = array();
2019 * @deprecated use StringUtils::explodeMarkup
2021 function wfExplodeMarkup( $separator, $text ) {
2022 return StringUtils
::explodeMarkup( $separator, $text );
2026 * Convert an arbitrarily-long digit string from one numeric base
2027 * to another, optionally zero-padding to a minimum column width.
2029 * Supports base 2 through 36; digit values 10-36 are represented
2030 * as lowercase letters a-z. Input is case-insensitive.
2032 * @param $input string of digits
2033 * @param $sourceBase int 2-36
2034 * @param $destBase int 2-36
2035 * @param $pad int 1 or greater
2036 * @param $lowercase bool
2037 * @return string or false on invalid input
2039 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
2040 $input = strval( $input );
2041 if( $sourceBase < 2 ||
2046 $sourceBase != intval( $sourceBase ) ||
2047 $destBase != intval( $destBase ) ||
2048 $pad != intval( $pad ) ||
2049 !is_string( $input ) ||
2053 $digitChars = ( $lowercase ) ?
'0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2054 $inDigits = array();
2057 // Decode and validate input string
2058 $input = strtolower( $input );
2059 for( $i = 0; $i < strlen( $input ); $i++
) {
2060 $n = strpos( $digitChars, $input{$i} );
2061 if( $n === false ||
$n > $sourceBase ) {
2067 // Iterate over the input, modulo-ing out an output digit
2068 // at a time until input is gone.
2069 while( count( $inDigits ) ) {
2071 $workDigits = array();
2074 foreach( $inDigits as $digit ) {
2075 $work *= $sourceBase;
2078 if( $work < $destBase ) {
2079 // Gonna need to pull another digit.
2080 if( count( $workDigits ) ) {
2081 // Avoid zero-padding; this lets us find
2082 // the end of the input very easily when
2083 // length drops to zero.
2087 // Finally! Actual division!
2088 $workDigits[] = intval( $work / $destBase );
2090 // Isn't it annoying that most programming languages
2091 // don't have a single divide-and-remainder operator,
2092 // even though the CPU implements it that way?
2093 $work = $work %
$destBase;
2097 // All that division leaves us with a remainder,
2098 // which is conveniently our next output digit.
2099 $outChars .= $digitChars[$work];
2102 $inDigits = $workDigits;
2105 while( strlen( $outChars ) < $pad ) {
2109 return strrev( $outChars );
2113 * Create an object with a given name and an array of construct parameters
2114 * @param string $name
2115 * @param array $p parameters
2117 function wfCreateObject( $name, $p ){
2118 $p = array_values( $p );
2119 switch ( count( $p ) ) {
2123 return new $name( $p[0] );
2125 return new $name( $p[0], $p[1] );
2127 return new $name( $p[0], $p[1], $p[2] );
2129 return new $name( $p[0], $p[1], $p[2], $p[3] );
2131 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2133 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2135 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2140 * Aliases for modularized functions
2142 function wfGetHTTP( $url, $timeout = 'default' ) {
2143 return Http
::get( $url, $timeout );
2145 function wfIsLocalURL( $url ) {
2146 return Http
::isLocalURL( $url );
2150 * Initialise php session
2152 function wfSetupSession() {
2153 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2154 if( $wgSessionsInMemcached ) {
2155 require_once( 'MemcachedSessions.php' );
2156 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2157 # If it's left on 'user' or another setting from another
2158 # application, it will end up failing. Try to recover.
2159 ini_set ( 'session.save_handler', 'files' );
2161 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2162 session_cache_limiter( 'private, must-revalidate' );
2167 * Get an object from the precompiled serialized directory
2169 * @return mixed The variable on success, false on failure
2171 function wfGetPrecompiledData( $name ) {
2174 $file = "$IP/serialized/$name";
2175 if ( file_exists( $file ) ) {
2176 $blob = file_get_contents( $file );
2178 return unserialize( $blob );
2184 function wfGetCaller( $level = 2 ) {
2185 $backtrace = wfDebugBacktrace();
2186 if ( isset( $backtrace[$level] ) ) {
2187 if ( isset( $backtrace[$level]['class'] ) ) {
2188 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2190 $caller = $backtrace[$level]['function'];
2193 $caller = 'unknown';
2198 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2199 function wfGetAllCallers() {
2200 return implode('/', array_map(
2201 create_function('$frame','
2202 return isset( $frame["class"] )?
2203 $frame["class"]."::".$frame["function"]:
2206 array_reverse(wfDebugBacktrace())));
2212 function wfMemcKey( /*... */ ) {
2213 global $wgDBprefix, $wgDBname;
2214 $args = func_get_args();
2215 if ( $wgDBprefix ) {
2216 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2218 $key = $wgDBname . ':' . implode( ':', $args );
2224 * Get a cache key for a foreign DB
2226 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2227 $args = array_slice( func_get_args(), 2 );
2229 $key = "$db-$prefix:" . implode( ':', $args );
2231 $key = $db . ':' . implode( ':', $args );
2237 * Get an ASCII string identifying this wiki
2238 * This is used as a prefix in memcached keys
2240 function wfWikiID() {
2241 global $wgDBprefix, $wgDBname;
2242 if ( $wgDBprefix ) {
2243 return "$wgDBname-$wgDBprefix";
2250 * Get a Database object
2251 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2252 * master (for write queries), DB_SLAVE for potentially lagged
2253 * read queries, or an integer >= 0 for a particular server.
2255 * @param mixed $groups Query groups. An array of group names that this query
2256 * belongs to. May contain a single string if the query is only
2259 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2260 global $wgLoadBalancer;
2261 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );