4 * Global functions used everywhere
9 * Some globals and requires needed
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
16 $wgNumberOfArticles = -1; # Unset
18 * Total number of views
19 * @global integer $wgTotalViews
23 * Total number of edits
24 * @global integer $wgTotalEdits
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'LogPage.php' );
31 require_once( 'normal/UtfNormalUtil.php' );
32 require_once( 'XmlFunctions.php' );
35 * Compatibility functions
37 * We more or less support PHP 5.0.x and up.
38 * Re-implementations of newer functions or functions in non-standard
39 * PHP extensions may be included here.
41 if( !function_exists('iconv') ) {
42 # iconv support is not in the default configuration and so may not be present.
43 # Assume will only ever use utf-8 and iso-8859-1.
44 # This will *not* work in all circumstances.
45 function iconv( $from, $to, $string ) {
46 if(strcasecmp( $from, $to ) == 0) return $string;
47 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
48 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
53 # UTF-8 substr function based on a PHP manual comment
54 if ( !function_exists( 'mb_substr' ) ) {
55 function mb_substr( $str, $start ) {
56 preg_match_all( '/./us', $str, $ar );
58 if( func_num_args() >= 3 ) {
59 $end = func_get_arg( 2 );
60 return join( '', array_slice( $ar[0], $start, $end ) );
62 return join( '', array_slice( $ar[0], $start ) );
67 if ( !function_exists( 'array_diff_key' ) ) {
69 * Exists in PHP 5.1.0+
70 * Not quite compatible, two-argument version only
71 * Null values will cause problems due to this use of isset()
73 function array_diff_key( $left, $right ) {
75 foreach ( $left as $key => $value ) {
76 if ( isset( $right[$key] ) ) {
77 unset( $result[$key] );
86 * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
87 * PHP 5 won't let you declare a 'clone' function, even conditionally,
88 * so it has to be a wrapper with a different name.
90 function wfClone( $object ) {
91 return clone( $object );
95 * Where as we got a random seed
97 $wgRandomSeeded = false;
100 * Seed Mersenne Twister
101 * No-op for compatibility; only necessary in PHP < 4.2.0
103 function wfSeedRandom() {
108 * Get a random decimal value between 0 and 1, in a way
109 * not likely to give duplicate values for any realistic
110 * number of articles.
114 function wfRandom() {
115 # The maximum random value is "only" 2^31-1, so get two random
116 # values to reduce the chance of dupes
117 $max = mt_getrandmax();
118 $rand = number_format( (mt_rand() * $max +
mt_rand())
119 / $max / $max, 12, '.', '' );
124 * We want / and : to be included as literal characters in our title URLs.
125 * %2F in the page titles seems to fatally break for some reason.
130 function wfUrlencode ( $s ) {
131 $s = urlencode( $s );
132 $s = preg_replace( '/%3[Aa]/', ':', $s );
133 $s = preg_replace( '/%2[Ff]/', '/', $s );
139 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
140 * In normal operation this is a NOP.
142 * Controlling globals:
143 * $wgDebugLogFile - points to the log file
144 * $wgProfileOnly - if set, normal debug messages will not be recorded.
145 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
146 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
148 * @param $text String
149 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
151 function wfDebug( $text, $logonly = false ) {
152 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
153 static $recursion = 0;
155 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
156 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
160 if ( $wgDebugComments && !$logonly ) {
161 if ( !isset( $wgOut ) ) {
164 if ( !StubObject
::isRealObject( $wgOut ) ) {
172 $wgOut->debug( $text );
174 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
175 # Strip unprintables; they can switch terminal modes when binary data
176 # gets dumped, which is pretty annoying.
177 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
178 @error_log
( $text, 3, $wgDebugLogFile );
183 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
184 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
186 * @param $logGroup String
187 * @param $text String
188 * @param $public Bool: whether to log the event in the public log if no private
189 * log file is specified, (default true)
191 function wfDebugLog( $logGroup, $text, $public = true ) {
192 global $wgDebugLogGroups;
193 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
194 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
195 $time = wfTimestamp( TS_DB
);
197 @error_log
( "$time $wiki: $text", 3, $wgDebugLogGroups[$logGroup] );
198 } else if ( $public === true ) {
199 wfDebug( $text, true );
204 * Log for database errors
205 * @param $text String: database error message.
207 function wfLogDBError( $text ) {
208 global $wgDBerrorLog;
209 if ( $wgDBerrorLog ) {
210 $host = trim(`hostname`
);
211 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
212 error_log( $text, 3, $wgDBerrorLog );
219 function wfLogProfilingData() {
220 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
221 global $wgProfiling, $wgUser;
222 if ( $wgProfiling ) {
224 $elapsed = $now - $wgRequestTime;
225 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
227 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
228 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
229 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
230 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
231 if( !empty( $_SERVER['HTTP_FROM'] ) )
232 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
234 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
235 // Don't unstub $wgUser at this late stage just for statistics purposes
236 if( StubObject
::isRealObject($wgUser) && $wgUser->isAnon() )
238 $log = sprintf( "%s\t%04.3f\t%s\n",
239 gmdate( 'YmdHis' ), $elapsed,
240 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
241 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
242 error_log( $log . $prof, 3, $wgDebugLogFile );
248 * Check if the wiki read-only lock file is present. This can be used to lock
249 * off editing functions, but doesn't guarantee that the database will not be
253 function wfReadOnly() {
254 global $wgReadOnlyFile, $wgReadOnly;
256 if ( !is_null( $wgReadOnly ) ) {
257 return (bool)$wgReadOnly;
259 if ( '' == $wgReadOnlyFile ) {
262 // Set $wgReadOnly for faster access next time
263 if ( is_file( $wgReadOnlyFile ) ) {
264 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
268 return (bool)$wgReadOnly;
273 * Get a message from anywhere, for the current user language.
275 * Use wfMsgForContent() instead if the message should NOT
276 * change depending on the user preferences.
278 * Note that the message may contain HTML, and is therefore
279 * not safe for insertion anywhere. Some functions such as
280 * addWikiText will do the escaping for you. Use wfMsgHtml()
281 * if you need an escaped message.
283 * @param $key String: lookup key for the message, usually
284 * defined in languages/Language.php
286 function wfMsg( $key ) {
287 $args = func_get_args();
288 array_shift( $args );
289 return wfMsgReal( $key, $args, true );
293 * Same as above except doesn't transform the message
295 function wfMsgNoTrans( $key ) {
296 $args = func_get_args();
297 array_shift( $args );
298 return wfMsgReal( $key, $args, true, false );
302 * Get a message from anywhere, for the current global language
303 * set with $wgLanguageCode.
305 * Use this if the message should NOT change dependent on the
306 * language set in the user's preferences. This is the case for
307 * most text written into logs, as well as link targets (such as
308 * the name of the copyright policy page). Link titles, on the
309 * other hand, should be shown in the UI language.
311 * Note that MediaWiki allows users to change the user interface
312 * language in their preferences, but a single installation
313 * typically only contains content in one language.
315 * Be wary of this distinction: If you use wfMsg() where you should
316 * use wfMsgForContent(), a user of the software may have to
317 * customize over 70 messages in order to, e.g., fix a link in every
320 * @param $key String: lookup key for the message, usually
321 * defined in languages/Language.php
323 function wfMsgForContent( $key ) {
324 global $wgForceUIMsgAsContentMsg;
325 $args = func_get_args();
326 array_shift( $args );
328 if( is_array( $wgForceUIMsgAsContentMsg ) &&
329 in_array( $key, $wgForceUIMsgAsContentMsg ) )
331 return wfMsgReal( $key, $args, true, $forcontent );
335 * Same as above except doesn't transform the message
337 function wfMsgForContentNoTrans( $key ) {
338 global $wgForceUIMsgAsContentMsg;
339 $args = func_get_args();
340 array_shift( $args );
342 if( is_array( $wgForceUIMsgAsContentMsg ) &&
343 in_array( $key, $wgForceUIMsgAsContentMsg ) )
345 return wfMsgReal( $key, $args, true, $forcontent, false );
349 * Get a message from the language file, for the UI elements
351 function wfMsgNoDB( $key ) {
352 $args = func_get_args();
353 array_shift( $args );
354 return wfMsgReal( $key, $args, false );
358 * Get a message from the language file, for the content
360 function wfMsgNoDBForContent( $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, false, $forcontent );
373 * Really get a message
374 * @return $key String: key to get.
376 * @return $useDB Boolean
377 * @return String: the requested message.
379 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
380 $fname = 'wfMsgReal';
382 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
383 $message = wfMsgReplaceArgs( $message, $args );
388 * This function provides the message source for messages to be edited which are *not* stored in the database.
389 * @param $key String:
391 function wfMsgWeirdKey ( $key ) {
392 $subsource = str_replace ( ' ' , '_' , $key ) ;
393 $source = wfMsgForContentNoTrans( $subsource ) ;
394 if ( wfEmptyMsg( $subsource, $source) ) {
395 # Try again with first char lower case
396 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
397 $source = wfMsgForContentNoTrans( $subsource ) ;
399 if ( wfEmptyMsg( $subsource, $source ) ) {
400 # Didn't work either, return blank text
407 * Fetch a message string value, but don't replace any keys yet.
410 * @param bool $forContent
414 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
415 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
417 if ( is_object( $wgMessageCache ) )
418 $transstat = $wgMessageCache->getTransform();
420 if( is_object( $wgMessageCache ) ) {
422 $wgMessageCache->disableTransform();
423 $message = $wgMessageCache->get( $key, $useDB, $forContent );
426 $lang = &$wgContLang;
431 wfSuppressWarnings();
433 if( is_object( $lang ) ) {
434 $message = $lang->getMessage( $key );
439 if($message === false)
440 $message = Language
::getMessage($key);
441 if ( $transform && strstr( $message, '{{' ) !== false ) {
442 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
446 if ( is_object( $wgMessageCache ) && ! $transform )
447 $wgMessageCache->setTransform( $transstat );
453 * Replace message parameter keys on the given formatted output.
455 * @param string $message
460 function wfMsgReplaceArgs( $message, $args ) {
461 # Fix windows line-endings
462 # Some messages are split with explode("\n", $msg)
463 $message = str_replace( "\r", '', $message );
466 if ( count( $args ) ) {
467 if ( is_array( $args[0] ) ) {
468 foreach ( $args[0] as $key => $val ) {
469 $message = str_replace( '$' . $key, $val, $message );
472 foreach( $args as $n => $param ) {
473 $replacementKeys['$' . ($n +
1)] = $param;
475 $message = strtr( $message, $replacementKeys );
483 * Return an HTML-escaped version of a message.
484 * Parameter replacements, if any, are done *after* the HTML-escaping,
485 * so parameters may contain HTML (eg links or form controls). Be sure
486 * to pre-escape them if you really do want plaintext, or just wrap
487 * the whole thing in htmlspecialchars().
490 * @param string ... parameters
493 function wfMsgHtml( $key ) {
494 $args = func_get_args();
495 array_shift( $args );
496 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
500 * Return an HTML version of message
501 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
502 * so parameters may contain HTML (eg links or form controls). Be sure
503 * to pre-escape them if you really do want plaintext, or just wrap
504 * the whole thing in htmlspecialchars().
507 * @param string ... parameters
510 function wfMsgWikiHtml( $key ) {
512 $args = func_get_args();
513 array_shift( $args );
514 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
518 * Returns message in the requested format
519 * @param string $key Key of the message
520 * @param array $options Processing rules:
521 * <i>parse<i>: parses wikitext to html
522 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
523 * <i>escape<i>: filters message trough htmlspecialchars
524 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
526 function wfMsgExt( $key, $options ) {
527 global $wgOut, $wgMsgParserOptions, $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) ) {
553 $parser = new Parser();
554 $parserOptions = new ParserOptions();
555 $parserOptions->setInterfaceMessage( true );
556 $parser->startExternalParse( $wgTitle, $parserOptions, OT_MSG
);
557 $string = $parser->transformMsg( $string, $parserOptions );
560 if ( in_array('escape', $options) ) {
561 $string = htmlspecialchars ( $string );
564 if( in_array('replaceafter', $options) ) {
565 $string = wfMsgReplaceArgs( $string, $args );
573 * Just like exit() but makes a note of it.
574 * Commits open transactions except if the error parameter is set
576 * @obsolete Please return control to the caller or throw an exception
578 function wfAbruptExit( $error = false ){
579 global $wgLoadBalancer;
580 static $called = false;
586 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
587 $bt = debug_backtrace();
588 for($i = 0; $i < count($bt) ; $i++
){
589 $file = isset($bt[$i]['file']) ?
$bt[$i]['file'] : "unknown";
590 $line = isset($bt[$i]['line']) ?
$bt[$i]['line'] : "unknown";
591 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
594 wfDebug('WARNING: Abrupt exit\n');
597 wfLogProfilingData();
600 $wgLoadBalancer->closeAll();
606 * @obsolete Please return control the caller or throw an exception
608 function wfErrorExit() {
609 wfAbruptExit( true );
613 * Print a simple message and die, returning nonzero to the shell if any.
614 * Plain die() fails to return nonzero to the shell if you pass a string.
617 function wfDie( $msg='' ) {
623 * Throw a debugging exception. This function previously once exited the process,
624 * but now throws an exception instead, with similar results.
626 * @param string $msg Message shown when dieing.
628 function wfDebugDieBacktrace( $msg = '' ) {
629 throw new MWException( $msg );
633 * Fetch server name for use in error reporting etc.
634 * Use real server name if available, so we know which machine
635 * in a server farm generated the current page.
638 function wfHostname() {
639 if ( function_exists( 'posix_uname' ) ) {
640 // This function not present on Windows
641 $uname = @posix_uname
();
645 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
646 return $uname['nodename'];
648 # This may be a virtual server.
649 return $_SERVER['SERVER_NAME'];
654 * Returns a HTML comment with the elapsed time since request.
655 * This method has no side effects.
658 function wfReportTime() {
659 global $wgRequestTime;
662 $elapsed = $now - $wgRequestTime;
664 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
665 wfHostname(), $elapsed );
669 function wfBacktrace() {
670 global $wgCommandLineMode;
671 if ( !function_exists( 'debug_backtrace' ) ) {
675 if ( $wgCommandLineMode ) {
680 $backtrace = debug_backtrace();
681 foreach( $backtrace as $call ) {
682 if( isset( $call['file'] ) ) {
683 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
684 $file = $f[count($f)-1];
688 if( isset( $call['line'] ) ) {
689 $line = $call['line'];
693 if ( $wgCommandLineMode ) {
694 $msg .= "$file line $line calls ";
696 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
698 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
699 $msg .= $call['function'] . '()';
701 if ( $wgCommandLineMode ) {
707 if ( $wgCommandLineMode ) {
717 /* Some generic result counters, pulled out of SearchEngine */
723 function wfShowingResults( $offset, $limit ) {
725 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
731 function wfShowingResultsNum( $offset, $limit, $num ) {
733 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
739 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
741 $fmtLimit = $wgLang->formatNum( $limit );
742 $prev = wfMsg( 'prevn', $fmtLimit );
743 $next = wfMsg( 'nextn', $fmtLimit );
745 if( is_object( $link ) ) {
748 $title = Title
::newFromText( $link );
749 if( is_null( $title ) ) {
754 if ( 0 != $offset ) {
755 $po = $offset - $limit;
756 if ( $po < 0 ) { $po = 0; }
757 $q = "limit={$limit}&offset={$po}";
758 if ( '' != $query ) { $q .= '&'.$query; }
759 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
760 } else { $plink = $prev; }
762 $no = $offset +
$limit;
763 $q = 'limit='.$limit.'&offset='.$no;
764 if ( '' != $query ) { $q .= '&'.$query; }
769 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
771 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
772 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
773 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
774 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
775 wfNumLink( $offset, 500, $title, $query );
777 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
783 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
785 if ( '' == $query ) { $q = ''; }
786 else { $q = $query.'&'; }
787 $q .= 'limit='.$limit.'&offset='.$offset;
789 $fmtLimit = $wgLang->formatNum( $limit );
790 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
796 * @todo FIXME: we may want to blacklist some broken browsers
798 * @return bool Whereas client accept gzip compression
800 function wfClientAcceptsGzip() {
803 # FIXME: we may want to blacklist some broken browsers
805 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
806 $_SERVER['HTTP_ACCEPT_ENCODING'],
808 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
809 wfDebug( " accepts gzip\n" );
817 * Obtain the offset and limit values from the request string;
818 * used in special pages
820 * @param $deflimit Default limit if none supplied
821 * @param $optionname Name of a user preference to check against
825 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
827 return $wgRequest->getLimitOffset( $deflimit, $optionname );
831 * Escapes the given text so that it may be output using addWikiText()
832 * without any linking, formatting, etc. making its way through. This
833 * is achieved by substituting certain characters with HTML entities.
834 * As required by the callers, <nowiki> is not used. It currently does
835 * not filter out characters which have special meaning only at the
836 * start of a line, such as "*".
838 * @param string $text Text to be escaped
840 function wfEscapeWikiText( $text ) {
842 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
843 array( '[', '|', ''', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
844 htmlspecialchars($text) );
851 function wfQuotedPrintable( $string, $charset = '' ) {
852 # Probably incomplete; see RFC 2045
853 if( empty( $charset ) ) {
854 global $wgInputEncoding;
855 $charset = $wgInputEncoding;
857 $charset = strtoupper( $charset );
858 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
860 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
861 $replace = $illegal . '\t ?_';
862 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
863 $out = "=?$charset?Q?";
864 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
875 return microtime(true);
879 * Sets dest to source and returns the original value of dest
880 * If source is NULL, it just returns the value, it doesn't set the variable
882 function wfSetVar( &$dest, $source ) {
884 if ( !is_null( $source ) ) {
891 * As for wfSetVar except setting a bit
893 function wfSetBit( &$dest, $bit, $state = true ) {
894 $temp = (bool)($dest & $bit );
895 if ( !is_null( $state ) ) {
906 * This function takes two arrays as input, and returns a CGI-style string, e.g.
907 * "days=7&limit=100". Options in the first array override options in the second.
908 * Options set to "" will not be output.
910 function wfArrayToCGI( $array1, $array2 = NULL )
912 if ( !is_null( $array2 ) ) {
913 $array1 = $array1 +
$array2;
917 foreach ( $array1 as $key => $value ) {
918 if ( '' !== $value ) {
922 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
929 * This is obsolete, use SquidUpdate::purge()
932 function wfPurgeSquidServers ($urlArr) {
933 SquidUpdate
::purge( $urlArr );
937 * Windows-compatible version of escapeshellarg()
938 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
939 * function puts single quotes in regardless of OS
941 function wfEscapeShellArg( ) {
942 $args = func_get_args();
945 foreach ( $args as $arg ) {
952 if ( wfIsWindows() ) {
953 // Escaping for an MSVC-style command line parser
954 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
955 // Double the backslashes before any double quotes. Escape the double quotes.
956 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE
);
959 foreach ( $tokens as $token ) {
961 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
967 // Double the backslashes before the end of the string, because
968 // we will soon add a quote
969 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
970 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
973 // Add surrounding quotes
974 $retVal .= '"' . $arg . '"';
976 $retVal .= escapeshellarg( $arg );
983 * wfMerge attempts to merge differences between three texts.
984 * Returns true for a clean merge and false for failure or a conflict.
986 function wfMerge( $old, $mine, $yours, &$result ){
989 # This check may also protect against code injection in
990 # case of broken installations.
991 if(! file_exists( $wgDiff3 ) ){
992 wfDebug( "diff3 not found\n" );
996 # Make temporary files
998 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
999 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1000 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1002 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1003 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1004 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1006 # Check for a conflict
1007 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1008 wfEscapeShellArg( $mytextName ) . ' ' .
1009 wfEscapeShellArg( $oldtextName ) . ' ' .
1010 wfEscapeShellArg( $yourtextName );
1011 $handle = popen( $cmd, 'r' );
1013 if( fgets( $handle, 1024 ) ){
1021 $cmd = $wgDiff3 . ' -a -e --merge ' .
1022 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1023 $handle = popen( $cmd, 'r' );
1026 $data = fread( $handle, 8192 );
1027 if ( strlen( $data ) == 0 ) {
1033 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1035 if ( $result === '' && $old !== '' && $conflict == false ) {
1036 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1045 function wfVarDump( $var ) {
1047 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1048 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
1051 $wgOut->addHTML( $s );
1056 * Provide a simple HTTP error.
1058 function wfHttpError( $code, $label, $desc ) {
1061 header( "HTTP/1.0 $code $label" );
1062 header( "Status: $code $label" );
1063 $wgOut->sendCacheControl();
1065 header( 'Content-type: text/html' );
1066 print "<html><head><title>" .
1067 htmlspecialchars( $label ) .
1068 "</title></head><body><h1>" .
1069 htmlspecialchars( $label ) .
1071 htmlspecialchars( $desc ) .
1072 "</p></body></html>\n";
1076 * Converts an Accept-* header into an array mapping string values to quality
1079 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1080 # No arg means accept anything (per HTTP spec)
1082 return array( $def => 1 );
1087 $parts = explode( ',', $accept );
1089 foreach( $parts as $part ) {
1090 # FIXME: doesn't deal with params like 'text/html; level=1'
1091 @list
( $value, $qpart ) = explode( ';', $part );
1092 if( !isset( $qpart ) ) {
1094 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1095 $prefs[$value] = $match[1];
1103 * Checks if a given MIME type matches any of the keys in the given
1104 * array. Basic wildcards are accepted in the array keys.
1106 * Returns the matching MIME type (or wildcard) if a match, otherwise
1109 * @param string $type
1110 * @param array $avail
1114 function mimeTypeMatch( $type, $avail ) {
1115 if( array_key_exists($type, $avail) ) {
1118 $parts = explode( '/', $type );
1119 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1120 return $parts[0] . '/*';
1121 } elseif( array_key_exists( '*/*', $avail ) ) {
1130 * Returns the 'best' match between a client's requested internet media types
1131 * and the server's list of available types. Each list should be an associative
1132 * array of type to preference (preference is a float between 0.0 and 1.0).
1133 * Wildcards in the types are acceptable.
1135 * @param array $cprefs Client's acceptable type list
1136 * @param array $sprefs Server's offered types
1139 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1140 * XXX: generalize to negotiate other stuff
1142 function wfNegotiateType( $cprefs, $sprefs ) {
1145 foreach( array_keys($sprefs) as $type ) {
1146 $parts = explode( '/', $type );
1147 if( $parts[1] != '*' ) {
1148 $ckey = mimeTypeMatch( $type, $cprefs );
1150 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1155 foreach( array_keys( $cprefs ) as $type ) {
1156 $parts = explode( '/', $type );
1157 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1158 $skey = mimeTypeMatch( $type, $sprefs );
1160 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1168 foreach( array_keys( $combine ) as $type ) {
1169 if( $combine[$type] > $bestq ) {
1171 $bestq = $combine[$type];
1180 * Returns an array where the values in the first array are replaced by the
1181 * values in the second array with the corresponding keys
1185 function wfArrayLookup( $a, $b ) {
1186 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1190 * Convenience function; returns MediaWiki timestamp for the present time.
1193 function wfTimestampNow() {
1195 return wfTimestamp( TS_MW
, time() );
1199 * Reference-counted warning suppression
1201 function wfSuppressWarnings( $end = false ) {
1202 static $suppressCount = 0;
1203 static $originalLevel = false;
1206 if ( $suppressCount ) {
1208 if ( !$suppressCount ) {
1209 error_reporting( $originalLevel );
1213 if ( !$suppressCount ) {
1214 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1221 * Restore error level to previous value
1223 function wfRestoreWarnings() {
1224 wfSuppressWarnings( true );
1227 # Autodetect, convert and provide timestamps of various types
1230 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1232 define('TS_UNIX', 0);
1235 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1240 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1245 * RFC 2822 format, for E-mail and HTTP headers
1247 define('TS_RFC2822', 3);
1250 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1252 * This is used by Special:Export
1254 define('TS_ISO_8601', 4);
1257 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1259 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1260 * DateTime tag and page 36 for the DateTimeOriginal and
1261 * DateTimeDigitized tags.
1263 define('TS_EXIF', 5);
1266 * Oracle format time.
1268 define('TS_ORACLE', 6);
1271 * Postgres format time.
1273 define('TS_POSTGRES', 7);
1276 * @param mixed $outputtype A timestamp in one of the supported formats, the
1277 * function will autodetect which format is supplied
1278 * and act accordingly.
1279 * @return string Time in the format specified in $outputtype
1281 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1286 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1288 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1289 (int)$da[2],(int)$da[3],(int)$da[1]);
1290 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1292 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1293 (int)$da[2],(int)$da[3],(int)$da[1]);
1294 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D",$ts,$da)) {
1296 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1297 (int)$da[2],(int)$da[3],(int)$da[1]);
1298 } elseif (preg_match("/^(\d{1,13})$/D",$ts,$datearray)) {
1301 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1303 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1304 str_replace("+00:00", "UTC", $ts)));
1305 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1307 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1308 (int)$da[2],(int)$da[3],(int)$da[1]);
1309 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/",$ts,$da)) {
1311 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1312 (int)$da[2],(int)$da[3],(int)$da[1]);
1314 # Bogus value; fall back to the epoch...
1315 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1320 switch($outputtype) {
1324 return gmdate( 'YmdHis', $uts );
1326 return gmdate( 'Y-m-d H:i:s', $uts );
1328 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1329 // This shouldn't ever be used, but is included for completeness
1331 return gmdate( 'Y:m:d H:i:s', $uts );
1333 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1335 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1337 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1339 throw new MWException( 'wfTimestamp() called with illegal output type.');
1344 * Return a formatted timestamp, or null if input is null.
1345 * For dealing with nullable timestamp columns in the database.
1346 * @param int $outputtype
1350 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1351 if( is_null( $ts ) ) {
1354 return wfTimestamp( $outputtype, $ts );
1359 * Check if the operating system is Windows
1361 * @return bool True if it's Windows, False otherwise.
1363 function wfIsWindows() {
1364 if (substr(php_uname(), 0, 7) == 'Windows') {
1372 * Swap two variables
1374 function swap( &$x, &$y ) {
1380 function wfGetCachedNotice( $name ) {
1381 global $wgOut, $parserMemc;
1382 $fname = 'wfGetCachedNotice';
1383 wfProfileIn( $fname );
1386 $notice = wfMsgForContent( $name );
1387 if( wfEmptyMsg( $name, $notice ) ||
$notice == '-' ) {
1388 wfProfileOut( $fname );
1392 $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
1393 if( is_array( $cachedNotice ) ) {
1394 if( md5( $notice ) == $cachedNotice['hash'] ) {
1395 $notice = $cachedNotice['html'];
1404 if( is_object( $wgOut ) ) {
1405 $parsed = $wgOut->parse( $notice );
1406 $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1409 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1414 wfProfileOut( $fname );
1418 function wfGetNamespaceNotice() {
1422 if ( !isset( $wgTitle ) ||
!is_object( $wgTitle ) )
1425 $fname = 'wfGetNamespaceNotice';
1426 wfProfileIn( $fname );
1428 $key = "namespacenotice-" . $wgTitle->getNsText();
1429 $namespaceNotice = wfGetCachedNotice( $key );
1430 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p><" ) {
1431 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1433 $namespaceNotice = "";
1436 wfProfileOut( $fname );
1437 return $namespaceNotice;
1440 function wfGetSiteNotice() {
1441 global $wgUser, $wgSiteNotice;
1442 $fname = 'wfGetSiteNotice';
1443 wfProfileIn( $fname );
1446 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1447 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1448 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1449 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1451 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1452 if( !$anonNotice ) {
1453 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1454 $siteNotice = !$siteNotice ?
$wgSiteNotice : $siteNotice;
1456 $siteNotice = $anonNotice;
1461 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1462 wfProfileOut( $fname );
1467 * BC wrapper for MimeMagic::singleton()
1470 function &wfGetMimeMagic() {
1471 return MimeMagic
::singleton();
1475 * Tries to get the system directory for temporary files.
1476 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1477 * and if none are set /tmp is returned as the generic Unix default.
1479 * NOTE: When possible, use the tempfile() function to create temporary
1480 * files to avoid race conditions on file creation, etc.
1484 function wfTempDir() {
1485 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1486 $tmp = getenv( $var );
1487 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1491 # Hope this is Unix of some kind!
1496 * Make directory, and make all parent directories if they don't exist
1498 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1499 if ( strval( $fullDir ) === '' ) {
1503 # Go back through the paths to find the first directory that exists
1504 $currentDir = $fullDir;
1505 $createList = array();
1506 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1507 # Strip trailing slashes
1508 $currentDir = rtrim( $currentDir, '/\\' );
1510 # Add to create list
1511 $createList[] = $currentDir;
1513 # Find next delimiter searching from the end
1514 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1515 if ( $p === false ) {
1516 $currentDir = false;
1518 $currentDir = substr( $currentDir, 0, $p );
1522 if ( count( $createList ) == 0 ) {
1523 # Directory specified already exists
1525 } elseif ( $currentDir === false ) {
1526 # Went all the way back to root and it apparently doesn't exist
1530 # Now go forward creating directories
1531 $createList = array_reverse( $createList );
1532 foreach ( $createList as $dir ) {
1533 # use chmod to override the umask, as suggested by the PHP manual
1534 if ( !mkdir( $dir, $mode ) ||
!chmod( $dir, $mode ) ) {
1542 * Increment a statistics counter
1544 function wfIncrStats( $key ) {
1546 $key = wfMemcKey( 'stats', $key );
1547 if ( is_null( $wgMemc->incr( $key ) ) ) {
1548 $wgMemc->add( $key, 1 );
1553 * @param mixed $nr The number to format
1554 * @param int $acc The number of digits after the decimal point, default 2
1555 * @param bool $round Whether or not to round the value, default true
1558 function wfPercent( $nr, $acc = 2, $round = true ) {
1559 $ret = sprintf( "%.${acc}f", $nr );
1560 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1564 * Encrypt a username/password.
1566 * @param string $userid ID of the user
1567 * @param string $password Password of the user
1568 * @return string Hashed password
1570 function wfEncryptPassword( $userid, $password ) {
1571 global $wgPasswordSalt;
1572 $p = md5( $password);
1575 return md5( "{$userid}-{$p}" );
1581 * Appends to second array if $value differs from that in $default
1583 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1584 if ( is_null( $changed ) ) {
1585 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1587 if ( $default[$key] !== $value ) {
1588 $changed[$key] = $value;
1593 * Since wfMsg() and co suck, they don't return false if the message key they
1594 * looked up didn't exist but a XHTML string, this function checks for the
1595 * nonexistance of messages by looking at wfMsg() output
1597 * @param $msg The message key looked up
1598 * @param $wfMsgOut The output of wfMsg*()
1601 function wfEmptyMsg( $msg, $wfMsgOut ) {
1602 return $wfMsgOut === "<$msg>";
1606 * Find out whether or not a mixed variable exists in a string
1608 * @param mixed needle
1609 * @param string haystack
1612 function in_string( $needle, $str ) {
1613 return strpos( $str, $needle ) !== false;
1616 function wfSpecialList( $page, $details ) {
1618 $details = $details ?
' ' . $wgContLang->getDirMark() . "($details)" : "";
1619 return $page . $details;
1623 * Returns a regular expression of url protocols
1627 function wfUrlProtocols() {
1628 global $wgUrlProtocols;
1630 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1631 // with LocalSettings files from 1.5
1632 if ( is_array( $wgUrlProtocols ) ) {
1633 $protocols = array();
1634 foreach ($wgUrlProtocols as $protocol)
1635 $protocols[] = preg_quote( $protocol, '/' );
1637 return implode( '|', $protocols );
1639 return $wgUrlProtocols;
1644 * Execute a shell command, with time and memory limits mirrored from the PHP
1645 * configuration if supported.
1646 * @param $cmd Command line, properly escaped for shell.
1647 * @param &$retval optional, will receive the program's exit code.
1648 * (non-zero is usually failure)
1649 * @return collected stdout as a string (trailing newlines stripped)
1651 function wfShellExec( $cmd, &$retval=null ) {
1652 global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
1654 if( ini_get( 'safe_mode' ) ) {
1655 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1657 return "Unable to run external programs in safe mode.";
1660 if ( php_uname( 's' ) == 'Linux' ) {
1661 $time = ini_get( 'max_execution_time' );
1662 $mem = intval( $wgMaxShellMemory );
1663 $filesize = intval( $wgMaxShellFileSize );
1665 if ( $time > 0 && $mem > 0 ) {
1666 $script = "$IP/bin/ulimit-tvf.sh";
1667 if ( is_executable( $script ) ) {
1668 $cmd = escapeshellarg( $script ) . " $time $mem $filesize $cmd";
1671 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1672 # This is a hack to work around PHP's flawed invocation of cmd.exe
1673 # http://news.php.net/php.internals/21796
1674 $cmd = '"' . $cmd . '"';
1676 wfDebug( "wfShellExec: $cmd\n" );
1679 $retval = 1; // error by default?
1680 $lastline = exec( $cmd, $output, $retval );
1681 return implode( "\n", $output );
1686 * This function works like "use VERSION" in Perl, the program will die with a
1687 * backtrace if the current version of PHP is less than the version provided
1689 * This is useful for extensions which due to their nature are not kept in sync
1690 * with releases, and might depend on other versions of PHP than the main code
1692 * Note: PHP might die due to parsing errors in some cases before it ever
1693 * manages to call this function, such is life
1695 * @see perldoc -f use
1697 * @param mixed $version The version to check, can be a string, an integer, or
1700 function wfUsePHP( $req_ver ) {
1701 $php_ver = PHP_VERSION
;
1703 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1704 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1708 * This function works like "use VERSION" in Perl except it checks the version
1709 * of MediaWiki, the program will die with a backtrace if the current version
1710 * of MediaWiki is less than the version provided.
1712 * This is useful for extensions which due to their nature are not kept in sync
1715 * @see perldoc -f use
1717 * @param mixed $version The version to check, can be a string, an integer, or
1720 function wfUseMW( $req_ver ) {
1723 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1724 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1728 * Escape a string to make it suitable for inclusion in a preg_replace()
1729 * replacement parameter.
1731 * @param string $string
1734 function wfRegexReplacement( $string ) {
1735 $string = str_replace( '\\', '\\\\', $string );
1736 $string = str_replace( '$', '\\$', $string );
1741 * Return the final portion of a pathname.
1742 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1743 * http://bugs.php.net/bug.php?id=33898
1745 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1746 * We'll consider it so always, as we don't want \s in our Unix paths either.
1748 * @param string $path
1751 function wfBaseName( $path ) {
1752 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1760 * Make a URL index, appropriate for the el_index field of externallinks.
1762 function wfMakeUrlIndex( $url ) {
1763 wfSuppressWarnings();
1764 $bits = parse_url( $url );
1765 wfRestoreWarnings();
1766 if ( !$bits ||
$bits['scheme'] !== 'http' ) {
1769 // Reverse the labels in the hostname, convert to lower case
1770 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1771 // Add an extra dot to the end
1772 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1773 $reversedHost .= '.';
1775 // Reconstruct the pseudo-URL
1776 $index = "http://$reversedHost";
1777 // Leave out user and password. Add the port, path, query and fragment
1778 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1779 if ( isset( $bits['path'] ) ) {
1780 $index .= $bits['path'];
1784 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1785 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1790 * Do any deferred updates and clear the list
1791 * TODO: This could be in Wiki.php if that class made any sense at all
1793 function wfDoUpdates()
1795 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1796 foreach ( $wgDeferredUpdateList as $update ) {
1797 $update->doUpdate();
1799 foreach ( $wgPostCommitUpdateList as $update ) {
1800 $update->doUpdate();
1802 $wgDeferredUpdateList = array();
1803 $wgPostCommitUpdateList = array();
1807 * More or less "markup-safe" explode()
1808 * Ignores any instances of the separator inside <...>
1809 * @param string $separator
1810 * @param string $text
1813 function wfExplodeMarkup( $separator, $text ) {
1814 $placeholder = "\x00";
1817 $text = str_replace( $placeholder, '', $text );
1820 $replacer = new ReplacerCallback( $separator, $placeholder );
1821 $cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );
1823 $items = explode( $separator, $cleaned );
1824 foreach( $items as $i => $str ) {
1825 $items[$i] = str_replace( $placeholder, $separator, $str );
1831 class ReplacerCallback
{
1832 function ReplacerCallback( $from, $to ) {
1833 $this->from
= $from;
1837 function go( $matches ) {
1838 return str_replace( $this->from
, $this->to
, $matches[1] );
1844 * Convert an arbitrarily-long digit string from one numeric base
1845 * to another, optionally zero-padding to a minimum column width.
1847 * Supports base 2 through 36; digit values 10-36 are represented
1848 * as lowercase letters a-z. Input is case-insensitive.
1850 * @param $input string of digits
1851 * @param $sourceBase int 2-36
1852 * @param $destBase int 2-36
1853 * @param $pad int 1 or greater
1854 * @return string or false on invalid input
1856 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1857 if( $sourceBase < 2 ||
1862 $sourceBase != intval( $sourceBase ) ||
1863 $destBase != intval( $destBase ) ||
1864 $pad != intval( $pad ) ||
1865 !is_string( $input ) ||
1870 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1871 $inDigits = array();
1874 // Decode and validate input string
1875 $input = strtolower( $input );
1876 for( $i = 0; $i < strlen( $input ); $i++
) {
1877 $n = strpos( $digitChars, $input{$i} );
1878 if( $n === false ||
$n > $sourceBase ) {
1884 // Iterate over the input, modulo-ing out an output digit
1885 // at a time until input is gone.
1886 while( count( $inDigits ) ) {
1888 $workDigits = array();
1891 foreach( $inDigits as $digit ) {
1892 $work *= $sourceBase;
1895 if( $work < $destBase ) {
1896 // Gonna need to pull another digit.
1897 if( count( $workDigits ) ) {
1898 // Avoid zero-padding; this lets us find
1899 // the end of the input very easily when
1900 // length drops to zero.
1904 // Finally! Actual division!
1905 $workDigits[] = intval( $work / $destBase );
1907 // Isn't it annoying that most programming languages
1908 // don't have a single divide-and-remainder operator,
1909 // even though the CPU implements it that way?
1910 $work = $work %
$destBase;
1914 // All that division leaves us with a remainder,
1915 // which is conveniently our next output digit.
1916 $outChars .= $digitChars[$work];
1919 $inDigits = $workDigits;
1922 while( strlen( $outChars ) < $pad ) {
1926 return strrev( $outChars );
1930 * Create an object with a given name and an array of construct parameters
1931 * @param string $name
1932 * @param array $p parameters
1934 function wfCreateObject( $name, $p ){
1935 $p = array_values( $p );
1936 switch ( count( $p ) ) {
1940 return new $name( $p[0] );
1942 return new $name( $p[0], $p[1] );
1944 return new $name( $p[0], $p[1], $p[2] );
1946 return new $name( $p[0], $p[1], $p[2], $p[3] );
1948 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1950 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
1952 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
1957 * Aliases for modularized functions
1959 function wfGetHTTP( $url, $timeout = 'default' ) {
1960 return Http
::get( $url, $timeout );
1962 function wfIsLocalURL( $url ) {
1963 return Http
::isLocalURL( $url );
1967 * Initialise php session
1969 function wfSetupSession() {
1970 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
1971 if( $wgSessionsInMemcached ) {
1972 require_once( 'MemcachedSessions.php' );
1973 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
1974 # If it's left on 'user' or another setting from another
1975 # application, it will end up failing. Try to recover.
1976 ini_set ( 'session.save_handler', 'files' );
1978 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
1979 session_cache_limiter( 'private, must-revalidate' );
1984 * Get an object from the precompiled serialized directory
1986 * @return mixed The variable on success, false on failure
1988 function wfGetPrecompiledData( $name ) {
1991 $file = "$IP/serialized/$name";
1992 if ( file_exists( $file ) ) {
1993 $blob = file_get_contents( $file );
1995 return unserialize( $blob );
2001 function wfGetCaller( $level = 2 ) {
2002 $backtrace = debug_backtrace();
2003 if ( isset( $backtrace[$level] ) ) {
2004 if ( isset( $backtrace[$level]['class'] ) ) {
2005 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2007 $caller = $backtrace[$level]['function'];
2010 $caller = 'unknown';
2015 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2016 function wfGetAllCallers() {
2017 return implode('/', array_map(
2018 create_function('$frame','
2019 return isset( $frame["class"] )?
2020 $frame["class"]."::".$frame["function"]:
2023 array_reverse(debug_backtrace())));
2029 function wfMemcKey( /*... */ ) {
2030 global $wgDBprefix, $wgDBname;
2031 $args = func_get_args();
2032 if ( $wgDBprefix ) {
2033 $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
2035 $key = $wgDBname . ':' . implode( ':', $args );
2041 * Get a cache key for a foreign DB
2043 function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
2044 $args = array_slice( func_get_args(), 2 );
2046 $key = "$db-$prefix:" . implode( ':', $args );
2048 $key = $db . ':' . implode( ':', $args );
2054 * Get an ASCII string identifying this wiki
2055 * This is used as a prefix in memcached keys
2057 function wfWikiID() {
2058 global $wgDBprefix, $wgDBname;
2059 if ( $wgDBprefix ) {
2060 return "$wgDBname-$wgDBprefix";