* API: All pages list
[mediawiki.git] / includes / GlobalFunctions.php
blob3079fba7af354fdd0e67beb3ee8002e25dbac6aa
1 <?php
3 /**
4 * Global functions used everywhere
5 * @package MediaWiki
6 */
8 /**
9 * Some globals and requires needed
12 /**
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
16 $wgNumberOfArticles = -1; # Unset
17 /**
18 * Total number of views
19 * @global integer $wgTotalViews
21 $wgTotalViews = -1;
22 /**
23 * Total number of edits
24 * @global integer $wgTotalEdits
26 $wgTotalEdits = -1;
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'LogPage.php' );
31 require_once( 'normal/UtfNormalUtil.php' );
32 require_once( 'XmlFunctions.php' );
34 /**
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 );
49 return $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 ) );
61 } else {
62 return join( '', array_slice( $ar[0], $start ) );
67 if ( !function_exists( 'array_diff_key' ) ) {
68 /**
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 ) {
74 $result = $left;
75 foreach ( $left as $key => $value ) {
76 if ( isset( $right[$key] ) ) {
77 unset( $result[$key] );
80 return $result;
85 /**
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 );
94 /**
95 * Where as we got a random seed
97 $wgRandomSeeded = false;
99 /**
100 * Seed Mersenne Twister
101 * No-op for compatibility; only necessary in PHP < 4.2.0
103 function wfSeedRandom() {
104 /* No-op */
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.
112 * @return string
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, '.', '' );
120 return $rand;
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.
127 * @param $s String:
128 * @return string
130 function wfUrlencode ( $s ) {
131 $s = urlencode( $s );
132 $s = preg_replace( '/%3[Aa]/', ':', $s );
133 $s = preg_replace( '/%2[Ff]/', '/', $s );
135 return $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 ) {
157 return;
160 if ( $wgDebugComments && !$logonly ) {
161 if ( !isset( $wgOut ) ) {
162 return;
164 if ( !StubObject::isRealObject( $wgOut ) ) {
165 if ( $recursion ) {
166 return;
168 $recursion++;
169 $wgOut->_unstub();
170 $recursion--;
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, $wgDBname;
193 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
194 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
195 $time = wfTimestamp( TS_DB );
196 @error_log( "$time $wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
197 } else if ( $public === true ) {
198 wfDebug( $text, true );
203 * Log for database errors
204 * @param $text String: database error message.
206 function wfLogDBError( $text ) {
207 global $wgDBerrorLog;
208 if ( $wgDBerrorLog ) {
209 $host = trim(`hostname`);
210 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
211 error_log( $text, 3, $wgDBerrorLog );
216 * @todo document
218 function wfLogProfilingData() {
219 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
220 global $wgProfiling, $wgUser;
221 if ( $wgProfiling ) {
222 $now = wfTime();
223 $elapsed = $now - $wgRequestTime;
224 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
225 $forward = '';
226 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
227 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
228 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
229 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
230 if( !empty( $_SERVER['HTTP_FROM'] ) )
231 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
232 if( $forward )
233 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
234 // Don't unstub $wgUser at this late stage just for statistics purposes
235 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
236 $forward .= ' anon';
237 $log = sprintf( "%s\t%04.3f\t%s\n",
238 gmdate( 'YmdHis' ), $elapsed,
239 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
240 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
241 error_log( $log . $prof, 3, $wgDebugLogFile );
247 * Check if the wiki read-only lock file is present. This can be used to lock
248 * off editing functions, but doesn't guarantee that the database will not be
249 * modified.
250 * @return bool
252 function wfReadOnly() {
253 global $wgReadOnlyFile, $wgReadOnly;
255 if ( !is_null( $wgReadOnly ) ) {
256 return (bool)$wgReadOnly;
258 if ( '' == $wgReadOnlyFile ) {
259 return false;
261 // Set $wgReadOnly for faster access next time
262 if ( is_file( $wgReadOnlyFile ) ) {
263 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
264 } else {
265 $wgReadOnly = false;
267 return (bool)$wgReadOnly;
272 * Get a message from anywhere, for the current user language.
274 * Use wfMsgForContent() instead if the message should NOT
275 * change depending on the user preferences.
277 * Note that the message may contain HTML, and is therefore
278 * not safe for insertion anywhere. Some functions such as
279 * addWikiText will do the escaping for you. Use wfMsgHtml()
280 * if you need an escaped message.
282 * @param $key String: lookup key for the message, usually
283 * defined in languages/Language.php
285 function wfMsg( $key ) {
286 $args = func_get_args();
287 array_shift( $args );
288 return wfMsgReal( $key, $args, true );
292 * Same as above except doesn't transform the message
294 function wfMsgNoTrans( $key ) {
295 $args = func_get_args();
296 array_shift( $args );
297 return wfMsgReal( $key, $args, true, false );
301 * Get a message from anywhere, for the current global language
302 * set with $wgLanguageCode.
304 * Use this if the message should NOT change dependent on the
305 * language set in the user's preferences. This is the case for
306 * most text written into logs, as well as link targets (such as
307 * the name of the copyright policy page). Link titles, on the
308 * other hand, should be shown in the UI language.
310 * Note that MediaWiki allows users to change the user interface
311 * language in their preferences, but a single installation
312 * typically only contains content in one language.
314 * Be wary of this distinction: If you use wfMsg() where you should
315 * use wfMsgForContent(), a user of the software may have to
316 * customize over 70 messages in order to, e.g., fix a link in every
317 * possible language.
319 * @param $key String: lookup key for the message, usually
320 * defined in languages/Language.php
322 function wfMsgForContent( $key ) {
323 global $wgForceUIMsgAsContentMsg;
324 $args = func_get_args();
325 array_shift( $args );
326 $forcontent = true;
327 if( is_array( $wgForceUIMsgAsContentMsg ) &&
328 in_array( $key, $wgForceUIMsgAsContentMsg ) )
329 $forcontent = false;
330 return wfMsgReal( $key, $args, true, $forcontent );
334 * Same as above except doesn't transform the message
336 function wfMsgForContentNoTrans( $key ) {
337 global $wgForceUIMsgAsContentMsg;
338 $args = func_get_args();
339 array_shift( $args );
340 $forcontent = true;
341 if( is_array( $wgForceUIMsgAsContentMsg ) &&
342 in_array( $key, $wgForceUIMsgAsContentMsg ) )
343 $forcontent = false;
344 return wfMsgReal( $key, $args, true, $forcontent, false );
348 * Get a message from the language file, for the UI elements
350 function wfMsgNoDB( $key ) {
351 $args = func_get_args();
352 array_shift( $args );
353 return wfMsgReal( $key, $args, false );
357 * Get a message from the language file, for the content
359 function wfMsgNoDBForContent( $key ) {
360 global $wgForceUIMsgAsContentMsg;
361 $args = func_get_args();
362 array_shift( $args );
363 $forcontent = true;
364 if( is_array( $wgForceUIMsgAsContentMsg ) &&
365 in_array( $key, $wgForceUIMsgAsContentMsg ) )
366 $forcontent = false;
367 return wfMsgReal( $key, $args, false, $forcontent );
372 * Really get a message
373 * @return $key String: key to get.
374 * @return $args
375 * @return $useDB Boolean
376 * @return String: the requested message.
378 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
379 $fname = 'wfMsgReal';
381 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
382 $message = wfMsgReplaceArgs( $message, $args );
383 return $message;
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
400 $source = "" ;
402 return $source ;
406 * Fetch a message string value, but don't replace any keys yet.
407 * @param string $key
408 * @param bool $useDB
409 * @param bool $forContent
410 * @return string
411 * @private
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 ) ) {
420 if ( ! $transform )
421 $wgMessageCache->disableTransform();
422 $message = $wgMessageCache->get( $key, $useDB, $forContent );
423 } else {
424 if( $forContent ) {
425 $lang = &$wgContLang;
426 } else {
427 $lang = &$wgLang;
430 wfSuppressWarnings();
432 if( is_object( $lang ) ) {
433 $message = $lang->getMessage( $key );
434 } else {
435 $message = false;
437 wfRestoreWarnings();
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 );
448 return $message;
452 * Replace message parameter keys on the given formatted output.
454 * @param string $message
455 * @param array $args
456 * @return string
457 * @private
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 );
464 // Replace arguments
465 if ( count( $args ) ) {
466 if ( is_array( $args[0] ) ) {
467 foreach ( $args[0] as $key => $val ) {
468 $message = str_replace( '$' . $key, $val, $message );
470 } else {
471 foreach( $args as $n => $param ) {
472 $replacementKeys['$' . ($n + 1)] = $param;
474 $message = strtr( $message, $replacementKeys );
478 return $message;
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().
488 * @param string $key
489 * @param string ... parameters
490 * @return string
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().
505 * @param string $key
506 * @param string ... parameters
507 * @return string
509 function wfMsgWikiHtml( $key ) {
510 global $wgOut;
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
525 function wfMsgExt( $key, $options ) {
526 global $wgOut, $wgMsgParserOptions, $wgParser;
528 $args = func_get_args();
529 array_shift( $args );
530 array_shift( $args );
532 if( !is_array($options) ) {
533 $options = array($options);
536 $string = wfMsgGetKey( $key, true, false, false );
538 if( !in_array('replaceafter', $options) ) {
539 $string = wfMsgReplaceArgs( $string, $args );
542 if( in_array('parse', $options) ) {
543 $string = $wgOut->parse( $string, true, true );
544 } elseif ( in_array('parseinline', $options) ) {
545 $string = $wgOut->parse( $string, true, true );
546 $m = array();
547 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
548 $string = $m[1];
550 } elseif ( in_array('parsemag', $options) ) {
551 global $wgTitle;
552 $parser = new Parser();
553 $parserOptions = new ParserOptions();
554 $parserOptions->setInterfaceMessage( true );
555 $parser->startExternalParse( $wgTitle, $parserOptions, OT_MSG );
556 $string = $parser->transformMsg( $string, $parserOptions );
559 if ( in_array('escape', $options) ) {
560 $string = htmlspecialchars ( $string );
563 if( in_array('replaceafter', $options) ) {
564 $string = wfMsgReplaceArgs( $string, $args );
567 return $string;
572 * Just like exit() but makes a note of it.
573 * Commits open transactions except if the error parameter is set
575 * @obsolete Please return control to the caller or throw an exception
577 function wfAbruptExit( $error = false ){
578 global $wgLoadBalancer;
579 static $called = false;
580 if ( $called ){
581 exit( -1 );
583 $called = true;
585 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
586 $bt = debug_backtrace();
587 for($i = 0; $i < count($bt) ; $i++){
588 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
589 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
590 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
592 } else {
593 wfDebug('WARNING: Abrupt exit\n');
596 wfLogProfilingData();
598 if ( !$error ) {
599 $wgLoadBalancer->closeAll();
601 exit( -1 );
605 * @obsolete Please return control the caller or throw an exception
607 function wfErrorExit() {
608 wfAbruptExit( true );
612 * Print a simple message and die, returning nonzero to the shell if any.
613 * Plain die() fails to return nonzero to the shell if you pass a string.
614 * @param string $msg
616 function wfDie( $msg='' ) {
617 echo $msg;
618 die( 1 );
622 * Throw a debugging exception. This function previously once exited the process,
623 * but now throws an exception instead, with similar results.
625 * @param string $msg Message shown when dieing.
627 function wfDebugDieBacktrace( $msg = '' ) {
628 throw new MWException( $msg );
632 * Fetch server name for use in error reporting etc.
633 * Use real server name if available, so we know which machine
634 * in a server farm generated the current page.
635 * @return string
637 function wfHostname() {
638 if ( function_exists( 'posix_uname' ) ) {
639 // This function not present on Windows
640 $uname = @posix_uname();
641 } else {
642 $uname = false;
644 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
645 return $uname['nodename'];
646 } else {
647 # This may be a virtual server.
648 return $_SERVER['SERVER_NAME'];
653 * Returns a HTML comment with the elapsed time since request.
654 * This method has no side effects.
655 * @return string
657 function wfReportTime() {
658 global $wgRequestTime;
660 $now = wfTime();
661 $elapsed = $now - $wgRequestTime;
663 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
664 wfHostname(), $elapsed );
665 return $com;
668 function wfBacktrace() {
669 global $wgCommandLineMode;
670 if ( !function_exists( 'debug_backtrace' ) ) {
671 return false;
674 if ( $wgCommandLineMode ) {
675 $msg = '';
676 } else {
677 $msg = "<ul>\n";
679 $backtrace = debug_backtrace();
680 foreach( $backtrace as $call ) {
681 if( isset( $call['file'] ) ) {
682 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
683 $file = $f[count($f)-1];
684 } else {
685 $file = '-';
687 if( isset( $call['line'] ) ) {
688 $line = $call['line'];
689 } else {
690 $line = '-';
692 if ( $wgCommandLineMode ) {
693 $msg .= "$file line $line calls ";
694 } else {
695 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
697 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
698 $msg .= $call['function'] . '()';
700 if ( $wgCommandLineMode ) {
701 $msg .= "\n";
702 } else {
703 $msg .= "</li>\n";
706 if ( $wgCommandLineMode ) {
707 $msg .= "\n";
708 } else {
709 $msg .= "</ul>\n";
712 return $msg;
716 /* Some generic result counters, pulled out of SearchEngine */
720 * @todo document
722 function wfShowingResults( $offset, $limit ) {
723 global $wgLang;
724 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
728 * @todo document
730 function wfShowingResultsNum( $offset, $limit, $num ) {
731 global $wgLang;
732 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
736 * @todo document
738 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
739 global $wgLang;
740 $fmtLimit = $wgLang->formatNum( $limit );
741 $prev = wfMsg( 'prevn', $fmtLimit );
742 $next = wfMsg( 'nextn', $fmtLimit );
744 if( is_object( $link ) ) {
745 $title =& $link;
746 } else {
747 $title = Title::newFromText( $link );
748 if( is_null( $title ) ) {
749 return false;
753 if ( 0 != $offset ) {
754 $po = $offset - $limit;
755 if ( $po < 0 ) { $po = 0; }
756 $q = "limit={$limit}&offset={$po}";
757 if ( '' != $query ) { $q .= '&'.$query; }
758 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
759 } else { $plink = $prev; }
761 $no = $offset + $limit;
762 $q = 'limit='.$limit.'&offset='.$no;
763 if ( '' != $query ) { $q .= '&'.$query; }
765 if ( $atend ) {
766 $nlink = $next;
767 } else {
768 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
770 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
771 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
772 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
773 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
774 wfNumLink( $offset, 500, $title, $query );
776 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
780 * @todo document
782 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
783 global $wgLang;
784 if ( '' == $query ) { $q = ''; }
785 else { $q = $query.'&'; }
786 $q .= 'limit='.$limit.'&offset='.$offset;
788 $fmtLimit = $wgLang->formatNum( $limit );
789 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
790 return $s;
794 * @todo document
795 * @todo FIXME: we may want to blacklist some broken browsers
797 * @return bool Whereas client accept gzip compression
799 function wfClientAcceptsGzip() {
800 global $wgUseGzip;
801 if( $wgUseGzip ) {
802 # FIXME: we may want to blacklist some broken browsers
803 if( preg_match(
804 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
805 $_SERVER['HTTP_ACCEPT_ENCODING'],
806 $m ) ) {
807 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
808 wfDebug( " accepts gzip\n" );
809 return true;
812 return false;
816 * Obtain the offset and limit values from the request string;
817 * used in special pages
819 * @param $deflimit Default limit if none supplied
820 * @param $optionname Name of a user preference to check against
821 * @return array
824 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
825 global $wgRequest;
826 return $wgRequest->getLimitOffset( $deflimit, $optionname );
830 * Escapes the given text so that it may be output using addWikiText()
831 * without any linking, formatting, etc. making its way through. This
832 * is achieved by substituting certain characters with HTML entities.
833 * As required by the callers, <nowiki> is not used. It currently does
834 * not filter out characters which have special meaning only at the
835 * start of a line, such as "*".
837 * @param string $text Text to be escaped
839 function wfEscapeWikiText( $text ) {
840 $text = str_replace(
841 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
842 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
843 htmlspecialchars($text) );
844 return $text;
848 * @todo document
850 function wfQuotedPrintable( $string, $charset = '' ) {
851 # Probably incomplete; see RFC 2045
852 if( empty( $charset ) ) {
853 global $wgInputEncoding;
854 $charset = $wgInputEncoding;
856 $charset = strtoupper( $charset );
857 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
859 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
860 $replace = $illegal . '\t ?_';
861 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
862 $out = "=?$charset?Q?";
863 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
864 $out .= '?=';
865 return $out;
870 * @todo document
871 * @return float
873 function wfTime() {
874 return microtime(true);
878 * Sets dest to source and returns the original value of dest
879 * If source is NULL, it just returns the value, it doesn't set the variable
881 function wfSetVar( &$dest, $source ) {
882 $temp = $dest;
883 if ( !is_null( $source ) ) {
884 $dest = $source;
886 return $temp;
890 * As for wfSetVar except setting a bit
892 function wfSetBit( &$dest, $bit, $state = true ) {
893 $temp = (bool)($dest & $bit );
894 if ( !is_null( $state ) ) {
895 if ( $state ) {
896 $dest |= $bit;
897 } else {
898 $dest &= ~$bit;
901 return $temp;
905 * This function takes two arrays as input, and returns a CGI-style string, e.g.
906 * "days=7&limit=100". Options in the first array override options in the second.
907 * Options set to "" will not be output.
909 function wfArrayToCGI( $array1, $array2 = NULL )
911 if ( !is_null( $array2 ) ) {
912 $array1 = $array1 + $array2;
915 $cgi = '';
916 foreach ( $array1 as $key => $value ) {
917 if ( '' !== $value ) {
918 if ( '' != $cgi ) {
919 $cgi .= '&';
921 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
924 return $cgi;
928 * This is obsolete, use SquidUpdate::purge()
929 * @deprecated
931 function wfPurgeSquidServers ($urlArr) {
932 SquidUpdate::purge( $urlArr );
936 * Windows-compatible version of escapeshellarg()
937 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
938 * function puts single quotes in regardless of OS
940 function wfEscapeShellArg( ) {
941 $args = func_get_args();
942 $first = true;
943 $retVal = '';
944 foreach ( $args as $arg ) {
945 if ( !$first ) {
946 $retVal .= ' ';
947 } else {
948 $first = false;
951 if ( wfIsWindows() ) {
952 // Escaping for an MSVC-style command line parser
953 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
954 // Double the backslashes before any double quotes. Escape the double quotes.
955 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
956 $arg = '';
957 $delim = false;
958 foreach ( $tokens as $token ) {
959 if ( $delim ) {
960 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
961 } else {
962 $arg .= $token;
964 $delim = !$delim;
966 // Double the backslashes before the end of the string, because
967 // we will soon add a quote
968 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
969 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
972 // Add surrounding quotes
973 $retVal .= '"' . $arg . '"';
974 } else {
975 $retVal .= escapeshellarg( $arg );
978 return $retVal;
982 * wfMerge attempts to merge differences between three texts.
983 * Returns true for a clean merge and false for failure or a conflict.
985 function wfMerge( $old, $mine, $yours, &$result ){
986 global $wgDiff3;
988 # This check may also protect against code injection in
989 # case of broken installations.
990 if(! file_exists( $wgDiff3 ) ){
991 wfDebug( "diff3 not found\n" );
992 return false;
995 # Make temporary files
996 $td = wfTempDir();
997 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
998 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
999 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1001 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1002 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1003 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1005 # Check for a conflict
1006 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1007 wfEscapeShellArg( $mytextName ) . ' ' .
1008 wfEscapeShellArg( $oldtextName ) . ' ' .
1009 wfEscapeShellArg( $yourtextName );
1010 $handle = popen( $cmd, 'r' );
1012 if( fgets( $handle, 1024 ) ){
1013 $conflict = true;
1014 } else {
1015 $conflict = false;
1017 pclose( $handle );
1019 # Merge differences
1020 $cmd = $wgDiff3 . ' -a -e --merge ' .
1021 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1022 $handle = popen( $cmd, 'r' );
1023 $result = '';
1024 do {
1025 $data = fread( $handle, 8192 );
1026 if ( strlen( $data ) == 0 ) {
1027 break;
1029 $result .= $data;
1030 } while ( true );
1031 pclose( $handle );
1032 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1034 if ( $result === '' && $old !== '' && $conflict == false ) {
1035 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1036 $conflict = true;
1038 return ! $conflict;
1042 * @todo document
1044 function wfVarDump( $var ) {
1045 global $wgOut;
1046 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1047 if ( headers_sent() || !@is_object( $wgOut ) ) {
1048 print $s;
1049 } else {
1050 $wgOut->addHTML( $s );
1055 * Provide a simple HTTP error.
1057 function wfHttpError( $code, $label, $desc ) {
1058 global $wgOut;
1059 $wgOut->disable();
1060 header( "HTTP/1.0 $code $label" );
1061 header( "Status: $code $label" );
1062 $wgOut->sendCacheControl();
1064 header( 'Content-type: text/html' );
1065 print "<html><head><title>" .
1066 htmlspecialchars( $label ) .
1067 "</title></head><body><h1>" .
1068 htmlspecialchars( $label ) .
1069 "</h1><p>" .
1070 htmlspecialchars( $desc ) .
1071 "</p></body></html>\n";
1075 * Converts an Accept-* header into an array mapping string values to quality
1076 * factors
1078 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1079 # No arg means accept anything (per HTTP spec)
1080 if( !$accept ) {
1081 return array( $def => 1 );
1084 $prefs = array();
1086 $parts = explode( ',', $accept );
1088 foreach( $parts as $part ) {
1089 # FIXME: doesn't deal with params like 'text/html; level=1'
1090 @list( $value, $qpart ) = explode( ';', $part );
1091 if( !isset( $qpart ) ) {
1092 $prefs[$value] = 1;
1093 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1094 $prefs[$value] = $match[1];
1098 return $prefs;
1102 * Checks if a given MIME type matches any of the keys in the given
1103 * array. Basic wildcards are accepted in the array keys.
1105 * Returns the matching MIME type (or wildcard) if a match, otherwise
1106 * NULL if no match.
1108 * @param string $type
1109 * @param array $avail
1110 * @return string
1111 * @private
1113 function mimeTypeMatch( $type, $avail ) {
1114 if( array_key_exists($type, $avail) ) {
1115 return $type;
1116 } else {
1117 $parts = explode( '/', $type );
1118 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1119 return $parts[0] . '/*';
1120 } elseif( array_key_exists( '*/*', $avail ) ) {
1121 return '*/*';
1122 } else {
1123 return NULL;
1129 * Returns the 'best' match between a client's requested internet media types
1130 * and the server's list of available types. Each list should be an associative
1131 * array of type to preference (preference is a float between 0.0 and 1.0).
1132 * Wildcards in the types are acceptable.
1134 * @param array $cprefs Client's acceptable type list
1135 * @param array $sprefs Server's offered types
1136 * @return string
1138 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1139 * XXX: generalize to negotiate other stuff
1141 function wfNegotiateType( $cprefs, $sprefs ) {
1142 $combine = array();
1144 foreach( array_keys($sprefs) as $type ) {
1145 $parts = explode( '/', $type );
1146 if( $parts[1] != '*' ) {
1147 $ckey = mimeTypeMatch( $type, $cprefs );
1148 if( $ckey ) {
1149 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1154 foreach( array_keys( $cprefs ) as $type ) {
1155 $parts = explode( '/', $type );
1156 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1157 $skey = mimeTypeMatch( $type, $sprefs );
1158 if( $skey ) {
1159 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1164 $bestq = 0;
1165 $besttype = NULL;
1167 foreach( array_keys( $combine ) as $type ) {
1168 if( $combine[$type] > $bestq ) {
1169 $besttype = $type;
1170 $bestq = $combine[$type];
1174 return $besttype;
1178 * Array lookup
1179 * Returns an array where the values in the first array are replaced by the
1180 * values in the second array with the corresponding keys
1182 * @return array
1184 function wfArrayLookup( $a, $b ) {
1185 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1189 * Convenience function; returns MediaWiki timestamp for the present time.
1190 * @return string
1192 function wfTimestampNow() {
1193 # return NOW
1194 return wfTimestamp( TS_MW, time() );
1198 * Reference-counted warning suppression
1200 function wfSuppressWarnings( $end = false ) {
1201 static $suppressCount = 0;
1202 static $originalLevel = false;
1204 if ( $end ) {
1205 if ( $suppressCount ) {
1206 --$suppressCount;
1207 if ( !$suppressCount ) {
1208 error_reporting( $originalLevel );
1211 } else {
1212 if ( !$suppressCount ) {
1213 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1215 ++$suppressCount;
1220 * Restore error level to previous value
1222 function wfRestoreWarnings() {
1223 wfSuppressWarnings( true );
1226 # Autodetect, convert and provide timestamps of various types
1229 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1231 define('TS_UNIX', 0);
1234 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1236 define('TS_MW', 1);
1239 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1241 define('TS_DB', 2);
1244 * RFC 2822 format, for E-mail and HTTP headers
1246 define('TS_RFC2822', 3);
1249 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1251 * This is used by Special:Export
1253 define('TS_ISO_8601', 4);
1256 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1258 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1259 * DateTime tag and page 36 for the DateTimeOriginal and
1260 * DateTimeDigitized tags.
1262 define('TS_EXIF', 5);
1265 * Oracle format time.
1267 define('TS_ORACLE', 6);
1270 * Postgres format time.
1272 define('TS_POSTGRES', 7);
1275 * @param mixed $outputtype A timestamp in one of the supported formats, the
1276 * function will autodetect which format is supplied
1277 * and act accordingly.
1278 * @return string Time in the format specified in $outputtype
1280 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1281 $uts = 0;
1282 $da = array();
1283 if ($ts==0) {
1284 $uts=time();
1285 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1286 # TS_DB
1287 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1288 (int)$da[2],(int)$da[3],(int)$da[1]);
1289 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1290 # TS_EXIF
1291 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1292 (int)$da[2],(int)$da[3],(int)$da[1]);
1293 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D",$ts,$da)) {
1294 # TS_MW
1295 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1296 (int)$da[2],(int)$da[3],(int)$da[1]);
1297 } elseif (preg_match("/^(\d{1,13})$/D",$ts,$datearray)) {
1298 # TS_UNIX
1299 $uts = $ts;
1300 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1301 # TS_ORACLE
1302 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1303 str_replace("+00:00", "UTC", $ts)));
1304 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1305 # TS_ISO_8601
1306 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1307 (int)$da[2],(int)$da[3],(int)$da[1]);
1308 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/",$ts,$da)) {
1309 # TS_POSTGRES
1310 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1311 (int)$da[2],(int)$da[3],(int)$da[1]);
1312 } else {
1313 # Bogus value; fall back to the epoch...
1314 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1315 $uts = 0;
1319 switch($outputtype) {
1320 case TS_UNIX:
1321 return $uts;
1322 case TS_MW:
1323 return gmdate( 'YmdHis', $uts );
1324 case TS_DB:
1325 return gmdate( 'Y-m-d H:i:s', $uts );
1326 case TS_ISO_8601:
1327 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1328 // This shouldn't ever be used, but is included for completeness
1329 case TS_EXIF:
1330 return gmdate( 'Y:m:d H:i:s', $uts );
1331 case TS_RFC2822:
1332 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1333 case TS_ORACLE:
1334 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1335 case TS_POSTGRES:
1336 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1337 default:
1338 throw new MWException( 'wfTimestamp() called with illegal output type.');
1343 * Return a formatted timestamp, or null if input is null.
1344 * For dealing with nullable timestamp columns in the database.
1345 * @param int $outputtype
1346 * @param string $ts
1347 * @return string
1349 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1350 if( is_null( $ts ) ) {
1351 return null;
1352 } else {
1353 return wfTimestamp( $outputtype, $ts );
1358 * Check if the operating system is Windows
1360 * @return bool True if it's Windows, False otherwise.
1362 function wfIsWindows() {
1363 if (substr(php_uname(), 0, 7) == 'Windows') {
1364 return true;
1365 } else {
1366 return false;
1371 * Swap two variables
1373 function swap( &$x, &$y ) {
1374 $z = $x;
1375 $x = $y;
1376 $y = $z;
1379 function wfGetCachedNotice( $name ) {
1380 global $wgOut, $parserMemc, $wgDBname;
1381 $fname = 'wfGetCachedNotice';
1382 wfProfileIn( $fname );
1384 $needParse = false;
1385 $notice = wfMsgForContent( $name );
1386 if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
1387 wfProfileOut( $fname );
1388 return( false );
1391 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1392 if( is_array( $cachedNotice ) ) {
1393 if( md5( $notice ) == $cachedNotice['hash'] ) {
1394 $notice = $cachedNotice['html'];
1395 } else {
1396 $needParse = true;
1398 } else {
1399 $needParse = true;
1402 if( $needParse ) {
1403 if( is_object( $wgOut ) ) {
1404 $parsed = $wgOut->parse( $notice );
1405 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1406 $notice = $parsed;
1407 } else {
1408 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1409 $notice = '';
1413 wfProfileOut( $fname );
1414 return $notice;
1417 function wfGetNamespaceNotice() {
1418 global $wgTitle;
1420 # Paranoia
1421 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1422 return "";
1424 $fname = 'wfGetNamespaceNotice';
1425 wfProfileIn( $fname );
1427 $key = "namespacenotice-" . $wgTitle->getNsText();
1428 $namespaceNotice = wfGetCachedNotice( $key );
1429 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1430 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1431 } else {
1432 $namespaceNotice = "";
1435 wfProfileOut( $fname );
1436 return $namespaceNotice;
1439 function wfGetSiteNotice() {
1440 global $wgUser, $wgSiteNotice;
1441 $fname = 'wfGetSiteNotice';
1442 wfProfileIn( $fname );
1443 $siteNotice = '';
1445 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1446 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1447 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1448 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1449 } else {
1450 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1451 if( !$anonNotice ) {
1452 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1453 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1454 } else {
1455 $siteNotice = $anonNotice;
1460 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1461 wfProfileOut( $fname );
1462 return $siteNotice;
1465 /** Global singleton instance of MimeMagic. This is initialized on demand,
1466 * please always use the wfGetMimeMagic() function to get the instance.
1468 * @private
1470 $wgMimeMagic= NULL;
1472 /** Factory functions for the global MimeMagic object.
1473 * This function always returns the same singleton instance of MimeMagic.
1474 * That objects will be instantiated on the first call to this function.
1475 * If needed, the MimeMagic.php file is automatically included by this function.
1476 * @return MimeMagic the global MimeMagic objects.
1478 function &wfGetMimeMagic() {
1479 global $wgMimeMagic;
1481 if (!is_null($wgMimeMagic)) {
1482 return $wgMimeMagic;
1485 if (!class_exists("MimeMagic")) {
1486 #include on demand
1487 require_once("MimeMagic.php");
1490 $wgMimeMagic= new MimeMagic();
1492 return $wgMimeMagic;
1497 * Tries to get the system directory for temporary files.
1498 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1499 * and if none are set /tmp is returned as the generic Unix default.
1501 * NOTE: When possible, use the tempfile() function to create temporary
1502 * files to avoid race conditions on file creation, etc.
1504 * @return string
1506 function wfTempDir() {
1507 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1508 $tmp = getenv( $var );
1509 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1510 return $tmp;
1513 # Hope this is Unix of some kind!
1514 return '/tmp';
1518 * Make directory, and make all parent directories if they don't exist
1520 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1521 if ( strval( $fullDir ) === '' ) {
1522 return true;
1525 # Go back through the paths to find the first directory that exists
1526 $currentDir = $fullDir;
1527 $createList = array();
1528 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1529 # Strip trailing slashes
1530 $currentDir = rtrim( $currentDir, '/\\' );
1532 # Add to create list
1533 $createList[] = $currentDir;
1535 # Find next delimiter searching from the end
1536 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1537 if ( $p === false ) {
1538 $currentDir = false;
1539 } else {
1540 $currentDir = substr( $currentDir, 0, $p );
1544 if ( count( $createList ) == 0 ) {
1545 # Directory specified already exists
1546 return true;
1547 } elseif ( $currentDir === false ) {
1548 # Went all the way back to root and it apparently doesn't exist
1549 return false;
1552 # Now go forward creating directories
1553 $createList = array_reverse( $createList );
1554 foreach ( $createList as $dir ) {
1555 # use chmod to override the umask, as suggested by the PHP manual
1556 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1557 return false;
1560 return true;
1564 * Increment a statistics counter
1566 function wfIncrStats( $key ) {
1567 global $wgDBname, $wgMemc;
1568 $key = "$wgDBname:stats:$key";
1569 if ( is_null( $wgMemc->incr( $key ) ) ) {
1570 $wgMemc->add( $key, 1 );
1575 * @param mixed $nr The number to format
1576 * @param int $acc The number of digits after the decimal point, default 2
1577 * @param bool $round Whether or not to round the value, default true
1578 * @return float
1580 function wfPercent( $nr, $acc = 2, $round = true ) {
1581 $ret = sprintf( "%.${acc}f", $nr );
1582 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1586 * Encrypt a username/password.
1588 * @param string $userid ID of the user
1589 * @param string $password Password of the user
1590 * @return string Hashed password
1592 function wfEncryptPassword( $userid, $password ) {
1593 global $wgPasswordSalt;
1594 $p = md5( $password);
1596 if($wgPasswordSalt)
1597 return md5( "{$userid}-{$p}" );
1598 else
1599 return $p;
1603 * Appends to second array if $value differs from that in $default
1605 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1606 if ( is_null( $changed ) ) {
1607 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1609 if ( $default[$key] !== $value ) {
1610 $changed[$key] = $value;
1615 * Since wfMsg() and co suck, they don't return false if the message key they
1616 * looked up didn't exist but a XHTML string, this function checks for the
1617 * nonexistance of messages by looking at wfMsg() output
1619 * @param $msg The message key looked up
1620 * @param $wfMsgOut The output of wfMsg*()
1621 * @return bool
1623 function wfEmptyMsg( $msg, $wfMsgOut ) {
1624 return $wfMsgOut === "&lt;$msg&gt;";
1628 * Find out whether or not a mixed variable exists in a string
1630 * @param mixed needle
1631 * @param string haystack
1632 * @return bool
1634 function in_string( $needle, $str ) {
1635 return strpos( $str, $needle ) !== false;
1638 function wfSpecialList( $page, $details ) {
1639 global $wgContLang;
1640 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1641 return $page . $details;
1645 * Returns a regular expression of url protocols
1647 * @return string
1649 function wfUrlProtocols() {
1650 global $wgUrlProtocols;
1652 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1653 // with LocalSettings files from 1.5
1654 if ( is_array( $wgUrlProtocols ) ) {
1655 $protocols = array();
1656 foreach ($wgUrlProtocols as $protocol)
1657 $protocols[] = preg_quote( $protocol, '/' );
1659 return implode( '|', $protocols );
1660 } else {
1661 return $wgUrlProtocols;
1666 * Execute a shell command, with time and memory limits mirrored from the PHP
1667 * configuration if supported.
1668 * @param $cmd Command line, properly escaped for shell.
1669 * @param &$retval optional, will receive the program's exit code.
1670 * (non-zero is usually failure)
1671 * @return collected stdout as a string (trailing newlines stripped)
1673 function wfShellExec( $cmd, &$retval=null ) {
1674 global $IP, $wgMaxShellMemory;
1676 if( ini_get( 'safe_mode' ) ) {
1677 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1678 $retval = 1;
1679 return "Unable to run external programs in safe mode.";
1682 if ( php_uname( 's' ) == 'Linux' ) {
1683 $time = ini_get( 'max_execution_time' );
1684 $mem = intval( $wgMaxShellMemory );
1686 if ( $time > 0 && $mem > 0 ) {
1687 $script = "$IP/bin/ulimit.sh";
1688 if ( is_executable( $script ) ) {
1689 $cmd = escapeshellarg( $script ) . " $time $mem $cmd";
1692 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1693 # This is a hack to work around PHP's flawed invocation of cmd.exe
1694 # http://news.php.net/php.internals/21796
1695 $cmd = '"' . $cmd . '"';
1697 wfDebug( "wfShellExec: $cmd\n" );
1699 $output = array();
1700 $retval = 1; // error by default?
1701 $lastline = exec( $cmd, $output, $retval );
1702 return implode( "\n", $output );
1707 * This function works like "use VERSION" in Perl, the program will die with a
1708 * backtrace if the current version of PHP is less than the version provided
1710 * This is useful for extensions which due to their nature are not kept in sync
1711 * with releases, and might depend on other versions of PHP than the main code
1713 * Note: PHP might die due to parsing errors in some cases before it ever
1714 * manages to call this function, such is life
1716 * @see perldoc -f use
1718 * @param mixed $version The version to check, can be a string, an integer, or
1719 * a float
1721 function wfUsePHP( $req_ver ) {
1722 $php_ver = PHP_VERSION;
1724 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1725 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1729 * This function works like "use VERSION" in Perl except it checks the version
1730 * of MediaWiki, the program will die with a backtrace if the current version
1731 * of MediaWiki is less than the version provided.
1733 * This is useful for extensions which due to their nature are not kept in sync
1734 * with releases
1736 * @see perldoc -f use
1738 * @param mixed $version The version to check, can be a string, an integer, or
1739 * a float
1741 function wfUseMW( $req_ver ) {
1742 global $wgVersion;
1744 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1745 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1749 * Escape a string to make it suitable for inclusion in a preg_replace()
1750 * replacement parameter.
1752 * @param string $string
1753 * @return string
1755 function wfRegexReplacement( $string ) {
1756 $string = str_replace( '\\', '\\\\', $string );
1757 $string = str_replace( '$', '\\$', $string );
1758 return $string;
1762 * Return the final portion of a pathname.
1763 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1764 * http://bugs.php.net/bug.php?id=33898
1766 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1767 * We'll consider it so always, as we don't want \s in our Unix paths either.
1769 * @param string $path
1770 * @return string
1772 function wfBaseName( $path ) {
1773 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1774 return $matches[1];
1775 } else {
1776 return '';
1781 * Make a URL index, appropriate for the el_index field of externallinks.
1783 function wfMakeUrlIndex( $url ) {
1784 wfSuppressWarnings();
1785 $bits = parse_url( $url );
1786 wfRestoreWarnings();
1787 if ( !$bits || $bits['scheme'] !== 'http' ) {
1788 return false;
1790 // Reverse the labels in the hostname, convert to lower case
1791 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1792 // Add an extra dot to the end
1793 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1794 $reversedHost .= '.';
1796 // Reconstruct the pseudo-URL
1797 $index = "http://$reversedHost";
1798 // Leave out user and password. Add the port, path, query and fragment
1799 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1800 if ( isset( $bits['path'] ) ) {
1801 $index .= $bits['path'];
1802 } else {
1803 $index .= '/';
1805 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1806 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1807 return $index;
1811 * Do any deferred updates and clear the list
1812 * TODO: This could be in Wiki.php if that class made any sense at all
1814 function wfDoUpdates()
1816 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1817 foreach ( $wgDeferredUpdateList as $update ) {
1818 $update->doUpdate();
1820 foreach ( $wgPostCommitUpdateList as $update ) {
1821 $update->doUpdate();
1823 $wgDeferredUpdateList = array();
1824 $wgPostCommitUpdateList = array();
1828 * More or less "markup-safe" explode()
1829 * Ignores any instances of the separator inside <...>
1830 * @param string $separator
1831 * @param string $text
1832 * @return array
1834 function wfExplodeMarkup( $separator, $text ) {
1835 $placeholder = "\x00";
1837 // Just in case...
1838 $text = str_replace( $placeholder, '', $text );
1840 // Trim stuff
1841 $replacer = new ReplacerCallback( $separator, $placeholder );
1842 $cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );
1844 $items = explode( $separator, $cleaned );
1845 foreach( $items as $i => $str ) {
1846 $items[$i] = str_replace( $placeholder, $separator, $str );
1849 return $items;
1852 class ReplacerCallback {
1853 function ReplacerCallback( $from, $to ) {
1854 $this->from = $from;
1855 $this->to = $to;
1858 function go( $matches ) {
1859 return str_replace( $this->from, $this->to, $matches[1] );
1865 * Convert an arbitrarily-long digit string from one numeric base
1866 * to another, optionally zero-padding to a minimum column width.
1868 * Supports base 2 through 36; digit values 10-36 are represented
1869 * as lowercase letters a-z. Input is case-insensitive.
1871 * @param $input string of digits
1872 * @param $sourceBase int 2-36
1873 * @param $destBase int 2-36
1874 * @param $pad int 1 or greater
1875 * @return string or false on invalid input
1877 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1878 if( $sourceBase < 2 ||
1879 $sourceBase > 36 ||
1880 $destBase < 2 ||
1881 $destBase > 36 ||
1882 $pad < 1 ||
1883 $sourceBase != intval( $sourceBase ) ||
1884 $destBase != intval( $destBase ) ||
1885 $pad != intval( $pad ) ||
1886 !is_string( $input ) ||
1887 $input == '' ) {
1888 return false;
1891 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1892 $inDigits = array();
1893 $outChars = '';
1895 // Decode and validate input string
1896 $input = strtolower( $input );
1897 for( $i = 0; $i < strlen( $input ); $i++ ) {
1898 $n = strpos( $digitChars, $input{$i} );
1899 if( $n === false || $n > $sourceBase ) {
1900 return false;
1902 $inDigits[] = $n;
1905 // Iterate over the input, modulo-ing out an output digit
1906 // at a time until input is gone.
1907 while( count( $inDigits ) ) {
1908 $work = 0;
1909 $workDigits = array();
1911 // Long division...
1912 foreach( $inDigits as $digit ) {
1913 $work *= $sourceBase;
1914 $work += $digit;
1916 if( $work < $destBase ) {
1917 // Gonna need to pull another digit.
1918 if( count( $workDigits ) ) {
1919 // Avoid zero-padding; this lets us find
1920 // the end of the input very easily when
1921 // length drops to zero.
1922 $workDigits[] = 0;
1924 } else {
1925 // Finally! Actual division!
1926 $workDigits[] = intval( $work / $destBase );
1928 // Isn't it annoying that most programming languages
1929 // don't have a single divide-and-remainder operator,
1930 // even though the CPU implements it that way?
1931 $work = $work % $destBase;
1935 // All that division leaves us with a remainder,
1936 // which is conveniently our next output digit.
1937 $outChars .= $digitChars[$work];
1939 // And we continue!
1940 $inDigits = $workDigits;
1943 while( strlen( $outChars ) < $pad ) {
1944 $outChars .= '0';
1947 return strrev( $outChars );
1951 * Create an object with a given name and an array of construct parameters
1952 * @param string $name
1953 * @param array $p parameters
1955 function wfCreateObject( $name, $p ){
1956 $p = array_values( $p );
1957 switch ( count( $p ) ) {
1958 case 0:
1959 return new $name;
1960 case 1:
1961 return new $name( $p[0] );
1962 case 2:
1963 return new $name( $p[0], $p[1] );
1964 case 3:
1965 return new $name( $p[0], $p[1], $p[2] );
1966 case 4:
1967 return new $name( $p[0], $p[1], $p[2], $p[3] );
1968 case 5:
1969 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1970 case 6:
1971 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
1972 default:
1973 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
1978 * Aliases for modularized functions
1980 function wfGetHTTP( $url, $timeout = 'default' ) {
1981 return Http::get( $url, $timeout );
1983 function wfIsLocalURL( $url ) {
1984 return Http::isLocalURL( $url );
1988 * Initialise php session
1990 function wfSetupSession() {
1991 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
1992 if( $wgSessionsInMemcached ) {
1993 require_once( 'MemcachedSessions.php' );
1994 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
1995 # If it's left on 'user' or another setting from another
1996 # application, it will end up failing. Try to recover.
1997 ini_set ( 'session.save_handler', 'files' );
1999 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
2000 session_cache_limiter( 'private, must-revalidate' );
2001 @session_start();
2005 * Get an object from the precompiled serialized directory
2007 * @return mixed The variable on success, false on failure
2009 function wfGetPrecompiledData( $name ) {
2010 global $IP;
2012 $file = "$IP/serialized/$name";
2013 if ( file_exists( $file ) ) {
2014 $blob = file_get_contents( $file );
2015 if ( $blob ) {
2016 return unserialize( $blob );
2019 return false;
2022 function wfGetCaller( $level = 2 ) {
2023 $backtrace = debug_backtrace();
2024 if ( isset( $backtrace[$level] ) ) {
2025 if ( isset( $backtrace[$level]['class'] ) ) {
2026 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2027 } else {
2028 $caller = $backtrace[$level]['function'];
2030 } else {
2031 $caller = 'unknown';
2033 return $caller;
2036 /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
2037 function wfGetAllCallers() {
2038 return implode('/', array_map(
2039 create_function('$frame','
2040 return isset( $frame["class"] )?
2041 $frame["class"]."::".$frame["function"]:
2042 $frame["function"];
2044 array_reverse(debug_backtrace())));