4 * Global functions used everywhere
8 * Some globals and requires needed
11 /** Total number of articles */
12 $wgNumberOfArticles = -1; # Unset
14 /** Total number of views */
17 /** Total number of edits */
21 require_once( 'LogPage.php' );
22 require_once( 'normal/UtfNormalUtil.php' );
23 require_once( 'XmlFunctions.php' );
26 * Compatibility functions
28 * We more or less support PHP 5.0.x and up.
29 * Re-implementations of newer functions or functions in non-standard
30 * PHP extensions may be included here.
32 if( !function_exists('iconv') ) {
33 # iconv support is not in the default configuration and so may not be present.
34 # Assume will only ever use utf-8 and iso-8859-1.
35 # This will *not* work in all circumstances.
36 function iconv( $from, $to, $string ) {
37 if(strcasecmp( $from, $to ) == 0) return $string;
38 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
39 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
44 # UTF-8 substr function based on a PHP manual comment
45 if ( !function_exists( 'mb_substr' ) ) {
46 function mb_substr( $str, $start ) {
48 preg_match_all( '/./us', $str, $ar );
50 if( func_num_args() >= 3 ) {
51 $end = func_get_arg( 2 );
52 return join( '', array_slice( $ar[0], $start, $end ) );
54 return join( '', array_slice( $ar[0], $start ) );
59 if ( !function_exists( 'array_diff_key' ) ) {
61 * Exists in PHP 5.1.0+
62 * Not quite compatible, two-argument version only
63 * Null values will cause problems due to this use of isset()
65 function array_diff_key( $left, $right ) {
67 foreach ( $left as $key => $unused ) {
68 if ( isset( $right[$key] ) ) {
69 unset( $result[$key] );
78 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
79 * PHP 5 won't let you declare a 'clone' function, even conditionally,
80 * so it has to be a wrapper with a different name.
82 function wfClone( $object ) {
83 return clone( $object );
87 * Where as we got a random seed
89 $wgRandomSeeded = false;
92 * Seed Mersenne Twister
93 * No-op for compatibility; only necessary in PHP < 4.2.0
95 function wfSeedRandom() {
100 * Get a random decimal value between 0 and 1, in a way
101 * not likely to give duplicate values for any realistic
102 * number of articles.
106 function wfRandom() {
107 # The maximum random value is "only" 2^31-1, so get two random
108 # values to reduce the chance of dupes
109 $max = mt_getrandmax() +
1;
110 $rand = number_format( (mt_rand() * $max +
mt_rand())
111 / $max / $max, 12, '.', '' );
116 * We want / and : to be included as literal characters in our title URLs.
117 * %2F in the page titles seems to fatally break for some reason.
122 function wfUrlencode ( $s ) {
123 $s = urlencode( $s );
124 $s = preg_replace( '/%3[Aa]/', ':', $s );
125 $s = preg_replace( '/%2[Ff]/', '/', $s );
131 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
132 * In normal operation this is a NOP.
134 * Controlling globals:
135 * $wgDebugLogFile - points to the log file
136 * $wgProfileOnly - if set, normal debug messages will not be recorded.
137 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
138 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
140 * @param $text String
141 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
143 function wfDebug( $text, $logonly = false ) {
144 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
145 static $recursion = 0;
147 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
148 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
152 if ( $wgDebugComments && !$logonly ) {
153 if ( !isset( $wgOut ) ) {
156 if ( !StubObject
::isRealObject( $wgOut ) ) {
164 $wgOut->debug( $text );
166 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
167 # Strip unprintables; they can switch terminal modes when binary data
168 # gets dumped, which is pretty annoying.
169 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
170 @error_log
( $text, 3, $wgDebugLogFile );
175 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
176 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
178 * @param $logGroup String
179 * @param $text String
180 * @param $public Bool: whether to log the event in the public log if no private
181 * log file is specified, (default true)
183 function wfDebugLog( $logGroup, $text, $public = true ) {
184 global $wgDebugLogGroups;
185 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
186 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
187 $time = wfTimestamp( TS_DB
);
189 @error_log
( "$time $wiki: $text", 3, $wgDebugLogGroups[$logGroup] );
190 } else if ( $public === true ) {
191 wfDebug( $text, true );
196 * Log for database errors
197 * @param $text String: database error message.
199 function wfLogDBError( $text ) {
200 global $wgDBerrorLog;
201 if ( $wgDBerrorLog ) {
202 $host = trim(`hostname`
);
203 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
204 error_log( $text, 3, $wgDBerrorLog );
211 function wfLogProfilingData() {
212 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
213 global $wgProfiling, $wgUser;
214 if ( $wgProfiling ) {
216 $elapsed = $now - $wgRequestTime;
217 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
219 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
220 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
221 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
222 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
223 if( !empty( $_SERVER['HTTP_FROM'] ) )
224 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
226 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
227 // Don't unstub $wgUser at this late stage just for statistics purposes
228 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
230 $log = sprintf( "%s\t%04.3f\t%s\n",
231 gmdate( 'YmdHis' ), $elapsed,
232 urldecode( $wgRequest->getRequestURL() . $forward ) );
233 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
234 error_log( $log . $prof, 3, $wgDebugLogFile );
240 * Check if the wiki read-only lock file is present. This can be used to lock
241 * off editing functions, but doesn't guarantee that the database will not be
245 function wfReadOnly() {
246 global $wgReadOnlyFile, $wgReadOnly;
248 if ( !is_null( $wgReadOnly ) ) {
249 return (bool)$wgReadOnly;
251 if ( '' == $wgReadOnlyFile ) {
254 // Set $wgReadOnly for faster access next time
255 if ( is_file( $wgReadOnlyFile ) ) {
256 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
260 return (bool)$wgReadOnly;
265 * Get a message from anywhere, for the current user language.
267 * Use wfMsgForContent() instead if the message should NOT
268 * change depending on the user preferences.
270 * Note that the message may contain HTML, and is therefore
271 * not safe for insertion anywhere. Some functions such as
272 * addWikiText will do the escaping for you. Use wfMsgHtml()
273 * if you need an escaped message.
275 * @param $key String: lookup key for the message, usually
276 * defined in languages/Language.php
278 * This function also takes extra optional parameters (not
279 * shown in the function definition), which can by used to
280 * insert variable text into the predefined message.
282 function wfMsg( $key ) {
283 $args = func_get_args();
284 array_shift( $args );
285 return wfMsgReal( $key, $args, true );
289 * Same as above except doesn't transform the message
291 function wfMsgNoTrans( $key ) {
292 $args = func_get_args();
293 array_shift( $args );
294 return wfMsgReal( $key, $args, true, false, false );
298 * Get a message from anywhere, for the current global language
299 * set with $wgLanguageCode.
301 * Use this if the message should NOT change dependent on the
302 * language set in the user's preferences. This is the case for
303 * most text written into logs, as well as link targets (such as
304 * the name of the copyright policy page). Link titles, on the
305 * other hand, should be shown in the UI language.
307 * Note that MediaWiki allows users to change the user interface
308 * language in their preferences, but a single installation
309 * typically only contains content in one language.
311 * Be wary of this distinction: If you use wfMsg() where you should
312 * use wfMsgForContent(), a user of the software may have to
313 * customize over 70 messages in order to, e.g., fix a link in every
316 * @param $key String: lookup key for the message, usually
317 * defined in languages/Language.php
319 function wfMsgForContent( $key ) {
320 global $wgForceUIMsgAsContentMsg;
321 $args = func_get_args();
322 array_shift( $args );
324 if( is_array( $wgForceUIMsgAsContentMsg ) &&
325 in_array( $key, $wgForceUIMsgAsContentMsg ) )
327 return wfMsgReal( $key, $args, true, $forcontent );
331 * Same as above except doesn't transform the message
333 function wfMsgForContentNoTrans( $key ) {
334 global $wgForceUIMsgAsContentMsg;
335 $args = func_get_args();
336 array_shift( $args );
338 if( is_array( $wgForceUIMsgAsContentMsg ) &&
339 in_array( $key, $wgForceUIMsgAsContentMsg ) )
341 return wfMsgReal( $key, $args, true, $forcontent, false );
345 * Get a message from the language file, for the UI elements
347 function wfMsgNoDB( $key ) {
348 $args = func_get_args();
349 array_shift( $args );
350 return wfMsgReal( $key, $args, false );
354 * Get a message from the language file, for the content
356 function wfMsgNoDBForContent( $key ) {
357 global $wgForceUIMsgAsContentMsg;
358 $args = func_get_args();
359 array_shift( $args );
361 if( is_array( $wgForceUIMsgAsContentMsg ) &&
362 in_array( $key, $wgForceUIMsgAsContentMsg ) )
364 return wfMsgReal( $key, $args, false, $forcontent );
369 * Really get a message
370 * @param $key String: key to get.
372 * @param $useDB Boolean
373 * @param $transform Boolean: Whether or not to transform the message.
374 * @param $forContent Boolean
375 * @return String: the requested message.
377 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
378 $fname = 'wfMsgReal';
379 wfProfileIn( $fname );
380 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
381 $message = wfMsgReplaceArgs( $message, $args );
382 wfProfileOut( $fname );
387 * This function provides the message source for messages to be edited which are *not* stored in the database.
388 * @param $key String:
390 function wfMsgWeirdKey ( $key ) {
391 $subsource = str_replace ( ' ' , '_' , $key ) ;
392 $source = wfMsgForContentNoTrans( $subsource ) ;
393 if ( wfEmptyMsg( $subsource, $source) ) {
394 # Try again with first char lower case
395 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
396 $source = wfMsgForContentNoTrans( $subsource ) ;
398 if ( wfEmptyMsg( $subsource, $source ) ) {
399 # Didn't work either, return blank text
406 * Fetch a message string value, but don't replace any keys yet.
409 * @param bool $forContent
413 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
414 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
416 if ( is_object( $wgMessageCache ) )
417 $transstat = $wgMessageCache->getTransform();
419 if( is_object( $wgMessageCache ) ) {
421 $wgMessageCache->disableTransform();
422 $message = $wgMessageCache->get( $key, $useDB, $forContent );
425 $lang = &$wgContLang;
430 wfSuppressWarnings();
432 if( is_object( $lang ) ) {
433 $message = $lang->getMessage( $key );
438 if($message === false)
439 $message = Language
::getMessage($key);
440 if ( $transform && strstr( $message, '{{' ) !== false ) {
441 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
445 if ( is_object( $wgMessageCache ) && ! $transform )
446 $wgMessageCache->setTransform( $transstat );
452 * Replace message parameter keys on the given formatted output.
454 * @param string $message
459 function wfMsgReplaceArgs( $message, $args ) {
460 # Fix windows line-endings
461 # Some messages are split with explode("\n", $msg)
462 $message = str_replace( "\r", '', $message );
465 if ( count( $args ) ) {
466 if ( is_array( $args[0] ) ) {
467 foreach ( $args[0] as $key => $val ) {
468 $message = str_replace( '$' . $key, $val, $message );
471 foreach( $args as $n => $param ) {
472 $replacementKeys['$' . ($n +
1)] = $param;
474 $message = strtr( $message, $replacementKeys );
482 * Return an HTML-escaped version of a message.
483 * Parameter replacements, if any, are done *after* the HTML-escaping,
484 * so parameters may contain HTML (eg links or form controls). Be sure
485 * to pre-escape them if you really do want plaintext, or just wrap
486 * the whole thing in htmlspecialchars().
489 * @param string ... parameters
492 function wfMsgHtml( $key ) {
493 $args = func_get_args();
494 array_shift( $args );
495 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
499 * Return an HTML version of message
500 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
501 * so parameters may contain HTML (eg links or form controls). Be sure
502 * to pre-escape them if you really do want plaintext, or just wrap
503 * the whole thing in htmlspecialchars().
506 * @param string ... parameters
509 function wfMsgWikiHtml( $key ) {
511 $args = func_get_args();
512 array_shift( $args );
513 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
517 * Returns message in the requested format
518 * @param string $key Key of the message
519 * @param array $options Processing rules:
520 * <i>parse<i>: parses wikitext to html
521 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
522 * <i>escape<i>: filters message trough htmlspecialchars
523 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
526 function wfMsgExt( $key, $options ) {
527 global $wgOut, $wgParser;
529 $args = func_get_args();
530 array_shift( $args );
531 array_shift( $args );
533 if( !is_array($options) ) {
534 $options = array($options);
537 $string = wfMsgGetKey( $key, true, false, false );
539 if( !in_array('replaceafter', $options) ) {
540 $string = wfMsgReplaceArgs( $string, $args );
543 if( in_array('parse', $options) ) {
544 $string = $wgOut->parse( $string, true, true );
545 } elseif ( in_array('parseinline', $options) ) {
546 $string = $wgOut->parse( $string, true, true );
548 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
551 } elseif ( in_array('parsemag', $options) ) {
552 global $wgMessageCache;
553 if ( isset( $wgMessageCache ) ) {
554 $string = $wgMessageCache->transform( $string );
558 if ( in_array('escape', $options) ) {
559 $string = htmlspecialchars ( $string );
562 if( in_array('replaceafter', $options) ) {
563 $string = wfMsgReplaceArgs( $string, $args );
571 * Just like exit() but makes a note of it.
572 * Commits open transactions except if the error parameter is set
574 * @obsolete Please return control to the caller or throw an exception
576 function wfAbruptExit( $error = false ){
577 global $wgLoadBalancer;
578 static $called = false;
584 $bt = wfDebugBacktrace();
586 for($i = 0; $i < count($bt) ; $i++
){
587 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
588 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
589 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
592 wfDebug('WARNING: Abrupt exit\n');
595 wfLogProfilingData();
598 $wgLoadBalancer->closeAll();
604 * @obsolete Please return control the caller or throw an exception
606 function wfErrorExit() {
607 wfAbruptExit( true );
611 * Print a simple message and die, returning nonzero to the shell if any.
612 * Plain die() fails to return nonzero to the shell if you pass a string.
615 function wfDie( $msg='' ) {
621 * Throw a debugging exception. This function previously once exited the process,
622 * but now throws an exception instead, with similar results.
624 * @param string $msg Message shown when dieing.
626 function wfDebugDieBacktrace( $msg = '' ) {
627 throw new MWException( $msg );
631 * Fetch server name for use in error reporting etc.
632 * Use real server name if available, so we know which machine
633 * in a server farm generated the current page.
636 function wfHostname() {
637 if ( function_exists( 'posix_uname' ) ) {
638 // This function not present on Windows
639 $uname = @posix_uname
();
643 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
644 return $uname['nodename'];
646 # This may be a virtual server.
647 return $_SERVER['SERVER_NAME'];
652 * Returns a HTML comment with the elapsed time since request.
653 * This method has no side effects.
656 function wfReportTime() {
657 global $wgRequestTime;
660 $elapsed = $now - $wgRequestTime;
662 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
663 wfHostname(), $elapsed );
668 * Safety wrapper for debug_backtrace().
670 * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
671 * murky circumstances, which may be triggered in part by stub objects
672 * or other fancy talkin'.
674 * Will return an empty array if Zend Optimizer is detected, otherwise
675 * the output from debug_backtrace() (trimmed).
677 * @return array of backtrace information
679 function wfDebugBacktrace() {
680 if( extension_loaded( 'Zend Optimizer' ) ) {
681 wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
684 return array_slice( debug_backtrace(), 1 );
688 function wfBacktrace() {
689 global $wgCommandLineMode;
691 if ( $wgCommandLineMode ) {
696 $backtrace = wfDebugBacktrace();
697 foreach( $backtrace as $call ) {
698 if( isset( $call['file'] ) ) {
699 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
700 $file = $f[count($f)-1];
704 if( isset( $call['line'] ) ) {
705 $line = $call['line'];
709 if ( $wgCommandLineMode ) {
710 $msg .= "$file line $line calls ";
712 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
714 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
715 $msg .= $call['function'] . '()';
717 if ( $wgCommandLineMode ) {
723 if ( $wgCommandLineMode ) {
733 /* Some generic result counters, pulled out of SearchEngine */
739 function wfShowingResults( $offset, $limit ) {
741 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
747 function wfShowingResultsNum( $offset, $limit, $num ) {
749 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
755 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
757 $fmtLimit = $wgLang->formatNum( $limit );
758 $prev = wfMsg( 'prevn', $fmtLimit );
759 $next = wfMsg( 'nextn', $fmtLimit );
761 if( is_object( $link ) ) {
764 $title = Title
::newFromText( $link );
765 if( is_null( $title ) ) {
770 if ( 0 != $offset ) {
771 $po = $offset - $limit;
772 if ( $po < 0 ) { $po = 0; }
773 $q = "limit={$limit}&offset={$po}";
774 if ( '' != $query ) { $q .= '&'.$query; }
775 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
776 } else { $plink = $prev; }
778 $no = $offset +
$limit;
779 $q = 'limit='.$limit.'&offset='.$no;
780 if ( '' != $query ) { $q .= '&'.$query; }
785 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
787 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
788 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
789 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
790 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
791 wfNumLink( $offset, 500, $title, $query );
793 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
799 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
801 if ( '' == $query ) { $q = ''; }
802 else { $q = $query.'&'; }
803 $q .= 'limit='.$limit.'&offset='.$offset;
805 $fmtLimit = $wgLang->formatNum( $limit );
806 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
812 * @todo FIXME: we may want to blacklist some broken browsers
814 * @return bool Whereas client accept gzip compression
816 function wfClientAcceptsGzip() {
819 # FIXME: we may want to blacklist some broken browsers
822 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
823 $_SERVER['HTTP_ACCEPT_ENCODING'],
825 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
826 wfDebug( " accepts gzip\n" );
834 * Obtain the offset and limit values from the request string;
835 * used in special pages
837 * @param $deflimit Default limit if none supplied
838 * @param $optionname Name of a user preference to check against
842 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
844 return $wgRequest->getLimitOffset( $deflimit, $optionname );
848 * Escapes the given text so that it may be output using addWikiText()
849 * without any linking, formatting, etc. making its way through. This
850 * is achieved by substituting certain characters with HTML entities.
851 * As required by the callers, <nowiki> is not used. It currently does
852 * not filter out characters which have special meaning only at the
853 * start of a line, such as "*".
855 * @param string $text Text to be escaped
857 function wfEscapeWikiText( $text ) {
859 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
860 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
861 htmlspecialchars($text) );
868 function wfQuotedPrintable( $string, $charset = '' ) {
869 # Probably incomplete; see RFC 2045
870 if( empty( $charset ) ) {
871 global $wgInputEncoding;
872 $charset = $wgInputEncoding;
874 $charset = strtoupper( $charset );
875 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
877 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
878 $replace = $illegal . '\t ?_';
879 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
880 $out = "=?$charset?Q?";
881 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
892 return microtime(true);
896 * Sets dest to source and returns the original value of dest
897 * If source is NULL, it just returns the value, it doesn't set the variable
899 function wfSetVar( &$dest, $source ) {
901 if ( !is_null( $source ) ) {
908 * As for wfSetVar except setting a bit
910 function wfSetBit( &$dest, $bit, $state = true ) {
911 $temp = (bool)($dest & $bit );
912 if ( !is_null( $state ) ) {
923 * This function takes two arrays as input, and returns a CGI-style string, e.g.
924 * "days=7&limit=100". Options in the first array override options in the second.
925 * Options set to "" will not be output.
927 function wfArrayToCGI( $array1, $array2 = NULL )
929 if ( !is_null( $array2 ) ) {
930 $array1 = $array1 +
$array2;
934 foreach ( $array1 as $key => $value ) {
935 if ( '' !== $value ) {
939 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
946 * This is obsolete, use SquidUpdate::purge()
949 function wfPurgeSquidServers ($urlArr) {
950 SquidUpdate
::purge( $urlArr );
954 * Windows-compatible version of escapeshellarg()
955 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
956 * function puts single quotes in regardless of OS
958 function wfEscapeShellArg( ) {
959 $args = func_get_args();
962 foreach ( $args as $arg ) {
969 if ( wfIsWindows() ) {
970 // Escaping for an MSVC-style command line parser
971 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
972 // Double the backslashes before any double quotes. Escape the double quotes.
973 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
976 foreach ( $tokens as $token ) {
978 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
984 // Double the backslashes before the end of the string, because
985 // we will soon add a quote
987 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
988 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
991 // Add surrounding quotes
992 $retVal .= '"' . $arg . '"';
994 $retVal .= escapeshellarg( $arg );
1001 * wfMerge attempts to merge differences between three texts.
1002 * Returns true for a clean merge and false for failure or a conflict.
1004 function wfMerge( $old, $mine, $yours, &$result ){
1007 # This check may also protect against code injection in
1008 # case of broken installations.
1009 if(! file_exists( $wgDiff3 ) ){
1010 wfDebug( "diff3 not found\n" );
1014 # Make temporary files
1016 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1017 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1018 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1020 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1021 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1022 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1024 # Check for a conflict
1025 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1026 wfEscapeShellArg( $mytextName ) . ' ' .
1027 wfEscapeShellArg( $oldtextName ) . ' ' .
1028 wfEscapeShellArg( $yourtextName );
1029 $handle = popen( $cmd, 'r' );
1031 if( fgets( $handle, 1024 ) ){
1039 $cmd = $wgDiff3 . ' -a -e --merge ' .
1040 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1041 $handle = popen( $cmd, 'r' );
1044 $data = fread( $handle, 8192 );
1045 if ( strlen( $data ) == 0 ) {
1051 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1053 if ( $result === '' && $old !== '' && $conflict == false ) {
1054 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1063 function wfVarDump( $var ) {
1065 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1066 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1069 $wgOut->addHTML( $s );
1074 * Provide a simple HTTP error.
1076 function wfHttpError( $code, $label, $desc ) {
1079 header( "HTTP/1.0 $code $label" );
1080 header( "Status: $code $label" );
1081 $wgOut->sendCacheControl();
1083 header( 'Content-type: text/html' );
1084 print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
1085 "<html><head><title>" .
1086 htmlspecialchars( $label ) .
1087 "</title></head><body><h1>" .
1088 htmlspecialchars( $label ) .
1090 nl2br( htmlspecialchars( $desc ) ) .
1091 "</p></body></html>\n";
1095 * Clear away any user-level output buffers, discarding contents.
1097 * Suitable for 'starting afresh', for instance when streaming
1098 * relatively large amounts of data without buffering, or wanting to
1099 * output image files without ob_gzhandler's compression.
1101 * The optional $resetGzipEncoding parameter controls suppression of
1102 * the Content-Encoding header sent by ob_gzhandler; by default it
1103 * is left. See comments for wfClearOutputBuffers() for why it would
1106 * Note that some PHP configuration options may add output buffer
1107 * layers which cannot be removed; these are left in place.
1109 * @parameter bool $resetGzipEncoding
1111 function wfResetOutputBuffers( $resetGzipEncoding=true ) {
1112 while( $status = ob_get_status() ) {
1113 if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
1114 // Probably from zlib.output_compression or other
1115 // PHP-internal setting which can't be removed.
1117 // Give up, and hope the result doesn't break
1121 if( !ob_end_clean() ) {
1122 // Could not remove output buffer handler; abort now
1123 // to avoid getting in some kind of infinite loop.
1126 if( $resetGzipEncoding ) {
1127 if( $status['name'] == 'ob_gzhandler' ) {
1128 // Reset the 'Content-Encoding' field set by this handler
1129 // so we can start fresh.
1130 header( 'Content-Encoding:' );
1137 * More legible than passing a 'false' parameter to wfResetOutputBuffers():
1139 * Clear away output buffers, but keep the Content-Encoding header
1140 * produced by ob_gzhandler, if any.
1142 * This should be used for HTTP 304 responses, where you need to
1143 * preserve the Content-Encoding header of the real result, but
1144 * also need to suppress the output of ob_gzhandler to keep to spec
1145 * and avoid breaking Firefox in rare cases where the headers and
1146 * body are broken over two packets.
1148 function wfClearOutputBuffers() {
1149 wfResetOutputBuffers( false );
1153 * Converts an Accept-* header into an array mapping string values to quality
1156 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1157 # No arg means accept anything (per HTTP spec)
1159 return array( $def => 1 );
1164 $parts = explode( ',', $accept );
1166 foreach( $parts as $part ) {
1167 # FIXME: doesn't deal with params like 'text/html; level=1'
1168 @list
( $value, $qpart ) = explode( ';', $part );
1170 if( !isset( $qpart ) ) {
1172 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1173 $prefs[$value] = $match[1];
1181 * Checks if a given MIME type matches any of the keys in the given
1182 * array. Basic wildcards are accepted in the array keys.
1184 * Returns the matching MIME type (or wildcard) if a match, otherwise
1187 * @param string $type
1188 * @param array $avail
1192 function mimeTypeMatch( $type, $avail ) {
1193 if( array_key_exists($type, $avail) ) {
1196 $parts = explode( '/', $type );
1197 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1198 return $parts[0] . '/*';
1199 } elseif( array_key_exists( '*/*', $avail ) ) {
1208 * Returns the 'best' match between a client's requested internet media types
1209 * and the server's list of available types. Each list should be an associative
1210 * array of type to preference (preference is a float between 0.0 and 1.0).
1211 * Wildcards in the types are acceptable.
1213 * @param array $cprefs Client's acceptable type list
1214 * @param array $sprefs Server's offered types
1217 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1218 * XXX: generalize to negotiate other stuff
1220 function wfNegotiateType( $cprefs, $sprefs ) {
1223 foreach( array_keys($sprefs) as $type ) {
1224 $parts = explode( '/', $type );
1225 if( $parts[1] != '*' ) {
1226 $ckey = mimeTypeMatch( $type, $cprefs );
1228 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1233 foreach( array_keys( $cprefs ) as $type ) {
1234 $parts = explode( '/', $type );
1235 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1236 $skey = mimeTypeMatch( $type, $sprefs );
1238 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1246 foreach( array_keys( $combine ) as $type ) {
1247 if( $combine[$type] > $bestq ) {
1249 $bestq = $combine[$type];
1258 * Returns an array where the values in the first array are replaced by the
1259 * values in the second array with the corresponding keys
1263 function wfArrayLookup( $a, $b ) {
1264 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1268 * Convenience function; returns MediaWiki timestamp for the present time.
1271 function wfTimestampNow() {
1273 return wfTimestamp( TS_MW
, time() );
1277 * Reference-counted warning suppression
1279 function wfSuppressWarnings( $end = false ) {
1280 static $suppressCount = 0;
1281 static $originalLevel = false;
1284 if ( $suppressCount ) {
1286 if ( !$suppressCount ) {
1287 error_reporting( $originalLevel );
1291 if ( !$suppressCount ) {
1292 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1299 * Restore error level to previous value
1301 function wfRestoreWarnings() {
1302 wfSuppressWarnings( true );
1305 # Autodetect, convert and provide timestamps of various types
1308 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1310 define('TS_UNIX', 0);
1313 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1318 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1323 * RFC 2822 format, for E-mail and HTTP headers
1325 define('TS_RFC2822', 3);
1328 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1330 * This is used by Special:Export
1332 define('TS_ISO_8601', 4);
1335 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1337 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1338 * DateTime tag and page 36 for the DateTimeOriginal and
1339 * DateTimeDigitized tags.
1341 define('TS_EXIF', 5);
1344 * Oracle format time.
1346 define('TS_ORACLE', 6);
1349 * Postgres format time.
1351 define('TS_POSTGRES', 7);
1354 * @param mixed $outputtype A timestamp in one of the supported formats, the
1355 * function will autodetect which format is supplied
1356 * and act accordingly.
1357 * @return string Time in the format specified in $outputtype
1359 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1364 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1366 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1367 (int)$da[2],(int)$da[3],(int)$da[1]);
1368 } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
1370 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1371 (int)$da[2],(int)$da[3],(int)$da[1]);
1372 } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
1374 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1375 (int)$da[2],(int)$da[3],(int)$da[1]);
1376 } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
1379 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1381 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1382 str_replace("+00:00", "UTC", $ts)));
1383 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1385 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1386 (int)$da[2],(int)$da[3],(int)$da[1]);
1387 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
1389 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1390 (int)$da[2],(int)$da[3],(int)$da[1]);
1391 } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
1393 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1394 (int)$da[2],(int)$da[3],(int)$da[1]);
1396 # Bogus value; fall back to the epoch...
1397 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1402 switch($outputtype) {
1406 return gmdate( 'YmdHis', $uts );
1408 return gmdate( 'Y-m-d H:i:s', $uts );
1410 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1411 // This shouldn't ever be used, but is included for completeness
1413 return gmdate( 'Y:m:d H:i:s', $uts );
1415 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1417 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1419 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1421 throw new MWException( 'wfTimestamp() called with illegal output type.');
1426 * Return a formatted timestamp, or null if input is null.
1427 * For dealing with nullable timestamp columns in the database.
1428 * @param int $outputtype
1432 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1433 if( is_null( $ts ) ) {
1436 return wfTimestamp( $outputtype, $ts );
1441 * Check if the operating system is Windows
1443 * @return bool True if it's Windows, False otherwise.
1445 function wfIsWindows() {
1446 if (substr(php_uname(), 0, 7) == 'Windows') {
1454 * Swap two variables
1456 function swap( &$x, &$y ) {
1462 function wfGetCachedNotice( $name ) {
1463 global $wgOut, $parserMemc;
1464 $fname = 'wfGetCachedNotice';
1465 wfProfileIn( $fname );
1469 if( $name === 'default' ) {
1471 global $wgSiteNotice;
1472 $notice = $wgSiteNotice;
1473 if( empty( $notice ) ) {
1474 wfProfileOut( $fname );
1478 $notice = wfMsgForContentNoTrans( $name );
1479 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1480 wfProfileOut( $fname );
1485 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1486 if( is_array( $cachedNotice ) ) {
1487 if( md5( $notice ) == $cachedNotice['hash'] ) {
1488 $notice = $cachedNotice['html'];
1497 if( is_object( $wgOut ) ) {
1498 $parsed = $wgOut->parse( $notice );
1499 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1502 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1507 wfProfileOut( $fname );
1511 function wfGetNamespaceNotice() {
1515 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1518 $fname = 'wfGetNamespaceNotice';
1519 wfProfileIn( $fname );
1521 $key = "namespacenotice-" . $wgTitle->getNsText();
1522 $namespaceNotice = wfGetCachedNotice( $key );
1523 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1524 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1526 $namespaceNotice = "";
1529 wfProfileOut( $fname );
1530 return $namespaceNotice;
1533 function wfGetSiteNotice() {
1534 global $wgUser, $wgSiteNotice;
1535 $fname = 'wfGetSiteNotice';
1536 wfProfileIn( $fname );
1539 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1540 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1541 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1543 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1544 if( !$anonNotice ) {
1545 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1547 $siteNotice = $anonNotice;
1550 if( !$siteNotice ) {
1551 $siteNotice = wfGetCachedNotice( 'default' );
1555 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1556 wfProfileOut( $fname );
1561 * BC wrapper for MimeMagic::singleton()
1564 function &wfGetMimeMagic() {
1565 return MimeMagic
::singleton();
1569 * Tries to get the system directory for temporary files.
1570 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1571 * and if none are set /tmp is returned as the generic Unix default.
1573 * NOTE: When possible, use the tempfile() function to create temporary
1574 * files to avoid race conditions on file creation, etc.
1578 function wfTempDir() {
1579 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1580 $tmp = getenv( $var );
1581 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1585 # Hope this is Unix of some kind!
1590 * Make directory, and make all parent directories if they don't exist
1592 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1593 if ( strval( $fullDir ) === '' ) {
1597 # Go back through the paths to find the first directory that exists
1598 $currentDir = $fullDir;
1599 $createList = array();
1600 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1601 # Strip trailing slashes
1602 $currentDir = rtrim( $currentDir, '/\\' );
1604 # Add to create list
1605 $createList[] = $currentDir;
1607 # Find next delimiter searching from the end
1608 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1609 if ( $p === false ) {
1610 $currentDir = false;
1612 $currentDir = substr( $currentDir, 0, $p );
1616 if ( count( $createList ) == 0 ) {
1617 # Directory specified already exists
1619 } elseif ( $currentDir === false ) {
1620 # Went all the way back to root and it apparently doesn't exist
1624 # Now go forward creating directories
1625 $createList = array_reverse( $createList );
1626 foreach ( $createList as $dir ) {
1627 # use chmod to override the umask, as suggested by the PHP manual
1628 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1629 wfDebugLog( 'mkdir', "Unable to create directory $dir\n" );
1637 * Increment a statistics counter
1639 function wfIncrStats( $key ) {
1641 $key = wfMemcKey( 'stats', $key );
1642 if ( is_null( $wgMemc->incr( $key ) ) ) {
1643 $wgMemc->add( $key, 1 );
1648 * @param mixed $nr The number to format
1649 * @param int $acc The number of digits after the decimal point, default 2
1650 * @param bool $round Whether or not to round the value, default true
1653 function wfPercent( $nr, $acc = 2, $round = true ) {
1654 $ret = sprintf( "%.${acc}f", $nr );
1655 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1659 * Encrypt a username/password.
1661 * @param string $userid ID of the user
1662 * @param string $password Password of the user
1663 * @return string Hashed password
1665 function wfEncryptPassword( $userid, $password ) {
1666 global $wgPasswordSalt;
1667 $p = md5( $password);
1670 return md5( "{$userid}-{$p}" );
1676 * Appends to second array if $value differs from that in $default
1678 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1679 if ( is_null( $changed ) ) {
1680 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1682 if ( $default[$key] !== $value ) {
1683 $changed[$key] = $value;
1688 * Since wfMsg() and co suck, they don't return false if the message key they
1689 * looked up didn't exist but a XHTML string, this function checks for the
1690 * nonexistance of messages by looking at wfMsg() output
1692 * @param $msg The message key looked up
1693 * @param $wfMsgOut The output of wfMsg*()
1696 function wfEmptyMsg( $msg, $wfMsgOut ) {
1697 return $wfMsgOut === "<$msg>";
1701 * Find out whether or not a mixed variable exists in a string
1703 * @param mixed needle
1704 * @param string haystack
1707 function in_string( $needle, $str ) {
1708 return strpos( $str, $needle ) !== false;
1711 function wfSpecialList( $page, $details ) {
1713 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1714 return $page . $details;
1718 * Returns a regular expression of url protocols
1722 function wfUrlProtocols() {
1723 global $wgUrlProtocols;
1725 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1726 // with LocalSettings files from 1.5
1727 if ( is_array( $wgUrlProtocols ) ) {
1728 $protocols = array();
1729 foreach ($wgUrlProtocols as $protocol)
1730 $protocols[] = preg_quote( $protocol, '/' );
1732 return implode( '|', $protocols );
1734 return $wgUrlProtocols;
1739 * Execute a shell command, with time and memory limits mirrored from the PHP
1740 * configuration if supported.
1741 * @param $cmd Command line, properly escaped for shell.
1742 * @param &$retval optional, will receive the program's exit code.
1743 * (non-zero is usually failure)
1744 * @return collected stdout as a string (trailing newlines stripped)
1746 function wfShellExec( $cmd, &$retval=null ) {
1747 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1749 if( ini_get( 'safe_mode' ) ) {
1750 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1752 return "Unable to run external programs in safe mode.";
1755 if ( php_uname( 's' ) == 'Linux' ) {
1756 $time = ini_get( 'max_execution_time' );
1757 $mem = intval( $wgMaxShellMemory );
1758 $filesize = intval( $wgMaxShellFileSize );
1760 if ( $time > 0 && $mem > 0 ) {
1761 $script = "$IP/bin/ulimit-tvf.sh";
1762 if ( is_executable( $script ) ) {
1763 $cmd = escapeshellarg( $script ) . " $time $mem $filesize $cmd";
1766 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1767 # This is a hack to work around PHP's flawed invocation of cmd.exe
1768 # http://news.php.net/php.internals/21796
1769 $cmd = '"' . $cmd . '"';
1771 wfDebug( "wfShellExec: $cmd\n" );
1774 $retval = 1; // error by default?
1775 exec( $cmd, $output, $retval ); // returns the last line of output.
1776 return implode( "\n", $output );
1781 * This function works like "use VERSION" in Perl, the program will die with a
1782 * backtrace if the current version of PHP is less than the version provided
1784 * This is useful for extensions which due to their nature are not kept in sync
1785 * with releases, and might depend on other versions of PHP than the main code
1787 * Note: PHP might die due to parsing errors in some cases before it ever
1788 * manages to call this function, such is life
1790 * @see perldoc -f use
1792 * @param mixed $version The version to check, can be a string, an integer, or
1795 function wfUsePHP( $req_ver ) {
1796 $php_ver = PHP_VERSION
;
1798 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1799 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1803 * This function works like "use VERSION" in Perl except it checks the version
1804 * of MediaWiki, the program will die with a backtrace if the current version
1805 * of MediaWiki is less than the version provided.
1807 * This is useful for extensions which due to their nature are not kept in sync
1810 * @see perldoc -f use
1812 * @param mixed $version The version to check, can be a string, an integer, or
1815 function wfUseMW( $req_ver ) {
1818 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1819 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1823 * @deprecated use StringUtils::escapeRegexReplacement
1825 function wfRegexReplacement( $string ) {
1826 return StringUtils
::escapeRegexReplacement( $string );
1830 * Return the final portion of a pathname.
1831 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1832 * http://bugs.php.net/bug.php?id=33898
1834 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1835 * We'll consider it so always, as we don't want \s in our Unix paths either.
1837 * @param string $path
1840 function wfBaseName( $path ) {
1842 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1850 * Generate a relative path name to the given file.
1851 * May explode on non-matching case-insensitive paths,
1852 * funky symlinks, etc.
1854 * @param string $path Absolute destination path including target filename
1855 * @param string $from Absolute source path, directory only
1858 function wfRelativePath( $path, $from ) {
1859 // Normalize mixed input on Windows...
1860 $path = str_replace( '/', DIRECTORY_SEPARATOR
, $path );
1861 $from = str_replace( '/', DIRECTORY_SEPARATOR
, $from );
1863 $pieces = explode( DIRECTORY_SEPARATOR
, dirname( $path ) );
1864 $against = explode( DIRECTORY_SEPARATOR
, $from );
1866 // Trim off common prefix
1867 while( count( $pieces ) && count( $against )
1868 && $pieces[0] == $against[0] ) {
1869 array_shift( $pieces );
1870 array_shift( $against );
1873 // relative dots to bump us to the parent
1874 while( count( $against ) ) {
1875 array_unshift( $pieces, '..' );
1876 array_shift( $against );
1879 array_push( $pieces, wfBaseName( $path ) );
1881 return implode( DIRECTORY_SEPARATOR
, $pieces );
1885 * Make a URL index, appropriate for the el_index field of externallinks.
1887 function wfMakeUrlIndex( $url ) {
1888 wfSuppressWarnings();
1889 $bits = parse_url( $url );
1890 wfRestoreWarnings();
1891 if ( !$bits ||
$bits['scheme'] !== 'http' ) {
1894 // Reverse the labels in the hostname, convert to lower case
1895 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1896 // Add an extra dot to the end
1897 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1898 $reversedHost .= '.';
1900 // Reconstruct the pseudo-URL
1901 $index = "http://$reversedHost";
1902 // Leave out user and password. Add the port, path, query and fragment
1903 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1904 if ( isset( $bits['path'] ) ) {
1905 $index .= $bits['path'];
1909 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1910 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1915 * Do any deferred updates and clear the list
1916 * TODO: This could be in Wiki.php if that class made any sense at all
1918 function wfDoUpdates()
1920 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1921 foreach ( $wgDeferredUpdateList as $update ) {
1922 $update->doUpdate();
1924 foreach ( $wgPostCommitUpdateList as $update ) {
1925 $update->doUpdate();
1927 $wgDeferredUpdateList = array();
1928 $wgPostCommitUpdateList = array();
1932 * @deprecated use StringUtils::explodeMarkup
1934 function wfExplodeMarkup( $separator, $text ) {
1935 return StringUtils
::explodeMarkup( $separator, $text );
1939 * Convert an arbitrarily-long digit string from one numeric base
1940 * to another, optionally zero-padding to a minimum column width.
1942 * Supports base 2 through 36; digit values 10-36 are represented
1943 * as lowercase letters a-z. Input is case-insensitive.
1945 * @param $input string of digits
1946 * @param $sourceBase int 2-36
1947 * @param $destBase int 2-36
1948 * @param $pad int 1 or greater
1949 * @return string or false on invalid input
1951 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1952 if( $sourceBase < 2 ||
1957 $sourceBase != intval( $sourceBase ) ||
1958 $destBase != intval( $destBase ) ||
1959 $pad != intval( $pad ) ||
1960 !is_string( $input ) ||
1965 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1966 $inDigits = array();
1969 // Decode and validate input string
1970 $input = strtolower( $input );
1971 for( $i = 0; $i < strlen( $input ); $i++
) {
1972 $n = strpos( $digitChars, $input{$i} );
1973 if( $n === false ||
$n > $sourceBase ) {
1979 // Iterate over the input, modulo-ing out an output digit
1980 // at a time until input is gone.
1981 while( count( $inDigits ) ) {
1983 $workDigits = array();
1986 foreach( $inDigits as $digit ) {
1987 $work *= $sourceBase;
1990 if( $work < $destBase ) {
1991 // Gonna need to pull another digit.
1992 if( count( $workDigits ) ) {
1993 // Avoid zero-padding; this lets us find
1994 // the end of the input very easily when
1995 // length drops to zero.
1999 // Finally! Actual division!
2000 $workDigits[] = intval( $work / $destBase );
2002 // Isn't it annoying that most programming languages
2003 // don't have a single divide-and-remainder operator,
2004 // even though the CPU implements it that way?
2005 $work = $work %
$destBase;
2009 // All that division leaves us with a remainder,
2010 // which is conveniently our next output digit.
2011 $outChars .= $digitChars[$work];
2014 $inDigits = $workDigits;
2017 while( strlen( $outChars ) < $pad ) {
2021 return strrev( $outChars );
2025 * Create an object with a given name and an array of construct parameters
2026 * @param string $name
2027 * @param array $p parameters
2029 function wfCreateObject( $name, $p ){
2030 $p = array_values( $p );
2031 switch ( count( $p ) ) {
2035 return new $name( $p[0] );
2037 return new $name( $p[0], $p[1] );
2039 return new $name( $p[0], $p[1], $p[2] );
2041 return new $name( $p[0], $p[1], $p[2], $p[3] );
2043 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
2045 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2047 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2052 * Aliases for modularized functions
2054 function wfGetHTTP( $url, $timeout = 'default' ) {
2055 return Http
::get( $url, $timeout );
2057 function wfIsLocalURL( $url ) {
2058 return Http
::isLocalURL( $url );
2062 * Initialise php session
2064 function wfSetupSession() {
2065 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure;
2066 if( $wgSessionsInMemcached ) {
2067 require_once( 'MemcachedSessions.php' );
2068 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2069 # If it's left on 'user' or another setting from another
2070 # application, it will end up failing. Try to recover.
2071 ini_set ( 'session.save_handler', 'files' );
2073 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure);
2074 session_cache_limiter( 'private, must-revalidate' );
2079 * Get an object from the precompiled serialized directory
2081 * @return mixed The variable on success, false on failure
2083 function wfGetPrecompiledData( $name ) {
2086 $file = "$IP/serialized/$name";
2087 if ( file_exists( $file ) ) {
2088 $blob = file_get_contents( $file );
2090 return unserialize( $blob );
2096 function wfGetCaller( $level = 2 ) {
2097 $backtrace = wfDebugBacktrace();
2098 if ( isset( $backtrace[$level] ) ) {
2099 if ( isset( $backtrace[$level]['class'] ) ) {
2100 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2102 $caller = $backtrace[$level]['function'];
2105 $caller = 'unknown';
2110 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2111 function wfGetAllCallers() {
2112 return implode('/', array_map(
2113 create_function('$frame','
2114 return isset( $frame["class"] )?
2115 $frame["class"]."::".$frame["function"]:
2118 array_reverse(wfDebugBacktrace())));
2124 function wfMemcKey( /*... */ ) {
2125 global $wgDBprefix, $wgDBname;
2126 $args = func_get_args();
2127 if ( $wgDBprefix ) {
2128 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2130 $key = $wgDBname . ':' . implode( ':', $args );
2136 * Get a cache key for a foreign DB
2138 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2139 $args = array_slice( func_get_args(), 2 );
2141 $key = "$db-$prefix:" . implode( ':', $args );
2143 $key = $db . ':' . implode( ':', $args );
2149 * Get an ASCII string identifying this wiki
2150 * This is used as a prefix in memcached keys
2152 function wfWikiID() {
2153 global $wgDBprefix, $wgDBname;
2154 if ( $wgDBprefix ) {
2155 return "$wgDBname-$wgDBprefix";
2162 * Get a Database object
2163 * @param integer $db Index of the connection to get. May be DB_MASTER for the
2164 * master (for write queries), DB_SLAVE for potentially lagged
2165 * read queries, or an integer >= 0 for a particular server.
2167 * @param mixed $groups Query groups. An array of group names that this query
2168 * belongs to. May contain a single string if the query is only
2171 function &wfGetDB( $db = DB_LAST
, $groups = array() ) {
2172 global $wgLoadBalancer;
2173 $ret = $wgLoadBalancer->getConnection( $db, true, $groups );